{"text": "# Nominal and Ordinal categorical variables\n\n# Animals - by default the order does not matter\nanimals_vector <- c(\"Elephant\", \"Giraffe\", \"Donkey\", \"Horse\")\nfactor_animals_vector <- factor(animals_vector)\nfactor_animals_vector\n\n# Temperature\ntemperature_vector <- c(\"High\", \"Low\", \"High\",\"Low\", \"Medium\")\nfactor_temperature_vector <- factor(temperature_vector, order = TRUE, levels = c(\"Low\", \"Medium\", \"High\"))\nfactor_temperature_vector\n\n# order: outlines that the order matters\n# levels: order of importance\n", "meta": {"hexsha": "b3d0da8b153a6a7e40e5af7b8c461ae52e95df64", "size": 509, "ext": "r", "lang": "R", "max_stars_repo_path": "R/DataAnalyst/Basics/factors-nominal-ordinal.r", "max_stars_repo_name": "James-McNeill/Learning", "max_stars_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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/DataAnalyst/Basics/factors-nominal-ordinal.r", "max_issues_repo_name": "James-McNeill/Learning", "max_issues_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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/DataAnalyst/Basics/factors-nominal-ordinal.r", "max_forks_repo_name": "James-McNeill/Learning", "max_forks_repo_head_hexsha": "3c4fe1a64240cdf5614db66082bd68a2f16d2afb", "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.9333333333, "max_line_length": 106, "alphanum_fraction": 0.7563850688, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.11757212272365286, "lm_q1q2_score": 0.04482079197543685}} {"text": "#R para Kindergarten, sala de 2 años (pero con conceptos no triviales de analisis de datos)\n#en la salita de 2 años NO se usan variables, tampoco sentencia if, loops ni funciones, ni parametros\n\nrm(list=ls())\n\n\n#entorno de ejecucion : PC local\n\n#set working directory\n#A un directorio correspondiente dentro de la máquina...\nsetwd(\"E:/UBA/2019-II/DM en Finanzas/Dropbox Prof/R\")\n\n\n\n#opcion nativa en R para cargar un dataset\n\n#cargo los datos, forma estandar\nt0 <- Sys.time()\ndataset <- read.table(\"../datasets/201902.txt\", sep=\"\\t\")\nt1 <- Sys.time()\n\n#calculo el tiempo de corrida, expresado en segundos\ntcorrida <- as.numeric(t1 - t0, units = \"secs\")\ntcorridamin <- as.numeric(tcorrida/60, units = \"mins\")\n\ncat(\"tiempo carga dataset con read.table \", tcorrida, \" segundos\\n\" )\ncat(\"tiempo carga dataset con read.table \", tcorridamin, \" minutos\\n\" )\n\n\n#opcion con libreria data.table\n\n#instalo el paquete, se hace una sola vez\ninstall.packages( \"data.table\" )\n#invoco a la libreria\nlibrary( \"data.table\" )\n\n#cargo los datos, con la funcion File Read de la libreria data.table\nt0 <- Sys.time()\ndataset <- data.table::fread(\"../datasets/201902.txt\")\nt1 <- Sys.time()\ntcorrida2 <- as.numeric(t1 - t0, units = \"secs\")\ntcorridamin2 <- as.numeric(tcorrida2/60, units = \"secs\")\n\ncat(\"tiempo carga dataset con fread \", tcorrida2, \" segundos\\n\" )\ncat(\"tiempo carga dataset con fread \", tcorridamin2, \" minutos\\n\" )\n\n\n#se observa una enorme diferencia en el tiempo de carga de un archivo\n# A partir de ahora usamos la libreria data.table para manejar los datasets\n\n#Notar como se llamó a la funcion data.table::fread() especificando la libreria\n#tambien se la podria haber llamado directamente con fread() \n\n\n#------------------------------------------------------------------------------\n#operaciones basicas a un dataset usando data.table\n\n\n#cantidad de columnas\nncol( dataset )\n\n#nombres de las columnas\n#están nombradas de v1 a v170\ncolnames( dataset )\n\n#cantidad de registros\nnrow( dataset )\n\n#ver que hay dentro\ndataset\n\n#ver un resumen\nsummary( dataset )\n\n#si quiero que el summary quede en un archivo\nsetwd(\"E:/UBA/2019-II/DM en Finanzas/Dropbox Prof/work\")\n\nsink(\"summary-kinder.txt\")\nsummary( dataset )\nsink()\n\n#calculo del promedio\nmean( dataset[ , mcuentas_saldo ] )\n#otra forma \nmean( dataset$mcuentas_saldo )\n\n\n#calculo de la mediana\nmedian( dataset[ , mcuentas_saldo ] )\n\n#minimo y maximo de una columna\n#tener en cuenta que esto incluye los saldos en pesos y dolares (pero expresados en pesos argentinos)\nmin( dataset[ , mcuentas_saldo ] )\nmax( dataset[ , mcuentas_saldo ] )\n\n\n#ver un campo en particular Frequency Table\nftable( dataset$clase_ternaria )\nftable( dataset$Visa_cuenta_estado )\nftable( dataset$Master_cuenta_estado )\n\n#Tabla de contingencia de un campo versus la clase\ndcast( dataset, Visa_cuenta_estado ~ clase_ternaria, length )\ndcast( dataset, Master_cuenta_estado ~ clase_ternaria, length )\n\n#Tabla de contingencia de dos campos versus la clase\ndcast( dataset, Visa_cuenta_estado + Master_cuenta_estado ~ clase_ternaria, length )\n\n#-----------------------------------\n#Verificar como los valores siguientes\n#surgen directamente o son sumas\n#de las celdas de la tabla de contingencia dcast( dataset, Visa_cuenta_estado ~ clase_ternaria, length )\n\n#filtrar registros con condiciones logicas\n#notar como se utiliza el == \n#notar que el AND es &\n#notal que el OR es |\n\nnrow( dataset[ Visa_cuenta_estado==19, ] )\n#la negacion\nnrow( dataset[ !(Visa_cuenta_estado==19), ] )\n\nnrow( dataset[ Visa_cuenta_estado==19 & clase_ternaria==\"BAJA+2\", ] )\nnrow( dataset[ Visa_cuenta_estado==10 & clase_ternaria==\"BAJA+2\", ] )\nnrow( dataset[ !(Visa_cuenta_estado==10) & clase_ternaria==\"BAJA+2\", ] )\n\n#notar como se deben poner los parentesis porque el operador \"&\" tiene mas precedencia que el operador \"|\"\nnrow( dataset[ (Visa_cuenta_estado==11 | Visa_cuenta_estado==12 ) & clase_ternaria==\"BAJA+2\", ] )\n#en forma equivalente se puede hacer \nnrow( dataset[ (Visa_cuenta_estado %in% c( 11, 12)) & clase_ternaria==\"BAJA+2\", ] )\n\n#la condicion para ver si un campo es nulo\nnrow( dataset[ is.na(Visa_cuenta_estado) & clase_ternaria==\"BAJA+2\", ] )\n\n#la condicion para que un campo NO sea nulo\nnrow( dataset[ !is.na(Visa_cuenta_estado) & clase_ternaria==\"BAJA+2\", ] )\n\n\n#-----------------------------------\n#Filtrando columnas\n#si ademas quiero filtrar columnas\ndataset[ Visa_cuenta_estado==19 & clase_ternaria==\"BAJA+2\", c( \"Visa_cuenta_estado\", \"Master_cuenta_estado\", \"mcuentas_saldo\", \"clase_ternaria\" )] \n\n#-----------------------------------\n#crear un nuevo atributo en una data.table\n\n#primero unos atributos basicos\n#Notar como NO se usa la sentencia if\ndataset[ , clase01 := 0 ]\ndataset[ clase_ternaria==\"BAJA+2\", clase01 := 1 ]\n\ndataset[ , ganancia := -500]\ndataset[ clase_ternaria==\"BAJA+2\", ganancia := 19500 ]\n\n#si le enviara estimulo a toda la base\nsum( dataset$ganancia )\n\n#-----------------------------------\n#aplico lo anterior a un predicado interesante\n# Predicado1 = Visa_cuenta_estado vale 11, 12 o 19 o es NULO\n#nada mal la ganancia de este simple predicado\nsum( dataset[ is.na( Visa_cuenta_estado ) | (Visa_cuenta_estado %in% c(11,12,19) ), ganancia ] )\n\n#para que va a contratar la empresa a un Data Scientist si con este simpre predicado gana millones ?\n\n\n#La cantidad de registros de ese predicado\nnrow( dataset[ is.na( Visa_cuenta_estado ) | (Visa_cuenta_estado %in% c(11,12,19) ), ] )\n\n#La cantidad de positivos de ese predicado\nsum( dataset[ is.na( Visa_cuenta_estado ) | (Visa_cuenta_estado %in% c(11,12,19) ), clase01 ] )\n\n#O lo puedo ver directamente con dcast\n#primero creo un nuevo atributo\ndataset[ , predicado1 := 0 ]\ndataset[ is.na( Visa_cuenta_estado ) | (Visa_cuenta_estado %in% c(11,12,19) ) , predicado1 := 1 ]\ndcast( dataset, predicado1 ~ clase_ternaria, length )\n\n#-----------------------------------\n#Ahora otre predicade buene y hermose\n\ndataset[ , predicado2 := 0 ]\ndataset[ tmovimientos_ultimos90dias <14 , predicado2 := 1 ]\nsum( dataset[ predicado2==1, ganancia ] )\n\n#Podria haber hecho\ndataset[ , predicado3 := FALSE ]\ndataset[ tmovimientos_ultimos90dias <14 , predicado3 := TRUE ]\nsum( dataset[ predicado3==TRUE, ganancia ] )\nsum( dataset[ (predicado3), ganancia ] )\n\n#Ganancia muy buena para un predicado encontrado en la inspiracion ...\n\n\n#------------------------------------------------------------------------------\n#A pesar de estar en salita de 2 años, pasamos a conceptos mineros un poco mas avanzados\n#jugando con la variable tmovimientos_ultimos90dias\n\n#cuantos valores distintos tiene tmovimientos_ultimos90dias\nnrow( unique( dataset[ , c(\"tmovimientos_ultimos90dias\")] ) ) \n#o tambien podria hacer\nlength( unique( dataset$tmovimientos_ultimos90dias) )\n\n#agrupo en data.table \ndataset[, sum(ganancia), by = tmovimientos_ultimos90dias]\n\n#ahora que me nombre la nueva variable\ndataset[, list( gan=sum(ganancia)), by = tmovimientos_ultimos90dias]\n\n#ahora qen una tabla\ntbl <- dataset[, list( gan=sum(ganancia)), by = tmovimientos_ultimos90dias]\n\n#ahora acumulo\ntbl[ , gan_acum := cumsum( gan ) ]\n\ntbl[ 1:30, ]\n\n#grafico\n\n#hago el primer grafico\nplot( tbl$tmovimientos_ultimos90dias, \n tbl$gan_acum, \n type=\"n\",\n main=\"Ganancia ordenando por tmovimientos_ultimos90dias\",\n xlab=\"tmovimientos_ultimos90dias\", \n ylab=\"Ganancia Acumulada\", \n pch=19)\n\nlines( tbl$tmovimientos_ultimos90dias, tbl$gan_acum, type=\"l\" , col=\"blue\", lwd=2)\n\n\n\n#me fui de escala, ahora grafico los primeros\nplot( tbl$tmovimientos_ultimos90dias[1:30], \n tbl$gan_acum[1:30], \n type=\"n\",\n main=\"Ganancia ordenando por tmovimientos_ultimos90dias\",\n xlab=\"tmovimientos_ultimos90dias\", \n ylab=\"Ganancia Acumulada\", \n pch=19)\n\nlines( tbl$tmovimientos_ultimos90dias[1:30], tbl$gan_acum[1:30], type=\"l\" , col=\"blue\", lwd=2)\n\n\n\n\n#------------------------------------------------------------------------------\n#ahora analizo la variable mcuentas_saldo\n\n#cuantos valores distintos tiene tmovimientos_ultimos90dias\nnrow( dataset )\nnrow( unique( dataset[ , c(\"mcuentas_saldo\")] ) ) \nnrow( dataset[ mcuentas_saldo==0, ] )\n\n#este animal es de otra especie !\n\n\n#primero veo si hay nulos\nnrow( dataset[ is.na( mcuentas_saldo ), ] )\n#no los hay en este caso ! asi evito angustias de alumnos \n\n\nmin( dataset$mcuentas_saldo )\nmax( dataset$mcuentas_saldo )\n\n\n#ordeno el dataset por la variable mcuentas_saldo\n#setorder es de la libreria data.table \nsetorder( dataset, mcuentas_saldo )\n\ndataset[ , idx := seq( nrow(dataset) ) ]\ndataset[ , pos_acum := cumsum( clase01 ) ]\ndataset[ , neg_acum := cumsum( (1-clase01) ) ]\ndataset[ , gan_acum := cumsum( ganancia ) ]\n\n#veo como quedaron los campos\ndataset[ 1:30, c(\"mcuentas_saldo\", \"clase_ternaria\", \"idx\", \"clase01\", \"ganancia\", \"pos_acum\", \"neg_acum\", \"gan_acum\" ) ]\n#el minero con ojo avezado se da cuenta que hay muchos BAJA+1 y BAJA+2 al comienzo\n\n\n#hago el primer grafico\nplot( dataset$idx, \n dataset$gan_acum, \n type=\"n\",\n main=\"Ganancia ordenando por mcuentas_saldo\",\n xlab=\"registros\", \n ylab=\"Ganancia Acumulada\", \n pch=19)\n\nlines( dataset$idx, dataset$gan_acum, type=\"l\" , col=\"blue\", lwd=2)\n\n\n#se fue de escala para ver el maximo, me fijo solo en los 15000 primeros registros\nplot( dataset$idx[1:15000], \n dataset$gan_acum[1:15000],\n type=\"n\",\n main=\"Ganancia ordenando por mcuentas_saldo\",\n xlab=\"registros ordenados por mcuentas_saldo\", \n ylab=\"Ganancia Acumulada\", \n pch=19)\n\nlines( dataset$idx[1:15000], dataset$gan_acum[1:15000], type=\"l\" , col=\"blue\", lwd=2)\n\n#busco realmente donde esta el maximo\nwhich.max( dataset$gan_acum )\n\ndataset[ which.max( dataset$gan_acum ), c(\"mcuentas_saldo\", \"clase_ternaria\", \"idx\", \"clase01\", \"ganancia\", \"pos_acum\", \"neg_acum\", \"gan_acum\" ) ]\n\n#-----------------------------------\n#tecnicamente hablando, no es del todo correcto ordenar por un campo\n#ya que para por ejemplo a dos registros con el mismo valor de mcuentas_saldo\n#setoder los dejo en el orden inicial\n\n#mi deseo es ordenar al azar cuando dos registros tienen el mismo valor de la variable\n\n#genero un vector al valores al azar con distribucion uniforme en el intervalo real continuo [0,1]\nrunif( 10 )\n\n#ahora agrego una variable al azar al dataset\ndataset[ , azar1 := runif( nrow(dataset) ) ]\n\n#ordeno primero por mcuentas_saldo y cuando valen lo mismo por azar1\nsetorder( dataset, mcuentas_saldo, azar1 )\n\nwhich.max( dataset$gan_acum )\ndataset[ which.max( dataset$gan_acum ), c(\"mcuentas_saldo\", \"clase_ternaria\", \"idx\", \"clase01\", \"ganancia\", \"pos_acum\", \"neg_acum\", \"gan_acum\" ) ]\n\ngraphics.off()\n\nplot( dataset$idx[1:15000], \n dataset$gan_acum[1:15000], \n type=\"n\",\n main=\"Ganancia ordenando por mcuentas_saldo\",\n xlab=\"registros ordenados por mcuentas_saldo\", \n ylab=\"Ganancia Acumulada\", \n pch=19)\n\nlines( dataset$idx[1:15000], dataset$gan_acum[1:15000], type=\"l\" , col=\"green\", lwd=2)\n\n\n#------------------------------------------------------------------------------\n#ahora creamos variables nuevas\n\ndataset[ , MV_cuenta_estado := pmax(Visa_cuenta_estado, Master_cuenta_estado, na.rm = TRUE) ]\n\n#Notar que el maximo de una columna es max , sin embargo el maximo de dos valores es pmax\n# na.rm es Remove NA's , si uno es nulo, se queda con el otro valor\n\ndataset[ , Visa_mconsumototal_rel := Visa_mconsumototal / Visa_mlimitecompra ]\n\n#deduzca cual es la diferencia entre las siguientes dos instrucciones\ndataset[ , MV_mconsumospesos := Master_mconsumospesos + Visa_mconsumospesos ]\ndataset[ , MV_mconsumospesos2 := rowSums( cbind(Master_mconsumospesos, Visa_mconsumospesos), na.rm=TRUE) ]\n\n\n#------------------------------------------------------------------------------\n#ahora pasamos a dividir un dataset en training y testing, 70% y 30%\n#como estamos en salita de 2 años, no parametrizamos\n\n#una primera aproximacion\ndataset[ , azar1 := runif( nrow(dataset) ) ]\n\ndataset[ , fold := 0 ]\ndataset[ azar1 > 0.7, fold := 1 ]\n\ntbl <- dcast( dataset, fold ~ clase_ternaria, length )\ntbl[ , pos_idx := get(\"BAJA+2\")/( get(\"BAJA+1\")+get(\"BAJA+2\")+get(\"CONTINUA\")) ]\ntbl\n\n#ahora hacemos una muestra estratificada\n\n#------------------------------------------------------------------------------\n#eliminar columnas de un dataset\ncolnames( dataset )\n\ndataset[ , MV_mconsumospesos:= NULL ]\ncolnames( dataset )\n\ndataset[ , c(\"Visa_mconsumototal_rel\",\"MV_mconsumospesos2\"):= NULL ]\ncolnames( dataset )\n\n#------------------------------------------------------------------------------\n\n#Enhorabuena !\n#Si ha entendido todo hasta aqui, esta en condiciones de avanzar a la salita de 3 años del kindergarten\n\n\n\n", "meta": {"hexsha": "e83ec7a95e2df762266ffdc54acdc0306bde586d", "size": 12812, "ext": "r", "lang": "R", "max_stars_repo_path": "kinder/kinder_2.r", "max_stars_repo_name": "ktavo/dm-finanzas-2019", "max_stars_repo_head_hexsha": "3063bc3dbf24781acbc25efc73418bad82730511", "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": "kinder/kinder_2.r", "max_issues_repo_name": "ktavo/dm-finanzas-2019", "max_issues_repo_head_hexsha": "3063bc3dbf24781acbc25efc73418bad82730511", "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": "kinder/kinder_2.r", "max_forks_repo_name": "ktavo/dm-finanzas-2019", "max_forks_repo_head_hexsha": "3063bc3dbf24781acbc25efc73418bad82730511", "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.9357326478, "max_line_length": 148, "alphanum_fraction": 0.6750702466, "num_tokens": 3921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367020358429, "lm_q2_score": 0.07585818106587033, "lm_q1q2_score": 0.034677558714889783}} {"text": "tests.verify: test performed on 2006.05.21 \n\n\n#### Test: tests.verify running hw.py 1.2\nHello, World! sin(1.2)=0.932039085967\nCPU time of hw.py: 0.1 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running datatrans1.py .datatrans_infile tmp1file\nCPU time of datatrans1.py: 0.1 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp1file ------\n0.1 5.36092e-01\n0.2 3.12343e+00\n0.3 5.87269e+00\n0.4 3.12343e+00\n\n#### Test: tests.verify running datatrans2.py .datatrans_infile tmp2file\nCPU time of datatrans2.py: 0.1 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp2file ------\n0.1 5.36092e-01\n0.2 3.12343e+00\n0.3 5.87269e+00\n0.4 3.12343e+00\n\n#### Test: tests.verify running datatrans3a.py .datatrans_infile tmp3afile\nCPU time of datatrans3a.py: 0.4 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp3afile ------\n0.1\t0.536092\n0.2\t3.12343\n0.3\t5.87269\n0.4\t3.12343\n\n#### Test: tests.verify running datatrans3b.py .datatrans_infile tmp3bfile\nCPU time of datatrans3b.py: 0.4 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp3bfile ------\n0.1 0.536092 \n0.2 3.12343 \n0.3 5.87269 \n0.4 3.12343 \n\n#### Test: tests.verify running convert1.py .convert_infile1\nCPU time of convert1.py: 0.1 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp-measurements.dat ------\n 0 0.00000e+00\n 1.5 1.00000e-01\n 3 2.00000e-01\n\n\n----- appending file tmp-model1.dat ------\n 0 1.00000e-01\n 1.5 1.00000e-01\n 3 2.00000e-01\n\n\n----- appending file tmp-model2.dat ------\n 0 1.00000e+00\n 1.5 1.88000e-01\n 3 2.50000e-01\n\n#### Test: tests.verify running convert2.py .convert_infile1\ny dictionary:\n{'tmp-model2': [1.0, 0.188, 0.25], 'tmp-model1': [0.10000000000000001, 0.10000000000000001, 0.20000000000000001], 'tmp-measurements': [0.0, 0.10000000000000001, 0.20000000000000001]}\nCPU time of convert2.py: 0.1 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp-measurements.dat ------\n 0 0.00000e+00\n 1.5 1.00000e-01\n 3 2.00000e-01\n\n\n----- appending file tmp-model1.dat ------\n 0 1.00000e-01\n 1.5 1.00000e-01\n 3 2.00000e-01\n\n\n----- appending file tmp-model2.dat ------\n 0 1.00000e+00\n 1.5 1.88000e-01\n 3 2.50000e-01\n\n#### Test: tests.verify running simviz1.py -A 5.0 -tstop 2 -case tmp4\nCPU time of simviz1.py: 0.2 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp4/tmp4.i ------\n\n 1\n 0.7\n 5\n y\n 5\n 6.28319\n 0.2\n 2\n 0.05\n \n\n----- appending file tmp4/tmp4.gnuplot ------\n\nset title 'tmp4: m=1 b=0.7 c=5 f(y)=y A=5 w=6.28319 y0=0.2 dt=0.05';\nplot 'sim.dat' title 'y(t)' with lines;\n\nset size ratio 0.3 1.5, 1.0; \n# define the postscript output format:\nset term postscript eps monochrome dashed 'Times-Roman' 28;\n# output file containing the plot:\nset output 'tmp4.ps';\n# basic plot command:\nplot 'sim.dat' title 'y(t)' with lines;\n# make a plot in PNG format:\nset term png small;\nset output 'tmp4.png';\nplot 'sim.dat' title 'y(t)' with lines;\n\n\n----- appending file tmp4/tmp4.ps (just 30 lines) ------\n%!PS-Adobe-2.0 EPSF-2.0\n%%Title: tmp4.ps\n%%Creator: gnuplot 4.0 patchlevel 0\n%%CreationDate: Sun May 21 12:04:22 2006\n%%DocumentFonts: (atend)\n%%BoundingBox: 50 50 590 302\n%%Orientation: Portrait\n%%EndComments\n/gnudict 256 dict def\ngnudict begin\n/Color false def\n/Solid false def\n/gnulinewidth 5.000 def\n/userlinewidth gnulinewidth def\n/vshift -93 def\n/dl {10.0 mul} def\n/hpt_ 31.5 def\n/vpt_ 31.5 def\n/hpt hpt_ def\n/vpt vpt_ def\n/Rounded false def\n/M {moveto} bind def\n/L {lineto} bind def\n/R {rmoveto} bind def\n/V {rlineto} bind def\n/N {newpath moveto} bind def\n/C {setrgbcolor} bind def\n/f {rlineto fill} bind def\n/vpt2 vpt 2 mul def\n/hpt2 hpt 2 mul def\n\n#### Test: tests.verify running loop4simviz2.py c 5 30 10 -yaxis -0.7 0.7 -A 5.0 -tstop 2 -case tmp4 -noscreenplot\nMPEG ENCODER STATS (1.5b)\n------------------------\nTIME STARTED: Sun May 21 12:04:31 2006\nMACHINE: unknown\nFIRST FILE: ./tmp_0000.ppm\nLAST FILE: ./tmp_0002.ppm\nPATTERN: i\nGOP_SIZE: 30\nSLICES PER FRAME: 1\nRANGE: +/-10\nPIXEL SEARCH: HALF\nPSEARCH: LOGARITHMIC\nBSEARCH: CROSS2\nQSCALE: 8 10 25\nREFERENCE FRAME: ORIGINAL\n\n\nCreating new GOP (closed = T) before frame 0\nFRAME 0 (I): 0 seconds (4654800 bits/s output)\nFRAME 1 (I): 0 seconds (4792800 bits/s output)\nFRAME 2 (I): 0 seconds (4861920 bits/s output)\n\n\nTIME COMPLETED: Sun May 21 12:04:32 2006\nTotal time: 1 seconds\n\n-------------------------\n*****I FRAME SUMMARY*****\n-------------------------\n Blocks: 5772 (476670 bits) ( 82 bpb)\n Frames: 3 (476984 bits) (158994 bpf) (99.8% of total)\n Compression: 74:1 ( 0.3228 bpp)\n Seconds: 0 ( 4.8649 fps) ( 2396160 pps) ( 9360 mps)\n---------------------------------------------\nTotal Compression: 74:1 ( 0.3234 bpp)\nTotal Frames Per Second: 3.000000 (5772 mps)\nCPU Time: 4.864865 fps (9359 mps)\nTotal Output Bit Rate (30 fps): 4778800 bits/sec\nMPEG file created in : movie.mpeg\n\n\n======FRAMES READ: 3\ngs -q -dBATCH -dNOPAUSE -sDEVICE=ppm -sOutputFile=tmp_0000.ppm tmp_c_5/tmp_c_5.ps\ntmp_c_5/tmp_c_5.ps transformed via gs to tmp_0000.ppm (1503 Kb)\ngs -q -dBATCH -dNOPAUSE -sDEVICE=ppm -sOutputFile=tmp_0001.ppm tmp_c_15/tmp_c_15.ps\ntmp_c_15/tmp_c_15.ps transformed via gs to tmp_0001.ppm (1503 Kb)\ngs -q -dBATCH -dNOPAUSE -sDEVICE=ppm -sOutputFile=tmp_0002.ppm tmp_c_25/tmp_c_25.ps\ntmp_c_25/tmp_c_25.ps transformed via gs to tmp_0002.ppm (1503 Kb)\nmpeg movie in output file movie.mpeg\nrunning python simviz2.py -yaxis -0.7 0.7 -A 5.0 -tstop 2 -case tmp4 -noscreenplot -c 5 -case tmp_c_5\nrunning python simviz2.py -yaxis -0.7 0.7 -A 5.0 -tstop 2 -case tmp4 -noscreenplot -c 15 -case tmp_c_15\nrunning python simviz2.py -yaxis -0.7 0.7 -A 5.0 -tstop 2 -case tmp4 -noscreenplot -c 25 -case tmp_c_25\nconverting PNG files to animated GIF:\nconvert -delay 50 -loop 1000 tmp_c_5/tmp_c_5.png tmp_c_15/tmp_c_15.png tmp_c_25/tmp_c_25.png tmp_c.gif\nconverting PostScript files to an MPEG movie:\nps2mpeg.py tmp_c_5/tmp_c_5.ps tmp_c_15/tmp_c_15.ps tmp_c_25/tmp_c_25.ps\nepsmerge -o tmp_c_runs.ps -x 2 -y 3 -par tmp_c_5/tmp_c_5.ps tmp_c_15/tmp_c_15.ps tmp_c_25/tmp_c_25.ps\nCPU time of loop4simviz2.py: 8.3 seconds on hplx30 i686, Linux\n\n\n\n----- appending file tmp_c_runs.html ------\n\n

c=5

\n

c=15

\n

c=25

\n

Movie

\n

MPEG Movie

\n\n\n#### Test: tests.verify running NumPy_basics.py \nzeros(n, Float): d [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\nzeros(n) l [0 0 0 0 0 0 0 0 0 0]\narrayrange(-5, 5, 0.5) d [-5. -4.5 -4. -3.5 -3. -2.5 -2. -1.5 -1. -0.5 0. 0.5 1. 1.5 2. \n 2.5 3. 3.5 4. 4.5 5. ]\ny = sin(x/2.0)*3.0: d [-1.79541643 -2.33421959 -2.72789228 -2.95195784 -2.99248496 -2.84695386\n -2.52441295 -2.04491628 -1.43827662 -0.74221188 0. 0.74221188\n 1.43827662 2.04491628 2.52441295 2.84695386 2.99248496 2.95195784\n 2.72789228 2.33421959 1.79541643]\npl = [0, 1.2, 4, -9.1, 5, 8]; array(pl, typecode=Float) [ 0. 1.2 4. -9.1 5. 8. ]\n\ncreating arrays of length 1E+06 ... \nfromfunction took 0.66 s and arange&sin took 0.39 s for length 1000000\n1.2\n[ 0. 10.]\n[[ 0. 1. 2. 3. 4. 5.]\n [ 6. 7. 8. 9. 10. 11.]\n [ 12. 13. 14. 15. 16. 17.]\n [ 18. 19. 20. 21. 22. 23.]\n [ 24. 25. 26. 27. 28. 29.]]\n[[ 6. 8. 10.]\n [ 12. 14. 16.]]\n[[ 2. 4.]\n [ 20. 22.]]\n[[ 2. 4.]\n [ 20. 22.]]\na[0,0]=2 a[0,1]=6 a[0,2]=12 \na[1,0]=4 a[1,1]=12 a[1,2]=24 \na.shape = (2,3); a= [[ 2. 6. 12.]\n [ 4. 12. 24.]]\na.shape = (size(a),); a= [ 2. 6. 12. 4. 12. 24.]\nb = 3*a - 1; b = clip(b, 0.1, 1.0E+20); c = cos(b) [ 5. 17. 35. 11. 35. 71.] [ 0.28366219 -0.27516334 -0.90369221 0.0044257 -0.90369221 -0.30902273]\nin-place operations:\nmultiply(a, 3.0, a); a= [ 6. 18. 36. 12. 36. 72.]\nsubtract(a, 1.0, a); a= [ 5. 17. 35. 11. 35. 71.]\ndivide (a, 3.0, a); a= [ 1.66666667 5.66666667 11.66666667 3.66666667 11.66666667 23.66666667]\nadd (a, 1.0, a); a= [ 2.66666667 6.66666667 12.66666667 4.66666667 12.66666667 24.66666667]\npower (a, 2.0, a); a= [ 7.11111111 44.44444444 160.44444444 21.77777778 160.44444444\n 608.44444444]\na *= 3.0; a= [ 21.33333333 133.33333333 481.33333333 65.33333333 481.33333333\n 1825.33333333]\na -= 1.0; a= [ 20.33333333 132.33333333 480.33333333 64.33333333 480.33333333\n 1824.33333333]\na /= 3.0; a= [ 6.77777778 44.11111111 160.11111111 21.44444444 160.11111111\n 608.11111111]\na += 1.0; a= [ 7.77777778 45.11111111 161.11111111 22.44444444 161.11111111\n 609.11111111]\na **= 2.0; a= [ 6.04938272e+01 2.03501235e+03 2.59567901e+04 5.03753086e+02\n 2.59567901e+04 3.71016346e+05]\na[2:4] = -1; a[-1] = a[0]; a= [[ 0. 1.2 4. ]\n [ 0. 1.2 4. ]]\na.shape = (3,2); a[:,0] [ 0. 4. 1.2]\na[:,1::2] [[ 1.2]\n [ 0. ]\n [ 4. ]]\ntranspose(a): [[ 0. 4. 1.2]\n [ 1.2 0. 4. ]]\nb array entries are of type Float so no casting is necessary\narrayrange(-5, 5, 0.5); variable type= typecode=d\narrayrange(-5, 5, 1); variable type= typecode=l\narrayrange(-5.0, 5, 1); variable type= typecode=d\narrayrange(-5, 5, 0.5, Complex); variable type= typecode=D\nreal part of x: [-5. -4.5 -4. -3.5 -3. -2.5 -2. -1.5 -1. -0.5 0. 0.5 1. 1.5 2. \n 2.5 3. 3.5 4. 4.5]\nimaginary part of x: [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\neval(file.read()) works\nread from binary (pickled) file: b1= [[ 1. 2.]\n [ 11. 12.]] b2= [[ 4. 5.]\n [ 14. 15.]]\nread from binary file: b= [[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]\n [ 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.]]\n\n\n--------- random numbers -------------\n\nrandom number on (0,1): 0.723068520556\nunform random number on (-1,1): -0.874106242503\nN(0,1) uniform random number: 1.42433423327\nmean of 10000 random uniform random numbers:\non (0,1): 0.49683461788 (should be 0.5)\non (-1,1): -0.00210852790364 (should be 0)\ngenerated 10000 N(0,1) samples with\nmean 0.00870529 and st.dev. 0.993361 using RandomArray.normal\nprobability N(0,1) < 1.5: 0.93\n\n\n--------- linear algebra -------------\n\ncorrect solution\ncorrect solution\nLinearAlgebra.determinant(A) = 1.19047619048e-05\nB is the inverse of A, check ||A*B-I|| = 0, result: 7.46661081945e-13\ndet(A)=1.19048e-05\neigenvalue 10.6047 has corresponding vector\n[ 0.47326857 0.49642858 0.51003386 0.51907706]\neigenvalue 0.215261 has corresponding vector\n[ 0.7065385 0.08012043 -0.33075785 -0.62047023]\neigenvalue 0.017824 has corresponding vector\n[ 0.06174023 -0.67059248 -0.07005871 0.73592503]\neigenvalue 0.000292584 has corresponding vector\n[-0.04451401 0.33097206 -0.79128654 0.51219294]\nA: [[ 3. 2.5 2.33333333 2.25 ]\n [ 3. 2.66666667 2.5 2.4 ]\n [ 3. 2.75 2.6 2.5 ]\n [ 3. 2.8 2.66666667 2.57142857]]\nx: [ 0. 0.5 1. 1.5]\nb: [ 6.95833333 7.43333333 7.725 7.92380952]\nA*x = [[ 0. 1.25 2.33333333 3.375 ]\n [ 0. 1.33333333 2.5 3.6 ]\n [ 0. 1.375 2.6 3.75 ]\n [ 0. 1.4 2.66666667 3.85714286]]\nb*x = [ 0. 3.71666667 7.725 11.88571429]\nmatrixmultiply(A,x) = [ 6.95833333 7.43333333 7.725 7.92380952]\ndot(A,x) = [ 6.95833333 7.43333333 7.725 7.92380952]\ninnerproduct(b,x) = 23.3273809524\ndot(b,x) = 23.3273809524\nMatrix M: Matrix([[ 3. , 2.5 , 2.33333333, 2.25 ],\n [ 3. , 2.66666667, 2.5 , 2.4 ],\n [ 3. , 2.75 , 2.6 , 2.5 ],\n [ 3. , 2.8 , 2.66666667, 2.57142857]])\ncolumn vector xm: [[ 0. ]\n [ 0.5]\n [ 1. ]\n [ 1.5]]\nM*xm = Matrix([[ 6.95833333],\n [ 7.43333333],\n [ 7.725 ],\n [ 7.92380952]])\nrow vector bm: Matrix([ [ 6.95833333, 7.43333333, 7.725 , 7.92380952]])\nbm*xm = Matrix([ [ 23.32738095]]) (inner product)\nxm*xb = Matrix([[ 0. , 0. , 0. , 0. ],\n [ 3.47916667, 3.71666667, 3.8625 , 3.96190476],\n [ 6.95833333, 7.43333333, 7.725 , 7.92380952],\n [ 10.4375 , 11.15 , 11.5875 , 11.88571429]]) (outer product)\n\nperforming some timings of \"somefunc*\" implementations...\n somefunc_NumPy (1 calls): elapsed=8.97336, CPU=8.09\n somefunc_NumPy2 (1 calls): elapsed=0.0820889, CPU=0.09\n somefunc_NumPy3 (1 calls): elapsed=0.118568, CPU=0.1\nend of ./NumPy_basics.py\nCPU time of NumPy_basics.py: 9.9 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running leastsquares.py \nCPU time of leastsquares.py: 0.6 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running SciPy.py vectorization\ncontrol numbers (vectorize) : 0.0 0.909307830212\ncontrol numbers (vectorize) : 0.0 0.909307830212\ncontrol numbers (vectorize) : 0.0 0.909307830212\ncontrol numbers (hand-coded) : 0.0 0.909307830212\nCPU time of somefuncv: 6.5\nCPU time of somefuncv2: 1.47\nCPU time of somefuncv3: 6.61\nCPU time of hand-coded function: 0.15\nCPU time: vectorize(NumPy sin)/hand-coded = 43.3\nCPU time: vectorize(math.sin)/hand-coded = 9.8\nCPU time of SciPy.py: 15.4 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running SciPy.py Oscillator 0.05\nCPU time of odeint: 0.18\nCPU time of oscillator: 0.18\nCPU time of SciPy.py: 1.3 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running SciPy.py integrate\n2.0 2.22044604925e-14\n2.0 2.22044604925e-14\nCPU time of SciPy.py: 0.6 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running ScientificPython.py \ntesting numbers with physical units:\narithmetics with PhysicalQuantity instances: 10.56 kg*km/s**2\nconverted to basic SI units: 10560.0 m*kg/s**2\nconverted to Mega Newton: 0.01056 MN\nadding 0.1 kPa m^2: 0.01066 MN\nstr(F): 0.01066 MN\nextract float value: 0.01066\n10660.0 m*kg/s**2\n0 Celcius in Farenheit: 32.0 degF\n\n\nTesting automatic derivatives:\n(function value, [d/dx, d/dy, d/dz]):\n(6.0250000000000004, [3.0, -1.0, 1.0])\n(sin(0), [cos(0)]): (0.0, [1.0])\n3rd order derivatives of x^3: (1, [3], [[6]], [[[6]]])\n(40, [3, -1, 20], [[0, 0, 0], [0, 0, 0], [0, 0, 20]])\nd^2(somefunc)/dzdx: 0\nd^2(somefunc)/dz^2: 20\n\n\ntesting interpolation:\ninterpolated: -0.942369478495 exact: -0.943548668636\ninterpolated derivative: 0.331095923354 exact: 0.331233920237\ndefinite integral: 1.83753871398 exact: 1.83907152908\ninterpolation in 2D grid: 0.946401714384 exact value: 0.968105223808\n\n\ntesting nonlinear least squares:\n([1.0864630262152011, 2.0402214672667118, 1.9767714371137151, 0.99937257343868868], 8.2409274338033922e-06)\nguess: [ 1. 2. 2. 1.]\n deviation: [-0.0865 -0.0402 0.0232 0.0006]\nguess: [ 0.95 1.95 1.95 0.95]\n deviation: [-0.171 0.1275 0.0785 0.0119]\nguess: [ 0.9 1.9 1.9 0.9]\n deviation: [-0.1974 0.3622 0.1669 0.0193]\nguess: [ 0.85 1.85 1.85 0.85]\n deviation: [-0.3122 0.4309 0.2334 0.0284]\nguess: [ 1.2 2.2 2.2 1.2]\n deviation: [-0.9721 -0.6498 -0.0425 -0.0059]\nguess: [ 0.75 1.75 1.75 0.75]\n deviation: [-0.6266 0.5119 0.3973 0.0569]\n\n\nTesting statistical computations:\nmean=1.00 standard deviation=0.50 skewness=-0.0 median=1.00, kurtosis=3.01\nhistogram array:\n[[ -1.2254e+00 1.1255e-04]\n [ -1.1365e+00 2.2511e-04]\n [ -1.0477e+00 6.7533e-04]\n [ -9.5885e-01 4.5022e-04]\n [ -8.7001e-01 2.2511e-04]\n [ -7.8116e-01 1.2381e-03]\n [ -6.9231e-01 2.3636e-03]\n [ -6.0347e-01 5.5152e-03]\n [ -5.1462e-01 8.6667e-03]\n [ -4.2578e-01 1.3619e-02]\n [ -3.3693e-01 2.5212e-02]\n [ -2.4809e-01 3.6468e-02]\n [ -1.5924e-01 5.2563e-02]\n [ -7.0394e-02 8.1039e-02]\n [ 1.8452e-02 1.1818e-01]\n [ 1.0730e-01 1.5679e-01]\n [ 1.9614e-01 2.1712e-01]\n [ 2.8499e-01 2.8206e-01]\n [ 3.7383e-01 3.7075e-01]\n [ 4.6268e-01 4.6429e-01]\n [ 5.5153e-01 5.3497e-01]\n [ 6.4037e-01 6.2389e-01]\n [ 7.2922e-01 6.8411e-01]\n [ 8.1806e-01 7.2800e-01]\n [ 9.0691e-01 7.7516e-01]\n [ 9.9575e-01 7.9452e-01]\n [ 1.0846e+00 8.0465e-01]\n [ 1.1734e+00 7.4162e-01]\n [ 1.2623e+00 6.9075e-01]\n [ 1.3511e+00 6.2344e-01]\n [ 1.4400e+00 5.4533e-01]\n [ 1.5288e+00 4.5866e-01]\n [ 1.6177e+00 3.8629e-01]\n [ 1.7065e+00 2.8836e-01]\n [ 1.7954e+00 2.2061e-01]\n [ 1.8842e+00 1.6467e-01]\n [ 1.9731e+00 1.2167e-01]\n [ 2.0619e+00 8.4754e-02]\n [ 2.1507e+00 5.4476e-02]\n [ 2.2396e+00 3.5117e-02]\n [ 2.3284e+00 2.4312e-02]\n [ 2.4173e+00 1.3507e-02]\n [ 2.5061e+00 8.4416e-03]\n [ 2.5950e+00 5.2901e-03]\n [ 2.6838e+00 2.1385e-03]\n [ 2.7727e+00 1.3507e-03]\n [ 2.8615e+00 9.0044e-04]\n [ 2.9504e+00 1.1255e-04]\n [ 3.0392e+00 4.5022e-04]\n [ 3.1281e+00 3.3766e-04]]\n50 [-1.2254 -1.1365 -1.0477 -0.9589 -0.87 -0.7812 -0.6923 -0.6035 -0.5146\n -0.4258 -0.3369 -0.2481 -0.1592 -0.0704 0.0185 0.1073 0.1961 0.285 \n 0.3738 0.4627 0.5515 0.6404 0.7292 0.8181 0.9069 0.9958 1.0846\n 1.1734 1.2623 1.3511 1.44 1.5288 1.6177 1.7065 1.7954 1.8842\n 1.9731 2.0619 2.1507 2.2396 2.3284 2.4173 2.5061 2.595 2.6838\n 2.7727 2.8615 2.9504 3.0392 3.1281]\n50 [ 1.1255e-04 2.2511e-04 6.7533e-04 4.5022e-04 2.2511e-04 1.2381e-03\n 2.3636e-03 5.5152e-03 8.6667e-03 1.3619e-02 2.5212e-02\n 3.6468e-02 5.2563e-02 8.1039e-02 1.1818e-01 1.5679e-01\n 2.1712e-01 2.8206e-01 3.7075e-01 4.6429e-01 5.3497e-01\n 6.2389e-01 6.8411e-01 7.2800e-01 7.7516e-01 7.9452e-01\n 8.0465e-01 7.4162e-01 6.9075e-01 6.2344e-01 5.4533e-01\n 4.5866e-01 3.8629e-01 2.8836e-01 2.2061e-01 1.6467e-01\n 1.2167e-01 8.4754e-02 5.4476e-02 3.5117e-02 2.4312e-02\n 1.3507e-02 8.4416e-03 5.2901e-03 2.1385e-03 1.3507e-03\n 9.0044e-04 1.1255e-04 4.5022e-04 3.3766e-04]\nCPU time of ScientificPython.py: 2.0 seconds on hplx30 i686, Linux\n\n\n#### Test: tests.verify running commontasks.py \nHello Pipe World\n./commontasks.py : cannot read file 'qqq'\nAn exception of type\n exceptions.IOError \noccurred, with value\n [Errno 2] No such file or directory: 'qqq'\narglist= ['myarg1', 'displacement', 'tmp.ps']\nfilename= myarg1 plottitle= displacement psfile= tmp.ps\narglist= ['myarg1', 'displacement', 'tmp.ps', 'myvar2']\nentry is myarg1\nentry is displacement\nentry is tmp.ps\nentry is myvar2\nIn-place manipulation of array entries:\nA[0]=1.2\nA[1]=-3.4\nA[2]=5.5\nA[3]=-9\nA[4]=100\nNo negative numbers:\nA[0]=1.2\nA[1]=0\nA[2]=5.5\nA[3]=0\nA[4]=100\na 'foreach'-type loop does not work:\nA[0]=1.2\nA[1]=-3.4\nA[2]=5.5\nA[3]=-9\nA[4]=100\n\nsplit with re.split:\nwords1[0] = \"iteration\"\nwords1[1] = \"12:\"\nwords1[2] = \"eps=\"\nwords1[3] = \"1.245E-05\"\n\nsplit with string.split instead:\nwords1[0] = \"iteration\"\nwords1[2] = \"12:\"\nwords1[4] = \"eps=\"\nwords1[6] = \"1.245E-05\"\nnewline1 is now [ iteration#12:#eps=#1.245E-05 ]\nwords2[0]=.myc_12\nwords2[1]=displacement\nwords2[2]=u(x,3.1415)\nwords2[3]= no upwinding\n['white', 'space', 'of', 'varying', 'length']\n['white', 'space', '', '', 'of', 'varying', '', '', '', 'length']\nYes, matched regex= <_sre.SRE_Match object at 0xb7b69138>\nregex sub:\n#!/usr/bin/env python\nimport sys, math # load system and math module\nr = float(sys.argv[1]) # extract the 1st command-line argument\ns = math.sin(r)\nprint \"Hello, World! sin(\" + str(r) + \")=\" + str(s)\n\n\n\nTesting dictionaries:\n\nlen(myargs)= 6\nThe option --myopt is not registered\nThe option -9.9 is not registered\ndictionary: cmlargs, key= -tstop value= 6.1\ndictionary: cmlargs, key= -c_in_H value= 9.8\ncmlargs['-c_in_H']=9.8\ncmlargs['-tstop']=6.1\n\n\n\n\nPython lacks auto convert of strings-numbers\na = 0.6\nhw.py is a plain file\nstat: 33261\nstat: 205289\nstat: 775\nstat: 1\nstat: 8029\nstat: 18029\nstat: 206\nstat: 1148205909\nstat: 1148199265\nstat: 1148199265\nhw.py is a regular file with 206 bytes and last accessed 1148205909\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/entries\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/.test1.c.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/fdmgrid.py.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/htmlsubst.py.svn-base\n0.01Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/intervalre.py.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/introre.py.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/realre.py.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/swap1.py.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/swap2.py.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/swap3.py.svn-base\n0.01Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/tests.r.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/tests.verify.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/verify_log.htm.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/verify_log_details.htm.svn-base\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/.test1.c\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/fdmgrid.py\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/htmlsubst.py\n0.01Mb /home/hpl/work/scripting/trunk/src/py/regex/intervalre.py\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/introre.py\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/realre.py\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/swap1.py\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/swap2.py\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/swap3.py\n0.01Mb /home/hpl/work/scripting/trunk/src/py/regex/tests.r\n0.01Mb /home/hpl/work/scripting/trunk/src/py/regex/tests.v\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/tests.verify\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/verify_log.htm\n0.00Mb /home/hpl/work/scripting/trunk/src/py/regex/verify_log_details.htm\n\n\nversion 3 of tree traversal: root= /home/hpl/work/scripting/trunk/src/py/regex\n/home/hpl/work/scripting/trunk/src/py/regex/.test1.c is 0.000672 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/realre.py is 0.001521 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/verify_log.htm is 0.000322 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/swap1.py is 0.000448 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/swap2.py is 0.00101 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/swap3.py is 0.001352 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/intervalre.py is 0.005451 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/verify_log_details.htm is 0.001306 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/tests.r is 0.011983 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/tests.v is 0.011983 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/tests.verify is 0.000366 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/htmlsubst.py is 0.000649 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/fdmgrid.py is 0.002941 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/introre.py is 0.001889 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/entries is 0.003859 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/.test1.c.svn-base is 0.000672 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/swap1.py.svn-base is 0.000448 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/intervalre.py.svn-base is 0.005451 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/swap2.py.svn-base is 0.00101 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/introre.py.svn-base is 0.001889 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/verify_log.htm.svn-base is 0.000322 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/swap3.py.svn-base is 0.001352 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/realre.py.svn-base is 0.001521 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/verify_log_details.htm.svn-base is 0.001306 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/fdmgrid.py.svn-base is 0.002941 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/tests.verify.svn-base is 0.000366 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/htmlsubst.py.svn-base is 0.000649 Mb\n/home/hpl/work/scripting/trunk/src/py/regex/.svn/text-base/tests.r.svn-base is 0.011983 Mb\ncreating mynewdir\nremoving mynewdir\nleading text ['listitem1', 'listitem2']\nanother leading text ['listitem1', 'listitem2']\nNo leading text ['listitem1', 'listitem2']\nNo leading text /home/hpl\n\bstatistics: avg=$avg, min=$min, max=$max\n\nbefore swap: v1= 1.3 v2= some text\nafter swap: v1= 1.3 v2= some text\nfiles of *.ps *.gif and *.py type:\ntmp_c_runs.ps\ntmp1.ps\ntmp2.ps\ntmp.ps\ntmp_c.gif\nNumPy_basics.py\nhw.py\nleastsquares.py\ndatatrans1.py\ndatatrans2.py\ndatatrans3.py\nScientificPython.py\ndatatrans-eff.py\ndatatrans3a.py\ndatatrans3b.py\ndatatrans3c.py\ndatatrans3d.py\nloop4simviz1.py\nloop4simviz2.py\ndatatrans3_err.py\ncommontasks.py\nsimviz1.py\nsimviz2.py\nconvert1.py\nconvert2.py\nconvert3.py\nSciPy.py\nOutput of the command perl -pe '' hw.py was\n\n#!/usr/bin/env python\nimport sys, math # load system and math module\nr = float(sys.argv[1]) # extract the 1st command-line argument\ns = math.sin(r)\nprint \"Hello, World! sin(\" + str(r) + \")=\" + str(s)\nfile= /usr/home/hpl/scripting/perl/intro/hw.pl\nhead= /usr/home/hpl/scripting/perl/intro\ntail= hw.pl\ndirname = /usr/home/hpl/scripting/perl/intro\nbasename= hw.pl\n\nYes! created tmp/some/tmp/tmp\n\n\nProgramming with classes:\nMyBase: i= 5 j= 7\nMySub: i= 7 j= 8 k= 9\ni1 is MyBase\ni2 is MySub\ni2 is MyBase too\ni1.__dict__: {'i': 5, 'j': 7}\ni2.__dict__: {'i': 7, 'k': 9, 'j': 8}\nNames: MyBase MyBase.write\ndir(i1): ['__doc__', '__init__', '__module__', 'i', 'j', 'write']\ndir(i2): ['__doc__', '__init__', '__module__', 'i', 'j', 'k', 'write']\nsome string\n['__doc__', '__init__', '__module__', 'i', 'j', 'k', 'q', 'write']\n\n\n\n\n\nmultiple inheritance:\nA.set\nB.set\nC.set\n{'a': 2, 'c': 0, 'b': 3}\nlist[6] raises an exception\nException type= exceptions.IndexError\nException value= list index out of range\naverage= 2.0\naverage= Empty argument list in average\nException type= Empty argument list in average\nException value= None\nException type= exceptions.IOError\nException value= [Errno 2] No such file or directory: 'ppp'\nitem 0: - description: initial shape of u\nitem 1: t description: initial shape of H\nitem 2: s description: shape of u at time=2.5\ncurve1 description: initial shape of u\ncurve2 description: initial shape of H\ncurve3 description: shape of u at time=2.5\n1.2 is greater than or equal to 100 (a is and b is )\n1.2 is less than 100 (a is and b is )\ntesting string b < 100: error!\ntesting float(b) < 100: ok\n{\n 'a' : 4,\n 'b' : {\n 'c' : 'some',\n 'd' : 77,\n },\n 'e' : {\n 'f' : {\n 'g' : 1,\n 'h' : 2,\n },\n 'i' : 4,\n },\n },\n\ndouble complex root=-1j\ncomplex root=(66.0302268206-1.99862731095j), complex root=(-0.030226820552+0.998627310945j)\ncomplex root=(2-2j), complex root=(-2+2j)\nfloat root=2.0, float root=-2.0\n\nregex:\n\n[ just a string with leading and trailing white space ]\n[just a string with leading and trailing white space ]\n[just a string with leading and trailing white space]\n\ncomments= []\ncomments= ['# a comment', '# another comment', '# third comment']\npoints2= [[ 0. 3. ]\n [ 0.1 3.57883668]\n [ 0.2 4.03471218]\n [ 0.3 4.26407817]\n [ 0.4 4.19914721]\n [ 0.5 3.81859485]\n [ 0.6 3.15092636]\n [ 0.7 2.2699763 ]\n [ 0.8 1.28325171]\n [ 0.9 0.31495911]\n [ 1. -0.51360499]\n [ 1.1 -1.10320415]\n [ 1.2 -1.39232922]\n [ 1.3 -1.36690931]\n [ 1.4 -1.06253328]\n [ 1.5 -0.558831 ]\n [ 1.6 0.03309841]\n [ 1.7 0.5882267 ]\n [ 1.8 0.98733573]\n [ 1.9 1.13583934]]\nhttp://www.ifi.uio.no/~hpl/downloadme.dat\nlines= ['Just a simple test for downloading files from the Internet.\\n']\nfinished\nCPU time of commontasks.py: 0.8 seconds on hplx30 i686, Linux\n\n", "meta": {"hexsha": "0dc7762448145f035ec805dd56fbc37b5a77d3e4", "size": 28701, "ext": "r", "lang": "R", "max_stars_repo_path": "sandbox/src1/TCSE3-3rd-examples/src/py/intro/tests.r", "max_stars_repo_name": "sniemi/SamPy", "max_stars_repo_head_hexsha": "e048756feca67197cf5f995afd7d75d8286e017b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2016-05-28T14:12:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T10:23:12.000Z", "max_issues_repo_path": "sandbox/src1/TCSE3-3rd-examples/src/py/intro/tests.r", "max_issues_repo_name": "sniemi/SamPy", "max_issues_repo_head_hexsha": "e048756feca67197cf5f995afd7d75d8286e017b", "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": "sandbox/src1/TCSE3-3rd-examples/src/py/intro/tests.r", "max_forks_repo_name": "sniemi/SamPy", "max_forks_repo_head_hexsha": "e048756feca67197cf5f995afd7d75d8286e017b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-07-13T10:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T10:23:23.000Z", "avg_line_length": 34.7890909091, "max_line_length": 182, "alphanum_fraction": 0.6402215951, "num_tokens": 12203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.05921024908116556, "lm_q1q2_score": 0.029142582110822823}} {"text": "LISP Interpreter Run\n\n[ Test new lisp & show how it works ]\n \naa [ initially all atoms eval to self ]\n\nexpression aa\nvalue aa\n\nnil [ except nil = the empty list ]\n\nexpression nil\nvalue ()\n\n'aa [ quote = literally ]\n\nexpression (' aa)\nvalue aa\n\n'(aa bb cc) [ delimiters are ' \" ( ) [ ] blank \\n ]\n\nexpression (' (aa bb cc))\nvalue (aa bb cc)\n\n(aa bb cc) [ what if quote omitted?! ]\n\nexpression (aa bb cc)\nvalue aa\n\n'car '(aa bb cc) [ here effect is different ]\n\nexpression (' (car (' (aa bb cc))))\nvalue (car (' (aa bb cc)))\n\ncar '(aa bb cc) [ car = first element of list ]\n\nexpression (car (' (aa bb cc)))\nvalue aa\n\ncar '((a b)c d)\n\nexpression (car (' ((a b) c d)))\nvalue (a b)\n\ncar '(aa)\n\nexpression (car (' (aa)))\nvalue aa\n\ncar aa [ ignore error ]\n\nexpression (car aa)\nvalue aa\n\ncdr '(aa bb cc) [ cdr = rest of list ]\n\nexpression (cdr (' (aa bb cc)))\nvalue (bb cc)\n\ncdr '((a b)c d)\n\nexpression (cdr (' ((a b) c d)))\nvalue (c d)\n\ncdr '(aa)\n\nexpression (cdr (' (aa)))\nvalue ()\n\ncdr aa [ ignore error ]\n\nexpression (cdr aa)\nvalue aa\n\ncadr '(aa bb cc) [ combinations of car & cdr ]\n\nexpression (car (cdr (' (aa bb cc))))\nvalue bb\n\ncaddr '(aa bb cc)\n\nexpression (car (cdr (cdr (' (aa bb cc)))))\nvalue cc\n\ncons 'aa '(bb cc) [ cons = inverse of car & cdr ]\n\nexpression (cons (' aa) (' (bb cc)))\nvalue (aa bb cc)\n\ncons'(a b)'(c d)\n\nexpression (cons (' (a b)) (' (c d)))\nvalue ((a b) c d)\n\ncons aa nil\n\nexpression (cons aa nil)\nvalue (aa)\n\ncons aa ()\n\nexpression (cons aa ())\nvalue (aa)\n\ncons aa bb [ ignore error ]\n\nexpression (cons aa bb)\nvalue aa\n\n(\"cons aa) [ supply nil for missing arguments ]\n\nexpression (cons aa)\nvalue (aa)\n\n(\"cons '(aa) '(bb) '(cc)) [ ignore extra arguments ]\n\nexpression (cons (' (aa)) (' (bb)) (' (cc)))\nvalue ((aa) bb)\n\natom ' aa [ is-atomic? predicate ]\n\nexpression (atom (' aa))\nvalue true\n\natom '(aa)\n\nexpression (atom (' (aa)))\nvalue false\n\natom '( )\n\nexpression (atom (' ()))\nvalue true\n\n= aa bb [ are-equal-S-expressions? predicate ]\n\nexpression (= aa bb)\nvalue false\n\n= aa aa\n\nexpression (= aa aa)\nvalue true\n\n= '(a b)'(a b)\n\nexpression (= (' (a b)) (' (a b)))\nvalue true\n\n= '(a b)'(a x)\n\nexpression (= (' (a b)) (' (a x)))\nvalue false\n\nif true x y [ if ... then ... else ... ]\n\nexpression (if true x y)\nvalue x\n\nif false x y\n\nexpression (if false x y)\nvalue y\n\nif xxx x y [ anything not false is true ]\n\nexpression (if xxx x y)\nvalue x\n\n[ display intermediate results ]\ncdr display cdr display cdr display '( a b c d e )\n\nexpression (cdr (display (cdr (display (cdr (display (' (a b \n c d e))))))))\ndisplay (a b c d e)\ndisplay (b c d e)\ndisplay (c d e)\nvalue (d e)\n\n('lambda(x y)x 1 2) [ lambda expression ]\n\nexpression ((' (lambda (x y) x)) 1 2)\nvalue 1\n\n('lambda(x y)y 1 2)\n\nexpression ((' (lambda (x y) y)) 1 2)\nvalue 2\n\n('lambda(x y)cons y cons x nil 1 2)\n\nexpression ((' (lambda (x y) (cons y (cons x nil)))) 1 2)\nvalue (2 1)\n\n(if true \"car \"cdr '(a b c)) [ function expressions ]\n\nexpression ((if true car cdr) (' (a b c)))\nvalue a\n\n(if false \"car \"cdr '(a b c))\n\nexpression ((if false car cdr) (' (a b c)))\nvalue (b c)\n\n('lambda()cons x cons y nil) [ function with no arguments ]\n\nexpression ((' (lambda () (cons x (cons y nil)))))\nvalue (x y)\n\n[ Here is a way to create an expression and then\n evaluate it in the current environment. EVAL (see\n below) does this using a clean environment instead. ]\n(display\ncons \"lambda cons nil cons display 'cons x cons y nil nil)\n\nexpression ((display (cons lambda (cons nil (cons (display ('\n (cons x (cons y nil)))) nil)))))\ndisplay (cons x (cons y nil))\ndisplay (lambda () (cons x (cons y nil)))\nvalue (x y)\n\n[ let ... be ... in ... ]\n \nlet x a cons x cons x nil [ first case, let x be ... in ... ]\n\nexpression ((' (lambda (x) (cons x (cons x nil)))) a)\nvalue (a a)\n\nx\n\nexpression x\nvalue x\n\n[ second case, let (f x) be ... in ... ]\n \nlet (f x) if atom display x x (f car x)\n (f '(((a)b)c))\n\nexpression ((' (lambda (f) (f (' (((a) b) c))))) (' (lambda (\n x) (if (atom (display x)) x (f (car x))))))\ndisplay (((a) b) c)\ndisplay ((a) b)\ndisplay (a)\ndisplay a\nvalue a\n\nf\n\nexpression f\nvalue f\n\nappend '(a b c) '(d e f) [ concatenate-list primitive ]\n\nexpression (append (' (a b c)) (' (d e f)))\nvalue (a b c d e f)\n\n[ define \"by hand\" temporarily ]\n \nlet (cat x y) if atom x y cons car x (cat cdr x y)\n (cat '(a b c) '(d e f))\n\nexpression ((' (lambda (cat) (cat (' (a b c)) (' (d e f))))) \n (' (lambda (x y) (if (atom x) y (cons (car x) (cat\n (cdr x) y))))))\nvalue (a b c d e f)\n\ncat\n\nexpression cat\nvalue cat\n\n[ define \"by hand\" permanently ]\n \ndefine (cat x y) if atom x y cons car x (cat cdr x y)\n\ndefine cat\nvalue (lambda (x y) (if (atom x) y (cons (car x) (cat (c\n dr x) y))))\n\ncat\n\nexpression cat\nvalue (lambda (x y) (if (atom x) y (cons (car x) (cat (c\n dr x) y))))\n\n(cat '(a b c) '(d e f))\n\nexpression (cat (' (a b c)) (' (d e f)))\nvalue (a b c d e f)\n\ndefine x (a b c) [ define atom, not function ]\n\ndefine x\nvalue (a b c)\n\ncons x nil\n\nexpression (cons x nil)\nvalue ((a b c))\n\ndefine x (d e f)\n\ndefine x\nvalue (d e f)\n\ncons x nil\n\nexpression (cons x nil)\nvalue ((d e f))\n\nsize abc [ size of S-expression in characters ]\n\nexpression (size abc)\nvalue 3\n\nsize ' ( a b c )\n\nexpression (size (' (a b c)))\nvalue 7\n\nlength ' ( a b c ) [ number of elements in list ]\n\nexpression (length (' (a b c)))\nvalue 3\n\nlength display bits ' a [ S-expression --> bits ]\n\nexpression (length (display (bits (' a))))\ndisplay (0 1 1 0 0 0 0 1 0 0 0 0 1 0 1 0)\nvalue 16\n\nlength display bits ' abc [ extra character is \\n ]\n\nexpression (length (display (bits (' abc))))\ndisplay (0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 0 0 1 1 0 0 0 1 1 0\n 0 0 0 1 0 1 0)\nvalue 32\n\nlength display bits nil\n\nexpression (length (display (bits nil)))\ndisplay (0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0)\nvalue 24\n\nlength display bits ' (a)\n\nexpression (length (display (bits (' (a)))))\ndisplay (0 0 1 0 1 0 0 0 0 1 1 0 0 0 0 1 0 0 1 0 1 0 0 1 0\n 0 0 0 1 0 1 0)\nvalue 32\n\n[ plus ]\n+ abc 15 [ not number --> 0 ]\n\nexpression (+ abc 15)\nvalue 15\n\n+ '(abc) 15\n\nexpression (+ (' (abc)) 15)\nvalue 15\n\n+ 10 15\n\nexpression (+ 10 15)\nvalue 25\n\n- 10 15 [ non-negative minus ]\n\nexpression (- 10 15)\nvalue 0\n\n- 15 10\n\nexpression (- 15 10)\nvalue 5\n\n* 10 15 [ times ]\n\nexpression (* 10 15)\nvalue 150\n\n^ 10 15 [ power ]\n\nexpression (^ 10 15)\nvalue 1000000000000000\n\n< 10 15 [ less than ]\n\nexpression (< 10 15)\nvalue true\n\n< 10 10\n\nexpression (< 10 10)\nvalue false\n\n> 15 10 [ greater than ]\n\nexpression (> 15 10)\nvalue true\n\n> 10 10\n\nexpression (> 10 10)\nvalue false\n\n<= 15 10 [ less than or equal ]\n\nexpression (<= 15 10)\nvalue false\n\n<= 10 10\n\nexpression (<= 10 10)\nvalue true\n\n>= 10 15 [ greater than or equal ]\n\nexpression (>= 10 15)\nvalue false\n\n>= 10 10\n\nexpression (>= 10 10)\nvalue true\n\n= 10 15 [ equal ]\n\nexpression (= 10 15)\nvalue false\n\n= 10 10\n\nexpression (= 10 10)\nvalue true\n\n[ here not number isn't considered zero ]\n= abc 0\n\nexpression (= abc 0)\nvalue false\n\n= 0003 3 [ other ways numbers are funny ]\n\nexpression (= 3 3)\nvalue true\n\n000099 [ leading zeros removed ]\n\nexpression 99\nvalue 99\n\n[ and numbers are constants ]\nlet x b cons x cons x nil\n\nexpression ((' (lambda (x) (cons x (cons x nil)))) b)\nvalue (b b)\n\nlet 99 45 cons 99 cons 99 nil\n\nexpression ((' (lambda (99) (cons 99 (cons 99 nil)))) 45)\nvalue (99 99)\n\ndefine 99 45\n\ndefine 99\nvalue 45\n\ncons 99 cons 99 nil\n\nexpression (cons 99 (cons 99 nil))\nvalue (99 99)\n\n[ decimal<-->binary conversions ]\n \nbase10-to-2 255\n\nexpression (base10-to-2 255)\nvalue (1 1 1 1 1 1 1 1)\n\nbase10-to-2 256\n\nexpression (base10-to-2 256)\nvalue (1 0 0 0 0 0 0 0 0)\n\nbase10-to-2 257\n\nexpression (base10-to-2 257)\nvalue (1 0 0 0 0 0 0 0 1)\n\nbase2-to-10 '(1 1 1 1)\n\nexpression (base2-to-10 (' (1 1 1 1)))\nvalue 15\n\nbase2-to-10 '(1 0 0 0 0)\n\nexpression (base2-to-10 (' (1 0 0 0 0)))\nvalue 16\n\nbase2-to-10 '(1 0 0 0 1)\n\nexpression (base2-to-10 (' (1 0 0 0 1)))\nvalue 17\n\n[ illustrate eval & try ]\n \neval display '+ display 5 display 15\n\nexpression (eval (display (' (+ (display 5) (display 15)))))\ndisplay (+ (display 5) (display 15))\ndisplay 5\ndisplay 15\nvalue 20\n\ntry 0 display '+ display 5 display 15 nil\n\nexpression (try 0 (display (' (+ (display 5) (display 15)))) \n nil)\ndisplay (+ (display 5) (display 15))\nvalue (success 20 (5 15))\n\ntry 0 display '+ debug 5 debug 15 nil\n\nexpression (try 0 (display (' (+ (debug 5) (debug 15)))) nil)\ndisplay (+ (debug 5) (debug 15))\ndebug 5\ndebug 15\nvalue (success 20 ())\n\n[ eval & try use initial variable bindings ]\n \ncons x nil\n\nexpression (cons x nil)\nvalue ((d e f))\n\neval 'cons x nil\n\nexpression (eval (' (cons x nil)))\nvalue (x)\n\ntry 0 'cons x nil nil\n\nexpression (try 0 (' (cons x nil)) nil)\nvalue (success (x) ())\n\ndefine five! [ to illustrate time limits ]\nlet (f x) if = display x 0 1 * x (f - x 1)\n (f 5)\n\ndefine five!\nvalue ((' (lambda (f) (f 5))) (' (lambda (x) (if (= (dis\n play x) 0) 1 (* x (f (- x 1)))))))\n\neval five!\n\nexpression (eval five!)\ndisplay 5\ndisplay 4\ndisplay 3\ndisplay 2\ndisplay 1\ndisplay 0\nvalue 120\n\n[ by the way, numbers can be big: ]\nlet (f x) if = x 0 1 * x (f - x 1)\n (f 100) [ one hundred factorial! ]\n\nexpression ((' (lambda (f) (f 100))) (' (lambda (x) (if (= x \n 0) 1 (* x (f (- x 1)))))))\nvalue 93326215443944152681699238856266700490715968264381\n 62146859296389521759999322991560894146397615651828\n 62536979208272237582511852109168640000000000000000\n 00000000\n\n[ time limit is nesting depth of re-evaluations\n due to function calls & eval & try ]\n \ntry 0 five! nil\n\nexpression (try 0 five! nil)\nvalue (failure out-of-time ())\n\ntry 1 five! nil\n\nexpression (try 1 five! nil)\nvalue (failure out-of-time ())\n\ntry 2 five! nil\n\nexpression (try 2 five! nil)\nvalue (failure out-of-time (5))\n\ntry 3 five! nil\n\nexpression (try 3 five! nil)\nvalue (failure out-of-time (5 4))\n\ntry 4 five! nil\n\nexpression (try 4 five! nil)\nvalue (failure out-of-time (5 4 3))\n\ntry 5 five! nil\n\nexpression (try 5 five! nil)\nvalue (failure out-of-time (5 4 3 2))\n\ntry 6 five! nil\n\nexpression (try 6 five! nil)\nvalue (failure out-of-time (5 4 3 2 1))\n\ntry 7 five! nil\n\nexpression (try 7 five! nil)\nvalue (success 120 (5 4 3 2 1 0))\n\ntry no-time-limit five! nil\n\nexpression (try no-time-limit five! nil)\nvalue (success 120 (5 4 3 2 1 0))\n\ndefine two* [ to illustrate running out of data ]\n let (f x) if = 0 x nil\n cons * 2 display read-bit (f - x 1)\n (f 5)\n\ndefine two*\nvalue ((' (lambda (f) (f 5))) (' (lambda (x) (if (= 0 x)\n nil (cons (* 2 (display (read-bit))) (f (- x 1)))\n ))))\n\ntry 6 two* '(1 0 1 0 1)\n\nexpression (try 6 two* (' (1 0 1 0 1)))\nvalue (failure out-of-time (1 0 1 0 1))\n\ntry 7 two* '(1 0 1 0 1)\n\nexpression (try 7 two* (' (1 0 1 0 1)))\nvalue (success (2 0 2 0 2) (1 0 1 0 1))\n\ntry 7 two* '(1 0 1)\n\nexpression (try 7 two* (' (1 0 1)))\nvalue (failure out-of-data (1 0 1))\n\ntry no-time-limit two* '(1 0 1)\n\nexpression (try no-time-limit two* (' (1 0 1)))\nvalue (failure out-of-data (1 0 1))\n\ntry 18\n'let (f x) if = 0 x nil\n cons * 2 display read-bit (f - x 1)\n (f 16)\nbits 'a\n\nexpression (try 18 (' ((' (lambda (f) (f 16))) (' (lambda (x)\n (if (= 0 x) nil (cons (* 2 (display (read-bit))) \n (f (- x 1)))))))) (bits (' a)))\nvalue (success (0 2 2 0 0 0 0 2 0 0 0 0 2 0 2 0) (0 1 1 \n 0 0 0 0 1 0 0 0 0 1 0 1 0))\n\n[ illustrate nested try's ]\n[ most constraining limit wins ]\n \ntry 20\n'cons abcdef try 10\n'let (f n) (f display + n 1) (f 0) [infinite loop]\nnil nil\n\nexpression (try 20 (' (cons abcdef (try 10 (' ((' (lambda (f)\n (f 0))) (' (lambda (n) (f (display (+ n 1))))))) \n nil))) nil)\nvalue (success (abcdef failure out-of-time (1 2 3 4 5 6 \n 7 8 9)) ())\n\ntry 10\n'cons abcdef try 20\n'let (f n) (f display + n 1) (f 0) [infinite loop]\nnil nil\n\nexpression (try 10 (' (cons abcdef (try 20 (' ((' (lambda (f)\n (f 0))) (' (lambda (n) (f (display (+ n 1))))))) \n nil))) nil)\nvalue (failure out-of-time ())\n\ntry 10\n'cons abcdef try 20\n'let (f n) (f debug + n 1) (f 0) [infinite loop]\nnil nil\n\nexpression (try 10 (' (cons abcdef (try 20 (' ((' (lambda (f)\n (f 0))) (' (lambda (n) (f (debug (+ n 1))))))) ni\n l))) nil)\ndebug 1\ndebug 2\ndebug 3\ndebug 4\ndebug 5\ndebug 6\ndebug 7\ndebug 8\nvalue (failure out-of-time ())\n\ntry no-time-limit\n'cons abcdef try 20\n'let (f n) (f display + n 1) (f 0) [infinite loop]\nnil nil\n\nexpression (try no-time-limit (' (cons abcdef (try 20 (' ((' \n (lambda (f) (f 0))) (' (lambda (n) (f (display (+ \n n 1))))))) nil))) nil)\nvalue (success (abcdef failure out-of-time (1 2 3 4 5 6 \n 7 8 9 10 11 12 13 14 15 16 17 18 19)) ())\n\ntry 10\n'cons abcdef try no-time-limit\n'let (f n) (f display + n 1) (f 0) [infinite loop]\nnil nil\n\nexpression (try 10 (' (cons abcdef (try no-time-limit (' ((' \n (lambda (f) (f 0))) (' (lambda (n) (f (display (+ \n n 1))))))) nil))) nil)\nvalue (failure out-of-time ())\n\n[ illustrate read-bit & read-exp ]\n \nread-bit\n\nexpression (read-bit)\nvalue out-of-data\n\nread-exp\n\nexpression (read-exp)\nvalue out-of-data\n\ntry 0 'read-bit nil\n\nexpression (try 0 (' (read-bit)) nil)\nvalue (failure out-of-data ())\n\ntry 0 'read-exp nil\n\nexpression (try 0 (' (read-exp)) nil)\nvalue (failure out-of-data ())\n\ntry 0 'read-exp bits 'abc\n\nexpression (try 0 (' (read-exp)) (bits (' abc)))\nvalue (success abc ())\n\ntry 0 'read-exp bits '(abc def)\n\nexpression (try 0 (' (read-exp)) (bits (' (abc def))))\nvalue (success (abc def) ())\n\ntry 0 'read-exp bits '(abc(def ghi)jkl)\n\nexpression (try 0 (' (read-exp)) (bits (' (abc (def ghi) jkl)\n )))\nvalue (success (abc (def ghi) jkl) ())\n\ntry 0 'cons read-exp cons read-bit nil bits 'abc\n\nexpression (try 0 (' (cons (read-exp) (cons (read-bit) nil)))\n (bits (' abc)))\nvalue (failure out-of-data ())\n\ntry 0 'cons read-exp cons read-bit nil append bits 'abc '(0)\n\nexpression (try 0 (' (cons (read-exp) (cons (read-bit) nil)))\n (append (bits (' abc)) (' (0))))\nvalue (success (abc 0) ())\n\ntry 0 'cons read-exp cons read-bit nil append bits 'abc '(1)\n\nexpression (try 0 (' (cons (read-exp) (cons (read-bit) nil)))\n (append (bits (' abc)) (' (1))))\nvalue (success (abc 1) ())\n\ntry 0 'read-exp bits '(a b c)\n\nexpression (try 0 (' (read-exp)) (bits (' (a b c))))\nvalue (success (a b c) ())\n\ntry 0 'cons read-exp cons read-exp nil bits '(a b c)\n\nexpression (try 0 (' (cons (read-exp) (cons (read-exp) nil)))\n (bits (' (a b c))))\nvalue (failure out-of-data ())\n\ntry 0 'cons read-exp cons read-exp nil\n append bits '(a b c) bits '(d e f)\n\nexpression (try 0 (' (cons (read-exp) (cons (read-exp) nil)))\n (append (bits (' (a b c))) (bits (' (d e f)))))\nvalue (success ((a b c) (d e f)) ())\n\nbits 'a [ to get characters codes ]\n\nexpression (bits (' a))\nvalue (0 1 1 0 0 0 0 1 0 0 0 0 1 0 1 0)\n\ntry 0 'read-exp '(0 1 1 0 0 0 0 1) ['a' but no \\n character]\n\nexpression (try 0 (' (read-exp)) (' (0 1 1 0 0 0 0 1)))\nvalue (failure out-of-data ())\n\ntry 0 'read-exp '(0 1 1 0 0 0 0 1 0 0 0 0 1 0 1)[0 missing]\n\nexpression (try 0 (' (read-exp)) (' (0 1 1 0 0 0 0 1 0 0 0 0 \n 1 0 1)))\nvalue (failure out-of-data ())\n\ntry 0 'read-exp '(0 1 1 0 0 0 0 1 0 0 0 0 1 0 1 0) [okay]\n\nexpression (try 0 (' (read-exp)) (' (0 1 1 0 0 0 0 1 0 0 0 0 \n 1 0 1 0)))\nvalue (success a ())\n\n[ if we get to \\n reading 8 bits at a time,\n we will always interpret as a valid S-expression ]\ntry 0 'read-exp\n '(0 0 0 0 1 0 1 0) [nothing in record; only \\n]\n\nexpression (try 0 (' (read-exp)) (' (0 0 0 0 1 0 1 0)))\nvalue (success () ())\n\ntry 0 'read-exp '(1 1 1 1 1 1 1 1 [unprintable character]\n 0 0 0 0 1 0 1 0) [is deleted]\n\nexpression (try 0 (' (read-exp)) (' (1 1 1 1 1 1 1 1 0 0 0 0 \n 1 0 1 0)))\nvalue (success () ())\n\nbits () [ to get characters codes ]\n\nexpression (bits ())\nvalue (0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0)\n\n[ three left parentheses==>three right parentheses supplied ]\ntry 0 'read-exp '(0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0\n 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0)\n\nexpression (try 0 (' (read-exp)) (' (0 0 1 0 1 0 0 0 0 0 1 0 \n 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 1 0)))\nvalue (success ((())) ())\n\n[ right parenthesis 'a'==>left parenthesis supplied ]\ntry 0 'read-exp '(0 0 1 0 1 0 0 1 0 1 1 0 0 0 0 1\n 0 0 0 0 1 0 1 0) [ & extra 'a' ignored ]\n\nexpression (try 0 (' (read-exp)) (' (0 0 1 0 1 0 0 1 0 1 1 0 \n 0 0 0 1 0 0 0 0 1 0 1 0)))\nvalue (success () ())\n\n[ 'a' right parenthesis==>'a' is seen & parenthesis ]\ntry 0 'read-exp '(0 1 1 0 0 0 0 1 0 0 1 0 1 0 0 1\n 0 0 0 0 1 0 1 0) [ is ignored ]\n\nexpression (try 0 (' (read-exp)) (' (0 1 1 0 0 0 0 1 0 0 1 0 \n 1 0 0 1 0 0 0 0 1 0 1 0)))\nvalue (success a ())\n\nEnd of LISP Run\n\nElapsed time is 1 seconds.\n", "meta": {"hexsha": "fbb960d900d52321d68e4485e70fc71a7e79ba1f", "size": 18151, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/examples.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/examples.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/examples.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": 20.744, "max_line_length": 62, "alphanum_fraction": 0.5448184673, "num_tokens": 6506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.0592102478360753, "lm_q1q2_score": 0.028911380849706698}} {"text": "#' Summary function\n#'\n#' @param object object with \"local_random_test\" class\n#' @param \\dots additional arguments affecting the summary produced.\n#'\n#' @method summary local_random_test\n#' @export\n#'\nsummary.local_random_test <- function(object, ...) {\n rdinfo <- object$RD.info\n bwinfo <- object$bandwidth\n res <- object$estimate\n\n show <- paste0(\n \"Local ATE by Local Random Approach\\n\\n\",\n \"RD Design Information\\n\",\n \"Running variable: \", rdinfo$running.variable, \"\\n\"\n )\n\n if (object$RD.info$assignment == \"greater\") {\n show <- paste0(\n show,\n \"Assignment rule: 1[x >=\", rdinfo$cutoff, \"]\\n\\n\"\n )\n } else {\n show <- paste0(\n show,\n \"Assignment rule: 1[x <=\", rdinfo$cutoff, \"]\\n\\n\"\n )\n }\n\n show <- paste0(\n show,\n \"Test information \\n\"\n )\n\n if (object$bandwidth$global) {\n show <- paste0(\n show,\n \"Use all observation: \", bwinfo$global, \"\\n\"\n )\n } else {\n show <- paste0(\n show,\n \"Use all observation: \", bwinfo$global, \"\\n\",\n \"Bandiwdth: [\", bwinfo$bw[1] + rdinfo$cutoff, \",\",\n bwinfo$bw[2] + rdinfo$cutoff, \"]\\n\"\n )\n }\n\n show <- paste0(\n show,\n \"Method of statistical test: \", res[[1]]$local.ate$method,\n \"\\n\\n\"\n )\n\n for (i in seq_len(length(res))) {\n show <- paste0(\n show,\n \"Outcome variables: \", res[[i]]$outcome, \"\\n\",\n \"---------------------------------------------------------------\\n\",\n \" Treated Control Local ATE \\n\",\n \"N Mean S.E. N Mean S.E. Estimate P-value\\n\",\n \"---------------------------------------------------------------\\n\",\n res[[i]]$observe$treat$N, \" \",\n sprintf(\"%1.2f\", res[[i]]$observe$treat$mean), \" \",\n sprintf(\"%1.2f\", res[[i]]$observe$treat$se), \" \",\n res[[i]]$observe$control$N, \" \",\n sprintf(\"%1.2f\", res[[i]]$observe$control$mean), \" \",\n sprintf(\"%1.2f\", res[[i]]$observe$control$se), \" \",\n sprintf(\"%1.2f\", res[[i]]$local.ate$estimate), \" \",\n sprintf(\"%1.2f\", res[[i]]$local.ate$p.value), \"\\n\",\n \"---------------------------------------------------------------\\n\\n\"\n )\n }\n\n cat(show)\n\n}\n", "meta": {"hexsha": "cdcdd08fa33ab3c8a6ab1a4ee4816c31123c27c3", "size": 2203, "ext": "r", "lang": "R", "max_stars_repo_path": "tmp/summary-method.r", "max_stars_repo_name": "KatoPachi/discreteRD", "max_stars_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "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": "tmp/summary-method.r", "max_issues_repo_name": "KatoPachi/discreteRD", "max_issues_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "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": "tmp/summary-method.r", "max_forks_repo_name": "KatoPachi/discreteRD", "max_forks_repo_head_hexsha": "f041c8a3ae3cea42f2db3286f95d2fc9a0893f4d", "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": 27.5375, "max_line_length": 75, "alphanum_fraction": 0.4811620517, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.05261895409053963, "lm_q1q2_score": 0.02589842491740083}} {"text": "# Reverse Complement Problem\n\nseq <- \"ACTGTTTCAGT\"\nseq_new <- strsplit(seq, \"\")[[1]]\n\ncomp <- c()\nfor (i in seq_new){\n if (i == \"A\"){\n comp <- c(comp, \"T\")\n }else if (i == \"T\"){\n comp <- c(comp, \"A\")\n }else if (i == \"C\"){\n comp <- c(comp, \"G\")\n }else if (i == \"G\"){\n comp <- c(comp, \"C\")\n }\n}\n\nrev_comp <- rev(comp)\nrev_comp_new <- paste0(rev_comp, collapse = \"\")\n\nprint (rev_comp_new)\n", "meta": {"hexsha": "00ad4b15a0a8df6cb8b2b07ffc4d3f3d0469a3ea", "size": 403, "ext": "r", "lang": "R", "max_stars_repo_path": "R.code/1.ReverseComplementProblem.r", "max_stars_repo_name": "AliYoussef96/Bioinformatica-tutorials", "max_stars_repo_head_hexsha": "8c45345c2dfac275f6481bb8c393a81870d2099c", "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.code/1.ReverseComplementProblem.r", "max_issues_repo_name": "AliYoussef96/Bioinformatica-tutorials", "max_issues_repo_head_hexsha": "8c45345c2dfac275f6481bb8c393a81870d2099c", "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.code/1.ReverseComplementProblem.r", "max_forks_repo_name": "AliYoussef96/Bioinformatica-tutorials", "max_forks_repo_head_hexsha": "8c45345c2dfac275f6481bb8c393a81870d2099c", "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": 17.5217391304, "max_line_length": 47, "alphanum_fraction": 0.5186104218, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.07585818785594478, "lm_q1q2_score": 0.02433692250614161}} {"text": "#! /usr/bin/Rscript\r\n# license: BSD 3-Clause License\r\n# author: https://github.com/ywd5\r\n# version: 20210314\r\n\r\nif(\"\" == \"get dependency\"){\r\n require(magrittr); require(tibble); require(dplyr); require(stringr); require(purrr);\r\n require(pegas)\r\n require(questionr)\r\n require(digest)#; require(openssl);\r\n}\r\n\r\nif(\"\" == \"test codes\"){\r\n ans <- list.files(pattern=\"^output\\\\.xml$\", full.names=TRUE, recursive=TRUE) %>%\r\n grep(pattern=\"first run\", x=., value=TRUE)\r\n tempo <- tempfile(); phased_loci <- vector(mode=\"list\", length=length(ans)); for(i in 1:length(ans)){\r\n ans[i] %>% read_xml() %>% xml_child(search=\"phased_loci\") %>% xml_contents() %>%\r\n as.character() %>% cat(., file=tempo, append=FALSE, sep=\"\")\r\n phased_loci[[i]] <- pegas::read.loci(file=tempo, header=TRUE, row.names=1L)\r\n }; file.remove(tempo); remove(tempo, i);\r\n #\r\n load(file=\"../can delete, unphased_loci.rdata\")\r\n locus_position <- unphased_loci$locus_position\r\n not_varied_loci <- unphased_loci$not_varied_loci\r\n remove(unphased_loci)\r\n # pegas::is.snp(phased_loci) # this code will treate triple-phase locus as not snp\r\n # phased_loci %>% pegas::rarefactionplot()\r\n # ?pegas::haplotype()\r\n # ?pegas::haplotype.loci()\r\n # haplo %>% ape::as.DNAbin()\r\n ExamineRarePhasedHaplotypes(phased_loci=phased_loci, locus_position=locus_position,\r\n not_varied_loci=not_varied_loci)\r\n}\r\n\r\nmessage(\"ExamineRarePhasedHaplotypes() may be able to tackle (deal with, cope with, handle) \",\r\n \"polyploid, but currently only support diploid\")\r\n# this function can work with snp and microsatellite loci\r\n\r\nExamineRarePhasedHaplotypes <- function(\r\n phased_loci, locus_position,\r\n not_varied_loci=base::rep(\"varied\", times=length(locus_position))\r\n){\r\n # control the input-------------------------------------------------------------------------------\r\n if(!is(object=phased_loci, class2=\"loci\")){stop(\"phased_loci must be a loci object\");}\r\n if(any(dim(phased_loci) == 0)){stop(\"phased_loci is empty\");}\r\n pegas::is.phased(phased_loci) %>% {if(!all(.)){warning(\"seperators of haplotypes should be |, not /\");}}\r\n if(\"\" != \"ensure data are from diploid\"){\r\n getPloidy(phased_loci) %>% {any(. != 2)} %>% {if(.){stop(\"only diploid data are supported\");}}\r\n }\r\n #\r\n if(!is.numeric(locus_position)){stop(\"locus_position must be integers\");}\r\n locus_position %<>% as.integer() %>% base::sort()\r\n if(anyNA(locus_position)){stop(\"locus_position must be integers\");}\r\n if(any(locus_position < 1L)){stop(\"locus_position can't be smaller than 1\");}\r\n if(anyDuplicated(locus_position) != 0){stop(\"locus_position can't contain duplicated items\");}\r\n #\r\n if(!is.character(not_varied_loci)){stop(\"not_varied_loci must be a character vector\");}\r\n if(length(not_varied_loci) == 0){stop(\"not_varied_loci is empty\");}\r\n if(anyNA(not_varied_loci)){stop(\"not_varied_loci can't contain NA\");}\r\n # control the relationship among inputs-----------------------------------------------------------\r\n (ncol(phased_loci) != length(locus_position)) %>% {if(.){stop(\"locus number are consistent\");}}\r\n not_varied_loci %>% {which(. == \"varied\")} %>% {length(.) != length(locus_position)} %>%\r\n {if(.){stop(\"locus_position doesn't match with not_varied_loci\");}}\r\n # get info, remove locus_position-----------------------------------------------------------------\r\n info <- phased_loci %>% {list(name=rownames(.), locus_position=locus_position, haplo_freq=integer(),\r\n n_indiv=nrow(.), n_locus=ncol(.), n_haplo=0L)}\r\n remove(locus_position)\r\n # convert phased_loci from loci into 2 matrices--------------------------------------------------------------\r\n if(\"\" == \"method 1, use pegas::haplotype()\"){\r\n # phased_loci %>% {pegas::haplotype(x=., locus=1:ncol(.), compress=TRUE)}\r\n ans <- {1:nrow(phased_loci)} %>% {. * 2} %>% {list(. - 1, .)}\r\n phased_loci %<>% {pegas::haplotype(x=., locus=1:ncol(.), compress=FALSE)} %>% base::t(x=.) %>%\r\n {mapply(FUN=function(xx, ii){xx[ii,]}, xx=list(.), ii=ans, SIMPLIFY=FALSE, USE.NAMES=FALSE)} %>%\r\n lapply(FUN=base::`rownames<-`, value=rownames(phased_loci))\r\n remove(ans)\r\n }\r\n if(\"\" != \"method 2, use pegas::loci2alleles()\"){\r\n ans <- {1:ncol(phased_loci)} %>% {. * 2} %>% {list(. - 1, .)}\r\n phased_loci %<>% loci2alleles() %>%\r\n {base::`colnames<-`(x=., value=base::sub(pattern=\"\\\\.(1|2)$\", replacement=\"\", x=colnames(.)))} %>%\r\n {mapply(FUN=function(xx, ii){xx[,ii]}, xx=list(.), ii=ans, SIMPLIFY=FALSE, USE.NAMES=FALSE)}\r\n remove(ans)\r\n }\r\n # split phased_loci into haplo and info_indiv, get info$haplo_freq, info$n_haplo------------------------\r\n phased_loci %<>% lapply(FUN=base::`colnames<-`, value=NULL) %>% lapply(FUN=purrr::array_tree, margin=1)\r\n #\r\n haplo <- phased_loci %>% lapply(FUN=base::unname) %>% {c(.[[1]], .[[2]])} %>%\r\n {list(all=., unique=base::unique(.))} # create haplo in list format\r\n haplo <- base::match(x=haplo$all, table=haplo$unique) %>% base::table() %>%\r\n as.character() %>% setNames(object=haplo$unique, nm=.) %>% simplify2array() %>%\r\n base::t(x=.) # get haplo occurrence times, change haplo from list into matrix\r\n str_rank <- function(xx){\r\n base::unique(xx) %>% stringr::str_sort(x=., numeric=TRUE) %>% base::match(x=xx, table=.)\r\n }\r\n haplo %<>% apply(X=., MARGIN=2, FUN=str_rank) %>% purrr::array_tree(array=., margin=2) %>%\r\n c(list(-as.integer(rownames(haplo))), .) %>% base::do.call(what=base::order, args=.) %>%\r\n haplo[.,] # sort haplo according to frequency and alphanumeric order\r\n remove(str_rank)\r\n info$haplo_freq <- rownames(haplo) %>% as.integer()\r\n info$n_haplo <- length(info$haplo_freq)\r\n #\r\n info_indiv <- tibble(name=info$name, genotype=\"\",\r\n haplotype_1=base::match(x=phased_loci[[1]], table=purrr::array_tree(array=haplo, margin=1)),\r\n haplotype_2=base::match(x=phased_loci[[2]], table=array_tree(array=haplo, margin=1)))\r\n info_indiv[info_indiv$haplotype_1 > info_indiv$haplotype_2,3:4] %<>% base::rev(x=.)\r\n #\r\n haplo %<>% {base::`rownames<-`(x=., value=paste0(\"hap\", 1:nrow(.)));}\r\n info_indiv$haplotype_1 %<>% {rownames(haplo)[.]}\r\n info_indiv$haplotype_2 %<>% {rownames(haplo)[.]}\r\n info_indiv %<>% dplyr::mutate(genotype=paste0(haplotype_1, \"/\", haplotype_2))\r\n #\r\n remove(phased_loci)\r\n # create output_directory-------------------------------------------------------------------------\r\n output_directory <- base::tempfile() %>% base::normalizePath(winslash=\"/\", mustWork=FALSE)\r\n base::dir.create(path=output_directory, recursive=FALSE)\r\n dir.exists(paths=output_directory) %>% {if(!.){stop(\"can't create directory: \", output_directory);}}\r\n if(!grepl(pattern=\"/$\", x=output_directory)){output_directory <- paste0(output_directory, \"/\");}\r\n # prepare an array for .xml-----------------------------------------------------------------------\r\n rare_haplo <- c(\"position\", \"residue\", \"residue_frequency\", \"other_residue_frequencies\",\r\n \"excised_frequency\") %>% list(five_items=., locus=NULL, haplotype=rownames(haplo)) %>%\r\n array(data=\"\", dim=c(5L, info$n_locus, info$n_haplo), dimnames=.)\r\n rare_haplo[1,,] <- info$locus_position %>% as.character() %>% list() %>% rep(times=info$n_haplo) %>% simplify2array()\r\n rare_haplo[2,,] <- base::t(haplo)\r\n #\r\n f_frequency <- function(xx, weight){\r\n # xx <- sample(letters[1:6], size=20, replace=TRUE)\r\n # weight <- sample(1:6, size=20, replace=TRUE)\r\n if(!is.character(xx) | length(xx) == 0){stop(\"invalid input\");}\r\n if(!is.integer(weight) | length(weight) != length(xx)){stop(\"invalid input\");}\r\n if(any(weight < 1)){stop(\"invalid input\");}\r\n xx <- questionr::wtd.table(x=xx, weights=weight, digits=10) %>% # wtd.table() will sort in lexical order\r\n {setNames(object=as.integer(.), nm=names(.));}\r\n ans <- rep(\"0\", times=length(xx))\r\n if(length(xx) > 1) for(i in 1:length(xx)){\r\n ans[i] <- xx[-i] %>% {paste0(unname(.), names(.), collapse=\",\");}\r\n }else{\r\n # Do nothing. Only happen when there's only 1 locus.\r\n }; i <- 0; remove(i);\r\n xx <- list(xx, setNames(object=ans, nm=names(xx)))\r\n return(xx) # remove(xx, weight, ans)\r\n }\r\n haplo_minus <- haplo %>% lapply(X=1:ncol(haplo), FUN=function(ii, xx){\r\n # apply(X=xx[,-ii], MARGIN=1, FUN=paste0, collapse=\"\")\r\n xx <- purrr::array_tree(array=xx[,-ii], margin=1)\r\n xx <- base::match(x=xx, table=base::unique(xx))\r\n xx <- paste0(\"_\", xx)\r\n return(xx)\r\n }, xx=.) %>% simplify2array()\r\n rare_haplo[3,,] <- haplo %>% apply(X=., MARGIN=2, FUN=f_frequency, weight=info$haplo_freq) %>%\r\n lapply(FUN=function(xx){xx[[1]]}) %>%\r\n mapply(FUN=function(xx, ii){unname(xx[ii]);}, xx=., ii=purrr::array_tree(array=haplo, margin=2),\r\n SIMPLIFY=TRUE, USE.NAMES=FALSE) %>% base::t(x=.)\r\n rare_haplo[4,,] <- haplo %>% apply(X=., MARGIN=2, FUN=f_frequency, weight=info$haplo_freq) %>%\r\n lapply(FUN=function(xx){xx[[2]]}) %>%\r\n mapply(FUN=function(xx, ii){unname(xx[ii]);}, xx=., ii=purrr::array_tree(array=haplo, margin=2),\r\n SIMPLIFY=TRUE, USE.NAMES=FALSE) %>% base::t(x=.)\r\n rare_haplo[5,,] <- haplo_minus %>% apply(X=., MARGIN=2, FUN=f_frequency, weight=info$haplo_freq) %>%\r\n lapply(FUN=function(xx){xx[[1]]}) %>%\r\n mapply(FUN=function(xx, ii){unname(xx[ii]);}, xx=., ii=purrr::array_tree(array=haplo_minus, margin=2),\r\n SIMPLIFY=TRUE, USE.NAMES=FALSE) %>% base::t(x=.)\r\n remove(f_frequency, haplo_minus)\r\n # get info_geno, modify info_indiv$genotype, get info_haplo------------------------------------------\r\n info_geno <- info_indiv %>% {base::split(x=.$name, f=.$genotype)} %>%\r\n {tibble(name=names(.), haplotype_1=\"\", haplotype_2=\"\", freq=lengths(.),\r\n occurrence_in_individual=lapply(X=unname(.), FUN=stringr::str_sort, numeric=TRUE))}\r\n ans <- info_geno$name %>% base::strsplit(split=\"/\") %>% simplify2array()\r\n info_geno$haplotype_1 <- ans[1,]\r\n info_geno$haplotype_2 <- ans[2,]\r\n remove(ans)\r\n info_geno %<>% .[c(\"haplotype_1\", \"haplotype_2\")] %>%\r\n lapply(FUN=function(xx){base::match(x=xx, table=stringr::str_sort(x=unique(xx), numeric=TRUE));}) %>%\r\n {base::order(.[[1]], .[[2]])} %>% info_geno[.,] %>% dplyr::mutate(name=paste0(\"gen\", 1:length(name)))\r\n #\r\n # if the haplotype names contain \"/\", there may be bugs.\r\n info_indiv$genotype <- info_geno %>% {paste0(.$haplotype_1, \"/\", .$haplotype_2)} %>%\r\n setNames(object=info_geno$name, nm=.) %>% .[info_indiv$genotype] %>% unname()\r\n #\r\n min_r <- rare_haplo[3,,] %>% apply(MARGIN=2, FUN=as.integer) %>% apply(MARGIN=2, base::min) %>% unname()\r\n max_e <- rare_haplo[5,,] %>% apply(MARGIN=2, FUN=as.integer) %>% apply(MARGIN=2, base::max) %>% unname()\r\n occurrence_in_i <- info_indiv %>% {base::split(x=c(.$name, .$name), f=c(.$haplotype_1, .$haplotype_2))} %>%\r\n {.[stringr::str_order(x=names(.), numeric=TRUE)]} %>% lapply(FUN=base::unique) %>%\r\n lapply(FUN=stringr::str_sort, numeric=TRUE)\r\n occurrence_in_g <- info_geno %>% {base::split(x=c(.$name, .$name), f=c(.$haplotype_1, .$haplotype_2))} %>%\r\n {.[stringr::str_order(x=names(.), numeric=TRUE)]} %>% lapply(FUN=base::unique) %>%\r\n lapply(FUN=stringr::str_sort, numeric=TRUE)\r\n info_haplo <- occurrence_in_i %>% {base::replace(x=., list=lengths(.) > 6L, values=list(\"...\"))} %>%\r\n lapply(FUN=paste0, collapse=\", \") %>% unlist() %>% unname() %>%\r\n tibble(name=rownames(haplo), freq=info$haplo_freq, occurrence_in_individual=occurrence_in_i,\r\n occurrence_in_genotype=occurrence_in_g, min_residue_freq=min_r, max_excised_freq=max_e, file=.) %>%\r\n dplyr::mutate(file=paste0(freq, \" \", min_residue_freq, \" \", max_excised_freq, \"; \", name, \"; \", file, \";.xml\")) %>%\r\n dplyr::mutate(file=paste0(output_directory, file))\r\n remove(min_r, max_e, occurrence_in_i, occurrence_in_g)\r\n # fill not_varied_loci in the array---------------------------------------------------------------\r\n dahlia <- array(data=\"\", dim=c(5, length(not_varied_loci), info$n_haplo), dimnames=dimnames(rare_haplo))\r\n dahlia[2,,] <- not_varied_loci %>%\r\n purrr::map_if(.x=., .p=(. != \"varied\"), .f=stringr::str_trunc, width=15, side=\"center\") %>%\r\n unlist() %>% list() %>% rep(times=info$n_haplo) %>% simplify2array()\r\n dahlia[,not_varied_loci == \"varied\",] <- rare_haplo\r\n rare_haplo <- dahlia\r\n remove(dahlia)\r\n # prepare the array for pretty print--------------------------------------------------------------\r\n # rare_haplo %>% apply(MARGIN=c(2, 3), FUN=function(xx){\r\n # stringr::str_pad(string=xx, width=max(nchar(xx)) + 2, side=\"both\")\r\n # }) %>% {base::`dimnames<-`(x=., value=base::replace(x=dimnames(rare_haplo), list=1L, values=dimnames(rare_haplo)[1]))}\r\n for(i in 1:length(not_varied_loci)) for(j in 1:info$n_haplo){\r\n rare_haplo[,i,j] %<>% {stringr::str_pad(string=., width=max(nchar(.)) + 2, side=\"both\")}\r\n }; remove(i, j);\r\n dimnames(rare_haplo)[[1]] %<>% stringr::str_pad(string=., width=max(nchar(.)) + 2, side=\"right\") %>% paste0(., \": \")\r\n # export and remove the array---------------------------------------------------------------------\r\n for(i in 1:nrow(info_haplo)){\r\n cat(\"\\n\",\r\n \"\\n\",\r\n \"\", info_haplo$name[i], \"\\n\",\r\n \"\", info_haplo$freq[i], \"\\n\",\r\n \"\", paste0(info_haplo$occurrence_in_individual[[i]], collapse=\", \"), \"\\n\",\r\n \"\", info_haplo$min_residue_freq[i], \"\\n\",\r\n \"\", info_haplo$max_excised_freq[i], \"\\n\",\r\n \"\\n\", file=info_haplo$file[i], append=FALSE, sep=\"\")\r\n write.table(x=rare_haplo[,,i], file=info_haplo$file[i], append=TRUE, quote=FALSE,\r\n sep=\"\", row.names=TRUE, col.names=FALSE)\r\n cat(\"\\n\", \"\\n\", file=info_haplo$file[i], append=TRUE, sep=\"\")\r\n }; remove(i);\r\n remove(rare_haplo)\r\n # export haplo, haplo_full, info_haplo, info_geno, info_indiv, etc to info.xml---------------------------\r\n haplo_full <- not_varied_loci %>% list() %>% rep(times=info$n_haplo) %>% simplify2array() %>%\r\n base::t(x=.) %>% base::`rownames<-`(x=., value=rownames(haplo))\r\n haplo_full[,not_varied_loci == \"varied\"] <- haplo\r\n info_haplo %<>% dplyr::select(name, freq, occurrence_in_individual, occurrence_in_genotype) %>%\r\n dplyr::mutate(occurrence_in_individual=lapply(X=occurrence_in_individual, FUN=paste0, collapse=\", \"),\r\n occurrence_in_genotype=lapply(X=occurrence_in_genotype, FUN=paste0, collapse=\", \")) %>%\r\n dplyr::mutate(occurrence_in_individual=unname(unlist(occurrence_in_individual)),\r\n occurrence_in_genotype=unname(unlist(occurrence_in_genotype)))\r\n info_geno %<>% dplyr::mutate(occurrence_in_individual=lapply(X=occurrence_in_individual, FUN=paste0, collapse=\", \")) %>%\r\n dplyr::mutate(occurrence_in_individual=unname(unlist(occurrence_in_individual)))\r\n file_ans <- paste0(output_directory, \"info.xml\")\r\n cat(\"\\n\",\r\n \"\", info$n_indiv, \"\\n\",\r\n \"\", nrow(info_geno), \"\\n\",\r\n \"\", info$n_haplo, \"\\n\",\r\n \"\", paste0(info$locus_position, collapse=\" \"), \"\\n\",\r\n \"\\n\", file=file_ans, append=FALSE, sep=\"\")\r\n write.table(x=haplo, file=file_ans, append=TRUE, sep=\"\\t\", row.names=TRUE, col.names=FALSE, fileEncoding=\"UTF-8\")\r\n cat(\"\\n\", \"\\n\", file=file_ans, append=TRUE, sep=\"\")\r\n write.table(x=haplo_full, file=file_ans, append=TRUE, sep=\"\\t\", row.names=TRUE, col.names=FALSE, fileEncoding=\"UTF-8\")\r\n cat(\"\\n\", \"\\n\", file=file_ans, append=TRUE, sep=\"\")\r\n suppressWarnings(expr={\r\n write.table(x=info_indiv, file=file_ans, append=TRUE, sep=\"\\t\", row.names=FALSE, col.names=TRUE, fileEncoding=\"UTF-8\")\r\n })\r\n cat(\"\\n\", \"\\n\", file=file_ans, append=TRUE, sep=\"\")\r\n suppressWarnings(expr={\r\n write.table(x=info_geno, file=file_ans, append=TRUE, sep=\"\\t\", row.names=FALSE, col.names=TRUE, fileEncoding=\"UTF-8\")\r\n })\r\n cat(\"\\n\", \"\\n\", file=file_ans, append=TRUE, sep=\"\")\r\n suppressWarnings(expr={\r\n write.table(x=info_haplo, file=file_ans, append=TRUE, sep=\"\\t\", row.names=FALSE, col.names=TRUE, fileEncoding=\"UTF-8\")\r\n })\r\n cat(\"\\n\", \"\\n\", file=file_ans, append=TRUE, sep=\"\")\r\n remove(file_ans)\r\n # calculate hash value of output_directory--------------------------------------------------------\r\n # file_name <- list.files(path=output_directory, full.names=TRUE, no..=TRUE)\r\n # file_sha1 <- vector(mode=\"character\", length=length(file_name))\r\n # for(i in 1:length(file_name)){\r\n # file_con <- base::file(description=file_name[i], open=\"rb\")\r\n # file_sha1[i] <- as.character(openssl::sha1(x=file_con))\r\n # base::close(con=file_con)\r\n # remove(file_con)\r\n # }; remove(i);\r\n old_files <- output_directory %>% list.files(path=., full.names=TRUE, no..=TRUE)\r\n output_directory <- old_files %>% stringr::str_sort(numeric=TRUE) %>%\r\n lapply(FUN=digest::digest, algo=\"crc32\", serialize=FALSE, file=TRUE) %>%\r\n unlist() %>% paste0(collapse=\"\") %>% digest::digest(algo=\"crc32\", serialize=TRUE) %>%\r\n paste0(\"./\", info$n_haplo, \"_\", ., strftime(x=Sys.time(), format=\"_%H%M%S/\")) %>%\r\n base::normalizePath(winslash=\"/\", mustWork=FALSE)\r\n dir.create(path=output_directory, recursive=FALSE)\r\n if(!dir.exists(output_directory)){stop(\"can't create directory: \", output_directory);}\r\n file.copy(from=old_files, to=output_directory, overwrite=TRUE) %>%\r\n {if(!all(.)){stop(\"error when coping files to new directory\");}} # try file.rename() in revision\r\n remove(old_files)\r\n # clean environment and return output_directory---------------------------------------------------\r\n remove(not_varied_loci, haplo, haplo_full, info, info_indiv, info_geno, info_haplo)\r\n message(\"\\nresults are written to this directory:\\n\", output_directory, \"\\n\")\r\n return(output_directory)\r\n}\r\n", "meta": {"hexsha": "bc390bb5dbfa9f32ff1c402fbc2eab12948a1aff", "size": 18402, "ext": "r", "lang": "R", "max_stars_repo_path": "5.ExamineRarePhasedHaplotypes().r", "max_stars_repo_name": "ywd5/RPhylogenyZM", "max_stars_repo_head_hexsha": "1c2ba53b793d1b20577738f0213cd5a01b2556fd", "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": "5.ExamineRarePhasedHaplotypes().r", "max_issues_repo_name": "ywd5/RPhylogenyZM", "max_issues_repo_head_hexsha": "1c2ba53b793d1b20577738f0213cd5a01b2556fd", "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": "5.ExamineRarePhasedHaplotypes().r", "max_forks_repo_name": "ywd5/RPhylogenyZM", "max_forks_repo_head_hexsha": "1c2ba53b793d1b20577738f0213cd5a01b2556fd", "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": 64.5684210526, "max_line_length": 136, "alphanum_fraction": 0.6176502554, "num_tokens": 5624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.05184546262100775, "lm_q1q2_score": 0.023901628199494054}} {"text": "#--------------------------------------------------------------------------#\n# This function will create a list of csv files that contain the isolates in \n# rows and loci in columns. This currently only works for unlabeled files,\n# but what it will do is allow the user to specify an entire directory to \n# analyze. \n#\n# It will change in the future, but it works for my purposes for now.\n#--------------------------------------------------------------------------#\ngetfile <- function(multFile=NULL, pattern=NULL){\n# the default option is to grab all of the files in a directory matching a \n# specified pattern. If no pattern is set, all files will be listed.\n\tif (is.null(multFile) || multFile == \"yes\"){\n\t\t# this sets the path variable that the user can use to set the path\n\t\t# to the files with setwd(x$path), where x is the datastructure \n\t\t# this function dumped into.\n\t\tpath <- sub(\"(^.+?/).+?\\\\.[a-z]{3}\", \"\\\\1\", file.path(file.choose()))\t\t\n\t\tif (!is.null(pattern)){\n\t\t\tpat <- pattern\n\t\t\tx <- list.files(path, pattern=pat)\n\t\t}\n\t\telse {\n\t\t\tx <- list.files(path)\n\t\t}\n\t}\n\telse {\n\t\t# if the user chooses to analyze only one file, a pattern is not needed\n\t\tcsv <- file.choose()\n\t\tpath <- sub(\"(^.+?/).+?\\\\.[a-z]{3}\", \"\\\\1\", file.path(csv))\n\t\tcsv <- sub(\"^.+?/(.+?\\\\.[a-z]{3})\", \"\\\\1\", csv)\n\t\tx <- csv\n\t}\n\tfilepath <- list(files=x, path=path)\n\treturn(filepath)\n}\n\n#--------------------------------------------------------------------------#\n# Here is the function that will produce the descrete distance matrix for \n# diploid organisms.\n# pop.matrix is a matrix of rows of individuals with columns of Loci.\n# Currently the loci are every two columns in the matrix.\n# Specifically, this compares two individuals at one locus. A loop for each \n# type of distance matrix will need to be constructued separately\n# \n# i is the row for each new individual in the pairwise comparison\n# j is the row for the reference individual\n# m is the column for the first allele in the locus\n# n is the column for the second allele in the locus\n# z is the measure of distance. It should be zero before the loop\n#\n# Again, this is for diploids. position of the allele at the locus does not\n# matter as the inheritance is unknown, so this algorithm takes that into\n# account when doing the calculations.\n#--------------------------------------------------------------------------#\t\ndifference.test <- function(pop.matrix, i, j, m, n, z){\n\t# This if loop is analyzing allele m of individual j against that of\n\t# individual i. If they are equal, then that means the distance is equal\n\t# to zero at that allele.\n\tif(pop.matrix[j,m] == pop.matrix[i,m]){\n\t\t# given that the distance between allele m in individuals j and i\n\t\t# are equal, there is only one more comparison to do. If allele n\n\t\t# of individual j is equal to that of individual i, then the\n\t\t# distance is equal to 0. If they are not equal, z at the locus is 1\n\t\tif(pop.matrix[j,n] != pop.matrix[i,n]){\n\t\t\tz <- z+1\n\t\t}\n\t}\n\t# If allele m of individual j is not equal to that of individual i, then\n\t# a test to see if allele m is equal to allele n in individuals j and i,\n\t# respectively.\n\telse if(pop.matrix[j,m] == pop.matrix[i,n]){\n\t\t# given that the distance between alleles m and n in individuals j\n\t\t# and i respectively are equal, the only comparison left is to \n\t\t# compare the distances between alleles m and n in individuals i and\n\t\t# j respectively. If they are not equal, z at the locus is 1\n\t\tif(pop.matrix[j,n] != pop.matrix[i,m]){\n\t\t\tz <- z+1\n\t\t}\n\t}\n\t# If neither allele in individual i is equal to allele m in individual j\n\t# z is equal to one and a tests if the n allele of individual j is equal\n\t# to either allele in individual i.\n\telse{\n\t\tz <- z+1\n\t\t# Testing if the n allele in individual j is not equal to either allele\n\t\t# in individual i. If neither is equal, z at the locus increases by 1.\n\t\tif(pop.matrix[j,n] != pop.matrix[i,m] && pop.matrix[j,n] != pop.matrix[i,n]){\n\t\t\tz <- z+1\n\t\t}\t\n\t}\n\t# The final value of z is returned. At this point it can take on the\n\t# values of 0, 1, or 2 if doing a pairwise comparison at a single locus.\n\t# For pairwise comparisons over multiple loci, z can take on any value\n\t# between 0 and 2*M where M is the number of loci sampled.\n\treturn(z)\n}\n\nstdIa <- function(x){\n\t#--------------------------------------------------------------------------#\n\t# This is the beginning of the analysis. It will take the list of files \n\t# provided by the user and pull the files out of the directory that has \n\t# been set by the user. \n\t#--------------------------------------------------------------------------#\n\tfor(a in 1:length(x)){\n\t\tpop <- read.table(file(description= x[a], open=\"r\")) \n\t\tpop.matrix <- as.matrix(pop)\n\t\tnumAlleles <- ncol(pop.matrix)\n\t\tnumIsolates <- nrow(pop.matrix)\n\t\tnp <- (numIsolates*(numIsolates-1))/2\n\t\t# Creation of the datastructures\n\t\tif (!exists(\"Ia.vector\")){\n\t\t\tIa.vector <- NULL\n\t\t\trbarD.vector <- NULL\n\t\t\tfile.vector <- NULL\n\t\t}\n\t\tD.matrix <- matrix(0, nrow=numIsolates, ncol=numIsolates)\n\t\td.matrix <- D.matrix\n\t\td.vector <- NULL\n\t\td2.vector <- NULL\n\t\tvard.vector <- NULL\n\t\tvardpair.vector <- NULL\n\t\tto.remove <- NULL\n\t#--------------------------------------------------------------------------#\n\t# This is the loop for analyzing the pairwise distances at each locus,\n\t# also known as d. These values will be placed into two vectors representing\n\t# the sum of d for each locus and the sum of d^2 for each locus. \n\t# \n\t# This will also calculate D, the pairwise comparison of all isolates over\n\t# all loci. \n\t#--------------------------------------------------------------------------#\n\t\t# Initiating the loop over the columns of the population matrix\n\t\tfor(m in seq(1, (numAlleles-1), 2)){\n\t\t\tn <- m+1\n\t\t\t# Loop for the columns of the distance matrix\n\t\t\tfor(j in 1:numIsolates){\n\t\t\t\t# Loop for the rows of the distance matrix\n\t\t\t\tfor(i in 1:numIsolates){\n\t\t\t\t\tz <- 0\n\t\t\t\t\t# Setting the contraint for the pairwise comparisons by the\n\t\t\t\t\t# equation (n(n-1))/2 where n = numIsolates \n\t\t\t\t\t# If this loop did not exist, the construction of the\n\t\t\t\t\t# distance matrix would take twice as long.\n\t\t\t\t\tif(j < i && i <= numIsolates){\n\t\t\t\t\t\tz <- difference.test(pop.matrix, i, j, m, n, z)\n\t\t\t\t\t}\n\t\t\t\t\t# The value of z (0, 1, or 2) is pushed into the matrix\n\t\t\t\t\td.matrix[i,j] <- d.matrix[i,j]+z\n\t\t\t\t\t# This value is added to the matrix for pairwise comparison\n\t\t\t\t\t# of all the isolates over all loci as opposed to each locus\n\t\t\t\t\tD.matrix[i,j] <- D.matrix[i,j]+d.matrix[i,j]\n\t\t\t\t}\n\t\t\t}\n\t\t\t# placing the sum of the resulting matrix into a vector for later\n\t\t\t# use\n\t\t\td.vector <- append(d.vector, sum(d.matrix))\n\t\t\t# placing the sum of the squares of the resulting matrix into a \n\t\t\t# vector for later use\n\t\t\td2.vector <- append(d2.vector, sum(d.matrix^2))\n\t\t\t# zeroing out the matrix\n\t\t\td.matrix[1:numIsolates,1:numIsolates] <- 0\n\t\t}\n\t\t# removing the matrix from the namespace as it is no longer needed.\n\t\trm(d.matrix)\n\t#--------------------------------------------------------------------------#\n\t# Now to begin the calculations. First, set the variance of D\n\t#--------------------------------------------------------------------------#\n\t\tvarD <- ((sum(D.matrix^2)-((sum(D.matrix))^2)/np))/np\n\t#--------------------------------------------------------------------------#\n\t# Next is to create a vector containing all of the variances of d (there\n\t# will be one for each locus)\n\t#--------------------------------------------------------------------------#\n\t\tvard.vector <- ((d2.vector-((d.vector^2)/np))/np)\n\t#--------------------------------------------------------------------------#\n\t# Here the roots of the products of the variances are being produced and\n\t# the sum of those values is taken.\n\t#--------------------------------------------------------------------------#\n\t\tfor (b in 1:length(d.vector)){\n\t\t\tfor (d in 1:length(d.vector)){\n\t\t\t\t# As pairwise multiplication is required, a pairwise constriant\n\t\t\t\t# loop must be set up. \n\t\t\t\tif(b < d && d <= length(d.vector)){\n\t\t\t\t\tvardpair <- sqrt(vard.vector[b]*vard.vector[d])\n\t\t\t\t\tvardpair.vector <- append(vardpair.vector, vardpair)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t#--------------------------------------------------------------------------#\n\t# The sum of the variances necessary for the calculation of Ia is calculated\n\t#--------------------------------------------------------------------------#\n\t\tsigVarj <- sum(vard.vector)\n\t\trm(vard.vector)\n\t#--------------------------------------------------------------------------#\n\t# Finally, the Index of Association and the standardized Index of associati-\n\t# on are calculated.\n\t#--------------------------------------------------------------------------#\n\t\tIa <- (varD/sigVarj)-1\n\t\trbarD <- (varD - sigVarj)/(2*sum(vardpair.vector))\n\t\t# Prints to screen as loop progresses\n\t\tprint(paste(\"File Name:\", x[a], sep=\" \"))\n\t\tprint(paste(\"Index of Association:\", Ia, sep=\" \"))\n\t\tprint(paste(\"Standardized Index of Association (rbarD):\", rbarD, sep=\" \"))\n\t\t# Saves the values of Ia, rbarD, and the filename into datastructures\n\t\t# that will be listed in a dataframe\n\t\tfile.vector <- append(file.vector, x[a])\n\t\tIa.vector <- append(Ia.vector, Ia)\n\t\trbarD.vector <- append(rbarD.vector, rbarD)\n\t}\n\t# Creating the data frame for output.\n\tIout <- list(Ia=Ia.vector, rbarD=rbarD.vector, File=file.vector)\n\treturn(as.data.frame(Iout))\n}", "meta": {"hexsha": "9b8f4efcde1b7f1144c47342339e4c49e0378337", "size": 9321, "ext": "r", "lang": "R", "max_stars_repo_path": "the_horror/OLDmultilocusFunctions.r", "max_stars_repo_name": "zkamvar/PiG_Multitool", "max_stars_repo_head_hexsha": "81a0bf7bc7830fac8fab18e548e97a088fe341d6", "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": "the_horror/OLDmultilocusFunctions.r", "max_issues_repo_name": "zkamvar/PiG_Multitool", "max_issues_repo_head_hexsha": "81a0bf7bc7830fac8fab18e548e97a088fe341d6", "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": "the_horror/OLDmultilocusFunctions.r", "max_forks_repo_name": "zkamvar/PiG_Multitool", "max_forks_repo_head_hexsha": "81a0bf7bc7830fac8fab18e548e97a088fe341d6", "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.3857142857, "max_line_length": 79, "alphanum_fraction": 0.5797661195, "num_tokens": 2330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.05582313563685471, "lm_q1q2_score": 0.02379860808569846}} {"text": "# Day 16: Packet Decoder\n\nget_day16_input_path <- function() {\n paste(getwd(), \"/2021/Day 16/Day16_input.txt\", sep = \"\")\n}\n\npackets <- matrix(ncol = 5)[-1, ]\npacket_depth <- 0\n\npart1 <- function() {\n readings <- readLines(get_day16_input_path())\n chars <- unlist(strsplit(readings[1], \"\"))\n\n binary <- R.utils::intToBin(strtoi(chars, base = 16L))\n binary_str <- paste(binary, collapse = \"\")\n bits <- unlist(strsplit(binary_str, \"\"))\n\n main_packet <- create_packet(bits)\n\n if (main_packet[2] == 4) {\n # Calculate literal value\n main_packet <- set_literal_value(bits, 7, main_packet)\n packets <<- rbind(packets, c(main_packet))\n } else {\n # Process operator\n packets <<- rbind(packets, c(main_packet))\n process_packets(bits, 7)\n }\n\n print(packets)\n cat(\"Sum of versions:\", sum(packets[, 1]), \"\\n\")\n cat(\"Sum of values:\", sum(packets[, 3]), \"\\n\")\n}\n\npart2 <- function() {\n print(\"TODO\")\n}\n\ncreate_packet <- function(bits) {\n version <- bits[1:3]\n version_dec <- strtoi(paste(version, collapse = \"\"), base = 2)\n\n type <- bits[4:6]\n type_dec <- strtoi(paste(type, collapse = \"\"), base = 2)\n\n # version, type, value, next_index\n packet <- c(version_dec, type_dec, 0, 0, packet_depth)\n packet\n}\n\n# Process Packets assumes it's being passed an Operator packet\n# Start Index is the index of the length indicator\nprocess_packets <- function(bits, start_index) {\n packet_depth <<- packet_depth + 1\n cat(\"Entering packet depth:\", packet_depth, \"\\n\")\n length_ind <- bits[start_index]\n next_packet_index <- 0\n\n if (length_ind == \"0\") {\n print(\"15-bit Operator\")\n # 15-bit length mode, parse length of all subpackets\n subpackets_len <- bits[(start_index + 1):(start_index + 15)]\n sp_len_dec <- strtoi(paste(subpackets_len, collapse = \"\"), base = 2)\n cat(sp_len_dec, \"bits to process\\n\")\n\n sp_bound <- start_index + 15 + sp_len_dec\n\n # Next packet index will pass up to previous caller\n # 15-bit mode makes this easy since it tells us where the packet ends\n next_packet_index <- sp_bound + 1\n sp_bits_start <- start_index + 15 + 1\n\n sp_bits <- bits[sp_bits_start:sp_bound]\n sp_bits <- sp_bits[!is.na(sp_bits)]\n\n end_of_bits <- FALSE\n bits_processed <- 0\n\n # Process packets while we have bits left to consume\n while (!end_of_bits) {\n packet <- create_packet(sp_bits)\n if (packet[2] == 4) {\n # Packet is a literal value\n packet <- set_literal_value(sp_bits, 7, packet)\n\n # Packet[4] is the index immediately after its last bit\n bits_processed <- bits_processed + packet[4] - 1\n cat(\"L Proc'd\", bits_processed, \"of\", sp_len_dec, \"bits\\n\")\n if (bits_processed == sp_len_dec) {\n end_of_bits <- TRUE\n } else {\n # We have more bits to go, trim the packet we just processed\n sp_bits <- sp_bits[packet[4]:length(sp_bits)]\n sp_bits <- sp_bits[!is.na(sp_bits)]\n }\n\n # Add literal value packet to list\n packets <<- rbind(packets, c(packet))\n } else {\n # This is an operator packet, add it to the list\n packets <<- rbind(packets, c(packet))\n\n # Recursively inspect this operator packet\n next_subpacket_index <- process_packets(sp_bits, 7)\n\n # Process packet returns the bounds of this packet + 1\n # (AKA the next packet starting point)\n bits_processed <- bits_processed + next_subpacket_index - 1\n cat(\"O Proc'd\", bits_processed, \"of\", sp_len_dec, \"bits\\n\")\n\n if (bits_processed == sp_len_dec) {\n end_of_bits <- TRUE\n } else {\n # We have more bits to go, trim the packet we just processed\n new_sp_bits_start <- sp_bits_start + bits_processed\n sp_bits <- bits[new_sp_bits_start:sp_bound]\n sp_bits <- sp_bits[!is.na(sp_bits)]\n }\n }\n }\n } else {\n print(\"11-bit operator\")\n # 11-bit length mode, parse number of subpackets in this packet\n num_subpackets <- bits[(start_index + 1):(start_index + 11)]\n sp_num_dec <- strtoi(paste(num_subpackets, collapse = \"\"), base = 2)\n\n cat(sp_num_dec, \"subpackets to process\\n\")\n\n # Move bits cursor up to first subpacket starting index\n sp_bits <- bits[(start_index + 11 + 1):length(bits)]\n sp_bits <- sp_bits[!is.na(sp_bits)]\n\n # Store running calculation of the next packet index\n # Harder than 15-bit mode since the length of this packet starts unknown\n next_packet_index <- start_index + 11 + 1\n for (i in 1:sp_num_dec) {\n packet <- create_packet(sp_bits)\n if (packet[2] == 4) {\n # Packet is a literal value\n packet <- set_literal_value(sp_bits, 7, packet)\n\n # Packet[4] is the index immediately after its last bit\n next_packet_index <- next_packet_index + packet[4] - 1\n cat(\"L Proc'd\", next_packet_index - 1, \"of ??? bits\\n\")\n\n # Trim the packet we just processed\n sp_bits <- sp_bits[packet[4]:length(sp_bits)]\n sp_bits <- sp_bits[!is.na(sp_bits)]\n\n # Add literal value packet to list\n packets <<- rbind(packets, c(packet))\n } else {\n # This is an operator packet, add it to the list\n packets <<- rbind(packets, c(packet))\n\n # Recursively inspect this operator packet\n next_packet_index <- next_packet_index +\n process_packets(sp_bits, 7) - 1\n cat(\"O Proc'd\", next_packet_index - 1, \"of ??? bits\\n\")\n\n # Trim the packet we just processed\n sp_bits <- bits[next_packet_index:length(bits)]\n sp_bits <- sp_bits[!is.na(sp_bits)]\n }\n }\n }\n cat(\"Exiting packet depth:\", packet_depth, \"\\n\")\n packet_depth <<- packet_depth - 1\n next_packet_index\n}\n\nset_literal_value <- function(bits, start_index, packet) {\n value <- \"\"\n last_num <- FALSE\n next_index <- start_index\n while (!last_num) {\n num <- bits[next_index:(next_index + 4)]\n if (num[1] == \"0\") {\n last_num <- TRUE\n }\n value <- paste(value, paste(num[2:5], collapse = \"\"), sep = \"\")\n next_index <- next_index + 5\n }\n packet[3] <- strtoi(value, base = 2)\n packet[4] <- next_index\n packet\n}\n\npart1()\npart2()\n", "meta": {"hexsha": "d1c73ba43b9a466b473eacd12e227d65ed019541", "size": 6858, "ext": "r", "lang": "R", "max_stars_repo_path": "2021/Day 16/Day16_PacketDecoder.r", "max_stars_repo_name": "jonmichalik/advent-of-code", "max_stars_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "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": "2021/Day 16/Day16_PacketDecoder.r", "max_issues_repo_name": "jonmichalik/advent-of-code", "max_issues_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "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": "2021/Day 16/Day16_PacketDecoder.r", "max_forks_repo_name": "jonmichalik/advent-of-code", "max_forks_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "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.9057591623, "max_line_length": 80, "alphanum_fraction": 0.5640128317, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04813677657875974, "lm_q1q2_score": 0.023128694776049934}} {"text": "# Program to check\nif the input number is prime or not\n# take input from the user\nnum = as.integer(readline(prompt = \"Enter a number: \"))\nflag = 0\n# prime numbers are greater than 1\nif (num > 1) {\n # check\n for factors\n flag = 1\n for (i in 2: (num - 1)) {\n if ((num % % i) == 0) {\n flag = 0\n break\n }\n }\n}\nif (num == 2) flag = 1\nif (flag == 1) {\n print(paste(num, \"is a prime number\"))\n} else {\n print(paste(num, \"is not a prime number\"))\n}\n", "meta": {"hexsha": "55ca95f6e91c63ca662880dd10e3659136114db5", "size": 464, "ext": "r", "lang": "R", "max_stars_repo_path": "packages/cspell-bundled-dicts/test-samples/sample.r", "max_stars_repo_name": "zwaldowski/cspell", "max_stars_repo_head_hexsha": "bbcf7938eb5c6cfab3893bd967e43f368472ac27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 72, "max_stars_repo_stars_event_min_datetime": "2017-01-26T14:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T16:57:19.000Z", "max_issues_repo_path": "packages/cspell-bundled-dicts/test-samples/sample.r", "max_issues_repo_name": "zwaldowski/cspell", "max_issues_repo_head_hexsha": "bbcf7938eb5c6cfab3893bd967e43f368472ac27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 85, "max_issues_repo_issues_event_min_datetime": "2017-01-25T22:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:54:17.000Z", "max_forks_repo_path": "packages/cspell-bundled-dicts/test-samples/sample.r", "max_forks_repo_name": "zwaldowski/cspell", "max_forks_repo_head_hexsha": "bbcf7938eb5c6cfab3893bd967e43f368472ac27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35, "max_forks_repo_forks_event_min_datetime": "2017-02-03T14:56:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-05T12:58:57.000Z", "avg_line_length": 19.3333333333, "max_line_length": 55, "alphanum_fraction": 0.5711206897, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022540649291935, "lm_q2_score": 0.06187598875104791, "lm_q1q2_score": 0.022908063087508018}} {"text": "dyn.load(\"chartr-ModelSpecFast.so\")\n\n# 24 models \n#' Generate a list of models to be used for fitting RTs and Choice\n#'\n#' @return A list of models\n#' @examples\n#' modelList = returnListOfModels()\nreturnListOfModels = function()\n{\n modelList = c(\n \"DDM\", # -1\n \"DDMSv\", # -2\n \"DDMSt\", # -3\n \"DDMSvSz\", # -4\n \"DDMSvSt\", # -5\n \"DDMSvSzSt\", # -6\n \n \"cDDM\", # -7\n \"cDDMSv\", # -8\n \"cDDMSt\", # -9\n \"cDDMSvSz\", # -10\n \"cDDMSvSt\", # -11\n \"cDDMSvSzSt\", # -12\n \n \"dDDM\", # -13\n \"dDDMSt\", # -14\n \"dDDMSv\", # -15\n \"dDDMSvSt\", # -16\n \"dDDMSvSzSt\", # -17\n \n \"cfkDDM\", # -18\n \"cfkDDMSt\", # -19\n \"cfkDDMSvSt\", # -20\n \"cfkDDMSvSzSt\", # -21\n \n \"lcDDM\",\n \n \"UGM\", # 1\n \"UGMSt\", # 2 \n \"UGMSv\", # 3\n \"UGMSvSt\", # 4\n \n \"bUGM\", # 5\n \"bUGMSt\", # 6\n \"bUGMSv\", # 7 \n \"bUGMSvSt\", # 8 \n \"bUGMSvSb\", # 9 \n \"bUGMSvSbSt\", # 10\n\n \"uDDM\", # 11\n \"uDDMSt\", # 12\n \"uDDMSv\", # 13\n \"uDDMSvSb\", # 14\n \"uDDMSvSt\", # 15\n \"uDDMSvSbSt\", # 16 \n \"uDDMSbSu\",\n \n \n \"nluDDM\", # 17\n \"nluDDMSv\", # 18\n \"nluDDMSvSb\", # 19\n \"nluDDMSvSt\", # 20\n \"nluDDMSvSbSt\", # 21\n \"nluDDMSbSu\",\n \"nluDDMSb\", \n \n \"nluDDMd\", # 22\n \"nluDDMdSvSb\", # 23\n \n \"uDDMd\", # 24\n \"uDDMdSvSb\", # 25 \n \"uDDMdSbSu\",\n \n \"uDDMSvSbSu\", # 26\n \n \"bUGMSvSbSu\", # 27\n \n \"ucDDM\"\n );\n modelIds = c(seq(-1,-22), seq(1,32));\n modelNames <- setNames( modelList, modelIds)\n names(modelIds) = modelList\n list(modelIds=modelIds,modelNames=modelNames)\n}\n\n\n#' printModels\n#'\n#' @return prints models\n#' @export \n#'\n#' @examples\n#' printModels()\nprintModels = function()\n{\n \n allValidModels = returnListOfModels()\n modelList = unname(allValidModels$modelNames);\n modelList = sort(modelList, decreasing=TRUE)\n \n cat(sprintf(\"CHaRTr has %d models\", length(modelList)))\n priorClass = '';\n for(m in modelList)\n {\n firstChar = substr(m,1,1);\n if(firstChar!=priorClass)\n cat(\"\\n\");\n cat(sprintf(\"\\n%15s\", m))\n\n switch(firstChar,\n \"D\"={\n modelClass = \"DDM\"\n },\n \"U\"={\n modelClass=\"UGM\"\n },\n \"n\"={\n modelClass=\"Nonlinear urgency\"\n },\n \"u\"={\n modelClass = \"urgency\"\n },\n \"c\"={\n modelClass = \"Collapsing\"\n },\n \"d\"={\n modelClass = \"Ditterich\"\n },\n \"b\"={\n modelClass = \"UGM with intercept\"\n }\n \n )\n priorClass = firstChar;\n cat(sprintf(\" ----- %s\",modelClass))\n }\n}\n\n\n\n\n#' paramsandlims\n#'\n#' @param model -- name of the model that is typically generated using list of models\n#' @param nds -- Number of stimulus levels used for decision-making\n#' @param fakePars -- Generate fakeparameters for simulations\n#' @param nstart -- Sometimes there is a true zero sensory evidence stimulus\n#'\n#' @return list with fields parnames, upper limits, lower limits, variable of whether it is a UGM class of models or DDM class of models, and fakeparams if generated.\n#' @export\n#'\n#' @examples\n#' paramsandlims(model='DDM',nds=7,fakePars=FALSE,nstart=1)\nparamsandlims=function(model, nds, fakePars=FALSE, nstart=1)\n{\n # Non UGMs will have values less than 0\n # UGMs will have values greater than 0\n listOfModels = returnListOfModels()\n \n fitUGM = listOfModels$modelIds[model]\n \n upper_v_ddm = .6;\n upper_aU_ddm = 1;\n upper_Ter = 0.8;\n upper_st0 = 0.6;\n upper_eta = .3;\n upper_zmin = 1;\n upper_zmax = 1;\n \n \n upper_v_urgency = 40;\n upper_aU_urgency = 20000;\n upper_eta_urgency = 20;\n upper_intercept = 1000;\n upper_ieta = 300;\n upper_usign_var = 20;\n upper_timecons_var = 2000;\n upper_intercept_ddm = 100;\n \n \n upper_aprime = 0.5;\n upper_k = 20;\n upper_lambda = 100;\n \n upper_delay = 4;\n upper_lambda_urgency = 5;\n \n upper_usigneta = 20;\n lower_usigneta = 0;\n \n NdriftRates = nds - nstart + 1; # Say 6 drift rates, starting at 2, means 5 conditions\n \n TempNamesDDM = c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\", \"st0\",\n \"zmin\",\"zmax\",\"sx\",\"sy\",\"delay\",\"lambda\", \"aprime\",\"k\",\"intercept\");\n \n \n fakeParsDDM = c(seq(0.04, 0.4, length.out = NdriftRates), 0.08, 0.3, 0.1, 0.15, 0.08, 0.12, 9, 9,0.14, 5, 0.3, 10, 4);\n names(fakeParsDDM) = TempNamesDDM;\n \n TempNamesUGM = c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\", \"st0\",\n \"intercept\",\"ieta\",\"timecons_var\",\"usign_var\", \"usigneta\", \"lambda\", \"aprime\",\"k\",\"delay\");\n fakeParsUGM = c(seq(1.5, 15, length.out=NdriftRates) + 0.5*rnorm(nds), 12000, 0.3, 4, 0.1, 1000, 600, 200,1,1, 5, 0.3, 10,0.3);\n names(fakeParsUGM) = TempNamesUGM;\n\n switch(model, \n DDM={ # 7 coherences, an upper bound, and a lower bound, symmetric bounds\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\")\n print(\"Vanilla diffusion model with no bells and whistles\")\n },\n DDMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\")\n print(\"Diffusion model with some drift variance\")\n },\n DDMSvSz={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"zmin\",\"zmax\")\n print(\"Diffusion model, Variable Baseline, Variable Movement Time\")\n },\n DDMSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"st0\")\n print(\"Diffusion model with some drift variance and variable movement time\")\n },\n DDMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\")\n print(\"Diffusion model with some drift variance and variable movement time\")\n },\n DDMSvSzSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"zmin\",\"zmax\",\"st0\")\n print(\"Diffusion model, Variable Baseline, Variable Movement Time\")\n },\n\n ratcliff={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"zmin\",\"zmax\",\"st0\")\n print(\"Ratcliff model with variable movement time\")\n },\n \n dDDM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"sx\",\"sy\",\"delay\",\"intercept\")\n print(\"Diffusion model with some drift variance and variable movement time and most importantly urgency\")\n },\n dDDMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"sx\",\"sy\",\"delay\",\"intercept\")\n print(\"Diffusion model with some drift variance and variable movement time and most importantly urgency\")\n },\n \n dDDMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"sx\",\"sy\",\"delay\",\"intercept\")\n print(\"Diffusion model with some drift variance and variable movement time and most importantly urgency\")\n },\n dDDMSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"st0\",\"sx\",\"sy\",\"delay\",\"intercept\")\n print(\"Diffusion model with some drift variance and variable movement time and most importantly urgency\")\n },\n \n \n \n dDDMSvSzSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"sx\",\"sy\",\"delay\",\"zmin\",\"zmax\",\"intercept\")\n print(\"Diffusion model with some drift variance and variable movement time and most importantly urgency\")\n },\n lcDDM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"lambda\",\"aprime\")\n print(\"Diffusion model with linear collapsing bounds\")\n upper_lambda = 10;\n },\n cDDM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"lambda\",\"aprime\",\"k\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n cDDMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\", \"lambda\",\"aprime\",\"k\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n cDDMSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"lambda\",\"aprime\",\"k\", \"st0\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n cDDMSvSz={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"lambda\",\"aprime\",\"k\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n cDDMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"lambda\",\"aprime\",\"k\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n cDDMSvSzSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"lambda\",\"aprime\",\"k\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n cfkDDM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"lambda\",\"aprime\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n cfkDDMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"lambda\",\"aprime\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n cfkDDMSvSz={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"lambda\",\"aprime\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n cfkDDMSvSz={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"lambda\",\"aprime\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n cfkDDMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"lambda\",\"aprime\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n cfkDDMSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"st0\",\"lambda\",\"aprime\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n cfkDDMSvSzSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"lambda\",\"aprime\",\"zmin\",\"zmax\")\n print(\"Diffusion model with some drift variance, variable movement time and collapsing bounds\")\n },\n \n \n \n \n \n \n \n UGM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\")\n print(\"Urgency Gating Model\")\n },\n UGMSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"st0\")\n print(\"Urgency gating model with some drift variance and variable residual movement time\")\n },\n UGMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\")\n print(\"Urgency Gating With Drift Variance\")\n \n },\n UGMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\")\n print(\"Urgency Gating, drift variance, variable residual movement time\")\n },\n \n bUGM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\")\n print(\"Urgency Gating with an intercept\") \n },\n bUGMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\")\n print(\"Urgency Gating with an intercept\") \n },\n bUGMSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\", \"st0\")\n print(\"Diffusion model with some drift variance, urgency gating, residual\n movement time, and an intercept for urgency gating\")\n }, \n bUGMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\", \"st0\")\n print(\"Diffusion model with some drift variance, urgency gating, residual\n movement time, and an intercept for urgency gating\")\n }, \n bUGMSvSb={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\")\n print(\"Diffusion model with some drift variance, urgency gating, variable residual \n movement time, and an intercept for urgency gating\")\n \n }, \n \n bUGMSvSbSu={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"usign_var\",\"intercept\", \"ieta\",\"usigneta\")\n print(\"Diffusion model with some drift variance, urgency gating, variable residual \n movement time, and an intercept for urgency gating\")\n }, \n \n \n bUGMSvSbSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"st0\")\n print(\"Diffusion model with some drift variance, urgency gating, variable residual \n movement time, and an intercept for urgency gating\")\n }, \n \n \n \n # A UGM model with variability in all the parameters so that the time constant is not causing unnecessary issues \n UGMSvallVar={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"st0\",\"timecons_var\",\"usign_var\")\n print(\"Full UGM model with variability in time constants and slope parameter\")\n }, \n \n # Urgency signal in PMd\n uDDMSvSb={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"usign_var\")\n print(\"DDM with Urgency and no gating and fixed Ter\")\n },\n \n uDDMSvSbSu={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"usign_var\",\"usigneta\")\n print(\"DDM with Urgency and no gating and fixed Ter\")\n },\n \n uDDMSbSu={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"ieta\",\"usign_var\",\"usigneta\")\n print(\"DDM with Urgency and no gating and fixed Ter\")\n },\n \n uDDMSbSuSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"ieta\",\"usign_var\",\"usigneta\",\"st0\")\n print(\"DDM with Urgency and no gating and fixed Ter\")\n },\n \n uDDMdSvSb={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\", \"intercept\",\"ieta\", \"usign_var\",\"delay\")\n print(\"DDM with Urgency and no gating, constant slope, and fixed Ter\")\n }, \n \n \n ucDDM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"usign_var\",\"lambda\",\"aprime\",\"k\")\n print(\"DDM with Urgency and no gating, constant slope, and fixed Ter\")\n upper_aprime = 1;\n }, \n \n uDDM={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"usign_var\")\n print(\"DDM with Urgency and no gating, constant slope, and fixed Ter\")\n }, \n \n uDDMd={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"usign_var\",\"delay\")\n print(\"DDM with Urgency and no gating, constant slope, and fixed Ter\")\n }, \n \n uDDMdSbSu={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"ieta\",\"usign_var\",\"usigneta\",\"delay\")\n print(\"DDM with Urgency and no gating and fixed Ter\")\n },\n \n uDDMSt = \n {\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"usign_var\",\"st0\")\n print(\"DDM with Urgency and no gating, constant slope, and variable Ter\")\n # upper_intercept=20;\n # upper_ieta=20;\n \n },\n\n uDDMSv={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"usign_var\")\n print(\"DDM with Urgency and no gating, constant slope, and fixed Ter\")\n }, \n uDDMSvSbSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"usign_var\",\"st0\")\n print(\"DDM with Urgency and no gating and variable Ter\")\n # upper_intercept=20;\n # upper_ieta=20;\n },\n \n uDDMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"usign_var\",\"st0\")\n print(\"DDM with Urgency and no gating, constant slope, and variable Ter\")\n # upper_intercept=20;\n # upper_ieta=20;\n \n }, \n \n nluDDM={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"usign_var\",\"lambda\",\"k\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n nluDDMSv={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"usign_var\",\"lambda\",\"k\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n nluDDMSvSb={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"usign_var\",\"lambda\",\"k\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n nluDDMSbSu={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"ieta\",\"usign_var\",\"usigneta\",\"lambda\",\"k\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n nluDDMSb={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"ieta\",\"usign_var\",\"lambda\",\"k\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n \n \n \n nluDDMdSvSb={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\", \"intercept\",\"ieta\", \"usign_var\",\"lambda\",\"k\",\"delay\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n \n nluDDMSvSt={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"usign_var\",\"lambda\",\"k\",\"st0\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n nluDDMSvSbSt={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"intercept\",\"ieta\",\"usign_var\",\"lambda\",\"k\",\"st0\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n nluDDMd={\n print(\"Nonlinear uDDM\")\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"intercept\",\"usign_var\",\"lambda\",\"k\",\"delay\")\n print(\"DDM with nonlinear Urgency and no gating, constant slope, and variable Ter\")\n },\n \n \n cUGMSvSt={\n parnames=c(paste(\"v\",(nstart):(nds),sep=\"\"),\"aU\",\"Ter\",\"eta\",\"st0\",\"lambda\",\"aprime\",\"k\")\n print(\"Collapsing bounds urgency gating model with a 100 ms time constant and variable non decision time\")\n upper_aU_urgency = 3;\n upper_v_urgency = 20;\n }\n ) \n parUppersDDM = c(rep(upper_v_ddm,NdriftRates), upper_aU_ddm, upper_Ter, upper_eta, upper_st0,\n upper_zmin, upper_zmax, 50, 50, 3, upper_lambda,upper_aprime,upper_k, upper_intercept_ddm);\n names(parUppersDDM) = TempNamesDDM;\n \n parUppersUGM = c(rep(upper_v_urgency,NdriftRates), upper_aU_urgency, upper_Ter, upper_eta_urgency, upper_st0,\n upper_intercept, upper_ieta, upper_timecons_var, upper_usign_var, upper_usigneta, upper_lambda_urgency,upper_aprime,upper_k, upper_delay)\n names(parUppersUGM) = TempNamesUGM;\n \n \n \n uppers = seq(1,length(parnames));\n for(i in seq(1,length(parnames))){\n if(fitUGM < 0)\n uppers[i] = parUppersDDM[parnames[i]] \n else\n uppers[i] = parUppersUGM[parnames[i]] \n \n }\n lowers=rep(0,length(uppers))\n \n # Set lower limit for Ter to be 0.15, otherwise you can get very low Ter values\n idx = which(parnames == \"Ter\")\n lowers[idx] = 0.05;\n \n \n if(fakePars)\n {\n fakeParams = seq(1,length(parnames));\n for(i in seq(1,length(parnames))){\n if(fitUGM < 0)\n fakeParams[i] = fakeParsDDM[parnames[i]] \n else\n fakeParams[i] = fakeParsUGM[parnames[i]] \n }\n names(fakeParams) = parnames;\n }\n else\n {\n fakeParams = NULL;\n }\n \n list(parnames=parnames, uppers=uppers, lowers=lowers, fitUGM=fitUGM, fakeParams = fakeParams)\n \n}\n# End the list of parameters for the models\n\n\n\n\n\n#' Title\n#'\n#' @param v drift rates\n#' @param eta Standard deviation for the drift rate\n#' @param aU upper bound\n#' @param aL lower bound\n#' @param Ter Non decision time\n#' @param intercept Intercept for the UGM\n#' @param ieta range of the uniform distribution for the UGM intercept\n#' @param st0 range of the uniform distribution for the reaction times\n#' @param z Startpoint of the UGM.\n#' @param zmin min range of start point\n#' @param zmax max range of start point\n#' @param nmc number of trials to run\n#' @param dt timestep: .001 s for DDM, 1 ms for UGM\n#' @param stoch.s a constant\n#' @param maxTimeStep - maximum number of timesteps for the simulation\n#' @param fitUGM - whether it is a UGM or not and what the modelID is used for back identifying model name. This modifies the timesteps\n#' @param timecons- Used only for fixed UGMs\n#' @param usign - a constant typically 1 which tells you how the urgency signal grows\n#' @param timecons_var \n#' @param usign_var \n#' @param sx - Parameter for the Ditterich urgency function\n#' @param sy - Parameter for the Ditterich urgency function\n#' @param delay - Delay parameter for the Ditterich urgency function\n#' @param lambda - Parameter for the collapsing bounds\n#' @param aprime - Parameter for the collapsing bounds\n#' @param k - Parameter for the collapsing bounds\n#' @param VERBOSE \n#'\n#' @return list with rts and responses\n#' @export\n#'\n#' @examples\n#' diffusionC(v=0.4, eta=0.05, aU=0.1,aL=0, Ter=0.3,z=0.05,nmc=1000,dt=0.001,stoch.s=0.1,maxTimeStep=4,fitUGM=-12)\ndiffusionC=function(v,eta,aU,aL,Ter,intercept,ieta,st0, z, zmin, zmax, nmc, dt,stoch.s,\n maxTimeStep,fitUGM,timecons,usign=1, timecons_var = timecons_var, usign_var = usign_var, usigneta= usigneta, \n sx=sx, sy=sy, delay=delay, lambda = lambda, aprime = aprime, k = k, VERBOSE=FALSE, FASTRAND=TRUE,\n nLUT=nLUT, LUT = LUT) \n # v - \n # eta - \n # aU - \n # intercept - intercept for the urgency signal\n # ieta - variability for the intercept\n # st0 - variability in non decision-time\n # z - start point\n # zmin - min range\n # zmax - max range\n # nmc - number of montecarlo simulations\n # dt - time step\n# fitUGM - Should we be fitting a UGM\n# timecons- fixed paramter for the Urgency gating model usually 100 - 200 ms\n# usign - Fixed value for the slope of the urgency signal, usually 1 for UGM\n# timecons_var - used if you wish to allow time constant to vary freely\n# usign_var - used if you wish to allow urgency signal slope to vary freely\n# sx, xy, delay - parameters for the Ditterich model\n# lambda, aprime, k - parameters for the collapsing bounds model\n{\n if(FASTRAND)\n dyn.load(\"chartr-ModelSpecFast.so\")\n else\n {\n dyn.load(\"chartr-ModelSpec.so\")\n # print(\"Slow Rand\")\n }\n \n rts <- resps <- numeric(nmc)\n \n listOfModels = returnListOfModels()\n \n modelName = unname(listOfModels$modelNames[as.character(fitUGM)])\n if(VERBOSE) \n print(modelName);\n \n \n switch(modelName,\n # DDM ----------------------------- \n # 1\n DDM={\n out=.C(\"DDM\",z=z,v=v,aU=aU,aL=aL, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep, \n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT))\n rts=out$rt + Ter;\n },\n # Same as the vanilla diffusion model, except with a modification of the \n # model to include some variability in the drift rates.\n \n # 2\n \n DDMSv={\n out=.C(\"DDMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt + Ter;\n },\n \n # 3\n \n DDMSt={\n out=.C(\"DDM\",z=z,v=v,aU=aU,aL=aL, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # 4\n \n DDMSvSt={\n out=.C(\"DDMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # 5\n \n DDMSvSz={\n out=.C(\"DDMSvSz\",zmin=zmin, zmax=zmax,v=v,aU=aU,aL=aL,eta=eta,s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n \n # Identical to the ratcliffSt model\n \n # 6\n \n \n DDMSvSzSt={\n out=.C(\"DDMSvSz\",zmin=zmin, zmax=zmax,v=v,aU=aU,aL=aL,eta=eta,s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n # ------------------------------- End DDM Section\n \n \n # bUGM section ----------------------------\n \n # 1\n bUGM={\n out=.C(\"bUGM\",z=z,v=v,aU=aU,aL=aL,timecons=timecons,\n usign=usign,intercept=intercept, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000) + Ter;\n },\n \n # 2\n bUGMSv={\n out=.C(\"bUGMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons=timecons,\n usign=usign,intercept=intercept, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), \n randomTable = as.double(LUT));\n rts=(out$rt/1000) + Ter;\n },\n \n # 3\n bUGMSt={\n out=.C(\"bUGM\",z=z,v=v,aU=aU,aL=aL,timecons=timecons,\n usign=usign,intercept=intercept, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), \n randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n # 4\n # Assume that this intercept is variable as well. Assume constant slope though (1 in case of Cisek)\n bUGMSvSb={\n out=.C(\"bUGMSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons=timecons,\n usign=usign,intercept=intercept,ieta=ieta, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000) + Ter;\n },\n \n \n \n bUGMSvSbSu={\n out=.C(\"bUGMSvSbSu\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons=timecons, usign_var=usign_var,\n intercept=intercept, ieta=ieta, usigneta=usigneta, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000) + Ter;\n },\n \n # 5\n bUGMSvSt={\n out=.C(\"bUGMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons=timecons,\n usign=usign,intercept=intercept, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), \n randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # 6\n # Var intercept, Var Ter\n bUGMSvSbSt={\n out=.C(\"bUGMSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons=timecons,\n usign=usign,intercept=intercept,ieta=ieta, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n\n # uDDM Section\n uDDM={\n out=.C(\"uDDM\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n \n ucDDM={\n out=.C(\"ucDDM\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,lambda=lambda, aprime=aprime,k=k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n uDDMd={\n out=.C(\"uDDMd\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var, delay = delay,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n \n uDDMSv={\n out=.C(\"uDDMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n uDDMSt={\n out=.C(\"uDDM\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), \n randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n nluDDM={\n \n out=.C(\"nluDDM\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMd={\n out=.C(\"nluDDMd\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var, delay = delay,\n lambda = lambda, k = k, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,\n maxTimeStep=maxTimeStep,rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), \n randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMdSvSb={\n out=.C(\"nluDDMdSvSb\",z=z,v=v,eta = eta, aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, ieta= ieta, usign_var=usign_var, delay = delay,\n lambda = lambda, k = k, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,\n maxTimeStep=maxTimeStep,rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), \n randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMSv={\n \n out=.C(\"nluDDMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMSvSb={\n \n out=.C(\"nluDDMSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, ieta=ieta, usign_var=usign_var,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMSbSu={\n \n out=.C(\"nluDDMSbSu\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, ieta=ieta, usign_var=usign_var,usigneta=usigneta,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMSb={\n \n out=.C(\"nluDDMSb\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, ieta=ieta, usign_var=usign_var,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n },\n \n nluDDMSvSt={\n \n out=.C(\"nluDDMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n nluDDMSvSbSt={\n \n out=.C(\"nluDDMSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, ieta=ieta, usign_var=usign_var,\n lambda = lambda, k = k,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n uDDMSvSt={\n out=.C(\"uDDMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept, usign_var=usign_var,s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n # Now assume a Urgency model where you fit the intercept, variability in this intercept and a variable slope\n uDDMSvSb={\n out=.C(\"uDDMSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,\n usign_var=usign_var, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n }, \n \n \n uDDMSvSbSu={\n \n out=.C(\"uDDMSvSbSu\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,\n usign_var=usign_var, usigneta=usigneta, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n }, \n \n uDDMSbSu={\n \n out=.C(\"uDDMSbSu\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,\n usign_var=usign_var, usigneta=usigneta, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n }, \n \n uDDMdSbSu={\n \n out=.C(\"uDDMdSbSu\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,\n usign_var=usign_var, usigneta=usigneta, delay=delay, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n }, \n \n uDDMSbSuSt={\n out=.C(\"uDDMSbSu\",z=z,v=v,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,\n usign_var=usign_var, usigneta=usigneta, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n }, \n \n uDDMdSvSb={\n out=.C(\"uDDMdSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, \n intercept=intercept,ieta=ieta,usign_var=usign_var, delay = delay,\n s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+Ter;\n }, \n \n uDDMSvSbSt={\n out=.C(\"uDDMSvSb\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,\n usign_var=usign_var, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n }, \n \n # Now assume a Urgency model where you fit the intercept, and a slope term. \n \n \n \n \n # -------------------------------- Models without any variable movement time\n \n \n # Same as the model with drift variance but incorporation of a variable\n # time for the non decision time (See Ratcliff and Tuerlinckx, 2002)\n \n \n \n \n # This is a bit of a misnomer. The Ratcliff model always assumes a variable residual movement time\n ratcliff={\n out=.C(\"ratcliff\",zmin=zmin, zmax=zmax,v=v,aU=aU,aL=aL,eta=eta,s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt) +runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n # dDDM section -----------------------------------------------------------------\n dDDM={\n out=.C(\"dDDM\",z=z,v=v,delay=delay, sx=sx, sy=sy, intercept=intercept, aU=aU,aL=aL,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n \n },\n dDDMSv={\n out=.C(\"dDDMSv\",z=z,v=v,eta=eta, delay=delay, sx=sx, sy=sy, intercept = intercept, aU=aU,aL=aL,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n \n },\n # This is the ditterich model that assumes a complex shape for the bound collapse\n dDDMSvSt={\n out=.C(\"dDDMSv\",z=z,v=v,eta=eta, delay=delay, sx=sx, sy=sy, intercept=intercept, aU=aU,aL=aL,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n dDDMSt={\n out=.C(\"dDDM\",z=z,v=v, delay=delay, sx=sx, sy=sy, intercept= intercept, aU=aU,aL=aL,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n dDDMSvSzSt={\n out=.C(\"dDDMSvSz\",zmin=zmin,zmax=zmax,v=v,eta=eta, delay=delay, sx=sx, sy=sy, intercept=intercept, aU=aU,aL=aL,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n # ------------------------------------------------------------------ dDDM\n \n \n cfkDDMSvSt={\n out=.C(\"cfkDDMSv\",z=z,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # Replicating model from Hawkins et al. 2015\n cfkDDMSvSzSt={\n out=.C(\"cfkDDMSvSz\",zmin=zmin,zmax=zmax,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n \n # --------------------------------------------- cDDM\n lcDDM={\n out=.C(\"lcDDM\",z=z,v=v,lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n \n cDDM={\n out=.C(\"cDDM\",z=z,v=v,lambda=lambda, aU=aU,aL=aL, aprime = aprime, k=k,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n cDDMSt={\n out=.C(\"cDDM\",z=z,v=v, lambda=lambda, aU=aU,aL=aL, aprime = aprime, k=k,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n cDDMSv={\n out=.C(\"cDDMSv\",z=z,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL, aprime = aprime, k=k,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n\n cDDMSvSz={\n out=.C(\"cDDMSvSz\",zmin=zmin, zmax=zmax,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL, aprime = aprime, k=k,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n \n cDDMSvSt={\n out=.C(\"cDDMSv\",z=z,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL, aprime = aprime, k=k,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n cDDMSvSzSt={\n out=.C(\"cDDMSvSz\",zmin=zmin, zmax=zmax,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL, aprime = aprime, k=k,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n \n # -----------------------------------------------cfkDDM\n # Now do all the Collapsing bounds without the variabililty in nondecision-time\n cfkDDM={\n out=.C(\"cfkDDM\",z=z,v=v, lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n \n \n cfkDDMSv={\n out=.C(\"cfkDDMSv\",z=z,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n \n cfkDDMSt={\n out=.C(\"cfkDDM\",z=z,v=v, lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # Replicating model from Hawkins et al. 2015\n cfkDDMSvSz={\n out=.C(\"cfkDDMSvSz\",zmin=zmin,zmax=zmax,v=v,eta=eta, lambda=lambda, aU=aU,aL=aL,aprime=aprime,\n s=stoch.s,dt=dt,response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=out$rt+Ter;\n },\n \n \n \n cUGMSvSt={\n out=.C(\"cUGMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons=timecons,lambda=lambda,\n k=k, aprime=aprime, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2); \n \n },\n \n #UGM\n \n UGM={\n out=.C(\"UGM\",z=z,v=v,aU=aU,aL=aL, timecons=timecons, usign=usign, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000) + Ter;\n },\n \n # DDM model now adding variability of the drift rate\n UGMSv={\n out=.C(\"UGMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL, timecons=timecons, usign=usign, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep, \n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000) + Ter;\n },\n # Now do the urgency model with variable Ter\n UGMSt={\n out=.C(\"UGM\",z=z,v=v,aU=aU,aL=aL, timecons=timecons, usign=usign, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # Consider a UGM with variable drift rate and also variable non decision time. \n UGMSvSt={\n out=.C(\"UGMSv\",z=z,v=v,eta=eta,aU=aU,aL=aL, timecons=timecons, usign=usign, s=stoch.s,dt=dt,\n response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep,\n rangeLow =as.integer(0), rangeHigh = as.integer(nLUT-1), randomTable = as.double(LUT));\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n },\n \n # Suggestion by somebody like paul Cisek who suggested adding an intercept to the urgency model to \n # better describe the RTs\n # The final mega model, adding variability and a slope for the data\n \n UGMallVar={\n out=.C(\"UGMSvallVar\",z=z,v=v,eta=eta,aU=aU,aL=aL,timecons = timecons, usign=usign, intercept=intercept,ieta=ieta,timecons_var=timecons_var,\n usign_var=usign_var, s=stoch.s,dt=dt, response=resps,rt=rts,n=nmc,maxTimeStep=maxTimeStep);\n rts=(out$rt/1000)+runif(n=nmc,min=Ter-st0/2,max=Ter+st0/2);\n \n }\n \n \n # Example to get a collapsing UGM up and running.\n \n # Now calibrate variable slope for the data\n \n )\n rts[rts<0]=0\n list(rts=rts,resps=out$resp)\n} \n\n\nmakeparamlist=function(params,fitUGM,ncohs, zeroCoh=FALSE) \n{\n # transform parameter vector from obj into usable form for getpreds\n # different parameter settings for DDM and DDM+UGM models\n if(zeroCoh)\n {\n v=c(0,params[paste(\"v\",2:length(ncohs),sep=\"\")])\n }\n else\n {\n v=c(params[paste(\"v\",1:length(ncohs),sep=\"\")])\n }\n aU=params[\"aU\"]\n Ter=params[\"Ter\"]\n \n if(fitUGM < 0) {\n aL=0\n z=aU/2\n } else {\n aL=-aU\n z=0\n }\n eta=params[\"eta\"]\n intercept = params[\"intercept\"]\n st0 = params[\"st0\"]\n ieta = params[\"ieta\"]\n zmin = params[\"zmin\"]\n zmax = params[\"zmax\"]\n \n timecons_var = params[\"timecons_var\"]\n usign_var = params[\"usign_var\"]\n usigneta = params[\"usigneta\"]\n \n sx = params[\"sx\"]\n sy = params[\"sy\"]\n delay = params[\"delay\"]\n \n k = params[\"k\"]\n aprime = params[\"aprime\"]\n lambda = params[\"lambda\"]\n \n \n # Use some scaling and delay parameters as well for the analysis of urgency models\n list(v=v,eta=eta,aU=aU,aL=aL,z=z,Ter=Ter, intercept=intercept,st0=st0, ieta=ieta, zmin = zmin, \n zmax = zmax, timecons_var = timecons_var, usign_var = usign_var, usigneta = usigneta,\n sx=sx, sy=sy, delay=delay, k=k, aprime = aprime, lambda = lambda) \n #,contp=contp,timecons=timecons,usign=usign)\n}\n\n\n# \n#\n#\n# \nsimulateRTs = function(model, ps, nmc=50000, maxiter=10000, nds=7, showAxisLabels = FALSE, plotData=TRUE, \n FASTRAND=TRUE){\n # model specifies the model to simulate\n # ps passes in parameters\n # nmc and maxiter are parameters for the simulation\n \n bailouttime=5\n trlsteps=seq(0,bailouttime,.001)\n maxTimeStep=as.double(length(trlsteps))\n \n \n # For the future to speed up analyses\n interval=0.00001;\n LUT=qnorm(seq(interval,1-interval,interval));\n nLUT = length(LUT);\n \n lwds=2.5\n ptcexs=1.4\n axcexs=.9\n labcexs=1.1\n \n Ter = ps[\"Ter\"]\n st0 = ps[\"st0\"]\n eta = ps[\"eta\"]\n aU = ps[\"aU\"]\n \n qps=seq(.1,.9,.1) ; \n nq=length(qps)\n \n dNameRows = c(\"cor\", \"err\");\n dNameCols = seq(1,nds,1);\n \n predps=array(dim=c(nds),dimnames=list(NULL))\n predrts=array(dim=c(nq,2,nds),dimnames=list(qps,c(\"cor\",\"err\"),NULL))\n counts = array(dim=c(2,nds), dimnames=list(dNameRows, dNameCols));\n pb = array(data=NA, dim = c(10,2,nds), dimnames=list(1:10, dNameRows, dNameCols))\n \n \n actualParams = paramsandlims(model, nds)\n fitUGM = unname(actualParams$fitUGM)\n lowers = actualParams$lowers\n uppers = actualParams$uppers\n parnames = actualParams$parnames\n \n stepsize=ifelse(fitUGM < 0,.001,1) # time step for diffusion process: .001s (DDM), 1ms (UGM)\n stoch.s=ifelse(fitUGM < 0,.1,100) # diffusion constant\n timecons=ifelse(fitUGM < 0,0,100) # time constant for low pass filter\n usign=ifelse(fitUGM < 0,0,1)\n \n if(fitUGM < 0) {\n aL=0 ; z=ps[\"aU\"]/2\n dt=.001 ; stoch.s=.1 ; usign=0 ; timecons=0\n } else {\n aL=-ps[\"aU\"] ; \n z=0\n dt=1 ; \n stoch.s=100; \n usign=1; \n timecons=100\n \n }\n graycol=rgb(red=80,green=80,blue=80,alpha=180,maxColorValue=255)\n graylinecol =rgb(red=20,green=20,blue=20,alpha=180,maxColorValue=255)\n \n \n # predictions for fitted parameters\n backcol=rgb(red=220,green=220,blue=220,alpha=180,maxColorValue=255)\n \n if(plotData)\n { \n par(pty=\"s\")\n plot(y=NULL,x=NULL,ylim=c(0.2,0.9),\n xlim=c(0,1),ylab=\"\",xlab=\"\",axes=F)\n xaxs=seq(0,1,.2) ; xaxs[xaxs<1]=gsub(\"0.\",\".\",xaxs[xaxs<1])\n \n axis(side=1,at=xaxs,NA,tcl=-.4, labels=NULL, pos=0.25, cex.axis=1.6)\n \n if(showAxisLabels){\n mtext(\"Reaction time (sec)\", side=2, line=3 , cex=1.5)\n mtext(\"Probability Correct \", side=1, line=3 , cex=1.5)\n }\n }\n \n \n \n for(v in 1:nds) {\n rts <- resps <- numeric(nmc)\n \n tic(paste(\"Condition\",v))\n tmp = diffusionC(v=ps[v], eta=ps[\"eta\"], aU = ps[\"aU\"], aL = aL, Ter=ps[\"Ter\"], \n intercept=ps[\"intercept\"], ieta=ps[\"ieta\"], st0 = ps[\"st0\"], z=z, zmin=ps[\"zmin\"],\n zmax=ps[\"zmax\"], timecons_var=ps[\"timecons_var\"], usign_var=ps[\"usign_var\"], usigneta = ps[\"usigneta\"],\n sx=ps[\"sx\"], sy=ps[\"sy\"], delay=ps[\"delay\"], lambda=ps[\"lambda\"], \n aprime=ps[\"aprime\"], k=ps[\"k\"], timecons=timecons, usign=usign, s=stoch.s,dt=dt,\n n=nmc,maxTimeStep=maxTimeStep, fitUGM=fitUGM, FASTRAND=FASTRAND, nLUT = nLUT, LUT = LUT)\n toc();\n # Now count the number of good and bad numbers\n counts[\"cor\",v] = sum(tmp$resp==1)\n counts[\"err\",v] = sum(tmp$resp==2)\n \n predps[v]=(table(tmp$resp)/nmc)[\"1\"]\n predrts[,\"cor\",v]=quantile(tmp$rt[tmp$resp==1],probs=qps)\n predrts[,\"err\",v]=quantile(tmp$rt[tmp$resp==2],probs=qps)\n \n pb[1:10,1,v] = counts[1,v]/10; # Divide by 10 because you have quantiles :)!\n pb[1:10,2,v] = counts[2,v]/10;\n \n }\n # If you want the data plotted on the \n if(plotData)\n {\n for(i in seq(1,nq,2)) {\n y=c(rev(predrts[i,\"err\",]),predrts[i,\"cor\",])\n x=c(rev(1-predps),predps)\n \n points(y=y,x=x,pch=21,col=graylinecol,bg=backcol, cex=ptcexs*2,type=\"b\",\n lwd=lwds*1.2)\n \n # text(0.5, 0.96*predrts[i,\"err\",1], qps[i]*100,col=graycol)\n }\n \n yaxs=seq(.3,max(c(round(1.25*max(predrts),digits=1),0.9)),.2)\n text(0.15, yaxs[length(yaxs)]-0.04, model,cex=1.5, pos=4)\n axis(side=2,at=yaxs,NA,tcl=-.4, labels=NULL, las=1, cex.axis=1.6)\n }\n list(q=predrts, p=predps, n=counts, pb = pb)\n}\n\nplotData = function(dat, ExistingPlot=FALSE) {\n qps=seq(.1,.9,.2) ; nq=length(qps)\n dat$q=dat$q[as.character(qps),,]\n if(!ExistingPlot)\n {\n plot(y=NULL,x=NULL,ylim=range(dat$q),xlim=c(0,1),ylab=\"\",xlab=\"\", frame.plot = FALSE )\n yaxs=seq(.3,round(1.2*max(dat$q),digits=1),.2)\n }\n points(x=rep(dat$p,each=nrow(dat$q)),y=dat$q[,\"cor\",],pch=4,col=\"green3\",lwd=2)\n use=(1-dat$p)>.01 # only plot if more than 2% corrects\n points(x=rep(1-dat$p[use],each=nrow(dat$q[,,use])),y=dat$q[,\"err\",use],pch=4,col=\"red2\",lwd=2)\n}\n\n", "meta": {"hexsha": "a8320642d2a12fca831e33a8eb6f0e47c01544f5", "size": 58942, "ext": "r", "lang": "R", "max_stars_repo_path": "chartr-HelperFunctions.r", "max_stars_repo_name": "mailchand/CHaRTr", "max_stars_repo_head_hexsha": "ba0f581b281ee531494e89be729831c5ce802152", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2019-04-13T12:39:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T00:52:57.000Z", "max_issues_repo_path": "chartr-HelperFunctions.r", "max_issues_repo_name": "mailchand/CHaRTr", "max_issues_repo_head_hexsha": "ba0f581b281ee531494e89be729831c5ce802152", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-03-05T00:10:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T14:19:43.000Z", "max_forks_repo_path": "chartr-HelperFunctions.r", "max_forks_repo_name": "mailchand/CHaRTr", "max_forks_repo_head_hexsha": "ba0f581b281ee531494e89be729831c5ce802152", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-31T14:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-30T20:40:36.000Z", "avg_line_length": 41.8622159091, "max_line_length": 166, "alphanum_fraction": 0.5466390689, "num_tokens": 17855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04535257555434332, "lm_q1q2_score": 0.02267628777717166}} {"text": "\n\n\n\n\n\n\n CHAPTER 16\n\n\n The LISP Editor\n\n\n\n\n\n\n\n 16.1. The Editors\n\n It is quite possible to use VI, Emacs or other stan-\n dard editors to edit your lisp programs, and many peo-\n ple do just that. However there is a lisp structure\n editor which is particularly good for the editing of\n lisp programs, and operates in a rather different\n fashion, namely within a lisp environment. applica-\n tion. It is handy to know how to use it for fixing\n problems without exiting from the lisp system (e.g.\n from the debugger so you can continue to execute\n rather than having to start over.) The editor is not\n quite like the top-level and debugger, in that it\n expects you to type editor commands to it. It will\n not evaluate whatever you happen to type. (There is\n an editor command to evaluate things, though.)\n\n The editor is available (assuming your system is set\n up correctly with a lisp library) by typing (load\n 'cmufncs) and (load 'cmuedit).\n\n The most frequent use of the editor is to change\n function definitions by starting the editor with one\n of the commands described in section 16.14. (see\n _\be_\bd_\bi_\bt_\bf), values (_\be_\bd_\bi_\bt_\bv), properties (_\be_\bd_\bi_\bt_\bp), and\n expressions (_\be_\bd_\bi_\bt_\be). The beginner is advised to\n start with the following (very basic) commands: _\bo_\bk,\n _\bu_\bn_\bd_\bo, _\bp, #, under which are explained two different\n basic commands which start with numbers, and f.\n\n This documentation, and the editor, were imported from\n PDP-10 CMULisp by Don Cohen. PDP-10 CMULisp is based\n on UCILisp, and the editor itself was derived from an\n early version of Interlisp. Lars Ericson, the author\n of this section, has provided this very concise sum-\n mary. Tutorial examples and implementation details\n may be found in the Interlisp Reference Manual, where\n a similar editor is described.\n\n\n\n\u001b9\n\n\u001b9The LISP Editor 16-1\n\n\n\n\n\n\n\nThe LISP Editor 16-2\n\n\n 16.2. Scope of Attention\n\n Attention-changing commands allow you to look at a\n different part of a Lisp expression you are editing.\n The sub-structure upon which the editor's attention is\n centered is called \"the current expression\". Chang-\n ing the current expression means shifting attention\n and not actually modifying any structure.\n\n____________________________________________________________\n\n_\bS_\bC_\bO_\bP_\bE _\bO_\bF _\bA_\bT_\bT_\bE_\bN_\bT_\bI_\bO_\bN _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\bn (_\bn>_\b0) . Makes the nth element of the current expression be\nthe new current expression.\n\n-_\bn (_\bn>_\b0). Makes the nth element from the end of the current\nexpression be the new current expression.\n\n_\b0. Makes the next higher expression be the new correct\nexpression. If the intention is to go back to the next\nhigher left parenthesis, use the command !0.\n\n_\bu_\bp . If a p command would cause the editor to type ...\nbefore typing the current expression, (the current expres-\nsion is a tail of the next higher expression) then has no\neffect; else, up makes the old current expression the first\nelement in the new current expression.\n\n!_\b0 . Goes back to the next higher left parenthesis.\n\n^ . Makes the top level expression be the current expres-\nsion.\n\n_\bn_\bx . Makes the current expression be the next expression.\n\n(_\bn_\bx _\bn) equivalent to n nx commands.\n\n!_\bn_\bx . Makes current expression be the next expression at a\nhigher level. Goes through any number of right parentheses\nto get to the next expression.\n\n _\bb_\bk . Makes the current expression be the previous expres-\nsion in the next higher expression.\n\n(_\bn_\bt_\bh _\bn) _\bn>_\b0 . Makes the list starting with the nth element\nof the current expression be the current expression.\n\n(_\bn_\bt_\bh $) - _\bg_\be_\bn_\be_\br_\ba_\bl_\bi_\bz_\be_\bd _\bn_\bt_\bh _\bc_\bo_\bm_\bm_\ba_\bn_\bd. nth locates $, and then\nbacks up to the current level, where the new current expres-\nsion is the tail whose first element contains, however dee-\nply, the expression that was the terminus of the location\noperation.\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-3\n\n\n:: . (pattern :: . $) e.g., (cond :: return). finds a\ncond that contains a return, at any depth.\n\n(_\bb_\be_\bl_\bo_\bw _\bc_\bo_\bm _\bx) . The below command is useful for locating a\nsubstructure by specifying something it contains. (below\ncond) will cause the cond clause containing the current\nexpression to become the new current expression. Suppose\nyou are editing a list of lists, and want to find a sublist\nthat contains a foo (at any depth). Then simply executes f\nfoo (below ).\n\n(_\bn_\be_\bx _\bx) . same as (_\bb_\be_\bl_\bo_\bw _\bx) followed by nx. For example,\nif you are deep inside of a selectq clause, you can advance\nto the next clause with (_\bn_\be_\bx _\bs_\be_\bl_\be_\bc_\bt_\bq).\n\n_\bn_\be_\bx. The atomic form of _\bn_\be_\bx is useful if you will be\nperforming repeated executions of (_\bn_\be_\bx _\bx). By simply\nmarking the chain corresponding to x, you can use _\bn_\be_\bx to\nstep through the sublists.\n____________________________________________________________\n\n\n\n\n\n 16.3. Pattern Matching Commands\n\n Many editor commands that search take patterns. A\n pattern _\bp_\ba_\bt matches with x if:\n\n____________________________________________________________\n\n_\bP_\bA_\bT_\bT_\bE_\bR_\bN _\bS_\bP_\bE_\bC_\bI_\bF_\bI_\bC_\bA_\bT_\bI_\bO_\bN _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n- _\bp_\ba_\bt is _\be_\bq to x.\n\n- _\bp_\ba_\bt is &.\n\n- _\bp_\ba_\bt is a number and equal to x.\n\n- if (car _\bp_\ba_\bt) is the atom *any*, (cdr _\bp_\ba_\bt) is a list of\npatterns, and _\bp_\ba_\bt matches x if and only if one of the pat-\nterns on (cdr _\bp_\ba_\bt) matches x.\n\n- if _\bp_\ba_\bt is a literal atom or string, and (nthchar _\bp_\ba_\bt -1)\nis @, then _\bp_\ba_\bt matches with any literal atom or string which\nhas the same initial characters as _\bp_\ba_\bt, e.g. ver@ matches\nwith verylongatom, as well as \"verylongstring\".\n\n- if (car _\bp_\ba_\bt) is the atom --, _\bp_\ba_\bt matches x if (a) (cdr\n_\bp_\ba_\bt)=nil, i.e. _\bp_\ba_\bt=(--), e.g., (a --) matches (a) (a b c)\nand (a . b) in other words, -- can match any tail of a\nlist. (b) (cdr _\bp_\ba_\bt) matches with some tail of x, e.g. (a\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-4\n\n\n-- (&)) will match with (a b c (d)), but not (a b c d), or\n(a b c (d) e). however, note that (a -- (&) --) will match\nwith (a b c (d) e). in other words, -- will match any inte-\nrior segment of a list.\n\n- if (car _\bp_\ba_\bt) is the atom ==, _\bp_\ba_\bt matches x if and only if\n(cdr _\bp_\ba_\bt) is _\be_\bq to x. (this pattern is for use by programs\nthat call the editor as a subroutine, since any non-atomic\nexpression in a command typed in by the user obviously can-\nnot be _\be_\bq to existing structure.) - otherwise if x is a\nlist, _\bp_\ba_\bt matches x if (car _\bp_\ba_\bt) matches (car x), and (cdr\n_\bp_\ba_\bt) matches (cdr x).\n\n- when searching, the pattern matching routine is called\nonly to match with elements in the structure, unless the\npattern begins with :::, in which case cdr of the pattern is\nmatched against tails in the structure. (in this case, the\ntail does not have to be a proper tail, e.g. (::: a --)\nwill match with the element (a b c) as well as with cdr of\n(x a b c), since (a b c) is a tail of (a b c).)\n____________________________________________________________\n\n\n\n\n\n 16.3.1. Commands That Search\n\n____________________________________________________________\n\n_\bS_\bE_\bA_\bR_\bC_\bH _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn . f informs the editor that the next command is\nto be interpreted as a pattern. If no pattern is given on\nthe same line as the f then the last pattern is used. f\npattern means find the next instance of pattern.\n\n(_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn _\bn). Finds the next instance of pattern.\n\n(_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn _\bt). similar to f pattern, except, for example,\nif the current expression is (cond ..), f cond will look for\nthe next cond, but (f cond t) will 'stay here'.\n\n(_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn _\bn) _\bn>_\b0. Finds the nth place that pattern\nmatches. If the current expression is (foo1 foo2 foo3), (f\nf00@ 3) will find foo3.\n\n(_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn) _\bo_\br (_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn _\bn_\bi_\bl). only matches with elements\nat the top level of the current expression. If the current\nexpression is (_\bp_\br_\bo_\bg _\bn_\bi_\bl (_\bs_\be_\bt_\bq _\bx (_\bc_\bo_\bn_\bd & &)) (_\bc_\bo_\bn_\bd &) ...) f\n(cond --) will find the cond inside the setq, whereas (f\n(cond --)) will find the top level cond, i.e., the second\none.\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-5\n\n\n(_\bs_\be_\bc_\bo_\bn_\bd . $) . same as (lc . $) followed by another (lc .\n$) except that if the first succeeds and second fails, no\nchange is made to the edit chain.\n\n(_\bt_\bh_\bi_\br_\bd . $) . Similar to second.\n\n(_\bf_\bs _\bp_\ba_\bt_\bt_\be_\br_\bn_\b1 ... _\bp_\ba_\bt_\bt_\be_\br_\bn_\bn) . equivalent to f pattern1 fol-\nlowed by f pattern2 ... followed by f pattern n, so that if\nf pattern m fails, edit chain is left at place pattern m-1\nmatched.\n\n(_\bf= _\be_\bx_\bp_\br_\be_\bs_\bs_\bi_\bo_\bn _\bx) . Searches for a structure eq to expres-\nsion.\n\n(_\bo_\br_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn_\b1 ... _\bp_\ba_\bt_\bt_\be_\br_\bn_\bn) . Searches for an expression\nthat is matched by either pattern1 or ... patternn.\n\n_\bb_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn . backwards find. If the current expression is\n(_\bp_\br_\bo_\bg _\bn_\bi_\bl (_\bs_\be_\bt_\bq _\bx (_\bs_\be_\bt_\bq _\by (_\bl_\bi_\bs_\bt _\bz))) (_\bc_\bo_\bn_\bd ((_\bs_\be_\bt_\bq _\bw --) --))\n--) f list followed by bf setq will leave the current\nexpression as (setq y (list z)), as will f cond followed by\nbf setq\n\n(_\bb_\bf _\bp_\ba_\bt_\bt_\be_\br_\bn _\bt). backwards find. Search always includes\ncurrent expression, i.e., starts at end of current expres-\nsion and works backward, then ascends and backs up, etc.\n____________________________________________________________\n\n\n\n\n\n 16.3.1.1. Location Specifications Many editor\n commands use a method of specifying position\n called a location specification. The meta-\n symbol $ is used to denote a location specifica-\n tion. $ is a list of commands interpreted as\n described above. $ can also be atomic, in which\n case it is interpreted as (list $). a location\n specification is a list of edit commands that\n are executed in the normal fashion with two\n exceptions. first, all commands not recognized\n by the editor are interpreted as though they had\n been preceded by f. The location specification\n (cond 2 3) specifies the 3rd element in the\n first clause of the next cond.\n\n the if command and the ## function provide a way\n of using in location specifications arbitrary\n predicates applied to elements in the current\n expression.\n\n In insert, delete, replace and change, if $ is\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-6\n\n\n nil (empty), the corresponding operation is per-\n formed on the current edit chain, i.e. (replace\n with (car x)) is equivalent to (:(car x)). for\n added readability, here is also permitted, e.g.,\n (insert (print x) before here) will insert\n (print x) before the current expression (but not\n change the edit chain). It is perfectly legal\n to ascend to insert, replace, or delete. for\n example (insert (_\br_\be_\bt_\bu_\br_\bn) after ^ prog -1) will\n go to the top, find the first prog, and insert a\n (_\br_\be_\bt_\bu_\br_\bn) at its end, and not change the current\n edit chain.\n\n The a, b, and : commands all make special\n checks in e1 thru em for expressions of the form\n (## . coms). In this case, the expression used\n for inserting or replacing is a copy of the\n current expression after executing coms, a list\n of edit commands. (insert (## f cond -1 -1)\n after3) will make a copy of the last form in\n the last clause of the next cond, and insert it\n after the third element of the current expres-\n sion.\n\n $. In descriptions of the editor, the meta-\n symbol $ is used to denote a location specifica-\n tion. $ is a list of commands interpreted as\n described above. $ can also be atomic.\n\n____________________________________________________________\n\n_\bL_\bO_\bC_\bA_\bT_\bI_\bO_\bN _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n(_\bl_\bc . $) . Provides a way of explicitly invoking the loca-\ntion operation. (lc cond 2 3) will perform search.\n\n(_\bl_\bc_\bl . $) . Same as lc except search is confined to current\nexpression. To find a cond containing a _\br_\be_\bt_\bu_\br_\bn, one might\nuse the location specification (cond (lcl _\br_\be_\bt_\bu_\br_\bn) ) where\nthe would reverse the effects of the lcl command, and make\nthe final current expression be the cond.\n____________________________________________________________\n\n\n\n\n\n 16.3.2. The Edit Chain The edit-chain is a list of\n which the first element is the the one you are now\n editing (\"current expression\"), the next element is\n what would become the current expression if you\n were to do a 0, etc., until the last element which\n is the expression that was passed to the editor.\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-7\n\n\n____________________________________________________________\n\n_\bE_\bD_\bI_\bT _\bC_\bH_\bA_\bI_\bN _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\bm_\ba_\br_\bk . Adds the current edit chain to the front of the list\nmarklst.\n\n_ . Makes the new edit chain be (car marklst).\n\n(_ _\bp_\ba_\bt_\bt_\be_\br_\bn) . Ascends the edit chain looking for a link\nwhich matches pattern. for example:\n\n__ . Similar to _ but also erases the mark.\n\n\\ . Makes the edit chain be the value of unfind. unfind is\nset to the current edit chain by each command that makes a\n\"big jump\", i.e., a command that usually performs more than\na single ascent or descent, namely ^, _, __, !nx, all com-\nmands that involve a search, e.g., f, lc, ::, below, et al\nand and themselves.\nif the user types f cond, and then f car, would take him\nback to the cond. another would take him back to the car,\netc.\n\n\\_\bp . Restores the edit chain to its state as of the last\nprint operation. If the edit chain has not changed since\nthe last printing, \\p restores it to its state as of the\nprinting before that one. If the user types p followed by 3\n2 1 p, \\p will return to the first p, i.e., would be\nequivalent to 0 0 0. Another \\p would then take him back to\nthe second p.\n____________________________________________________________\n\n\n\n\n\n 16.4. Printing Commands\n\n____________________________________________________________\n\n_\bP_\bR_\bI_\bN_\bT_\bI_\bN_\bG _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\bp Prints current expression in abbreviated form. (p m)\nprints mth element of current expression in abbreviated\nform. (p m n) prints mth element of current expression as\nthough printlev were given a depth of n. (p 0 n) prints\ncurrent expression as though printlev were given a depth of\nn. (p cond 3) will work.\n\n? . prints the current expression as though printlev were\ngiven a depth of 100.\n\u001b9\n\n\u001b9 Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-8\n\n\n_\bp_\bp . pretty-prints the current expression.\n\n_\bp_\bp*. is like pp, but forces comments to be shown.\n____________________________________________________________\n\n\n\n\n\n 16.5. Structure Modification Commands\n\n All structure modification commands are undoable. See\n _\bu_\bn_\bd_\bo.\n\n\n____________________________________________________________\n\n_\bS_\bT_\bR_\bU_\bC_\bT_\bU_\bR_\bE _\bM_\bO_\bD_\bI_\bF_\bI_\bC_\bA_\bT_\bI_\bO_\bN _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n# [_\be_\bd_\bi_\bt_\bo_\br _\bc_\bo_\bm_\bm_\ba_\bn_\bd_\bs] (n) n>1 deletes the corresponding ele-\nment from the current expression.\n\n(_\bn _\be_\b1 ... _\be_\bm) _\bn,_\bm>_\b1 replaces the nth element in the current\nexpression with e1 ... em.\n\n(-_\bn _\be_\b1 ... _\be_\bm) _\bn,_\bm>_\b1 inserts e1 ... em before the n ele-\nment in the current expression.\n\n(_\bn _\be_\b1 ... _\be_\bm) (the letter \"n\" for \"next\" or \"nconc\", not a\nnumber) m>1 attaches e1 ... em at the end of the current\nexpression.\n\n(_\ba _\be_\b1 ... _\be_\bm) . inserts e1 ... em after the current\nexpression (or after its first element if it is a tail).\n\n(_\bb _\be_\b1 ... _\be_\bm) . inserts e1 ... em before the current\nexpression. to insert foo before the last element in the\ncurrent expression, perform -1 and then (b foo).\n\n(: _\be_\b1 ... _\be_\bm) . replaces the current expression by e1 ...\nem. If the current expression is a tail then replace its\nfirst element.\n\n_\bd_\be_\bl_\be_\bt_\be _\bo_\br (:) . deletes the current expression, or if the\ncurrent expression is a tail, deletes its first element.\n\n(_\bd_\be_\bl_\be_\bt_\be . $). does a (lc . $) followed by delete. current\nedit chain is not changed.\n\n(_\bi_\bn_\bs_\be_\br_\bt _\be_\b1 ... _\be_\bm _\bb_\be_\bf_\bo_\br_\be . $) . similar to (lc. $) fol-\nlowed by (b e1 ... em).\n\n(_\bi_\bn_\bs_\be_\br_\bt _\be_\b1 ... _\be_\bm _\ba_\bf_\bt_\be_\br . $). similar to insert before\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-9\n\n\nexcept uses a instead of b.\n\n(_\bi_\bn_\bs_\be_\br_\bt _\be_\b1 ... _\be_\bm _\bf_\bo_\br . $). similar to insert before\nexcept uses : for b.\n\n(_\br_\be_\bp_\bl_\ba_\bc_\be $ _\bw_\bi_\bt_\bh _\be_\b1 ... _\be_\bm) . here $ is the segment of the\ncommand between replace and with.\n\n(_\bc_\bh_\ba_\bn_\bg_\be $ _\bt_\bo _\be_\b1 ... _\be_\bm) . same as replace with.\n____________________________________________________________\n\n\n\n\n\n 16.6. Extraction and Embedding Commands\n\n____________________________________________________________\n\n_\bE_\bX_\bT_\bR_\bA_\bC_\bT_\bI_\bO_\bN _\bA_\bN_\bD _\bE_\bM_\bB_\bE_\bD_\bD_\bI_\bN_\bG _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n(_\bx_\bt_\br . $) . replaces the original current expression with\nthe expression that is current after performing (lcl . $).\n\n(_\bm_\bb_\bd _\bx) . x is a list, substitutes the current expression\nfor all instances of the atom * in x, and replaces the\ncurrent expression with the result of that substitution.\n(mbd x) : x atomic, same as (mbd (x *)).\n\n(_\be_\bx_\bt_\br_\ba_\bc_\bt $_\b1 _\bf_\br_\bo_\bm $_\b2) . extract is an editor command which\nreplaces the current expression with one of its subexpres-\nsions (from any depth). ($1 is the segment between extract\nand from.) example: if the current expression is (print\n(cond ((null x) y) (t z))) then following (extract y from\ncond), the current expression will be (print y). (extract 2\n-1 from cond), (extract y from 2), (extract 2 -1 from 2)\nwill all produce the same result.\n\n(_\be_\bm_\bb_\be_\bd $ _\bi_\bn . _\bx) . embed replaces the current expression\nwith a new expression which contains it as a subexpression.\n($ is the segment between embed and in.) example: (embed\nprint in setq x), (embed 3 2 in _\br_\be_\bt_\bu_\br_\bn), (embed cond 3 1 in\n(or * (null x))).\n____________________________________________________________\n\n\n\n\n\n 16.7. Move and Copy Commands\n\n\n\u001b9\n\n\u001b9 Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-10\n\n\n____________________________________________________________\n\n_\bM_\bO_\bV_\bE _\bA_\bN_\bD _\bC_\bO_\bP_\bY _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n(_\bm_\bo_\bv_\be $_\b1 _\bt_\bo _\bc_\bo_\bm . $_\b2) . ($1 is the segment between move and\nto.) where com is before, after, or the name of a list com-\nmand, e.g., :, n, etc. If $2 is nil, or (here), the current\nposition specifies where the operation is to take place. If\n$1 is nil, the move command allows the user to specify some\nplace the current expression is to be moved to. if the\ncurrent expression is (a b d c), (move 2 to after 4) will\nmake the new current expression be (a c d b).\n\n(_\bm_\bv _\bc_\bo_\bm . $) . is the same as (move here to com . $).\n\n(_\bc_\bo_\bp_\by $_\b1 _\bt_\bo _\bc_\bo_\bm . $_\b2) is like move except that the source\nexpression is not deleted.\n\n(_\bc_\bp _\bc_\bo_\bm . $). is like mv except that the source expression\nis not deleted.\n____________________________________________________________\n\n\n\n\n\n 16.8. Parentheses Moving Commands The commands\n presented in this section permit modification of the\n list structure itself, as opposed to modifying com-\n ponents thereof. their effect can be described as\n inserting or removing a single left or right\n parenthesis, or pair of left and right parentheses.\n\n____________________________________________________________\n\n_\bP_\bA_\bR_\bE_\bN_\bT_\bH_\bE_\bS_\bE_\bS _\bM_\bO_\bV_\bI_\bN_\bG _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n(_\bb_\bi _\bn _\bm) . both in. inserts parentheses before the nth\nelement and after the mth element in the current expression.\nexample: if the current expression is (a b (c d e) f g),\nthen (bi 2 4) will modify it to be (a (b (c d e) f) g). (bi\nn) : same as (bi n n). example: if the current expression\nis (a b (c d e) f g), then (bi -2) will modify it to be (a b\n(c d e) (f) g).\n\n(_\bb_\bo _\bn) . both out. removes both parentheses from the nth\nelement. example: if the current expression is (a b (c d\ne) f g), then (bo d) will modify it to be (a b c d e f g).\n\n(_\bl_\bi _\bn) . left in. inserts a left parenthesis before the\nnth element (and a matching right parenthesis at the end of\nthe current expression). example: if the current expres-\nsion is (a b (c d e) f g), then (li 2) will modify it to be\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-11\n\n\n(a (b (c d e) f g)).\n\n(_\bl_\bo _\bn) . left out. removes a left parenthesis from the\nnth element. all elements following the nth element are\ndeleted. example: if the current expression is (a b (c d e)\nf g), then (lo 3) will modify it to be (a b c d e).\n\n(_\br_\bi _\bn _\bm) . right in. move the right parenthesis at the\nend of the nth element in to after the mth element. inserts\na right parenthesis after the mth element of the nth ele-\nment. The rest of the nth element is brought up to the\nlevel of the current expression. example: if the current\nexpression is (a (b c d e) f g), (ri 2 2) will modify it to\nbe (a (b c) d e f g).\n\n(_\br_\bo _\bn) . right out. move the right parenthesis at the end\nof the nth element out to the end of the current expres-\nsion. removes the right parenthesis from the nth element,\nmoving it to the end of the current expression. all elements\nfollowing the nth element are moved inside of the nth\nelement. example: if the current expression is (a b (c d e)\nf g), (ro 3) will modify it to be (a b (c d e f g)).\n\n(_\br _\bx _\by) replaces all instances of x by y in the current\nexpression, e.g., (r caadr cadar). x can be the s-\nexpression (or atom) to be substituted for, or can be a pat-\ntern which specifies that s-expression (or atom).\n\n(_\bs_\bw _\bn _\bm) switches the nth and mth elements of the current\nexpression. for example, if the current expression is (list\n(cons (car x) (car y)) (cons (cdr y))), (sw 2 3) will\nmodify it to be (list (cons (cdr x) (cdr y)) (cons (car x)\n(car y))). (sw car cdr) would produce the same result.\n____________________________________________________________\n\n\n\n\n\n 16.8.1. Using to and thru\n\n to, thru, extract, embed, delete, replace, and move\n can be made to operate on several contiguous ele-\n ments, i.e., a segment of a list, by using the to\n or thru command in their respective location\n specifications. thru and to are intended to be\n used in conjunction with extract, embed, delete,\n replace, and move. to and thru can also be used\n directly with xtr (which takes after a location\n specification), as in (xtr (2 thru 4)) (from the\n current expression).\n\n\u001b9\n\n\u001b9 Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-12\n\n\n____________________________________________________________\n\n_\bT_\bO _\bA_\bN_\bD _\bT_\bH_\bR_\bU _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n($_\b1 _\bt_\bo $_\b2) . same as thru except last element not\nincluded.\n\n($_\b1 _\bt_\bo). same as ($1 thru -1)\n\n($_\b1 _\bt_\bh_\br_\bu $_\b2) . If the current expression is (a (b (c d)\n(e) (f g h) i) j k), following (c thru g), the current\nexpression will be ((c d) (e) (f g h)). If both $1 and $2\nare numbers, and $2 is greater than $1, then $2 counts from\nthe beginning of the current expression, the same as $1. in\nother words, if the current expression is (a b c d e f g),\n(3 thru 4) means (c thru d), not (c thru f). in this case,\nthe corresponding bi command is (bi 1 $2-$1+1).\n\n($_\b1 _\bt_\bh_\br_\bu). same as ($_\b1 _\bt_\bh_\br_\bu -_\b1).\n____________________________________________________________\n\n\n\n\n\n 16.9. Undoing Commands each command that causes struc-\n ture modification automatically adds an entry to the\n front of undolst containing the information required\n to restore all pointers that were changed by the com-\n mand. The undo command undoes the last, i.e., most\n recent such command.\n\n____________________________________________________________\n\n_\bU_\bN_\bD_\bO _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\bu_\bn_\bd_\bo . the undo command undoes most recent, structure\nmodification command that has not yet been undone, and\nprints the name of that command, e.g., mbd undone. The edit\nchain is then exactly what it was before the 'undone' com-\nmand had been performed.\n\n!_\bu_\bn_\bd_\bo . undoes all modifications performed during this\nediting session, i.e., this call to the editor.\n\n_\bu_\bn_\bb_\bl_\bo_\bc_\bk . removes an undo-block. If executed at a non-\nblocked state, i.e., if undo or !undo could operate, types\nnot blocked.\n\n_\bt_\be_\bs_\bt . adds an undo-block at the front of undolst. note\nthat test together with !undo provide a 'tentative'\nmode for editing, i.e., the user can perform a number of\nchanges, and then undo all of them with a single !undo\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-13\n\n\ncommand.\n\n_\bu_\bn_\bd_\bo_\bl_\bs_\bt [_\bv_\ba_\bl_\bu_\be]. each editor command that causes structure\nmodification automatically adds an entry to the front of\nundolst containing the information required to restore all\npointers that were changed by the command.\n\n?? prints the entries on undolst. The entries are listed\nmost recent entry first.\n____________________________________________________________\n\n\n\n\n\n 16.10. Commands that Evaluate\n\n____________________________________________________________\n\n_\bE_\bV_\bA_\bL_\bU_\bA_\bT_\bI_\bO_\bN _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\be . only when typed in, (i.e., (insert d before e) will\ntreat e as a pattern) causes the editor to call the\nlisp interpreter giving it the next input as argument.\n\n(_\be _\bx) evaluates x, and prints the result. (e x t) same\nas (e x) but does not print.\n\n(_\bi _\bc _\bx_\b1 ... _\bx_\bn) same as (c y1 ... yn) where yi=(eval xi).\nexample: (i 3 (cdr foo)) will replace the 3rd element of\nthe current expression with the cdr of the value of foo. (i\nn foo (car fie)) will attach the value of foo and car of the\nvalue of fie to the end of the current expression. (i f=\nfoo t) will search for an expression eq to the value of foo.\nIf c is not an atom, it is evaluated as well.\n\n(_\bc_\bo_\bm_\bs _\bx_\b1 ... _\bx_\bn) . each xi is evaluated and its value\nexecuted as a command. The i command is not very convenient\nfor computing an entire edit command for execution, since\nit computes the command name and its arguments separately.\nalso, the i command cannot be used to compute an atomic\ncommand. The coms and comsq commands provide more gen-\neral ways of computing commands. (coms (cond (x (list 1\nx)))) will replace the first element of the current expres-\nsion with the value of x if non-nil, otherwise do nothing.\n(nil as a command is a nop.)\n\n(_\bc_\bo_\bm_\bs_\bq _\bc_\bo_\bm_\b1 ... _\bc_\bo_\bm_\bn) . executes com1 ... comn. comsq is\nmainly useful in conjunction with the coms command. for\nexample, suppose the user wishes to compute an entire list\nof commands for evaluation, as opposed to computing each\ncommand one at a time as does the coms command. he would\nthen write (coms (cons (quote comsq) x)) where x computed\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-14\n\n\nthe list of commands, e.g., (coms (cons (quote comsq)\n(get foo (quote commands))))\n____________________________________________________________\n\n\n\n\n\n 16.11. Commands that Test\n\n____________________________________________________________\n\n_\bT_\bE_\bS_\bT_\bI_\bN_\bG _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n(_\bi_\bf _\bx) generates an error unless the value of (eval x) is\nnon-nil, i.e., if (eval x) causes an error or (eval x)=nil,\nif will cause an error. (if x coms1 coms2) if (eval x) is\nnon-nil, execute coms1; if (eval x) causes an error or is\nequal to nil, execute coms2. (if x coms1) if (eval x)\nis non-nil, execute coms1; otherwise generate an error.\n\n(_\bl_\bp . _\bc_\bo_\bm_\bs) . repeatedly executes coms, a list of commands,\nuntil an error occurs. (lp f print (n t)) will\nattach a t at the end of every print expression. (lp f\nprint (if (## 3) nil ((n t)))) will attach a t at the end\nof each print expression which does not already have a\nsecond argument. (i.e. the form (## 3) will cause an\nerror if the edit command 3 causes an error, thereby select-\ning ((n t)) as the list of commands to be executed. The if\ncould also be written as (if (cddr (##)) nil ((n t))).).\n\n(_\bl_\bp_\bq . _\bc_\bo_\bm_\bs) same as lp but does not print n occurrences.\n\n(_\bo_\br_\br _\bc_\bo_\bm_\bs_\b1 ... _\bc_\bo_\bm_\bs_\bn) . orr begins by executing coms1, a\nlist of commands. If no error occurs, orr is finished.\notherwise, orr restores the edit chain to its original\nvalue, and continues by executing coms2, etc. If none of\nthe command lists execute without errors, i.e., the orr\n\"drops off the end\", orr generates an error. otherwise, the\nedit chain is left as of the completion of the first command\nlist which executes without error.\n____________________________________________________________\n\n\n\n\n\n 16.12. Editor Macros\n\n Many of the more sophisticated branching commands in\n the editor, such as orr, if, etc., are most often\n used in conjunction with edit macros. The macro\n feature permits the user to define new commands and\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-15\n\n\n thereby expand the editor's repertoire. (however,\n built in commands always take precedence over mac-\n ros, i.e., the editor's repertoire can be expanded,\n but not modified.) macros are defined by using the m\n command.\n\n (_\bm _\bc . _\bc_\bo_\bm_\bs) for c an atom, m defines c as an atomic\n command. (if a macro is redefined, its new defini-\n tion replaces its old.) executing c is then the same\n as executing the list of commands coms. macros\n can also define list commands, i.e., commands that\n take arguments. (m (c) (arg[1] ... arg[n]) . coms) c\n an atom. m defines c as a list command. executing (c\n e1 ... en) is then performed by substituting e1\n for arg[1], ... en for arg[n] throughout coms,\n and then executing coms. a list command can be\n defined via a macro so as to take a fixed or\n indefinite number of 'arguments'. The form given\n above specified a macro with a fixed number of argu-\n ments, as indicated by its argument list. if the of\n arguments. (m (c) args . coms) c, args both atoms,\n defines c as a list command. executing (c e1 ...\n en) is performed by substituting (e1 ... en), i.e.,\n cdr of the command, for args throughout coms, and then\n executing coms.\n\n (m bp bk up p) will define bp as an atomic command\n which does three things, a bk, an up, and a p. note\n that macros can use commands defined by macros as well\n as built in commands in their definitions. for\n example, suppose z is defined by (m z -1 (if (null\n (##)) nil (p))), i.e. z does a -1, and then if the\n current expression is not nil, a p. now we can define\n zz by (m zz -1 z), and zzz by (m zzz -1 -1 z) or (m\n zzz -1 zz). we could define a more general bp by (m\n (bp) (n) (bk n) up p). (bp 3) would perform (bk\n 3), followed by an up, followed by a p. The com-\n mand second can be defined as a macro by (m (2nd) x\n (orr ((lc . x) (lc . x)))).\n\n Note that for all editor commands, 'built in' com-\n mands as well as commands defined by macros, atomic\n definitions and list definitions are completely\n independent. in other words, the existence of an\n atomic definition for c in no way affects the treat-\n ment of c when it appears as car of a list command,\n and the existence of a list definition for c in no way\n affects the treatment of c when it appears as an\n atom. in particular, c can be used as the name of\n either an atomic command, or a list command, or both.\n in the latter case, two entirely different defini-\n tions can be used. note also that once c is\n defined as an atomic command via a macro definition,\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-16\n\n\n it will not be searched for when used in a location\n specification, unless c is preceded by an f. (insert\n -- before bp) would not search for bp, but instead\n perform a bk, an up, and a p, and then do the inser-\n tion. The corresponding also holds true for list com-\n mands.\n\n (_\bb_\bi_\bn_\bd . _\bc_\bo_\bm_\bs) bind is an edit command which is\n useful mainly in macros. it binds three dummy vari-\n ables #1, #2, #3, (initialized to nil), and then exe-\n cutes the edit commands coms. note that these\n bindings are only in effect while the commands are\n being executed, and that bind can be used recursively;\n it will rebind #1, #2, and #3 each time it is\n invoked.\n\n _\bu_\bs_\be_\br_\bm_\ba_\bc_\br_\bo_\bs [_\bv_\ba_\bl_\bu_\be]. this variable contains the\n users editing macros . if you want to save your mac-\n ros then you should save usermacros. you should\n probably also save editcomsl.\n\n _\be_\bd_\bi_\bt_\bc_\bo_\bm_\bs_\bl [_\bv_\ba_\bl_\bu_\be]. editcomsl is the list of \"list\n commands\" recognized by the editor. (these are the\n ones of the form (command arg1 arg2 ...).)\n\n\n\n\n 16.13. Miscellaneous Editor Commands\n\n____________________________________________________________\n\n_\bM_\bI_\bS_\bC_\bE_\bL_\bL_\bA_\bN_\bE_\bO_\bU_\bS _\bE_\bD_\bI_\bT_\bO_\bR _\bC_\bO_\bM_\bM_\bA_\bN_\bD _\bS_\bU_\bM_\bM_\bA_\bR_\bY\n\n_\bo_\bk . Exits from the editor.\n\n_\bn_\bi_\bl . Unless preceded by f or bf, is always a null opera-\ntion.\n\n_\bt_\bt_\by: . Calls the editor recursively. The user can then\ntype in commands, and have them executed. The tty: command\nis completed when the user exits from the lower editor\n(with ok or stop). the tty: command is extremely use-\nful. it enables the user to set up a complex operation,\nand perform interactive attention-changing commands part\nway through it. for example the command (move 3 to after\ncond 3 p tty:) allows the user to interact, in effect,\nwithin the move command. he can verify for himself\nthat the correct location has been found, or complete the\nspecification \"by hand\". in effect, tty: says \"I'll tell you\nwhat you should do when you get there.\"\n\n_\bs_\bt_\bo_\bp . exits from the editor with an error. mainly for use\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-17\n\n\nin conjunction with tty: commands that the user wants to\nabort. since all of the commands in the editor are errset\nprotected, the user must exit from the editor via a command.\nstop provides a way of distinguishing between a successful\nand unsuccessful (from the user's standpoint) editing ses-\nsion.\n\n_\bt_\bl . tl calls (top-level). to return to the editor just\nuse the _\br_\be_\bt_\bu_\br_\bn top-level command.\n\n_\br_\be_\bp_\ba_\bc_\bk . permits the 'editing' of an atom or string.\n\n(_\br_\be_\bp_\ba_\bc_\bk $) does (lc . $) followed by repack, e.g. (repack\nthis@).\n\n(_\bm_\ba_\bk_\be_\bf_\bn _\bf_\bo_\br_\bm _\ba_\br_\bg_\bs _\bn _\bm) . makes (car form) an expr with the\nnth through mth elements of the current expression with\neach occurrence of an element of (cdr form) replaced by\nthe corresponding element of args. The nth through mth\nelements are replaced by form.\n\n(_\bm_\ba_\bk_\be_\bf_\bn _\bf_\bo_\br_\bm _\ba_\br_\bg_\bs _\bn). same as (makefn form args n n).\n\n(_\bs _\bv_\ba_\br . $) . sets var (using setq) to the current expres-\nsion after performing (lc . $). (s foo) will set\nfoo to the current expression, (s foo -1 1) will set foo to\nthe first element in the last element of the current expres-\nsion.\n____________________________________________________________\n\n\n\n\n\n 16.14. Editor Functions\n\n\n(editf s_x1 ...)\n\n SIDE EFFECT: edits a function. s_x1 is the name of the\n function, any additional arguments are an\n optional list of commands.\n\n RETURNS: s_x1.\n\n NOTE: if s_x1 is not an editable function, editf gen-\n erates an fn not editable error.\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-18\n\n\n(edite l_expr l_coms s_atm))\nedits an expression. its value is the last element of\n(editl (list l_expr) l_coms s_atm nil nil).\n\n\n(editracefn s_com)\nis available to help the user debug complex edit macros, or\nsubroutine calls to the editor. editracefn is to be\ndefined by the user. whenever the value of editracefn is\nnon-nil, the editor calls the function editracefn\nbefore executing each command (at any level), giving it\nthat command as its argument. editracefn is initially equal\nto nil, and undefined.\n\n\n(editv s_var [ g_com1 ... ])\n\n SIDE EFFECT: similar to editf, for editing values.\n editv sets the variable to the value\n returned.\n\n RETURNS: the name of the variable whose value was\n edited.\n\n\n(editp s_x)\n\n SIDE EFFECT: similar to editf for editing property\n lists. used if x is nil.\n\n RETURNS: the atom whose property list was edited.\n\n\n(editl coms atm marklst mess)\n\n SIDE EFFECT: editl is the editor. its first argument\n is the edit chain, and its value is an\n edit chain, namely the value of l at the\n time editl is exited. (l is a special\n variable, and so can be examined or set by\n edit commands. ^ is equivalent to (e\n (setq l(last l)) t).) coms is an optional\n list of commands. for interactive edit-\n ing, coms is nil. in this case, editl\n types edit and then waits for input from\n the teletype. (if mess is not nil editl\n types it instead of edit. for example,\n the tty: command is essentially (setq l\n (editl l nil nil nil (quote tty:))).)\n exit occurs only via an ok, stop, or save\n command. If coms is not nil, no message\n is typed, and each member of coms is\n treated as a command and executed. If an\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-19\n\n\n error occurs in the execution of one of\n the commands, no error message is printed\n , the rest of the commands are ignored,\n and editl exits with an error, i.e., the\n effect is the same as though a stop com-\n mand had been executed. If all commands\n execute successfully, editl returns the\n current value of l. marklst is the list\n of marks. on calls from editf, atm is the\n name of the function being edited; on\n calls from editv, the name of the vari-\n able, and calls from editp, the atom of\n which some property of its property list\n is being edited. The property list of atm\n is used by the save command for saving the\n state of the edit. save will not save\n anything if atm=nil i.e., when editing\n arbitrary expressions via edite or editl\n directly.\n\n\n(editfns s_x [ g_coms1 ... ])\nfsubr function, used to perform the same editing operations\non several functions. editfns maps down the list of func-\ntions, prints the name of each function, and calls the edi-\ntor (via editf) on that function.\n\n EXAMPLE: editfns foofns (r fie fum)) will change every\n fie to fum in each of the functions on\n foofns.\n\n NOTE: the call to the editor is errset protected,\n so that if the editing of one function causes an\n error, editfns will proceed to the next func-\n tion. in the above example, if one of the\n functions did not contain a fie, the r command\n would cause an error, but editing would con-\n tinue with the next function. The value of\n editfns is nil.\n\n\n(edit4e pat y)\n\n SIDE EFFECT: is the pattern match routine.\n\n RETURNS: t if pat matches y. see edit-match for defini-\n tion of 'match'.\n\n NOTE: before each search operation in the editor\n begins, the entire pattern is scanned for\n atoms or strings that end in at-signs. These\n are replaced by patterns of the form (cons\n (quote /@) (explodec atom)). from the\n\n\n Printed: July 21, 1983\n\n\n\n\n\n\n\nThe LISP Editor 16-20\n\n\n standpoint of edit4e, pattern type 5, atoms or\n strings ending in at-signs, is really \"if\n car[pat] is the atom @ (at-sign), pat will match\n with any literal atom or string whose ini-\n tial character codes (up to the @) are the same\n as those in cdr[pat].\" if the user wishes to\n call edit4e directly, he must therefore convert\n any patterns which contain atoms or strings\n ending in at-signs to the form recognized by\n edit4e. this can be done via the function\n editfpat.\n\n(editfpat pat flg)\nmakes a copy of pat with all patterns of type 5 (see edit-\nmatch) converted to the form expected by edit4e. flg should\nbe passed as nil (flg=t is for internal use by the editor).\n\n\n(editfindp x pat flg)\n\n NOTE: Allows a program to use the edit find command as\n a pure predicate from outside the editor. x is\n an expression, pat a pattern. The value of edit-\n findp is t if the command f pat would succeed,\n nil otherwise. editfindp calls editfpat to con-\n vert pat to the form expected by edit4e, unless\n flg=t. if the program is applying editfindp to\n several different expressions using the same pat-\n tern, it will be more efficient to call editfpat\n once, and then call editfindp with the converted\n pattern and flg=t.\n\n\n(## g_com1 ...)\n\n RETURNS: what the current expression would be after\n executing the edit commands com1 ... starting\n from the present edit chain. generates an\n error if any of comi cause errors. The\n current edit chain is never changed. example:\n (i r (quote x) (## (cons ..z))) replaces all\n x's in the current expression by the first\n cons containing a z.\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: July 21, 1983\n\n\n\n", "meta": {"hexsha": "a24d20257d85f60334f89d90421d7cca46ea5774", "size": 46548, "ext": "r", "lang": "R", "max_stars_repo_path": "lisplib/manual/ch16.r", "max_stars_repo_name": "omasanori/franz-lisp", "max_stars_repo_head_hexsha": "64e037d26cd382c0b88e0a5dc261bd2c29191af8", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2016-11-03T05:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T06:10:55.000Z", "max_issues_repo_path": "lisplib/manual/ch16.r", "max_issues_repo_name": "omasanori/franz-lisp", "max_issues_repo_head_hexsha": "64e037d26cd382c0b88e0a5dc261bd2c29191af8", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-05-19T16:13:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T20:48:51.000Z", "max_forks_repo_path": "lisplib/manual/ch16.r", "max_forks_repo_name": "omasanori/franz-lisp", "max_forks_repo_head_hexsha": "64e037d26cd382c0b88e0a5dc261bd2c29191af8", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-11-09T16:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T20:56:43.000Z", "avg_line_length": 35.3977186312, "max_line_length": 122, "alphanum_fraction": 0.6315201512, "num_tokens": 14945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17106120013047912, "lm_q2_score": 0.12765261536566067, "lm_q1q2_score": 0.021836409584244355}} {"text": "# Day 14: Extended Polymerization\n\nget_day14_input_path <- function() {\n paste(getwd(), \"/2021/Day 14/Day14_input.txt\", sep = \"\")\n}\n\nchars <- matrix(ncol = 2)[-1, ]\n\npart1 <- function(num_steps = 10) {\n readings <- readLines(get_day14_input_path())\n\n polymer <- readings[1]\n rules <- parse_rules(readings[3:length(readings)])\n\n for (i in 1:num_steps) {\n polymer <- polymerize(polymer, rules)\n }\n\n polymer_arr <- unlist(strsplit(polymer, \"\"))\n uniq_elements <- unique(polymer_arr)\n\n highest_count <- 0\n lowest_count <- 2147483647\n\n for (e in seq_len(length(uniq_elements))) {\n sum_of_letter <- sum(polymer_arr == uniq_elements[e])\n\n if (e == 1) {\n highest_count <- sum_of_letter\n lowest_count <- sum_of_letter\n } else {\n if (sum_of_letter > highest_count) {\n highest_count <- sum_of_letter\n }\n if (sum_of_letter < lowest_count) {\n lowest_count <- sum_of_letter\n }\n }\n }\n\n print(toString(highest_count - lowest_count))\n}\n\npart2 <- function(num_steps = 40) {\n readings <- readLines(get_day14_input_path())\n\n polymer <- readings[1]\n last_char <- rev(unlist(strsplit(polymer, \"\")))[1]\n rules <- parse_rules(readings[3:length(readings)])\n\n pairs <- optimize_pairs(polymer)\n\n for (i in 1:num_steps) {\n pairs <- polymerize_arr(pairs, rules, i == num_steps)\n }\n\n chars <<- merge_set(chars, last_char, 1)\n char_sums <- sort(as.numeric(chars[, 2]), decreasing = TRUE)\n\n print(chars)\n print(toString(char_sums[1] - char_sums[length(char_sums)]))\n}\n\nparse_rules <- function(readings) {\n templates <- strsplit(readings, \" -> \")\n rules <- list()\n\n for (i in seq_len(length(templates))) {\n template <- unlist(templates[i])\n rules[[template[1]]] <- append(rules[[template[1]]], template[2])\n }\n rules\n}\n\npolymerize <- function(polymer, rules) {\n polymer_arr <- unlist(strsplit(polymer, \"\"))\n elements_to_insert <- c()\n\n for (i in seq_len(length(polymer_arr) - 1)) {\n template <- paste(polymer_arr[i], polymer_arr[i + 1], sep = \"\")\n elements_to_insert <- append(elements_to_insert, rules[[template]])\n }\n\n new_polymer_arr <- c()\n\n for (e in seq_len(length(elements_to_insert))) {\n new_polymer_arr <- append(new_polymer_arr, polymer_arr[e])\n new_polymer_arr <- append(new_polymer_arr, elements_to_insert[e])\n }\n\n new_polymer_arr <- append(new_polymer_arr, polymer_arr[length(polymer_arr)])\n paste(new_polymer_arr, collapse = \"\")\n}\n\noptimize_pairs <- function(polymer) {\n pairs <- matrix(ncol = 2)[-1, ]\n polymer_arr <- unlist(strsplit(polymer, \"\"))\n\n for (i in seq_len(length(polymer_arr) - 1)) {\n template <- paste(polymer_arr[i], polymer_arr[i + 1], sep = \"\")\n pairs <- merge_set(pairs, template, 1)\n }\n pairs\n}\n\npolymerize_arr <- function(pairs, rules, calc_chars) {\n new_pairs <- matrix(ncol = 2)[-1, ]\n\n for (i in seq_len(nrow(pairs))) {\n element_to_insert <- rules[[pairs[i, 1]]]\n\n char_arr <- unlist(strsplit(pairs[i, 1], \"\"))\n pair_arr <- char_arr\n pair_arr[1] <- paste(pair_arr[1], element_to_insert, sep = \"\")\n pair_arr[2] <- paste(element_to_insert, pair_arr[2], sep = \"\")\n\n for (p in seq_len(length(pair_arr))) {\n new_pairs <- merge_set(new_pairs, pair_arr[p], pairs[i, 2])\n }\n\n if (calc_chars) {\n chars <<- merge_set(chars, char_arr[1], pairs[i, 2])\n chars <<- merge_set(chars, element_to_insert, pairs[i, 2])\n }\n }\n new_pairs\n}\n\nmerge_set <- function(set, element, num_to_add) {\n match <- which(set[, 1] == element, arr.ind = TRUE)\n\n if (length(match) == 0) {\n set <- rbind(set, c(element, num_to_add))\n } else {\n set[match, 2] <- as.numeric(set[match, 2]) +\n as.numeric(num_to_add)\n }\n set\n}\n\npart1()\npart2()\n", "meta": {"hexsha": "5eed70b2e86d90e8eff7c02de07c91c5acc6f5d9", "size": 4015, "ext": "r", "lang": "R", "max_stars_repo_path": "2021/Day 14/Day14_ExtendedPolymerization.r", "max_stars_repo_name": "jonmichalik/advent-of-code", "max_stars_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "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": "2021/Day 14/Day14_ExtendedPolymerization.r", "max_issues_repo_name": "jonmichalik/advent-of-code", "max_issues_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "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": "2021/Day 14/Day14_ExtendedPolymerization.r", "max_forks_repo_name": "jonmichalik/advent-of-code", "max_forks_repo_head_hexsha": "4e8689435417412d20a134b83694978e45799bf0", "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.0769230769, "max_line_length": 80, "alphanum_fraction": 0.595267746, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.04468086931857751, "lm_q1q2_score": 0.02094597272606126}} {"text": "##\n# spr_class.r\n# Copyright (C) Jonathan Bramble 2011\n# \n# FBF-Optics is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# FBF-Optics is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License along\n# with this program. If not, see .\n\n#' An S4 class to represent a SPR experiment for a single angle point.\n#' \n#'\n#' @slot lambda Wavelength of light\n#' @slot n_entry Refractive index of the entry medium, eg a Prism\n#' @slot n_exit Refractive index of the exit medium\n#' @slot angle Exterior angle in degrees\n#' \nSPR <- setClass(\"SPR\", \n representation(\n lambda=\"numeric\",\n n_entry=\"numeric\",\n n_exit=\"numeric\",\n angle=\"numeric\",\n layers=\"list\"\n ),\n prototype(lambda=633e-9,n_entry=1.85,n_exit=1.33,angle=55)\n)\n\n#' An S4 class to represent a SPR experiment over a range of thicknesses for one layer.\n#' \n#'\n#' @slot lambda Wavelength of light\n#' @slot n_entry Refractive index of the entry medium, eg a Prism\n#' @slot angle Exterior angle in degrees\n#' @slot n_exit Refractive index of the exit medium\n#' \nSPRD <- setClass(\"SPRD\", \n representation(\n points=\"numeric\",\n lambda=\"numeric\",\n n_entry=\"numeric\",\n n_exit=\"numeric\",\n angle=\"numeric\",\n layers=\"list\"\n ),\n prototype(lambda=633e-9,n_entry=1.85,n_exit=1.33,angle=50)\n)\n\n#' An S4 class to represent a SPR experiment over a range of angles.\n#' G represents an angular variation to produce the classic spr curve\n#'\n#' @slot points The number of data points\n#' @slot lambda Wavelength of light\n#' @slot n_entry Refractive index of the entry medium, eg a Prism\n#' @slot n_exit Refractive index of the exit medium\n#' @slot start_angle Exterior starting angle in degrees\n#' @slot end_angle Exterior ending angle in degrees\n#' \nSPRG <- setClass(\"SPRG\", \n representation(\n points=\"numeric\",\n lambda=\"numeric\",\n n_entry=\"numeric\",\n n_exit=\"numeric\",\n start_angle=\"numeric\",\n end_angle=\"numeric\",\n layers=\"list\"\n ),\n prototype(points=100,lambda=633e-9,n_entry=1.78,n_exit=1.33,start_angle=45,end_angle=60)\n)\n\n#' An S4 class to represent a SPR experiment over a range of thicknesses for one layer.\n#' \n#'\n#' @slot lambda Wavelength of light\n#' @slot n_entry Refractive index of the entry medium, eg a Prism\n#' @slot angle Exterior angle in degrees\n#' @slot n_exit Refractive index of the exit medium\n#' TODO: ADD OTHER SLOTS\nSPRI <- setClass(\"SPRI\", \n representation(\n points=\"numeric\",\n lambda=\"numeric\",\n n_entry=\"numeric\",\n n_exit=\"numeric\",\n angle=\"numeric\",\n polariser=\"numeric\",\n modulator=\"numeric\",\n analyser=\"numeric\",\n mod_amplitude=\"numeric\",\n layers=\"list\"\n ),\n prototype(lambda=633e-9,n_entry=1.78,n_exit=1.33,angle=50,polariser=30,modulator=30,analyser=172,mod_amplitude=1)\n)\n\nvaliditySPR <- function(object){\n retval <- NULL\n if(object@angle > 90) {\n retval <- c(retval,\"angle is greater than 90\")\n }\n if ( is.null(retval)) return (TRUE)\n else return ( retval )\n}\n\nvaliditySPRG <- function(object){\n ## add real tests here - what can we check? n_entry > n_exit? end_angle > start_angle, end angle < 90\n retval <- NULL\n if(object@end_angle > 90) {\n retval <- c(retval,\"end angle is greater than 90\")\n }\n if ( is.null(retval)) return (TRUE)\n else return ( retval )\n}\n\nvaliditySPRD <- function(object){\n ## add real tests here - what can we check? n_entry > n_exit? end_angle > start_angle, end angle < 90\n retval <- NULL\n if(object@angle > 90) {\n retval <- c(retval,\"end angle is greater than 90\")\n }\n if ( is.null(retval)) return (TRUE)\n else return ( retval )\n}\n\n\nsetValidity(\"SPR\",validitySPR)\nsetValidity(\"SPRD\",validitySPRD)\nsetValidity(\"SPRG\",validitySPRG)\nsetValidity(\"SPRI\",validitySPR)\n\n#setters\nsetGeneric(\"points<-\",function(x,value) standardGeneric(\"points<-\"))\nsetGeneric(\"angle<-\",function(x,value) standardGeneric(\"angle<-\"))\nsetGeneric(\"n_entry<-\",function(x,value) standardGeneric(\"n_entry<-\"))\nsetGeneric(\"n_exit<-\",function(x,value) standardGeneric(\"n_exit<-\"))\nsetGeneric(\"start_angle<-\",function(x,value) standardGeneric(\"start_angle<-\"))\nsetGeneric(\"end_angle<-\",function(x,value) standardGeneric(\"end_angle<-\"))\nsetGeneric(\"lambda<-\",function(x,value) standardGeneric(\"lambda<-\"))\nsetGeneric(\"polariser<-\",function(x,value) standardGeneric(\"polariser<-\"))\nsetGeneric(\"analyser<-\",function(x,value) standardGeneric(\"analyser<-\"))\nsetGeneric(\"mod_amplitude<-\",function(x,value) standardGeneric(\"mod_amplitude<-\"))\nsetGeneric(\"modulator<-\",function(x,value) standardGeneric(\"modulator<-\"))\nsetGeneric(\"run\", function(object) {standardGeneric(\"run\")})\n\nsetReplaceMethod(\"points\",\"SPR\", function(x,value) {x@points <- value; validObject(x); x})\nsetReplaceMethod(\"angle\",\"SPR\", function(x,value) {x@angle <- value; validObject(x); x})\nsetReplaceMethod(\"n_entry\",\"SPR\", function(x,value) {x@n_entry <- value; validObject(x); x})\nsetReplaceMethod(\"n_exit\",\"SPR\", function(x,value) {x@n_exit <- value; validObject(x); x})\nsetReplaceMethod(\"lambda\",\"SPR\", function(x,value) {x@lambda <- value; validObject(x); x})\n\nsetReplaceMethod(\"points\",\"SPRD\", function(x,value) {x@points <- value; validObject(x); x})\nsetReplaceMethod(\"angle\",\"SPRD\", function(x,value) {x@angle <- value; validObject(x); x})\nsetReplaceMethod(\"n_entry\",\"SPRD\", function(x,value) {x@n_entry <- value; validObject(x); x})\nsetReplaceMethod(\"n_exit\",\"SPRD\", function(x,value) {x@n_exit <- value; validObject(x); x})\nsetReplaceMethod(\"lambda\",\"SPRD\", function(x,value) {x@lambda <- value; validObject(x); x})\n\nsetReplaceMethod(\"points\",\"SPRG\", function(x,value) {x@points <- value; validObject(x); x})\nsetReplaceMethod(\"start_angle\",\"SPRG\", function(x,value) {x@start_angle <- value; validObject(x); x})\nsetReplaceMethod(\"end_angle\",\"SPRG\", function(x,value) {x@end_angle <- value; validObject(x); x})\nsetReplaceMethod(\"n_entry\",\"SPRG\", function(x,value) {x@n_entry <- value; validObject(x); x})\nsetReplaceMethod(\"n_exit\",\"SPRG\", function(x,value) {x@n_exit <- value; validObject(x); x})\nsetReplaceMethod(\"lambda\",\"SPRG\", function(x,value) {x@lambda <- value; validObject(x); x})\n\nsetReplaceMethod(\"points\",\"SPRI\", function(x,value) {x@points <- value; validObject(x); x})\nsetReplaceMethod(\"angle\",\"SPRI\", function(x,value) {x@angle <- value; validObject(x); x})\nsetReplaceMethod(\"n_entry\",\"SPRI\", function(x,value) {x@n_entry <- value; validObject(x); x})\nsetReplaceMethod(\"n_exit\",\"SPRI\", function(x,value) {x@n_exit <- value; validObject(x); x})\nsetReplaceMethod(\"lambda\",\"SPRI\", function(x,value) {x@lambda <- value; validObject(x); x})\nsetReplaceMethod(\"polariser\",\"SPRI\", function(x,value) {x@polariser <- value; validObject(x); x})\nsetReplaceMethod(\"analyser\",\"SPRI\", function(x,value) {x@analyser <- value; validObject(x); x})\nsetReplaceMethod(\"mod_amplitude\",\"SPRI\", function(x,value) {x@mod_amplitude <- value; validObject(x); x})\nsetReplaceMethod(\"modulator\",\"SPRI\", function(x,value) {x@modulator <- value; validObject(x); x})\n\n\nsetGeneric(\"curve\", function(object) {standardGeneric(\"curve\")})\nsetGeneric(\"sprmin\", function(object){standardGeneric(\"sprmin\")})\nsetGeneric(\"rppval\", function(e1,e2) {standardGeneric(\"rppval\")})\n\nsetMethod(\"rppval\",signature(e1=\"SPR\",e2=\"numeric\"),function(e1,e2){\n Rpp<-S4_SPRVAL(e1,e2)\n return(Rpp)\n})\n\nsetMethod(\"sprmin\",signature(object=\"SPR\"),function(object){\n Rpp<-S4_SPRMIN(object)\n return(Rpp)\n})\n\nsetMethod(\"sprmin\",signature(object=\"SPRG\"),function(object){\n Rpp<-S4_SPRMIN(object)\n return(Rpp)\n})\n\nsetMethod(\"curve\",signature(object=\"SPRD\"),function(object){\n Rpp<-S4_SPRD(object)\n return(Rpp)\n})\n\nsetMethod(\"curve\",signature(object=\"SPRG\"),function(object){\n Rpp<-S4_SPRG(object)\n int_angle <- seq(length=object@points,from=object@start_angle,to=object@end_angle)\n dat <- cbind(int_angle,Rpp)\n return(dat)\n})\n\nsetMethod(\"curve\",signature(object=\"SPRG\"),function(object){\n Rpp<-S4_SPRG(object)\n int_angle <- seq(length=object@points,from=object@start_angle,to=object@end_angle)\n dat <- cbind(int_angle,Rpp)\n return(dat)\n})\n\nsetMethod(\"run\",signature(object=\"SPRI\"),function(object){\n Rpp<-S4_SPRI(object)\n return(Rpp)\n})\n\nsetMethod(\"show\", signature(object=\"SPR\"), function(object){\n cat(\" SPR base data \\n\") \n cat(\" Wavelength:\", object@lambda , \"\\n\")\n cat(\" Angle:\", object@angle , \"\\n\")\n cat(\" Entry Medium Index:\", object@n_entry , \"\\n\")\n cat(\" Exit Medium Index:\", object@n_exit , \"\\n\")\n})\n\nsetMethod(\"show\", signature(object=\"SPRD\"), function(object){\n cat(\" SPRD base data \\n\") \n cat(\" Number of data points:\", object@points , \"\\n\")\n cat(\" Wavelength:\", object@lambda , \"\\n\")\n cat(\" Angle:\", object@angle , \"\\n\")\n cat(\" Entry Medium Index:\", object@n_entry , \"\\n\")\n cat(\" Exit Medium Index:\", object@n_exit , \"\\n\")\n})\n\nsetMethod(\"show\", signature(object=\"SPRG\"), function(object){\n cat(\" SPRG base data \\n\") \n cat(\" Number of data points:\", object@points , \"\\n\")\n cat(\" Wavelength:\", object@lambda , \"\\n\")\n cat(\" Starting Angle:\", object@start_angle , \"\\n\")\n cat(\" Ending Angle:\", object@end_angle , \"\\n\")\n cat(\" Entry Medium Index:\", object@n_entry , \"\\n\")\n cat(\" Exit Medium Index:\", object@n_exit , \"\\n\")\n})\n\nsetMethod(\"show\", signature(object=\"SPRI\"), function(object){\n cat(\" SPRI base data \\n\") \n cat(\" Number of data points:\", object@points , \"\\n\")\n cat(\" Wavelength:\", object@lambda , \"\\n\")\n cat(\" Angle:\", object@angle , \"\\n\")\n cat(\" Entry Medium Index:\", object@n_entry , \"\\n\")\n cat(\" Exit Medium Index:\", object@n_exit , \"\\n\")\n})\n\n\nsetMethod(\"+\", signature(e1=\"SPR\",e2=\"IsoLayer\"), function(e1,e2){\n e1@layers <- c(e1@layers,e2)\n structure(e1,class=\"SPR\")\n})\n\nsetMethod(\"+\", signature(e1=\"SPRD\",e2=\"IsoLayer\"), function(e1,e2){\n e1@layers <- c(e1@layers,e2)\n structure(e1,class=\"SPRD\")\n})\n\nsetMethod(\"+\", signature(e1=\"SPRG\",e2=\"IsoLayer\"), function(e1,e2){\n e1@layers <- c(e1@layers,e2)\n structure(e1,class=\"SPRG\")\n})\n\nsetMethod(\"+\", signature(e1=\"SPRI\",e2=\"IsoLayer\"), function(e1,e2){\n e1@layers <- c(e1@layers,e2)\n structure(e1,class=\"SPRI\")\n})\n", "meta": {"hexsha": "3359ad1941049311cf373387a9e32662c10c280b", "size": 10984, "ext": "r", "lang": "R", "max_stars_repo_path": "R/spr_class.r", "max_stars_repo_name": "jonbramble/RFBFoptics", "max_stars_repo_head_hexsha": "db7768b0e2f0e7defe3cf572292bd4f0c16c08ce", "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/spr_class.r", "max_issues_repo_name": "jonbramble/RFBFoptics", "max_issues_repo_head_hexsha": "db7768b0e2f0e7defe3cf572292bd4f0c16c08ce", "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": "R/spr_class.r", "max_forks_repo_name": "jonbramble/RFBFoptics", "max_forks_repo_head_hexsha": "db7768b0e2f0e7defe3cf572292bd4f0c16c08ce", "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": 38.9503546099, "max_line_length": 130, "alphanum_fraction": 0.6581391114, "num_tokens": 2935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.06560484476669959, "lm_q1q2_score": 0.020824701725996535}} {"text": "## Created on Friday, January 28, 2022 at 6:08pm EDT by WeekendEditor on WeekendEditorMachine.\n## Copyright (c) 2022, SomeWeekendReading.blog. All rights reserved. As if you care.\n\ntoolsDir <- \"../../tools\" #\nsource(file.path(toolsDir, \"pipeline-tools.r\")) #\nsource(file.path(toolsDir, \"graphics-tools.r\")) # Various graphics hacks\n\nlibrary(\"lubridate\") # For floor_date(), ceiling_date()\nlibrary(\"PerformanceAnalytics\") # For chart.Correlation()\nlibrary(\"plyr\") # For ddply()\n\n##\n## Research question: Does the MWRA's metagenomic measurement of SARS-COV-2 RNA in\n## wastewater predict later hospitalization or death rates or positive test rates?\n##\n## Hypotheses: hospitalization & death rates might work; positive test rates probably\n## won't, due to changes in test availability, test type, and testing policy.\n##\n## Did not consider test positivity rates, since testing has changed from basically unavailable\n## to somewhat available, and the reporting has been spotty enough to make the numbers useless.\n##\n## Should consider forcing intercept to 0 in linear models, for 0 COVID deaths when there's\n## 0 SARS-CoV2 RNA present. Might improve some of the fits, from the look of it.\n##\n## This time we're using US county-level data from the New York Times (updated daily?):\n## https://github.com/nytimes/covid-19-data\n## The file we want is us-counties.csv, at top level.\n##\n## See also the covdata package, which incorporates several data sources (now out of date):\n## https://kjhealy.github.io/covdata/\n##\n## CDC on wastewater surveillance:\n## https://twitter.com/CDCgov/status/1436074326437019651\n## https://www.cdc.gov/mmwr/volumes/70/wr/mm7036a2.htm?s_cid=mm7036a2_w\n## https://www.cdc.gov/mmwr/volumes/70/wr/pdfs/mm7036a2-H.pdf\n##\n## Biobot.io suggests:\n## https://usafacts.org/visualizations/coronavirus-covid-19-spread-map/\n##\n## MWRA on viral RNA levels in wastewater:\n## https://www.mwra.com/biobot/biobotdata.htm\n##\n## But going to biobot.io finds this repository:\n## https://github.com/biobotanalytics/covid19-wastewater-data\n##\n## See: wastewater_by_county.csv and cases_by_county.csv\n##\n## However, it doesn't contain data for Norfolk county MA, and has very different\n## numbers (hence the use of the word \"normalized\"?). I don't understand it, so I'm\n## going to stick with the direct-from-the-MWRA data.\n##\n## Getting the MWRA data out of PDF hell (latest was MWRAData20220128-data.pdf):\n##\n## - Just pasting it into a text file or even a spreadsheet is a bit of a nightmare, where the\n## values never QUITE go where you want.\n## - We used the method in https://productivityspot.com/convert-pdf-to-google-sheets/:\n## o Download the MWRA PDF file to our local machine, then upload to Google Drive.\n## o In Google Drive, open the PDF file with Google Docs (not a PDF viewer).\n## o Select the table (not the whole document, which has header lines &c). E.g., click\n## on topmost, leftmost cell then command-click (control-click) on the bottommost, rightmost\n## cell at the bottom of the file. Then copy.\n## o Open a new Google Sheets spreadsheet, select A1, and paste.\n## o Download it as a .tsv file, spot-check against the .pdf, then gzip compress it.\n## No idea why that works whereas copying from PDF preview to any other spreadsheet just\n## gives chaos. Possibly because it's seamless Google tools from end to end?\n##\n## Anyway, spot-checking the result against the original confirms that it's likely right, at\n## least in the 20-30 places we checked.\n##\n\ndoit <- function(## Inputs\n dataDir = \"./data\",\n ## *** NB: On 2021-01-25, the South RNA was 3772, which looks like an\n ## outlier, even after averaging with the North.\n mwraDataFile = \"MWRAData20220201-data.tsv.gz\",\n covidDataFile = \"us-counties.csv.gz\",\n state = \"Massachusetts\",\n counties = c(\"Suffolk\", \"Middlesex\", \"Norfolk\"),\n\n ## Outputs\n resultsDir = \"./results\",\n txFile = \"mwra-covid-transcript.txt\",\n jointDataFile = \"mwra-covid-joint-data.tsv\",\n nsPlotFile = \"plot-north-south.png\",\n predSetFile = \"mwra-covid-joint-data-prediction-set.tsv\",\n corrPlotFile1 = \"plot-med-loads-vs-RNA-1.png\",\n corrPlotFile2 = \"plot-med-loads-vs-RNA-2.png\",\n lagPlotFile = \"plot-RNA-%s-lags.png\",\n regPlotFile = \"plot-RNA-%s-regression.png\",\n regStatsFile = \"finalRegressionsTable.tsv\") {\n\n reportStructure <- function(df) { # Report structure of a dataframe\n cat(sprintf(\"\\n - Structure:\\n o %d rows\\n o %d columns: %s\\n\",\n nrow(df), ncol(df), paste(colnames(df), collapse = \", \")))\n showDataframeHeadTail(df) # Show first few & last few rows\n } # Basically shape + column names\n\n isNonNegativeIntOrNA <- function(x) { is.na(x) | (is.integer(x) & x >= 0) }\n\n loadCOVIDData <- function(dataDir, covidDataFile, theState, counties) {\n f <- file.path(dataDir, covidDataFile) # Where the data lives\n cat(sprintf(\"* Reading US county-level COVID data from %s\", f))\n covidData <- transform(subset(loadCompressedDataframe(f, sep = \",\", header = TRUE, quote = \"\"),\n subset = state == theState & county %in% counties),\n date = as.Date(as.character(date), format = \"%Y-%m-%d\"),\n county = factor(county)) # Drop unused levels\n covidData <- covidData[order(covidData$\"date\"), ] # Sort by date; insist dates increment by 1\n ddply(covidData, \"county\", function(cdf) { stopifnot(all(diff(cdf$\"date\") == 1)); NULL })\n\n empties <- c(\"state\", \"fips\", names(which(sapply(covidData, function(c) { all(is.na(c)) }))))\n cat(sprintf(\"\\n - Dropping %d columns for being empty or for being state & fips: %s\",\n length(empties), paste(empties, collapse = \", \")))\n covidData <- subset(covidData, select = setdiff(colnames(covidData), c(empties)))\n\n stopifnot(colnames(covidData) == c(\"date\", \"county\", \"cases\", \"deaths\"))\n colnames(covidData) <- c(\"Date\", \"County\", \"Cases\", \"Deaths\")\n\n ## Sanity check, because not everybody is sane. At least, not all the time\n stopifnot(all(isNonNegativeIntOrNA(covidData$\"Cases\")))\n stopifnot(all(isNonNegativeIntOrNA(covidData$\"Deaths\")))\n\n cat(sprintf(\"\\n - Differentiating cumulative cases & deaths to get daily increments\"))\n covidData <- ddply(covidData, \"County\", function(cdf) {\n cbind(cdf, # Initial value from cumulant, diff after\n data.frame(Cases.New = c(cdf[1, \"Cases\"], diff(cdf$\"Cases\")),\n Deaths.New = c(cdf[1, \"Deaths\"], diff(cdf$\"Deaths\"))))\n }) #\n\n reportStructure(covidData) # See what we caught\n covidData # Return the data\n } #\n\n loadMWRAData <- function(dataDir, mwraDataFile) { # Load the MWRA's metagenomic data\n f <- file.path(dataDir, mwraDataFile) # Painfully hand-extracted from a PDF\n cat(sprintf(\"\\n* Reading MWRA wastewater RNA data from %s\", f))\n mwraData <- transform(loadCompressedDataframe(f, sep = \"\\t\", header = TRUE,\n na.strings = c(\"ND\", \"\")),\n Sample.Date = as.Date(as.character(Sample.Date), format = \"%m/%d/%Y\"))\n colnames(mwraData)[1:11] <- c(\"Date\", \"South\", \"North\", \"South.7\", \"North.7\",\n \"South.LCL\", \"South.UCL\", \"North.LCL\", \"North.UCL\",\n \"South.Variant\", \"North.Variant\")\n\n ## *** UCL & LCL columns make no sense: they don't bracket the data or its 7 day average?\n mwraData <- subset(mwraData, # Drop cols we don't understand & can't use\n select = -c(South.Variant, North.Variant,\n South.LCL, North.LCL,\n South.UCL, North.UCL))\n stopifnot(colnames(mwraData) == c(\"Date\", \"South\", \"North\", \"South.7\", \"North.7\"))\n\n mwraData <- subset(mwraData, # Keep only rows w/ at least 1 datum\n subset = !is.na(South) | !is.na(North) | !is.na(South.7) | !is.na(North.7))\n\n ## Sanity check, because not everybody is sane. At least, not all the time\n stopifnot(all(isNonNegativeIntOrNA(mwraData$\"South\")))\n stopifnot(all(isNonNegativeIntOrNA(mwraData$\"North\")))\n stopifnot(all(isNonNegativeIntOrNA(mwraData$\"South.7\")))\n stopifnot(all(isNonNegativeIntOrNA(mwraData$\"North.7\")))\n ## stopifnot(all(diff(mwraData$\"Date\") == 1)) # Missing data 2020-05-12 thru 2020-05-20\n\n reportStructure(mwraData) # See what fish we caught\n mwraData # Return the data\n } #\n\n makeJointData <- function(mwraData, covidData, resultsDir, jointDataFile) {\n ## NB: MWRA data is copied for each county in this slightly crazy representation!\n cat(\"\\n\\n* Constructing joint dataset by inner join on dates\")\n jointData <- merge(mwraData, covidData, by = \"Date\", all = FALSE)\n jointData <- jointData[order(jointData$\"Date\"), ] # Sort it by date\n\n f <- file.path(resultsDir, jointDataFile) # Save it away for peer review\n saveDataframe(jointData, f) #\n cat(sprintf(\"\\n - Saved to %s\", f)) #\n\n reportStructure(jointData) # See what we caught\n cat(\"\\n\") #\n jointData # Return the data\n } #\n\n plotNorthSouth <- function(jointData, resultsDir, nsPlotFile) {\n jointData <- unique(subset(jointData, select = c(Date, North, South)))\n jointData <- subset(jointData, subset = complete.cases(jointData))\n f <- file.path(resultsDir, nsPlotFile) #\n withPNG(f, 850, 425, FALSE, function() { #\n withPars(function() { #\n rnaCols <- c(\"North\" = \"blue\", \"South\" = \"gray\")\n matplot(x = jointData$\"Date\", # North & south RNA vs time\n y = subset(jointData, select = names(rnaCols)),\n type = \"p\", pch = 21, col = \"black\", bg = rnaCols, log = \"y\",\n xaxt = \"n\", xlab = NA, ylab = \"RNA (copies/ml, log scale)\",\n main = \"RNA Levels vs Time\") #\n axis.Date(1, #\n at = seq(from = floor_date(min(jointData$\"Date\"), \"month\"),\n to = ceiling_date(max(jointData$\"Date\"), \"month\"),\n by = \"2 months\"), # Kind of miraculous this works at all\n format = \"%Y-%b-%d\") # it's really seq.Date()\n legend(\"topleft\", bg = \"antiquewhite\", inset = 0.01,\n pch = 21, pt.bg = rnaCols, pt.cex = 1.5, legend = names(rnaCols))\n\n jointRange <- c(5, max(jointData$\"North\", jointData$\"South\", na.rm = TRUE))\n scatterplotWithDensities(xs = jointData$\"South\", ys = jointData$\"North\",\n bgs = \"steelblue\", log = \"xy\",\n regressionColor = NULL,# doesn't work on log scale\n xlab = \"South RNA (copies/ml, log scale)\",\n ylab = \"North RNA (copies/ml, log scale)\",\n xlim = jointRange, ylim = jointRange,\n main = as.expression(bquote(bold(paste(\n \"North/South Correlation: \",\n bolditalic(R)^2 == .(\n sprintf(\"%.0f%%\",\n 100.0 * cor(jointData$\"North\",\n jointData$\"South\")^2)))))))\n\n title(main = \"MWRA Wastewater SARS-CoV2 RNA: North vs South\", outer = TRUE)\n\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # Background\n mar = c(7, 4, 2, 1), # Margins (e.g., to hold date labels)\n mgp = c(3.00, 0.5, 0), # Axis title, label, tick\n mfrow = c(1, 2), # 1x2 array of plots\n oma = c(0, 0, 1, 0), # Make room at top for overall title\n ps = 16, # Larget type size for file capture\n las = 2) # Labels perpendicular to axes\n }) # End file capture\n cat(sprintf(\"* Plot of north vs south RNA to %s\\n\", f))\n TRUE # Flag that it was done\n } #\n\n makePredictionSet <- function(jointData, resultsDir, predSetFile) {\n cat(sprintf(\"* Making prediction set:\")) # Data used in regressions (with lags)\n\n cat(sprintf(\"\\n - Averaging North and South daily mRNA measurements\"))\n rnaData <- subset(transform(unique(subset(jointData, select = c(Date, South, North))),\n RNA = ifelse(is.na(South),\n North, #\n ifelse(is.na(North),\n South,\n (South + North) / 2.0))),\n select = c(Date, RNA)) #\n\n cat(sprintf(\"\\n - For each day, summing cases and deaths over counties\"))\n medData <- ddply(unique(subset(jointData, select = c(Date, County, Cases.New, Deaths.New))),\n \"Date\", #\n function(ddf) { #\n data.frame(Cases = sum(ddf$\"Cases.New\"), Deaths = sum(ddf$\"Deaths.New\"))\n }) #\n\n cat(sprintf(\"\\n - Outer joining RNA data and medical data\"))\n predictionSet <- merge(rnaData, medData, by = \"Date\", all = TRUE)\n# stopifnot(all(diff(predictionSet$\"Date\") == 1)) # Missing data 2021-May-12 thru 2021-May-20\n reportStructure(predictionSet) #\n\n f <- file.path(resultsDir, predSetFile) # Save results for peer review\n saveDataframe(predictionSet, f) #\n cat(sprintf(\"\\n - Saved to %s.\\n\", f)) #\n\n predictionSet # Return the prediction set\n } #\n\n plotCorrelations <- function(predictionSet, resultsDir, corrPlotFile1, corrPlotFile2) {\n\n timeFile <- file.path(resultsDir, corrPlotFile1) #\n withPNG(timeFile, 600, 600, FALSE, function() { #\n withPars(function() { #\n matplot(x = predictionSet$\"Date\", #\n ## *** Z-scoring is a bit of a hack here, making the values harder to\n ## interpret. But it DOES get them all on the same scale so we can see\n ## the structure in the plot. If there were only 2 vars, I'd do a second\n ## y axis on the right; but as there are 5...\n y = scale(as.matrix(predictionSet[, c(\"RNA\", \"Cases\", \"Deaths\")])),\n xaxt = \"n\", xlab = NA, ylab = \"Z-scored RNA & med vars\",\n main = \"RNA & Medical Vars vs Time\", #\n pch = 21, col = \"black\", bg = 1 : (2 + 1))\n axis.Date(1, # *** Get dates to print more regularly?\n at = seq(from = floor_date(min(jointData$\"Date\"), \"month\"),\n to = ceiling_date(max(jointData$\"Date\"), \"month\"),\n by = \"month\"), # Kind of miraculous this works at all\n format = \"%Y-%b-%d\") #\n legend(\"top\", , bg = \"antiquewhite\", inset = 0.01,\n pch = 21, pt.bg = 1 : (2 + 1), legend = c(\"RNA\", \"Cases\", \"Deaths\"))\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # Background\n mar = c(7, 3, 2, 1), # Margins (e.g., to hold date labels)\n mgp = c(1.75, 0.5, 0), # Axis title, label, tick\n ps = 16, # Larget type size for file capture\n las = 2) # Labels perpendicular to axes\n }) #\n cat(sprintf(\"* Correlation time courses plotted to %s\", timeFile))\n\n chartFile <- file.path(resultsDir, corrPlotFile2) #\n withPNG(chartFile, 600, 600, FALSE, function() { #\n chart.Correlation(subset(predictionSet, select = -Date), histogram = TRUE, pch = 19)\n }) #\n cat(sprintf(\"\\n* Correlation chart plotted to %s\\n\", chartFile))\n\n TRUE # Flag that it has been done\n } #\n\n lagVector <- function(x, k) { # Put k NA's @ front, drop last k values\n if (k < 0) # Don't be silly\n stop(sprintf(\"lagVector() can't handle negative k = %d?!\", k))\n else if (k > length(x)) # Really: don't be silly\n stop(sprintf(\"lagVector() can't handle k = %d, > length of vector %d?!\", k, length(x)))\n else if (k == 0) # Ok, this is only a LITTLE silly\n x # lag of 0 means no change\n else # Otherwise reasonable lag: put k NA's on\n c(rep(NA, k), head(x, -k)) # the front, drop the last k elements\n } #\n\n lmp <- function (mdl) { anova(mdl)$\"Pr(>F)\"[[1]] } # Why isn't this cached in the model?!\n\n laggedRegressions <- function(predictionSet, depVar, indepVar, lags) {\n ldply(lags, function(lag) { # For each lag, construct dataset with\n mdl <- lm(as.formula(sprintf(\"%s ~ %s\", depVar, \"indepVar.lag\")),\n data = transform(predictionSet, # RNA lagged, extract p-value and adj R2\n indepVar.lag = lagVector(predictionSet[, indepVar], lag)))\n data.frame(MedVar = depVar, Lag = lag, p = lmp(mdl), Adj.R2 = summary(mdl)$\"adj.r.squared\")\n }) # We'll use this to find the best lags\n } # for each medical load variable\n\n plotLaggedRegressions <- function(waveName, regressionLags, resultsDir, lagPlotFile) {\n cat(sprintf(\"\\n* Scatterplotting significance & strength vs RNA lag\"))\n ddply(regressionLags, \"MedVar\", function(mvdf) { #\n f <- file.path(resultsDir, sprintf(lagPlotFile, as.character(mvdf[1, \"MedVar\"])))\n\n withPNG(f, 400, 400, FALSE, function() {\n withPars(function() { # Plot -log10(p) & Adj R2 (diff y axes)\n plot(x = mvdf$\"Lag\", y = jitter(-log10(mvdf$\"p\")),\n pch = 21, col = \"black\", bg = \"black\", xlab = \"Lag\", ylab = \"-log10(p)\",\n main = sprintf(\"%s %s: Effect of Lag\", waveName, as.character(mvdf[1, \"MedVar\"])))\n par(new = TRUE) # \"as if for a new plot\"... sheesh\n plot(x = mvdf$\"Lag\", y = mvdf$\"Adj.R2\", # Other y axis (different scale)\n pch = 21, col = \"blue\", bg = \"blue\", ylim = range(mvdf$\"Adj.R2\"),\n xaxt = \"n\", yaxt = \"n\", xlab = NA, ylab = NA, main = NA)\n axis(4, col = \"blue\", col.ticks = \"blue\", col.axis = \"blue\")\n mtext(\"Adjusted R2\", side = 4, col = \"blue\", line = 2)\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # Background\n mar = c(3, 3, 2, 3), # Margins (e.g., to hold date labels)\n mgp = c(1.7, 0.5, 0), # Axis title, label, tick\n ps = 16) # Larget type size for file capture\n })\n\n cat(sprintf(\"\\n - %s\", f)) #\n NULL #\n }) #\n cat(\"\\n\") #\n\n TRUE #\n } #\n\n findOptimalLags <- function(regressionLags) { # Find best by p-value (same as R^2)\n cat(\"\\n* Optimal lags for each medical variable:\\n\")\n optimalLags <- ddply(regressionLags, \"MedVar\", function(df) {\n minp <- min(df$\"p\") #\n subset(df, subset = p == minp) #\n }) #\n print(optimalLags) #\n optimalLags #\n } #\n\n finalRegressions <- function(waveName, optimalLags, predictionSet, resultsDir, regPlotFile) {\n cat(\"* Trying some regressions at the optimal lag for each variable:\")\n ddply(optimalLags, \"MedVar\", function(df) { #\n mv <- as.character(df[1, \"MedVar\"]) #\n lag <- df[1, \"Lag\"] #\n cat(sprintf(\"\\n - Regressing %s on RNA at lag %d days:\", mv, lag))\n\n mdl <- lm(as.formula(sprintf(\"%s ~ RNA\", mv)), #\n data = transform(predictionSet, RNA = lagVector(predictionSet[, \"RNA\"], lag)))\n mdlSum <- summary(mdl)\n mdlCI <- confint(mdl)\n print(summary(mdl)) #\n print(mdlCI) #\n\n p <- lmp(mdl) #\n adj.R2 <- summary(mdl)$\"adj.r.squared\" #\n\n f <- file.path(resultsDir, sprintf(regPlotFile, mv))\n withPNG(f, 400, 400, FALSE, function() { #\n withPars(function() { #\n ## Confidence intervals: 95% ci of mean at that input\n ## Prediction intervals: 95% ci of single prediction at that input\n ## PI always wider than CI, for same reason that sd is wider than se of mean by sqrt(N)\n RNARange <- range(predictionSet$\"RNA\", na.rm = TRUE)\n predictFrom <- data.frame(\"RNA\" = seq(from = RNARange[[1]], to = RNARange[[2]],\n length.out = 100))\n mdlPredictsCI <- cbind(predictFrom, predict(mdl, newdata = predictFrom,\n interval = \"confidence\"))\n mdlPredictsPI <- cbind(predictFrom, predict(mdl, newdata = predictFrom,\n interval = \"prediction\"))\n\n plot(x = lagVector(predictionSet$\"RNA\", lag), y = predictionSet[, mv],\n pch = 21, bg = \"blue\", #\n xlab = sprintf(\"RNA (copies/ml, %d days lag)\", lag), ylab = mv,\n main = sprintf(\"%s %s vs RNA\", waveName, mv))\n mtext(as.expression(bquote( # Report regression stats at bottom\n paste(italic(p) %~% .(scientificExpression(p, places = 1)), \", adjusted \",\n italic(R)^2 %~% .(sprintf(\"%.1f%%\", 100.0 * adj.R2)))\n )), side = 1, line = 3.2) #\n abline(reg = mdl, col = \"black\", lwd = 2) #\n\n lightBlue <- rgb(0, 0, 1, alpha = 0.2) # Conf interval of mean in light color\n polygon(x = c(mdlPredictsCI[,\"RNA\"], rev(mdlPredictsCI[, \"RNA\"])),\n y = c(mdlPredictsCI[, \"lwr\"], rev(mdlPredictsCI[, \"upr\"])),\n col = lightBlue, border = NA) #\n\n lighterBlue <- rgb(0, 0, 1, alpha = 0.1) # Prediction interval in even lighter color\n polygon(x = c(mdlPredictsPI[,\"RNA\"], rev(mdlPredictsPI[, \"RNA\"])),\n y = c(mdlPredictsPI[, \"lwr\"], rev(mdlPredictsPI[, \"upr\"])),\n col = lighterBlue, border = NA) #\n\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # Background\n mar = c(4, 3, 2, 1), # Margins (e.g., to hold date labels)\n mgp = c(1.7, 0.5, 0), # Axis title, label, tick\n ps = 16) # Larger type size for file capture\n }) #\n cat(sprintf(\"\\n o Plot to %s\\n\", f)) #\n\n data.frame(MedVar = mv,\n Wave = waveName,\n Lag.Days = lag,\n p = signif(p, digits = 2),\n AdjR2Pct = signif(100.0 * adj.R2, digits = 1),\n Intercept = signif(coef(mdl)[[\"(Intercept)\"]], digits = 2),\n InterceptCL = sprintf(\"%+.2f - %+.2f\",\n mdlCI[\"(Intercept)\", \"2.5 %\"], mdlCI[\"(Intercept)\", \"97.5 %\"]),\n Slope = signif(coef(mdl)[[\"RNA\"]], digits = 2),\n SlopeCL = sprintf(\"%+.2f - %+.2f\",\n mdlCI[\"RNA\", \"2.5 %\"], mdlCI[\"RNA\", \"97.5 %\"]))\n }) #\n } #\n\n ## Main body of script begins here\n withTranscript(dataDir, resultsDir, txFile, \"MWRA COVID Analysis\", function() {\n\n heraldPhase(\"Archival\") # For peer review\n archiveAnalysisScript(resultsDir, \"./mwra-covid-3.r\")\n\n heraldPhase(\"Loading datasets and constructing joint dataset\")\n maybeAssign(\"covidData\", function() { loadCOVIDData(dataDir, covidDataFile, state, counties) })\n maybeAssign(\"mwraData\", function() { loadMWRAData(dataDir, mwraDataFile) })\n maybeAssign(\"jointData\", function() { # Assemble via inner join on dates\n makeJointData(mwraData, covidData, resultsDir, jointDataFile)\n }) #\n\n heraldPhase(\"Exploratory plots\") # See the general shape of the data\n maybeAssign(\"nsPlotDone\", function() { plotNorthSouth(jointData, resultsDir, nsPlotFile) })\n\n heraldPhase(\"Prediction set\") # Make dataset used by regressions: average\n maybeAssign(\"predictionSet\", function() { # RNA over north/south, sum deaths/cases\n makePredictionSet(jointData, resultsDir, predSetFile)\n }) # over counties\n\n heraldPhase(\"Correlation plots\") #\n maybeAssign(\"corrPlotsDone\", function() { #\n plotCorrelations(predictionSet, resultsDir, corrPlotFile1, corrPlotFile2)\n }) #\n\n heraldPhase(\"Lagged regressions\") #\n ## *** NB: The right way to do this is with an ARIMA time series model. I'm being\n ## lazy here, examining univariate prediction from RNA, with various lags. This is\n ## also not the right way as far as multiple hypothesis test correction (22 lags\n ## checked), and of course there's no crossvalidation since we only have 2 real waves in MA.\n maybeAssign(\"regressionLags\", function() { #\n cat(sprintf(\"* Regressing medical vars on RNA at various lags to test predictive power\"))\n rbind(laggedRegressions(predictionSet, \"Cases\", \"RNA\", 0:21),\n laggedRegressions(predictionSet, \"Deaths\", \"RNA\", 0:21))\n }) #\n maybeAssign(\"lrPlotsDone\", function() { #\n plotLaggedRegressions(\"All\", regressionLags, resultsDir, lagPlotFile)\n }) #\n maybeAssign(\"optimalLags\", function() { findOptimalLags(regressionLags) })\n\n heraldPhase(\"Final regressions\") #\n maybeAssign(\"finalRegressionsTable\", function() { #\n finalRegressions(\"All\", optimalLags, predictionSet, resultsDir, regPlotFile)\n }) #\n print(finalRegressionsTable)\n\n ## Redo separately for each of the 3 waves:\n ## > plot(x = predictionSet$\"Date\", y = predictionSet$\"RNA\", log = \"y\", las = 3, xlab = \"Time\", ylab = \"Cases\")\n ##\n ## Wave1: 2020-03-01 to 2020-07-01\n ## Wave2: 2020-10-01 to 2021-06-01\n ## Wave2.5: 2021-06-01 to 2021-11-01 (Delta)\n ## Wave3: 2021-11-01 to 2022-02-01 (Omicron starts on top of Delta)\n predictionSetWave1 <<- subset(predictionSet, #\n subset = \"2020-03-01\" <= Date & Date <= \"2020-07-01\")\n predictionSetWave2 <<- subset(predictionSet, #\n subset = \"2020-10-01\" <= Date & Date <= \"2021-06-01\")\n predictionSetWave2.5 <<- subset(predictionSet, #\n subset = \"2021-06-01\" <= Date & Date <= \"2021-11-01\")\n predictionSetWave3 <<- subset(predictionSet, #\n subset = \"2021-11-01\" <= Date & Date <= \"2022-02-01\")\n\n doWave <- function(waveName, predictionSet) { #\n print(waveName) #\n resultsDir <- file.path(resultsDir, waveName) #\n makeDirectory(resultsDir) #\n regressionLags <- rbind(laggedRegressions(predictionSet, \"Cases\", \"RNA\", 0:21),\n laggedRegressions(predictionSet, \"Deaths\", \"RNA\", 0:21))\n plotLaggedRegressions(waveName, regressionLags, resultsDir,\n sprintf(\"%s-%s\", waveName, lagPlotFile))\n optimalLags <- findOptimalLags(regressionLags) #\n finalRegressionsTable <<- rbind(finalRegressionsTable,\n finalRegressions(waveName, optimalLags, predictionSet,\n resultsDir, sprintf(\"%s-%s\",\n waveName, regPlotFile)))\n } #\n\n doWave(\"Wave1\", predictionSetWave1) #\n doWave(\"Wave2\", predictionSetWave2) #\n doWave(\"Wave2.5\", predictionSetWave2.5) #\n doWave(\"Wave3\", predictionSetWave3) #\n\n finalRegressionsTable <<- finalRegressionsTable[order(finalRegressionsTable$\"MedVar\",\n finalRegressionsTable$\"Wave\"), ]\n saveDataframe(finalRegressionsTable, file.path(resultsDir, regStatsFile))\n print(finalRegressionsTable) # Capture to transcript\n\n }) # End of transcript capture\n} #\n", "meta": {"hexsha": "56a27a07e1a1c2f513bf3eb527bc07eaf9704a7b", "size": 31989, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2022-02-04-wastewater-reredux-mwra-covid-3.r", "max_stars_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_stars_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "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": "assets/2022-02-04-wastewater-reredux-mwra-covid-3.r", "max_issues_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_issues_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "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": "assets/2022-02-04-wastewater-reredux-mwra-covid-3.r", "max_forks_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_forks_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "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": 61.0477099237, "max_line_length": 115, "alphanum_fraction": 0.4965456876, "num_tokens": 7585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04084571153154022, "lm_q1q2_score": 0.02042285576577011}} {"text": "\n# coding: utf-8\n\n# #1. Ambientes de trabajo\n# \n# Lo primero es crear el ambiente de trabajo para todos los laboratorios. Hay dos opciones: realizarlo remotamente en COLAB de Google, o hacerlo localmente usando el programa RSTUDIO.\n# \n# Resumidamente, RSTUDIO es más costoso al principio pero al final se gana tiempo (principalmente si se va a realizar mucho cómputo). Por otro lado, COLAB permite rápidamente ponerse a trabajar. Supondremos que se realiza el práctico en COLAB, pudiendo cambiar más adelante.\n\n# ##1.a) Ambiente COLAB remoto\n# \n# 1. Abrir en navegador: https://colab.research.google.com/\n# 2. Abrir el notebook de la tarea:\n# File-> Open Notebook -> Github -> https://github.com/prbocca/na101_master -> homework_1_graphs\n# 3. Guardar el notebook en su Google Drive:\n# File -> Save a Copy in Drive... \n# 4. Renombrar el archivo `\"cedula ID\"_ar_hw1.ipynb`, por ejemplo *33484022_ar_hw1.ipynb*\n# 5. Al final usted deberá descargar el notebook. Asegurarse que se están guardando las salidas de ejecución en el notebook: File -> Download .ipynb\n# 6. Luego estos archivos deberán ser enviados a prbocca@fing.edu.uy \n# \n\n# ##1.b) Ambiente RSTUDIO local (opcional)\n# \n# Es posible instalar un ambiente de trabajo (IDE) local y los paquetes básicos necesarios para todos los prácticos.\n# Este proceso puede demorar y se recomienda hacerlo fuera del práctico.\n# \n# Este ambiente de trabajo es opcional y recomendado para realizar mucho cómputo. En lo que resta del curso se asumirá que se utiliza la plataforma en linea: https://colab.research.google.com/, en donde se puede ejectuar y resolver todos los prácticos del curso.\n# \n# \n# 1. Instalar Rstudio. Descargar desde: https://www.rstudio.com/products/rstudio/\n# 2. Instalar Paquetes básicos. En una consola de R:\n# ```\n# # cargar librerias\n# load_libs <- function(libraries = libs, install=TRUE){\n# if (install){ # instalar librerias no instaladas\n# new.packages <- libs[!(libs %in% installed.packages()[,\"Package\"])]\n# if(length(new.packages)) install.packages(new.packages)\n# }\n# #cargo librerias \n# for (lib in libraries){\n# require(lib, character.only=TRUE, quietly = FALSE)\n# } \n# } \n# libs = c(\"igraph\", \"igraphdata\", \"GO.db\", \"GOstats\", \"ROCR\", \"ape\", \"car\", \"eigenmodel\", \"ergm\", \"fdrtool\", \"ggplot2\", \"huge\", \"kernlab\", \"lattice\", \"mixer\", \"network\", \"networkDynamic\", \"networkTomography\", \"ngspatial\", \"org.Sc.sgd.db\", \"sna\", \"vioplot\") \n# load_libs(libs)\n# ```\n# \n# 3. Abrir el .r de la tarea en: https://github.com/prbocca/na101_master/tree/master/homework_1_graphs\n\n# ## 1.c) Cargar Librerias\n# \n# En esta primera ejecución se asignan los recursos. Además instalar las librerías lleva tiempo. Es de esperar que esto demore unos minutos.\n# \n# Lamentablemente, el entorno de Colab se pierde luego de un tiempo de inactividad. Esto incluye que se deben volver a cargar las librerías y a descargar los datos (se borran todos los datos temporales).\n# \n# Todas las librerías debe instalarse correctamente, si el proceso se interrumpe o alguna librería da error en la instalación, entonces habrá problemas en el código más adelante. Si tiene este tipo de problemas pruebe hacer `Runtime -> Factory reset runtime`, y volver a intentar.\n\n# In[ ]:\n\n# cargar librerias\nload_libs <- function(libraries = libs, install=TRUE){\n if (install){ # instalar librerias no instaladas\n new.packages <- libs[!(libs %in% installed.packages()[,\"Package\"])]\n if(length(new.packages)) install.packages(new.packages)\n }\n #cargo librerias \n for (lib in libraries){\n require(lib, character.only=TRUE, quietly = FALSE)\n } \n} \n\nlibs = c(\"R.matlab\", \"sand\",\"igraph\",\"igraphdata\") #procesamiento en paralelo\n\nload_libs(libs)\n\n\n# ## 1.d) Descargar funciones auxiliares\n# \n# Para facilitar el trabajo a realizar en los prácticos, se ofrecen un conjunto de funciones auxiliares. El siguiente código carga dichas funciones.\n# \n# Es necesario repetir esta tarea siempre que se inicia una ejecución.\n\n# In[ ]:\n\n#directorio donde se va a trabajar\ndata_path = \"/content/ar/hw1/\"\n\ndir.create(data_path, showWarnings = FALSE, recursive = TRUE)\nsetwd(data_path)\ngetwd()\nlist.files()\n\n# cargo funciones auxiliares\nsource(\"https://raw.githubusercontent.com/prbocca/na101_master/master/homeworks_common.r\")\n\n\n# # 2. Tutorial del lenguaje *R*\n# \n# Es necesario conocer el lenguaje *R* para ganar fluidez en el práctico. Quien no conoce el lenguaje debe realizar algún tutorial rápido.\n# , por ejemplo: `igraph_demo(\"crashR\")` (que lamentablemente no anda en COLAB).\n# \n\n# In[ ]:\n\n# lamentablemente el paquete tcltk de COLAB no permite interfaz interactiva, por lo que este tutorial solo anda localemente (en el ambiente RSTUDIO).\nlibrary(\"tcltk\")\nif (interactive()){\n igraph_demo(\"crashR\")\n }else{\n print(\"Lo siento en su ambiente no funciona este tutorial.\")\n }\n\n\n# # 3. Tutorial de manipular grafos de redes\n# \n# Si aun no lo tiene, descargar el libro de práctico [SANDR]: Kolaczyk, E.D. and Csárdi, G. \"Statistical Analysis of Network Data with R\". Use R!, Springer New York, 2014. ISBN 9781493909834. Disponible\n# en http://timbo.org.uy/.\n# Ir a la descarga directamente siguiendo el link (Noviembre, 2019): https://link-springer-com.proxy.timbo.org.uy/book/10.1007%2F978-1-4939-0983-4\n# \n# \n# Seguir el texto del Capítulo 2 del libro [SANDR], ejecutando el código fuente incluido. Utilizar el manual de referencia del paquete igraph para extender el conocimiento: http://igraph.org/r/doc/igraph.pdf\n# \n# **Aquí se incluyen las celdas de código del libro, pero no su explicación. Entonces, es importante seguir la lectura del libro. Esta sección no será evaluada, sientase libre de cambiar y probar nuevos códigos para aprender.**\n# \n# **Observación: algunos comandos han cambiado en las últimas versiones de igraph, aquí se incluye una actualización respecto al libro.**\n\n# In[ ]:\n\ng <- graph.formula(1-2, 1-3, 2-3, 2-4, 3-5, 4-5, 4-6, 4-7, 5-6, 6-7)\n\n\n# In[ ]:\n\nV(g)\n\n\n# In[ ]:\n\nE(g)\n\n\n# In[ ]:\n\nprint_all(g)\n\n\n# In[ ]:\n\nplot(g)\n\n\n# In[ ]:\n\ndg <- graph.formula(1-+2, 1-+3, 2++3)\nplot(dg)\n\n\n# In[ ]:\n\ndg <- graph.formula(Sam-+Mary, Sam-+Tom, Mary++Tom)\nprint_all(dg)\n\n\n# In[ ]:\n\nV(dg)$name <- c(\"Sam\", \"Mary\", \"Tom\")\n\n\n# In[ ]:\n\nE(dg)\n\n\n# In[ ]:\n\nget.adjacency(g)\n\n\n# In[ ]:\n\nh <- induced.subgraph(g, 1:5)\nprint_all(h)\n\n\n# In[ ]:\n\nh <- g - vertices(c(6,7))\n\n\n# In[ ]:\n\nh <- h + vertices(c(6,7))\ng <- h + edges(c(4,6),c(4,7),c(5,6),c(6,7))\n\n\n# In[ ]:\n\nh1 <- h\nh2 <- graph.formula(4-6, 4-7, 5-6, 6-7)\ng <- graph.union(h1,h2)\n\n\n# In[ ]:\n\nV(dg)$name\n\n\n# In[ ]:\n\nV(g)$color <- \"red\"\n\n\n# In[ ]:\n\nis.weighted(g)\nwg <- g\nE(wg)$weight <- runif(ecount(wg))\nis.weighted(wg)\n\n\n# In[ ]:\n\ng$name <- \"Toy Graph\"\n\n\n# In[ ]:\n\ng.lazega <- graph.data.frame(elist.lazega,\n directed=\"FALSE\",\n vertices=v.attr.lazega)\ng.lazega$name <- \"Lazega Lawyers\"\n\n\n# In[ ]:\n\nvcount(g.lazega)\n\n\n# In[ ]:\n\necount(g.lazega)\n\n\n# In[ ]:\n\nlist.vertex.attributes(g.lazega)\n\n\n# In[ ]:\n\nis.simple(g)\n\n\n# In[ ]:\n\nmg <- g + edge(2,3)\nprint_all(mg)\nis.simple(mg)\n\n\n# In[ ]:\n\nE(mg)$weight <- 1\nwg2 <- simplify(mg)\nis.simple(wg2)\n\n\n# In[ ]:\n\nprint_all(wg2)\n\n\n# In[ ]:\n\nE(wg2)$weight\n\n\n# In[ ]:\n\nneighbors(g, 5)\n\n\n# In[ ]:\n\ndegree(g)\n\n\n# In[ ]:\n\ndegree(dg, mode=\"in\")\ndegree(dg, mode=\"out\")\n\n\n# In[ ]:\n\nis.connected(g)\n\n\n# In[ ]:\n\nclusters(g)\n\n\n# In[ ]:\n\nis.connected(dg, mode=\"weak\")\nis.connected(dg, mode=\"strong\")\n\n\n# In[ ]:\n\ndiameter(g, weights=NA)\n\n\n# In[ ]:\n\ng.full <- graph.full(7)\ng.ring <- graph.ring(7)\ng.tree <- graph.tree(7, children=2, mode=\"undirected\")\ng.star <- graph.star(7, mode=\"undirected\")\npar(mfrow=c(2, 2))\nplot(g.full)\nplot(g.ring)\nplot(g.tree)\nplot(g.star)\n\n\n# In[ ]:\n\nis.dag(dg)\n\n\n# In[ ]:\n\ng.bip <- graph.formula(actor1:actor2:actor3,\n movie1:movie2, actor1:actor2 - movie1,\n actor2:actor3 - movie2)\nV(g.bip)$type <- grepl('^movie', V(g.bip)$name)\nprint_all(g.bip, v=T)\n\n\n# In[ ]:\n\nproj <- bipartite.projection(g.bip)\nprint_all(proj[[1]])\nprint_all(proj[[2]])\n\n\n# # 4. Explorar una red de comunicaciones: emails de la empresa Enron\n# \n# La red de emails de la empresa Enron se publicó durante una investigación federal de EE.UU (si usted esta interesado en leer más sobre el escándalo de Enron, ver http://en.wikipedia.org/wiki/Enron_scandal). \n# \n# En éste ejercicio haremos cálculos sencillos sobre el grafo de esta red usando *R*.\n# \n# La red completa está disponible online en http://www.cs.cmu.edu/~enron/ y contiene $517.431$ correos extraidos de los directorios de correo de $150$ usuarios. Aqui utilizaremos un grafo más pequeño, preparado por C. E. Priebe et al., que consiste en $34.427$ correos enviados entre $184$ correos de empleados de Enron (ver http://cis.jhu.edu/~parky/Enron/enron.html por más detalles). Los correos son del periodo 13/11/1998 al 21/06/2002 ($44$ meses).\n# \n\n# ## 4.a) Descargar los datos y crear matriz de adyacencia\n# \n# Descargar el subconjunto de datos de `Enron.zip` de github.com\n\n# In[ ]:\n\n# load data\ndownload.file(url=\"https://github.com/prbocca/na101_master/blob/master/homework_1_graphs/Enron.zip?raw=true\", destfile=\"Enron.zip\", mode=\"wb\")\nunzip(zipfile=\"Enron.zip\")\n\nlist.files()\n\n\n# $\\newcommand \\ind [1] {{\\mathbb I \\left\\{#1\\right\\} } }$\n# $\\def\\bbA{{\\mathbf A}}$\n# El .zip contiene dos archivos creados en `Matlab`.\n# Para cargar archivos de `Matlab` en `R`, utilizar el paquete `R.matlab`.\n# \n# En el archivo `Y.mat` se encuentra el arreglo de tres dimensiones $\\underline{\\mathbf Y} \\in \\mathbb{R}^{184 \\times 184 \\times 44}$, que contiene la secuencia de matrices de adyacencia \n# que representa la red de quién le envió correo a quién para cada uno de los $44$ meses.\n# Notar que el grafo de la red es dirigido y ponderado, \n# dado que el elemento $[\\underline{\\mathbf Y}]_{ijt}$ indica la cantidad de correos enviados por el empleado $i$ al empleado $j$ durante el mes $t$.\n# \n# Además, desde el otro archivo, cargar el arreglo `employees` que contiene el nombre, la cuenta y cargo en la empresa para cada uno de los $184$ empleados (vértices) en $G$.\n# \n\n# In[ ]:\n\n# cargo la matriz de correos enviados\nY = readMat(\"Y.mat\")$Y \nstr(Y)\n\n# cargo los datos de cada empleado\nemployees = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: usar readMat() y algunas funciones auxiliares para transformar el texto \n# y obtener un vector de strings (chr [1:184])\n#\n#\n#\n##################################################################\nstr(employees)\n\n\n# Construir la matriz binaria de adyacencia ${\\mathbf A}\\in\\{0,1\\}^{184\\times184}$ que agrega todos los correos a lo largo del tiempo\n# (es decir, sumar $\\underline{\\mathbf Y}$ en la tercera dimension, y definir $[{\\mathbf A}]_{ij}=\\ind{\\sum_{t=1}^{44}[\\underline{\\mathbf Y}]_{ijt}>0}$). \n# \n\n# In[ ]:\n\n# matriz de adyacencia con peso (cantidad de correos enviados en todos los meses)\nA_weight = rowSums(Y, na.rm = FALSE, dims = 2)\nstr(A_weight)\n\n# matriz de adyacencia binaria\nA = ifelse(A_weight>0, 1, 0)\nstr(A)\n\n\n# ## 4.b) Construir un grafo a partir de la matriz de adyacencia\n# \n# Construir el grafo (con `igraph`) a partir de la matriz de adyacencia $\\bbA$ y agregar los atributos de vértices del arreglo `employees`.\n\n# In[ ]:\n\n# podría construise usando la matriz de adyacencia binaria\n# g = graph.adjacency(A)\n\n# pero optamos por hacerlo usando la matriz de adyacencia con pesos, así nos quedan en el grafo\ng = graph.adjacency(A_weight, weighted = TRUE)\nV(g)$id = employees\n\nsummary(g)\n\n\n# Más adelante veremos como graficar este grafo. Por ahora, la siguiente es una visualización sencilla.\n\n# In[ ]:\n\nplot(g, edge.color=\"gray\", edge.width=1, edge.lty=1, edge.arrow.size=.5, \n vertex.size=3, vertex.label=NA,\n layout=layout_nicely(g))\n\n\n# Ahora nos familiarizarnos con operaciones básicas sobre grafos.\n# \n# Para cada uno de las siguientes partes, realizar los cálculos usando la matriz de adyacencia $\\bbA$ (con álegebra de matrices), y usando el grafo (con métodos de `igraph`).\n# \n# \n\n# ## 4.c) Cantidad de aristas (arcos)\n# \n# Calcular la cantidad de aristas (arcos) en la red.\n# Es decir, la cantidad de parejas únicas ordenadas $(u,v)\\in E$ donde $u,v\\in V$.\n\n# In[ ]:\n\n# numero de aristas dirigidas: 3007\ncant_aristadirigida_matriz = sum(A)\nprintf(\"MATRIZ. las aristas dirigidas son: %s\", cant_aristadirigida_matriz)\n\n# con grafos\ncant_aristadirigida_grafo = length(E(g))\nprintf(\"GRAFO. las aristas dirigidas también las calculamos con: %s o con %s\", cant_aristadirigida_grafo, ecount(g))\n\n\n# ## 4.d) Cantidad de aristas no dirigidas\n# \n# Calcular la cantidad de aristas no dirigidas en la red (es decir, la cantidad de parejas únicas no ordenadas $(u,v)\\in E$\n# donde $u,v\\in V$. Esto significa que si $(u,v)\\in E$ o $(v,u)\\in E$, entonces se debe contar el par como una única arista.\n# \n\n# In[ ]:\n\n# con matrices\n#numero de aristas no dirigidas: 2097\nA.und = ifelse((A + t(A)) > 0, 1, 0)\nA.und.triang = A.und\nA.und.triang[lower.tri(A.und.triang)] = 0\ncant_aristanodirigida_matriz = sum(A.und.triang)\nprintf(\"MATRIZ. las aristas no dirigidas son: %s\", sum(cant_aristanodirigida_matriz))\n\n#con grafos\ncant_aristanodirigida_grafo = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: convertir el grafo a no dirigído \n#\n#\n##################################################################\nprintf(\"GRAFO. las aristas no dirigidas también las calculamos con: %s\", cant_aristanodirigida_grafo)\n\n\n# ## 4.e) Cantidad de arcos mutuos\n# \n# Calcular la cantidad de arcos mutuos en la red (es decir, la cantidad de parejas $(u,v)$ donde $\\{(u,v),(v,u)\\}\\subseteq E$\n# y $u,v\\in V$). Esto significa que si existen ambas $(u,v)\\in E$ y $(v,u)\\in E$, debe contarse el par como mutual.\n\n# In[ ]:\n\n# con matrices\ncant_aristamutua_matriz = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: usar una matriz triangular luego de transformar la matriz de adyacencia\n#\n#\n##################################################################\nprintf(\"MATRIZ. las aristas mutuas son: %s\", cant_aristamutua_matriz)\n\n\n#con grafos\ncant_aristamutua_grafo = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: convertir el grafo a no dirigído \n#\n#\n##################################################################\nprintf(\"GRAFO. las aristas mutuas también las calculamos con: %s\", cant_aristamutua_grafo)\n\n\n# ## 4.f) Empleados que no recibieron ningún correo\n# \n# Calcular la cantidad de vértices con $d_v^{\\text{in}}=0$, y listar los nombres de los empleados correspondientes.\n# \n\n# In[ ]:\n\n#find people not geting any email: 3\n# [1] \"Vince Kaminski (j..kaminski) Manager Risk Management Head\" \"Mary Fischer (mary.fischer) Employee \" \n# [3] \"xxx Smith (m..smith) xxx \" \nidx.notgetting = colSums(A)==0\ncant_notgetting_matriz = sum(idx.notgetting)\nprintf(\"MATRIZ. los empleados que no recibieron correo son: %s\", cant_notgetting_matriz)\nemployees[idx.notgetting]\n\n#con grafos\ncant_notgetting_grafo = sum(degree(g, mode = \"in\")==0)\nprintf(\"GRAFO. los empleados que no recibieron correo son: %s\", cant_notgetting_grafo)\nV(g)$id[degree(g, mode = \"in\")==0]\n\n\n# ## 4.g) Empleados que no enviaron ningún correo\n# \n# Calcular la cantidad de vértices con $d_v^{\\text{out}}=0$, y listar los nombres de los empleados correspondientes. \n# \n\n# In[ ]:\n\n# con matrices\ncant_notsending_matriz = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Similar a quienes no recibieron\n#\n#\n##################################################################\nprintf(\"MATRIZ. los empleados que no enviaron correo son: %s\", cant_notsending_matriz)\n\n\n# con grafos\ncant_notsending_grafo = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Similar a quienes no recibieron\n#\n#\n##################################################################\nprintf(\"GRAFO. los empleados que no enviaron correo son: %s\", cant_notsending_grafo) \n\n\n# ## 4.h) Cantidad de empleados contactados por al menos otros 30 empleados\n# \n# Calcular la cantidad de empleados que fueron contactados por $30$ o más empleados.\n\n# In[ ]:\n\n# con matrices\ncant_indegree30_matriz = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Similar a quienes no recibieron\n#\n#\n##################################################################\nprintf(\"MATRIZ. los contactados por al menos otros 30 empleados son: %s\", cant_indegree30_matriz)\n\n\n# con grafos\ncant_indegree30_grafo = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Similar a quienes no recibieron\n#\n#\n##################################################################\nprintf(\"GRAFO. los contactados por al menos otros 30 empleados son: %s\", cant_indegree30_grafo)\n\n\n\n# ## 4.i) Cantidad de empleados que contactaron a al menos otros 30 empleados\n# \n# Calcular la cantidad de empleados que contactaron a $30$ o más empleados.\n\n# In[ ]:\n\n#con matrices\ncant_outdegree30_matriz = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Similar a quienes no recibieron\n#\n#\n##################################################################\nprintf(\"MATRIZ. los que contactaron a al menos otros 30 empleados son: %s\", cant_outdegree30_matriz)\n\n#con grafos\ncant_outdegree30_grafo = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Similar a quienes no recibieron\n#\n#\n##################################################################\nprintf(\"GRAFO. los que contactaron a al menos otros 30 empleados son: %s\", cant_outdegree30_grafo)\n\n\n\n# ## 4.j) Cantidad de triángulos dirigidos\n# \n# Calcular la cantidad de triángulos dirigidos en $G$. \n# Recordar que $G$ es dirigido y la orientación de los triángulos importa, es decir, $i\\to j \\to k \\to i$ es lo mismo que $k \\to i \\to j \\to k $, pero diferente a $i\\to k \\to j \\to i$.\n# \n\n# In[ ]:\n\n#numero de triangulos dirigidos: 6819\nprintf(\"MATRIZ. Cantidad de triángulos dirigidos son: %s\", sum(diag(A %*% A %*% A/3)))\n\n# con matrices\ncant_triangnodirigido_matriz = NA\n##################################################################\n#\n# TU CÓDIGO ACÁ \n# Tip: similar a anterior\n#\n#\n##################################################################\nprintf(\"MATRIZ. Cantidad de triángulos no dirigidos son: %s\", cant_triangnodirigido_matriz)\n\n\n# con grafos\ncant_triangnodirigido_grafo = NA\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Buscar una función en igraph que ayude\n#\n#\n##################################################################\nprintf(\"GRAFO. Cantidad de triángulos no dirigidos son: %s\", cant_triangnodirigido_grafo)\n\n\n# ## 4.k) ¿Es el grafo conexo?\n# \n# Solo usando grafos, determinar si el grafo dirigido es débilmente y fuértemente conexo. \n# En caso de no serlo obtener el subgrafo con la componente conexa más grande (llamada componente gigante).\n\n# In[ ]:\n\nprintf(\"GRAFO. Es débilmente conexo: %s\", is.connected(g, mode = \"weak\"))\nprintf(\"GRAFO. Es fuertemente conexo: %s\", is.connected(g, mode = \"strong\"))\n\ng_components = components(g, mode = c(\"weak\", \"strong\"))\nstr(g_components)\n\nc_gigante = which.max(g_components$csize) #la componente mas grande\nvids_gigante = which(g_components$membership == c_gigante)\ng_gigante = induced_subgraph(g, vids_gigante)\nsummary(g_gigante)\nV(g)$id[g_components$membership != c_gigante] \n# sobran los vertices:\n#'Vince Kaminski (j..kaminski) Manager Risk Management Head'\n# 'Mary Fischer (mary.fischer) Employee '\n\nplot(g_gigante, edge.color=\"gray\", edge.width=1, edge.lty=1, edge.arrow.size=.5, \n vertex.size=3, vertex.label=NA,\n #vertex.color=nodes, vertex.shape = shapes,\n layout=layout_nicely(g_gigante))\n\n\n# ## 4.l) Guardar y cargar grafos\n# \n# Usando el paquete `igraph` guardar el grafo $G$ en formato PAJEK.\n# Luego cargar una copia del grafo en $G_\\text{copia}$.\n# ¿Porqué los dos grafos no son identicos?\n\n# In[ ]:\n\n#grabar els grafo G\nfilename_g = \"enron_g.pjk\"\n##################################################################\n# TU CÓDIGO ACÁ \n# Tip: Buscar una función en igraph que ayude\n#\n#\n##################################################################\n\n\n# cargar el grafo\ng_copia = read.graph(file=filename_g, format= \"pajek\")\nsummary(g_copia)\n\n#son iguales?\nidentical(g, g_copia)\n\n", "meta": {"hexsha": "2cfbc821e8328ca543f98b33314a0180d878e6b4", "size": 21154, "ext": "r", "lang": "R", "max_stars_repo_path": "r_deprecated/homework_1_graphs/ar_hw1.r", "max_stars_repo_name": "prbocca/na101_master", "max_stars_repo_head_hexsha": "63640fbaa5c4d149052f8123587ebe360aea6fd1", "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": "r_deprecated/homework_1_graphs/ar_hw1.r", "max_issues_repo_name": "prbocca/na101_master", "max_issues_repo_head_hexsha": "63640fbaa5c4d149052f8123587ebe360aea6fd1", "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_deprecated/homework_1_graphs/ar_hw1.r", "max_forks_repo_name": "prbocca/na101_master", "max_forks_repo_head_hexsha": "63640fbaa5c4d149052f8123587ebe360aea6fd1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-16T19:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T19:06:12.000Z", "avg_line_length": 29.586013986, "max_line_length": 453, "alphanum_fraction": 0.6210645741, "num_tokens": 6048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15817433687509236, "lm_q2_score": 0.12252319970181708, "lm_q1q2_score": 0.01938002586464943}} {"text": "# food web functions modified from Owen Petchey\n# original functions were found at thetrophiclink.org\n# and are available on github here: https://github.com/opetchey/dumping_ground/blob/master/random_cascade_niche/FoodWebFunctions.r\n\n\n## some code to plot a predation matrix\n## some useful functions script has slightly different Plot.matrix code\nPlot.matrix <- function(web, title=\" \", point.cex=0.5, trait.cex=1,\n diag.line=T, traits=F, by.consumer=T, axes.labels=F, sp.pt.ch=NA, pt.col=\"black\"){\n \n S <- length(web[,1])\n\n ##point.cex <- 30/30\n ##trait.cex <- 30/30\n \n dimnames(web) <- list(1:S, 1:S)\n consumer <- rep(1:S, each=S)\n resource <- rep(1:S, S)\n web.list <- Matrix.to.list(web)\n par(xpd=T)\n plot(consumer, resource, pch=19, type=\"n\", cex=0.1,\n ann=F, axes=F,\n xlim=c(1, S), ylim=c(1, S))\n if(length(traits)==1)\n points(web.list[,2], S+1-as.numeric(web.list[,1]),\n type=\"p\", pch=19, cex=point.cex, col=pt.col)\n if(length(traits)==length(web)){\n\n colours.to.use <- rev(heat.colors(30)[c(-1:-5, -26:-30)])\n ##colours.to.use <- rev(gray(1:30/30)[c(-1:-5, -26:-30)])\n \n if(by.consumer){\n integer.traits <- matrix(0, S, S)\n for(i in 1:S){\n traits.01 <- traits[,i]-min(traits[,i])\n traits.01 <- traits.01/max(traits.01)\n integer.traits[,i] <- round(traits.01*19)+1\n integer.traits[traits[,i]==0,i] = NaN\n \n }\n }\n \n if(!by.consumer){\n colours.to.use <- heat.colors(20)\n traits.01 <- traits-min(traits)\n traits.01 <- traits.01/max(traits.01)\n integer.traits <- round(traits.01*19)+1\n }\n\n if(point.cex>trait.cex){\n points(web.list[,2], S+1-as.numeric(web.list[,1]),\n type=\"p\", pch=19, cex=point.cex, col=\"black\")##colours.to.use[integer.traits])\n points(rep(1:S, each=S), rep(S:1, times=S), \n pch=19, cex=trait.cex, col=colours.to.use[integer.traits])\n }\n if(point.cex1)\n result <- rbind(result, t.result)\n }\n } \n result\n}\n\nFraction.omnivores <- function(web) {\n TLs <- GetTL(web)\n non.int.TL <- web[,TLs %% 1 != 0]\n if(is.matrix(non.int.TL))\n frac.omniv <- sum(apply(non.int.TL, 2, sum) > 1) / length(web[,1])\n if(is.vector(non.int.TL)) \n frac.omniv <- (sum(non.int.TL) > 1) / length(web[,1])\n frac.omniv\n}\n\nLevel.omnivory <- function(web) {\n\n TLs <- GetTL(web)\n\n if( sum(is.na(TLs)) == length(TLs) )\n rr <- NA\n\n if( sum(is.na(TLs)) != length(TLs) ) {\n\n \n web.TLs <- matrix(rep(TLs, length(web[,1])), length(web[,1]), length(web[,1]))\n lo.pc <- numeric(length=length(web[,1]))\n for(i in 1:length(web[,1])) {\n tt <- web.TLs[web[,i]==1,i]\n if(length(tt)==0 | sum(!is.na(tt))==0 )\n lo.pc[i] = NA\n if(length(tt)>0 & sum(!is.na(tt))!=0)\n lo.pc[i] <- sd(tt)\n }\n rr <- mean(lo.pc, na.rm=T)\n }\n rr\n}\n\n\n## return the proportion of bottom, intermediate, top,\n## unconnected and purely cannibalistic specie\nBottom.Intermediate.Top <- function(web, proportion=TRUE, check.web=FALSE){\n \n ## find the names and numbers of BIT, unconnected and pure cannibals\n names.all <- 1:length(web[1,])\n dimnames(web) <- list(names.all, names.all)\n names.Bottom <- names.all[apply(web, 2, sum)==0 & apply(web, 1, sum)!=0]#pulls out names where column sum ==0, and where row sum == >0. e.g. an alga does not consume anyhting (column sum == 0) but is consumed (row sum = >0)\n number.Bottom <- length(names.Bottom)\n names.Top <- names.all[apply(web, 2, sum)!=0 & apply(web, 1, sum)==0]\n number.Top <- length(names.Top)\n names.Unconnected <- names.all[apply(web, 2, sum)==0 & apply(web, 1, sum)==0]\n number.Unconnected <- length(names.Unconnected)\n number.Pure.cannibals <- 0\n names.Pure.cannibals <- character(0)\n for(i in 1:length(web[,1]))\n if(web[i,i]!=0 && sum(web[-i,i]+web[i,-i])==0){\n if(number.Pure.cannibals==0){\n names.Pure.cannibals <- dimnames(web)[[1]][i]\n number.Pure.cannibals <- 1\n }\n else{\n names.Pure.cannibals <- c(names.Pure.cannibals, dimnames(web)[[1]][i])\n number.Pure.cannibals <- number.Pure.cannibals + 1\n }\n }\n names.Intermediate <- dimnames(web)[[1]][is.na(match(dimnames(web)[[1]],\n c(names.Bottom, names.Top, names.Unconnected, names.Pure.cannibals)))]\n number.Intermediate <- length(web[1,])-number.Bottom-number.Top-number.Unconnected-number.Pure.cannibals\n\n if(proportion)\n result <- list(Bottom=names.Bottom,\n Intermediate=names.Intermediate,\n Top=names.Top,\n Unconnected=names.Unconnected,\n Pure.cannibals=names.Pure.cannibals,\n Proportions.of.each=c(number.Bottom, number.Intermediate, number.Top, number.Unconnected, number.Pure.cannibals)/length(web[1,]))\n if(!proportion)\n result <- list(Bottom=names.Bottom,\n Intermediate=names.Intermediate,\n Top=names.Top,\n Unconnected=names.Unconnected,\n Pure.cannibals=names.Pure.cannibals,\n Proportions.of.each=c(number.Bottom, number.Intermediate, number.Top, number.Unconnected, number.Pure.cannibals))\n result\n}\n\nNum.herbivores <- function(web) {\n \n S <- length(web[,1])\n ## Find the rows/columns with basal species\n B.rows <- c(1:S)[apply(web, 2, sum)==0 & apply(web, 1, sum)!=0]\n ## Find r/c wth species that only eat basal\n if(length(B.rows)==0)\n Nh <- NA\n\n if(length(B.rows)>0) {\n if( length(B.rows)>1 & (S-length(B.rows))>1 )\n Nh <- sum( apply(web[B.rows,], 2, function(x) sum(x!=0)>0) &\n apply(web[-B.rows,], 2, function(x) sum(x!=0)==0) )\n \n if( length(B.rows)==1 & (S-length(B.rows))>1 )\n Nh <- sum( web[B.rows,]!=0 &\n apply(web[-B.rows,], 2, function(x) sum(x!=0)==0) )\n \n if( length(B.rows)>1 & (S-length(B.rows))==1 )\n Nh <- sum( apply(web[B.rows,], 2, function(x) sum(x!=0)>0) &\n web[-B.rows,]==0) \n }\n Nh\n\n}\n \n \nCannibals <- function(web)\n length(dimnames(web)[[1]][diag(web)==1]) / length(web[1,])\n\nGen.sd <- function(web)\n # below is Pomeranz correction feb 2020\n sd(colSums(web)/(sum(web)/length(web[,1])))\n\t## corrected, cf. Thomas Barnum, 24.1.1013\n\t## sd(colSums(web)/sum(web)/length(web[,1]))\n ##sd(colSums(web)/sum(web))\n\nVul.sd <- function(web)\n # below is Pomeranz correction feb 2020\n sd(rowSums(web)/(sum(web)/length(web[,1])))\n## corrected, cf. Thomas Barnum, 24.1.1013\n\t## sd(rowSums(web)/sum(web)/length(web[,1]))\n ##sd(rowSums(web)/sum(web))\n\nMaxsim <- function(web){\n sims <- matrix(0, length(web[,1]), length(web[,1]))\n for(i in 1:length(web[,1]))\n for(j in 1:length(web[,1]))\n sims[i,j] <- T.sim.ij(web, i, j)\n diag(sims) <- NA\n mean(apply(sims, 1, function(x) max(x[!is.na(x)])))\n}\n\n## used by Maxsim\nT.sim.ij <- function(web, i, j){\n same <- sum(web[i,] & web[j,]) + sum(web[,i] & web[,j])\n total <- sum(web[i,] | web[j,]) + sum(web[,i] | web[,j])\n same / total\n}\n\nGetTL <- function(web){\n \n ## takes predation matrix with consumers in columns\n ## identify the columns with basal species\n tweb <- t(web)\n\n ## make the rows add to one\n rs <- rowSums(tweb)\n for(i in 1:length(tweb[,1]))\n tweb[i,tweb[i,]==1] = 1/rs[i]\n\n nb.TL <- try(solve(diag(length(tweb[,1])) - tweb), T)\n\n if(class(nb.TL)==\"try-error\")\n nbTL <- rep(NA, length(tweb[,1]))\n\n if(class(nb.TL)!=\"try-error\")\n nbTL <- rowSums(nb.TL)\n\n nbTL\n \n}\n \n \n\n## takes a food web in matrix format and coverts it to list format\nMatrix.to.list <- function(web.matrix, predator.first=TRUE){\n if(length(dimnames(web.matrix)[[1]])==length(web.matrix[1,]))\n species.names <- dimnames(web.matrix)[[1]]\n else\n species.names <- 1:length(web.matrix[,1])\n web.list <- matrix(0, sum(web.matrix), 2)\n counter <- 1\n for(i in 1:length(web.matrix[,1]))\n for(j in 1:length(web.matrix[,1]))\n if(web.matrix[i,j]==1){\n web.list[counter,] <- c(species.names[i],species.names[j])\n counter <- counter + 1\n }\n if(!predator.first)\n web.list <- cbind(web.list[,2], web.list[,1])\n web.list\n}\n\n", "meta": {"hexsha": "4e084743e0f6e0c7942e9ee3773b2fecc797a24c", "size": 14526, "ext": "r", "lang": "R", "max_stars_repo_path": "functions/FoodWebFunctions.r", "max_stars_repo_name": "Jpomz/probably-feeling-anxious", "max_stars_repo_head_hexsha": "f8fa34180ad34ea7302ba139e2573241466f3b8b", "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": "functions/FoodWebFunctions.r", "max_issues_repo_name": "Jpomz/probably-feeling-anxious", "max_issues_repo_head_hexsha": "f8fa34180ad34ea7302ba139e2573241466f3b8b", "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": "functions/FoodWebFunctions.r", "max_forks_repo_name": "Jpomz/probably-feeling-anxious", "max_forks_repo_head_hexsha": "f8fa34180ad34ea7302ba139e2573241466f3b8b", "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.4700460829, "max_line_length": 226, "alphanum_fraction": 0.4935976869, "num_tokens": 4031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.039638840944537325, "lm_q1q2_score": 0.01889106557528496}} {"text": "\n\n\n\n\n\n\n CHAPTER 2\n\n\n Data Structure Access\n\n\n\n\n The following functions allow one to create and manipu-\nlate the various types of lisp data structures. Refer to\n1.2 for details of the data structures known to FRANZ LISP.\n\n\n\n 2.1. Lists\n\n The following functions exist for the creation\n and manipulating of lists. Lists are composed of a\n linked list of objects called either 'list cells',\n 'cons cells' or 'dtpr cells'. Lists are normally ter-\n minated with the special symbol nil. nil is both a\n symbol and a representation for the empty list ().\n\n\n\n 2.1.1. list creation\n\n(cons 'g_arg1 'g_arg2)\n\n RETURNS: a new list cell whose car is g_arg1 and whose\n cdr is g_arg2.\n\n(xcons 'g_arg1 'g_arg2)\n\n EQUIVALENT TO: (_\bc_\bo_\bn_\bs '_\bg__\ba_\br_\bg_\b2 '_\bg__\ba_\br_\bg_\b1)\n\n(ncons 'g_arg)\n\n EQUIVALENT TO: (_\bc_\bo_\bn_\bs '_\bg__\ba_\br_\bg _\bn_\bi_\bl)\n\n(list ['g_arg1 ... ])\n\n RETURNS: a list whose elements are the g_arg_\bi.\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9Data Structure Access 2-1\n\n\n\n\n\n\n\nData Structure Access 2-2\n\n\n(append 'l_arg1 'l_arg2)\n\n RETURNS: a list containing the elements of l_arg1 fol-\n lowed by l_arg2.\n\n NOTE: To generate the result, the top level list cells\n of l_arg1 are duplicated and the cdr of the last\n list cell is set to point to l_arg2. Thus this\n is an expensive operation if l_arg1 is large.\n See the descriptions of _\bn_\bc_\bo_\bn_\bc and _\bt_\bc_\bo_\bn_\bc for\n cheaper ways of doing the _\ba_\bp_\bp_\be_\bn_\bd if the list\n l_arg1 can be altered.\n\n(append1 'l_arg1 'g_arg2)\n\n RETURNS: a list like l_arg1 with g_arg2 as the last\n element.\n\n NOTE: this is equivalent to (append 'l_arg1 (list\n 'g_arg2)).\n\n\n ____________________________________________________\n\n ; A common mistake is using append to add one element to the end of a list\n -> (_\ba_\bp_\bp_\be_\bn_\bd '(_\ba _\bb _\bc _\bd) '_\be)\n (a b c d . e)\n ; The user intended to say:\n -> (_\ba_\bp_\bp_\be_\bn_\bd '(_\ba _\bb _\bc _\bd) '(_\be))\n (_\ba _\bb _\bc _\bd _\be)\n ; _\bb_\be_\bt_\bt_\be_\br _\bi_\bs _\ba_\bp_\bp_\be_\bn_\bd_\b1\n -> (_\ba_\bp_\bp_\be_\bn_\bd_\b1 '(_\ba _\bb _\bc _\bd) '_\be)\n (_\ba _\bb _\bc _\bd _\be)\n ____________________________________________________\n\n\n\n\n(quote! [g_qform_\bi] ...[! 'g_eform_\bi] ... [!! 'l_form_\bi] ...)\n\n RETURNS: The list resulting from the splicing and\n insertion process described below.\n\n NOTE: _\bq_\bu_\bo_\bt_\be! is the complement of the _\bl_\bi_\bs_\bt function.\n _\bl_\bi_\bs_\bt forms a list by evaluating each for in the\n argument list; evaluation is suppressed if the\n form is _\bq_\bu_\bo_\bt_\beed. In _\bq_\bu_\bo_\bt_\be!, each form is impli-\n citly _\bq_\bu_\bo_\bt_\beed. To be evaluated, a form must be\n preceded by one of the evaluate operations ! and\n !!. ! g_eform evaluates g_form and the value is\n inserted in the place of the call; !! l_form\n evaluates l_form and the value is spliced into\n the place of the call.\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-3\n\n\n `Splicing in' means that the parentheses sur-\n rounding the list are removed as the example\n below shows. Use of the evaluate operators can\n occur at any level in a form argument.\n\n Another way to get the effect of the _\bq_\bu_\bo_\bt_\be! func-\n tion is to use the backquote character macro (see\n 8.3.3).\n\n\n ____________________________________________________\n\n (_\bq_\bu_\bo_\bt_\be! _\bc_\bo_\bn_\bs ! (_\bc_\bo_\bn_\bs _\b1 _\b2) _\b3) = (_\bc_\bo_\bn_\bs (_\b1 . _\b2) _\b3)\n (_\bq_\bu_\bo_\bt_\be! _\b1 !! (_\bl_\bi_\bs_\bt _\b2 _\b3 _\b4) _\b5) = (_\b1 _\b2 _\b3 _\b4 _\b5)\n (_\bs_\be_\bt_\bq _\bq_\bu_\bo_\bt_\be_\bd '_\be_\bv_\ba_\bl_\be_\bd)(_\bq_\bu_\bo_\bt_\be! ! ((_\bI _\ba_\bm ! _\bq_\bu_\bo_\bt_\be_\bd))) = ((_\bI _\ba_\bm _\be_\bv_\ba_\bl_\be_\bd))\n (_\bq_\bu_\bo_\bt_\be! _\bt_\br_\by ! '(_\bt_\bh_\bi_\bs ! _\bo_\bn_\be)) = (_\bt_\br_\by (_\bt_\bh_\bi_\bs ! _\bo_\bn_\be))\n ____________________________________________________\n\n\n\n\n\n(bignum-to-list 'b_arg)\n\n RETURNS: A list of the fixnums which are used to\n represent the bignum.\n\n NOTE: the inverse of this function is _\bl_\bi_\bs_\bt-_\bt_\bo-_\bb_\bi_\bg_\bn_\bu_\bm.\n\n(list-to-bignum 'l_ints)\n\n WHERE: l_ints is a list of fixnums.\n\n RETURNS: a bignum constructed of the given fixnums.\n\n NOTE: the inverse of this function is _\bb_\bi_\bg_\bn_\bu_\bm-_\bt_\bo-_\bl_\bi_\bs_\bt.\n\n\n\n\n 2.1.2. list predicates\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-4\n\n\n(dtpr 'g_arg)\n\n RETURNS: t iff g_arg is a list cell.\n\n NOTE: that (dtpr '()) is nil. The name dtpr is a con-\n traction for ``dotted pair''.\n\n(listp 'g_arg)\n\n RETURNS: t iff g_arg is a list object or nil.\n\n(tailp 'l_x 'l_y)\n\n RETURNS: l_x, if a list cell _\be_\bq to l_x is found by\n _\bc_\bd_\bring down l_y zero or more times, nil other-\n wise.\n\n\n ____________________________________________________\n\n -> (_\bs_\be_\bt_\bq _\bx '(_\ba _\bb _\bc _\bd) _\by (_\bc_\bd_\bd_\br _\bx))\n (c d)\n -> (_\ba_\bn_\bd (_\bd_\bt_\bp_\br _\bx) (_\bl_\bi_\bs_\bt_\bp _\bx)) ; x and y are dtprs and lists\n t\n -> (_\bd_\bt_\bp_\br '()) ; () is the same as nil and is not a dtpr\n nil\n -> (_\bl_\bi_\bs_\bt_\bp '()) ; however it is a list\n t\n -> (_\bt_\ba_\bi_\bl_\bp _\by _\bx)\n (c d)\n ____________________________________________________\n\n\n\n\n(length 'l_arg)\n\n RETURNS: the number of elements in the top level of\n list l_arg.\n\n\n\n 2.1.3. list accessing\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-5\n\n\n(car 'l_arg)\n(cdr 'l_arg)\n\n RETURNS: _\bc_\bo_\bn_\bs cell. (_\bc_\ba_\br (_\bc_\bo_\bn_\bs x y)) is always x, (_\bc_\bd_\br\n (_\bc_\bo_\bn_\bs x y)) is always y. In FRANZ LISP, the\n cdr portion is located first in memory. This\n is hardly noticeable, and we mention it pri-\n marily as a curiosity.\n\n(c..r 'lh_arg)\n\n WHERE: the .. represents any positive number of a's\n and d's.\n\n RETURNS: the result of accessing the list structure in\n the way determined by the function name. The\n a's and d's are read from right to left, a d\n directing the access down the cdr part of the\n list cell and an a down the car part.\n\n NOTE: lh_arg may also be nil, and it is guaranteed that\n the car and cdr of nil is nil. If lh_arg is a\n hunk, then (_\bc_\ba_\br '_\bl_\bh__\ba_\br_\bg) is the same as\n (_\bc_\bx_\br _\b1 '_\bl_\bh__\ba_\br_\bg) and (_\bc_\bd_\br '_\bl_\bh__\ba_\br_\bg) is the same as\n (_\bc_\bx_\br _\b0 '_\bl_\bh__\ba_\br_\bg).\n It is generally hard to read and understand the\n context of functions with large strings of a's\n and d's, but these functions are supported by\n rapid accessing and open-compiling (see Chapter\n 12).\n\n(nth 'x_index 'l_list)\n\n RETURNS: the nth element of l_list, assuming zero-based\n index. Thus (nth 0 l_list) is the same as\n (car l_list). _\bn_\bt_\bh is both a function, and a\n compiler macro, so that more efficient code\n might be generated than for _\bn_\bt_\bh_\be_\bl_\be_\bm (described\n below).\n\n NOTE: If x_arg1 is non-positive or greater than the\n length of the list, nil is returned.\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-6\n\n\n(nthcdr 'x_index 'l_list)\n\n RETURNS: the result of _\bc_\bd_\bring down the list l_list\n x_index times.\n\n NOTE: If x_index is less than 0, then\n (_\bc_\bo_\bn_\bs _\bn_\bi_\bl '_\bl__\bl_\bi_\bs_\bt) is returned.\n\n(nthelem 'x_arg1 'l_arg2)\n\n RETURNS: The x_arg1'_\bs_\bt element of the list l_arg2.\n\n NOTE: This function comes from the PDP-11 Lisp system.\n\n(last 'l_arg)\n\n RETURNS: the last list cell in the list l_arg.\n\n EXAMPLE: _\bl_\ba_\bs_\bt does NOT return the last element of a\n list!\n (_\bl_\ba_\bs_\bt '(_\ba _\bb)) = (b)\n\n(ldiff 'l_x 'l_y)\n\n RETURNS: a list of all elements in l_x but not in l_y\n , i.e., the list difference of l_x and l_y.\n\n NOTE: l_y must be a tail of l_x, i.e., _\be_\bq to the result\n of applying some number of _\bc_\bd_\br's to l_x. Note\n that the value of _\bl_\bd_\bi_\bf_\bf is always new\n list structure unless l_y is nil, in which case\n (_\bl_\bd_\bi_\bf_\bf _\bl__\bx _\bn_\bi_\bl) is l_x itself. If l_y is not\n a tail of l_x, _\bl_\bd_\bi_\bf_\bf generates an error.\n\n EXAMPLE: (_\bl_\bd_\bi_\bf_\bf '_\bl__\bx (_\bm_\be_\bm_\bb_\be_\br '_\bg__\bf_\bo_\bo '_\bl__\bx)) gives all\n elements in l_x up to the first g_foo.\n\n\n\n 2.1.4. list manipulation\n\n(rplaca 'lh_arg1 'g_arg2)\n\n RETURNS: the modified lh_arg1.\n\n SIDE EFFECT: the car of lh_arg1 is set to g_arg2. If\n lh_arg1 is a hunk then the second element\n of the hunk is set to g_arg2.\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-7\n\n\n(rplacd 'lh_arg1 'g_arg2)\n\n RETURNS: the modified lh_arg1.\n\n SIDE EFFECT: the cdr of lh_arg2 is set to g_arg2. If\n lh_arg1 is a hunk then the first element\n of the hunk is set to g_arg2.\n\n\n(attach 'g_x 'l_l)\n\n RETURNS: l_l whose _\bc_\ba_\br is now g_x, whose _\bc_\ba_\bd_\br is the\n original (_\bc_\ba_\br _\bl__\bl), and whose _\bc_\bd_\bd_\br is the ori-\n ginal (_\bc_\bd_\br _\bl__\bl).\n\n NOTE: what happens is that g_x is added to the begin-\n ning of list l_l yet maintaining the same list\n cell at the beginning of the list.\n\n(delete 'g_val 'l_list ['x_count])\n\n RETURNS: the result of splicing g_val from the top\n level of l_list no more than x_count times.\n\n NOTE: x_count defaults to a very large number, thus if\n x_count is not given, all occurrences of g_val\n are removed from the top level of l_list. g_val\n is compared with successive _\bc_\ba_\br's of l_list using\n the function _\be_\bq_\bu_\ba_\bl.\n\n SIDE EFFECT: l_list is modified using rplacd, no new\n list cells are used.\n\n(delq 'g_val 'l_list ['x_count])\n(dremove 'g_val 'l_list ['x_count])\n\n RETURNS: the result of splicing g_val from the top\n level of l_list no more than x_count times.\n\n NOTE: _\bd_\be_\bl_\bq (and _\bd_\br_\be_\bm_\bo_\bv_\be) are the same as _\bd_\be_\bl_\be_\bt_\be except\n that _\be_\bq is used for comparison instead of _\be_\bq_\bu_\ba_\bl.\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-8\n\n\n\n ____________________________________________________\n\n ; note that you should use the value returned by _\bd_\be_\bl_\be_\bt_\be or _\bd_\be_\bl_\bq\n ; and not assume that g_val will always show the deletions.\n ; For example\n\n -> (_\bs_\be_\bt_\bq _\bt_\be_\bs_\bt '(_\ba _\bb _\bc _\ba _\bd _\be))\n (a b c a d e)\n -> (_\bd_\be_\bl_\be_\bt_\be '_\ba _\bt_\be_\bs_\bt)\n (b c d e) ; the value returned is what we would expect\n -> _\bt_\be_\bs_\bt\n (a b c d e) ; but test still has the first a in the list!\n ____________________________________________________\n\n\n\n\n(remq 'g_x 'l_l ['x_count])\n(remove 'g_x 'l_l)\n\n RETURNS: a _\bc_\bo_\bp_\by of l_l with all top level elements\n _\be_\bq_\bu_\ba_\bl to g_x removed. _\br_\be_\bm_\bq uses _\be_\bq instead of\n _\be_\bq_\bu_\ba_\bl for comparisons.\n\n NOTE: remove does not modify its arguments like _\bd_\be_\bl_\be_\bt_\be,\n and _\bd_\be_\bl_\bq do.\n\n(insert 'g_object 'l_list 'u_comparefn 'g_nodups)\n\n RETURNS: a list consisting of l_list with g_object des-\n tructively inserted in a place determined by\n the ordering function u_comparefn.\n\n NOTE: (_\bc_\bo_\bm_\bp_\ba_\br_\be_\bf_\bn '_\bg__\bx '_\bg__\by) should return something\n non-nil if g_x can precede g_y in sorted order,\n nil if g_y must precede g_x. If u_comparefn is\n nil, alphabetical order will be used. If g_nodups\n is non-nil, an element will not be inserted if an\n equal element is already in the list. _\bi_\bn_\bs_\be_\br_\bt\n does binary search to determine where to insert\n the new element.\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-9\n\n\n(merge 'l_data1 'l_data2 'u_comparefn)\n\n RETURNS: the merged list of the two input sorted lists\n l_data1 and l_data1 using binary comparison\n function u_comparefn.\n\n NOTE: (_\bc_\bo_\bm_\bp_\ba_\br_\be_\bf_\bn '_\bg__\bx '_\bg__\by) should return something\n non-nil if g_x can precede g_y in sorted order,\n nil if g_y must precede g_x. If u_comparefn is\n nil, alphabetical order will be used.\n u_comparefn should be thought of as \"less than or\n equal\". _\bm_\be_\br_\bg_\be changes both of its data argu-\n ments.\n\n(subst 'g_x 'g_y 'l_s)\n(dsubst 'g_x 'g_y 'l_s)\n\n RETURNS: the result of substituting g_x for all _\be_\bq_\bu_\ba_\bl\n occurrences of g_y at all levels in l_s.\n\n NOTE: If g_y is a symbol, _\be_\bq will be used for comparis-\n ons. The function _\bs_\bu_\bb_\bs_\bt does not modify l_s but\n the function _\bd_\bs_\bu_\bb_\bs_\bt (destructive substitution)\n does.\n\n(lsubst 'l_x 'g_y 'l_s)\n\n RETURNS: a copy of l_s with l_x spliced in for every\n occurrence of of g_y at all levels. Splicing\n in means that the parentheses surrounding the\n list l_x are removed as the example below\n shows.\n\n\n ____________________________________________________\n\n -> (_\bs_\bu_\bb_\bs_\bt '(_\ba _\bb _\bc) '_\bx '(_\bx _\by _\bz (_\bx _\by _\bz) (_\bx _\by _\bz)))\n ((a b c) y z ((a b c) y z) ((a b c) y z))\n -> (_\bl_\bs_\bu_\bb_\bs_\bt '(_\ba _\bb _\bc) '_\bx '(_\bx _\by _\bz (_\bx _\by _\bz) (_\bx _\by _\bz)))\n (a b c y z (a b c y z) (a b c y z))\n ____________________________________________________\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-10\n\n\n(subpair 'l_old 'l_new 'l_expr)\n\n WHERE: there are the same number of elements in\n l_old as l_new.\n\n RETURNS: the list l_expr with all occurrences of a\n object in l_old replaced by the corresponding\n one in l_new. When a substitution is made, a\n copy of the value to substitute in is not\n made.\n\n EXAMPLE: (_\bs_\bu_\bb_\bp_\ba_\bi_\br '(_\ba _\bc)' (_\bx _\by) '(_\ba _\bb _\bc _\bd)) = (_\bx _\bb _\by _\bd)\n\n\n(nconc 'l_arg1 'l_arg2 ['l_arg3 ...])\n\n RETURNS: A list consisting of the elements of l_arg1\n followed by the elements of l_arg2 followed by\n l_arg3 and so on.\n\n NOTE: The _\bc_\bd_\br of the last list cell of l_arg_\bi is\n changed to point to l_arg_\bi+_\b1.\n\n\n ____________________________________________________\n\n ; _\bn_\bc_\bo_\bn_\bc is faster than _\ba_\bp_\bp_\be_\bn_\bd because it doesn't allocate new list cells.\n -> (_\bs_\be_\bt_\bq _\bl_\bi_\bs_\b1 '(_\ba _\bb _\bc))\n (a b c)\n -> (_\bs_\be_\bt_\bq _\bl_\bi_\bs_\b2 '(_\bd _\be _\bf))\n (d e f)\n -> (_\ba_\bp_\bp_\be_\bn_\bd _\bl_\bi_\bs_\b1 _\bl_\bi_\bs_\b2)\n (a b c d e f)\n -> _\bl_\bi_\bs_\b1\n (a b c) ; note that lis1 has not been changed by _\ba_\bp_\bp_\be_\bn_\bd\n -> (_\bn_\bc_\bo_\bn_\bc _\bl_\bi_\bs_\b1 _\bl_\bi_\bs_\b2)\n (a b c d e f) ; _\bn_\bc_\bo_\bn_\bc returns the same value as _\ba_\bp_\bp_\be_\bn_\bd\n -> _\bl_\bi_\bs_\b1\n (a b c d e f) ; but in doing so alters lis1\n ____________________________________________________\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-11\n\n\n(reverse 'l_arg)\n(nreverse 'l_arg)\n\n RETURNS: the list l_arg with the elements at the top\n level in reverse order.\n\n NOTE: The function _\bn_\br_\be_\bv_\be_\br_\bs_\be does the reversal in place,\n that is the list structure is modified.\n\n(nreconc 'l_arg 'g_arg)\n\n EQUIVALENT TO: (_\bn_\bc_\bo_\bn_\bc (_\bn_\br_\be_\bv_\be_\br_\bs_\be '_\bl__\ba_\br_\bg) '_\bg__\ba_\br_\bg)\n\n\n\n\n 2.2. Predicates\n\n The following functions test for properties of\n data objects. When the result of the test is either\n 'false' or 'true', then nil will be returned for\n 'false' and something other than nil (often t) will be\n returned for 'true'.\n\n(arrayp 'g_arg)\n\n RETURNS: t iff g_arg is of type array.\n\n(atom 'g_arg)\n\n RETURNS: t iff g_arg is not a list or hunk object.\n\n NOTE: (_\ba_\bt_\bo_\bm '()) returns t.\n\n(bcdp 'g_arg)\n\n RETURNS: t iff g_arg is a data object of type binary.\n\n NOTE: This function is a throwback to the PDP-11 Lisp\n system. The name stands for binary code predi-\n cate.\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-12\n\n\n(bigp 'g_arg)\n\n RETURNS: t iff g_arg is a bignum.\n\n(dtpr 'g_arg)\n\n RETURNS: t iff g_arg is a list cell.\n\n NOTE: that (dtpr '()) is nil.\n\n(hunkp 'g_arg)\n\n RETURNS: t iff g_arg is a hunk.\n\n(listp 'g_arg)\n\n RETURNS: t iff g_arg is a list object or nil.\n\n(stringp 'g_arg)\n\n RETURNS: t iff g_arg is a string.\n\n(symbolp 'g_arg)\n\n RETURNS: t iff g_arg is a symbol.\n\n(valuep 'g_arg)\n\n RETURNS: t iff g_arg is a value cell\n\n(vectorp 'v_vector)\n\n RETURNS: t iff the argument is a vector.\n\n(vectorip 'v_vector)\n\n RETURNS: t iff the argument is an immediate-vector.\n\n(type 'g_arg)\n(typep 'g_arg)\n\n RETURNS: a symbol whose pname describes the type of\n g_arg.\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-13\n\n\n(signp s_test 'g_val)\n\n RETURNS: t iff g_val is a number and the given test\n s_test on g_val returns true.\n\n NOTE: The fact that _\bs_\bi_\bg_\bn_\bp simply returns nil if g_val\n is not a number is probably the most important\n reason that _\bs_\bi_\bg_\bn_\bp is used. The permitted values\n for s_test and what they mean are given in this\n table.\n\n\u001b8 ____________________\n s_test tested\n\n\u001b8 ____________________\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b____________________\n l g_val < 0\n le g_val <\b_ 0\n e g_val = 0\n n g_val =\b/ 0\n ge g_val >\b_ 0\n g g_val > 0\n\u001b8 ____________________\n\u001b7 |\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\n\n\n\n\n\n\n\n |\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\b\u001b7|\n\n\n\n\n\n\n\n\n\n\n(eq 'g_arg1 'g_arg2)\n\n RETURNS: t if g_arg1 and g_arg2 are the exact same lisp\n object.\n\n NOTE: _\bE_\bq simply tests if g_arg1 and g_arg2 are located\n in the exact same place in memory. Lisp objects\n which print the same are not necessarily _\be_\bq. The\n only objects guaranteed to be _\be_\bq are interned\n symbols with the same print name. [Unless a sym-\n bol is created in a special way (such as with\n _\bu_\bc_\bo_\bn_\bc_\ba_\bt or _\bm_\ba_\bk_\bn_\ba_\bm) it will be interned.]\n\n(neq 'g_x 'g_y)\n\n RETURNS: t if g_x is not _\be_\bq to g_y, otherwise nil.\n\n(equal 'g_arg1 'g_arg2)\n(eqstr 'g_arg1 'g_arg2)\n\n RETURNS: t iff g_arg1 and g_arg2 have the same struc-\n ture as described below.\n\n NOTE: g_arg and g_arg2 are _\be_\bq_\bu_\ba_\bl if\n\n (1) they are _\be_\bq.\n\n (2) they are both fixnums with the same value\n\n\n\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-14\n\n\n (3) they are both flonums with the same value\n\n (4) they are both bignums with the same value\n\n (5) they are both strings and are identical.\n\n (6) they are both lists and their cars and cdrs are\n _\be_\bq_\bu_\ba_\bl.\n\n\n ____________________________________________________\n\n ; _\be_\bq is much faster than _\be_\bq_\bu_\ba_\bl, especially in compiled code,\n ; however you cannot use _\be_\bq to test for equality of numbers outside\n ; of the range -1024 to 1023. _\be_\bq_\bu_\ba_\bl will always work.\n -> (_\be_\bq _\b1_\b0_\b2_\b3 _\b1_\b0_\b2_\b3)\n t\n -> (_\be_\bq _\b1_\b0_\b2_\b4 _\b1_\b0_\b2_\b4)\n nil\n -> (_\be_\bq_\bu_\ba_\bl _\b1_\b0_\b2_\b4 _\b1_\b0_\b2_\b4)\n t\n ____________________________________________________\n\n\n\n\n\n(not 'g_arg)\n(null 'g_arg)\n\n RETURNS: t iff g_arg is nil.\n\n\n(member 'g_arg1 'l_arg2)\n(memq 'g_arg1 'l_arg2)\n\n RETURNS: that part of the l_arg2 beginning with the\n first occurrence of g_arg1. If g_arg1 is not\n in the top level of l_arg2, nil is returned.\n\n NOTE: _\bm_\be_\bm_\bb_\be_\br tests for equality with _\be_\bq_\bu_\ba_\bl, _\bm_\be_\bm_\bq tests\n for equality with _\be_\bq.\n\n\n\n\n 2.3. Symbols and Strings\n\n In many of the following functions the distinc-\n tion between symbols and strings is somewhat blurred.\n To remind ourselves of the difference, a string is a\n null terminated sequence of characters, stored as com-\n pactly as possible. Strings are used as constants in\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-15\n\n\n FRANZ LISP. They _\be_\bv_\ba_\bl to themselves. A symbol has\n additional structure: a value, property list, function\n binding, as well as its external representation (or\n print-name). If a symbol is given to one of the\n string manipulation functions below, its print name\n will be used as the string.\n\n Another popular way to represent strings in Lisp\n is as a list of fixnums which represent characters.\n The suffix 'n' to a string manipulation function indi-\n cates that it returns a string in this form.\n\n\n\n 2.3.1. symbol and string creation\n\n(concat ['stn_arg1 ... ])\n(uconcat ['stn_arg1 ... ])\n\n RETURNS: a symbol whose print name is the result of\n concatenating the print names, string charac-\n ters or numerical representations of the\n sn_arg_\bi.\n\n NOTE: If no arguments are given, a symbol with a null\n pname is returned. _\bc_\bo_\bn_\bc_\ba_\bt places the symbol\n created on the oblist, the function _\bu_\bc_\bo_\bn_\bc_\ba_\bt does\n the same thing but does not place the new symbol\n on the oblist.\n\n EXAMPLE: (_\bc_\bo_\bn_\bc_\ba_\bt '_\ba_\bb_\bc (_\ba_\bd_\bd _\b3 _\b4) \"_\bd_\be_\bf\") = abc7def\n\n(concatl 'l_arg)\n\n EQUIVALENT TO: (_\ba_\bp_\bp_\bl_\by '_\bc_\bo_\bn_\bc_\ba_\bt '_\bl__\ba_\br_\bg)\n\n\n(implode 'l_arg)\n(maknam 'l_arg)\n\n WHERE: l_arg is a list of symbols, strings and small\n fixnums.\n\n RETURNS: The symbol whose print name is the result of\n concatenating the first characters of the\n print names of the symbols and strings in the\n list. Any fixnums are converted to the\n equivalent ascii character. In order to con-\n catenate entire strings or print names, use\n the function _\bc_\bo_\bn_\bc_\ba_\bt.\n\n NOTE: _\bi_\bm_\bp_\bl_\bo_\bd_\be interns the symbol it creates, _\bm_\ba_\bk_\bn_\ba_\bm\n does not.\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-16\n\n\n(gensym ['s_leader])\n\n RETURNS: a new uninterned atom beginning with the first\n character of s_leader's pname, or beginning\n with g if s_leader is not given.\n\n NOTE: The symbol looks like x0nnnnn where x is\n s_leader's first character and nnnnn is the\n number of times you have called gensym.\n\n(copysymbol 's_arg 'g_pred)\n\n RETURNS: an uninterned symbol with the same print name\n as s_arg. If g_pred is non nil, then the\n value, function binding and property list of\n the new symbol are made _\be_\bq to those of s_arg.\n\n\n(ascii 'x_charnum)\n\n WHERE: x_charnum is between 0 and 255.\n\n RETURNS: a symbol whose print name is the single char-\n acter whose fixnum representation is\n x_charnum.\n\n\n(intern 's_arg)\n\n RETURNS: s_arg\n\n SIDE EFFECT: s_arg is put on the oblist if it is not\n already there.\n\n(remob 's_symbol)\n\n RETURNS: s_symbol\n\n SIDE EFFECT: s_symbol is removed from the oblist.\n\n(rematom 's_arg)\n\n RETURNS: t if s_arg is indeed an atom.\n\n SIDE EFFECT: s_arg is put on the free atoms list,\n effectively reclaiming an atom cell.\n\n NOTE: This function does _\bn_\bo_\bt check to see if s_arg is\n on the oblist or is referenced anywhere. Thus\n calling _\br_\be_\bm_\ba_\bt_\bo_\bm on an atom in the oblist may\n result in disaster when that atom cell is reused!\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-17\n\n\n 2.3.2. string and symbol predicates\n\n(boundp 's_name)\n\n RETURNS: nil if s_name is unbound: that is, it has\n never been given a value. If x_name has the\n value g_val, then (nil . g_val) is returned.\n See also _\bm_\ba_\bk_\bu_\bn_\bb_\bo_\bu_\bn_\bd.\n\n(alphalessp 'st_arg1 'st_arg2)\n\n RETURNS: t iff the `name' of st_arg1 is alphabetically\n less than the name of st_arg2. If st_arg is a\n symbol then its `name' is its print name. If\n st_arg is a string, then its `name' is the\n string itself.\n\n\n\n 2.3.3. symbol and string accessing\n\n(symeval 's_arg)\n\n RETURNS: the value of symbol s_arg.\n\n NOTE: It is illegal to ask for the value of an unbound\n symbol. This function has the same effect as\n _\be_\bv_\ba_\bl, but compiles into much more efficient code.\n\n(get_pname 's_arg)\n\n RETURNS: the string which is the print name of s_arg.\n\n(plist 's_arg)\n\n RETURNS: the property list of s_arg.\n\n(getd 's_arg)\n\n RETURNS: the function definition of s_arg or nil if\n there is no function definition.\n\n NOTE: the function definition may turn out to be an\n array header.\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-18\n\n\n(getchar 's_arg 'x_index)\n(nthchar 's_arg 'x_index)\n(getcharn 's_arg 'x_index)\n\n RETURNS: the x_index_\bt_\bh character of the print name of\n s_arg or nil if x_index is less than 1 or\n greater than the length of s_arg's print name.\n\n NOTE: _\bg_\be_\bt_\bc_\bh_\ba_\br and _\bn_\bt_\bh_\bc_\bh_\ba_\br return a symbol with a single\n character print name, _\bg_\be_\bt_\bc_\bh_\ba_\br_\bn returns the fixnum\n representation of the character.\n\n(substring 'st_string 'x_index ['x_length])\n(substringn 'st_string 'x_index ['x_length])\n\n RETURNS: a string of length at most x_length starting\n at x_index_\bt_\bh character in the string.\n\n NOTE: If x_length is not given, all of the characters\n for x_index to the end of the string are\n returned. If x_index is negative the string\n begins at the x_index_\bt_\bh character from the end.\n If x_index is out of bounds, nil is returned.\n\n NOTE: _\bs_\bu_\bb_\bs_\bt_\br_\bi_\bn_\bg returns a list of symbols, _\bs_\bu_\bb_\bs_\bt_\br_\bi_\bn_\bg_\bn\n returns a list of fixnums. If _\bs_\bu_\bb_\bs_\bt_\br_\bi_\bn_\bg_\bn is\n given a 0 x_length argument then a single fixnum\n which is the x_index_\bt_\bh character is returned.\n\n\n\n 2.3.4. symbol and string manipulation\n\n(set 's_arg1 'g_arg2)\n\n RETURNS: g_arg2.\n\n SIDE EFFECT: the value of s_arg1 is set to g_arg2.\n\n(setq s_atm1 'g_val1 [ s_atm2 'g_val2 ... ... ])\n\n WHERE: the arguments are pairs of atom names and\n expressions.\n\n RETURNS: the last g_val_\bi.\n\n SIDE EFFECT: each s_atm_\bi is set to have the value\n g_val_\bi.\n\n NOTE: _\bs_\be_\bt evaluates all of its arguments, _\bs_\be_\bt_\bq does not\n evaluate the s_atm_\bi.\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-19\n\n\n(desetq sl_pattern1 'g_exp1 [... ...])\n\n RETURNS: g_expn\n\n SIDE EFFECT: This acts just like _\bs_\be_\bt_\bq if all the\n sl_pattern_\bi are symbols. If sl_pattern_\bi\n is a list then it is a template which\n should have the same structure as g_exp_\bi\n The symbols in sl_pattern are assigned to\n the corresponding parts of g_exp. (See\n also _\bs_\be_\bt_\bf )\n\n EXAMPLE: (_\bd_\be_\bs_\be_\bt_\bq (_\ba _\bb (_\bc . _\bd)) '(_\b1 _\b2 (_\b3 _\b4 _\b5)))\n sets a to 1, b to 2, c to 3, and d to (4 5).\n\n\n(setplist 's_atm 'l_plist)\n\n RETURNS: l_plist.\n\n SIDE EFFECT: the property list of s_atm is set to\n l_plist.\n\n(makunbound 's_arg)\n\n RETURNS: s_arg\n\n SIDE EFFECT: the value of s_arg is made `unbound'. If\n the interpreter attempts to evaluate s_arg\n before it is again given a value, an\n unbound variable error will occur.\n\n(aexplode 's_arg)\n(explode 'g_arg)\n(aexplodec 's_arg)\n(explodec 'g_arg)\n(aexploden 's_arg)\n(exploden 'g_arg)\n\n RETURNS: a list of the characters used to print out\n s_arg or g_arg.\n\n NOTE: The functions beginning with 'a' are internal\n functions which are limited to symbol arguments.\n The functions _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be and _\be_\bx_\bp_\bl_\bo_\bd_\be return a list\n of characters which _\bp_\br_\bi_\bn_\bt would use to print the\n argument. These characters include all necessary\n escape characters. Functions _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be_\bc and\n _\be_\bx_\bp_\bl_\bo_\bd_\be_\bc return a list of characters which _\bp_\ba_\bt_\bo_\bm\n would use to print the argument (i.e. no escape\n characters). Functions _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be_\bn and _\be_\bx_\bp_\bl_\bo_\bd_\be_\bn\n are similar to _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be_\bc and _\be_\bx_\bp_\bl_\bo_\bd_\be_\bc except that\n a list of fixnum equivalents of characters are\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-20\n\n\n returned.\n\n\n ____________________________________________________\n\n -> (_\bs_\be_\bt_\bq _\bx '|_\bq_\bu_\bo_\bt_\be _\bt_\bh_\bi_\bs _\b\\| _\bo_\bk?|)\n |quote this \\| ok?|\n -> (_\be_\bx_\bp_\bl_\bo_\bd_\be _\bx)\n (q u o t e |\\\\| | | t h i s |\\\\| | | |\\\\| |\\|| |\\\\| | | o k ?)\n ; note that |\\\\| just means the single character: backslash.\n ; and |\\|| just means the single character: vertical bar\n ; and | | means the single character: space\n\n -> (_\be_\bx_\bp_\bl_\bo_\bd_\be_\bc _\bx)\n (q u o t e | | t h i s | | |\\|| | | o k ?)\n -> (_\be_\bx_\bp_\bl_\bo_\bd_\be_\bn _\bx)\n (113 117 111 116 101 32 116 104 105 115 32 124 32 111 107 63)\n ____________________________________________________\n\n\n\n\n\n\n 2.4. Vectors\n\n See Chapter 9 for a discussion of vectors. They\n are less efficient that hunks but more efficient than\n arrays.\n\n\n\n 2.4.1. vector creation\n\n(new-vector 'x_size ['g_fill ['g_prop]])\n\n RETURNS: A vector of length x_size. Each data entry is\n initialized to g_fill, or to nil, if the argu-\n ment g_fill is not present. The vector's pro-\n perty is set to g_prop, or to nil, by default.\n\n(new-vectori-byte 'x_size ['g_fill ['g_prop]])\n(new-vectori-word 'x_size ['g_fill ['g_prop]])\n(new-vectori-long 'x_size ['g_fill ['g_prop]])\n\n RETURNS: A vectori with x_size elements in it. The\n actual memory requirement is two long words +\n x_size*(n bytes), where n is 1 for new-\n vector-byte, 2 for new-vector-word, or 4 for\n new-vectori-long. Each data entry is initial-\n ized to g_fill, or to zero, if the argument\n g_fill is not present. The vector's property\n is set to g_prop, or nil, by default.\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-21\n\n\n Vectors may be created by specifying multiple initial\n values:\n\n(vector ['g_val0 'g_val1 ...])\n\n RETURNS: a vector, with as many data elements as there\n are arguments. It is quite possible to have a\n vector with no data elements. The vector's\n property will be a null list.\n\n(vectori-byte ['x_val0 'x_val2 ...])\n(vectori-word ['x_val0 'x_val2 ...])\n(vectori-long ['x_val0 'x_val2 ...])\n\n RETURNS: a vectori, with as many data elements as there\n are arguments. The arguments are required to\n be fixnums. Only the low order byte or word\n is used in the case of vectori-byte and\n vectori-word. The vector's property will be\n null.\n\n\n\n 2.4.2. vector reference\n\n(vref 'v_vect 'x_index)\n(vrefi-byte 'V_vect 'x_bindex)\n(vrefi-word 'V_vect 'x_windex)\n(vrefi-long 'V_vect 'x_lindex)\n\n RETURNS: the desired data element from a vector. The\n indices must be fixnums. Indexing is zero-\n based. The vrefi functions sign extend the\n data.\n\n(vprop 'Vv_vect)\n\n RETURNS: The Lisp property associated with a vector.\n\n(vget 'Vv_vect 'g_ind)\n\n RETURNS: The value stored under g_ind if the Lisp pro-\n perty associated with 'Vv_vect is a disembo-\n died property list.\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-22\n\n\n(vsize 'Vv_vect)\n(vsize-byte 'V_vect)\n(vsize-word 'V_vect)\n\n RETURNS: the number of data elements in the vector.\n For immediate-vectors, the functions vsize-\n byte and vsize-word return the number of data\n elements, if one thinks of the binary data as\n being comprised of bytes or words.\n\n\n\n 2.4.3. vector modfication\n\n(vset 'v_vect 'x_index 'g_val)\n(vseti-byte 'V_vect 'x_bindex 'x_val)\n(vseti-word 'V_vect 'x_windex 'x_val)\n(vseti-long 'V_vect 'x_lindex 'x_val)\n\n RETURNS: the datum.\n\n SIDE EFFECT: The indexed element of the vector is set\n to the value. As noted above, for vseti-\n word and vseti-byte, the index is con-\n strued as the number of the data element\n within the vector. It is not a byte\n address. Also, for those two functions,\n the low order byte or word of x_val is\n what is stored.\n\n(vsetprop 'Vv_vect 'g_value)\n\n RETURNS: g_value. This should be either a symbol or a\n disembodied property list whose _\bc_\ba_\br is a sym-\n bol identifying the type of the vector.\n\n SIDE EFFECT: the property list of Vv_vect is set to\n g_value.\n\n(vputprop 'Vv_vect 'g_value 'g_ind)\n\n RETURNS: g_value.\n\n SIDE EFFECT: If the vector property of Vv_vect is a\n disembodied property list, then vputprop\n adds the value g_value under the indicator\n g_ind. Otherwise, the old vector property\n is made the first element of the list.\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-23\n\n\n 2.5. Arrays\n\n See Chapter 9 for a complete description of\n arrays. Some of these functions are part of a Maclisp\n array compatibility package representing only one sim-\n ple way of using the array structure of FRANZ LISP.\n\n\n\n 2.5.1. array creation\n\n(marray 'g_data 's_access 'g_aux 'x_length 'x_delta)\n\n RETURNS: an array type with the fields set up from the\n above arguments in the obvious way (see\n 1.2.10).\n\n(*array 's_name 's_type 'x_dim1 ... 'x_dim_\bn)\n(array s_name s_type x_dim1 ... x_dim_\bn)\n\n WHERE: s_type may be one of t, nil, fixnum, flonum,\n fixnum-block and flonum-block.\n\n RETURNS: an array of type s_type with n dimensions of\n extents given by the x_dim_\bi.\n\n SIDE EFFECT: If s_name is non nil, the function defini-\n tion of s_name is set to the array struc-\n ture returned.\n\n NOTE: These functions create a Maclisp compatible\n array. In FRANZ LISP arrays of type t, nil, fix-\n num and flonum are equivalent and the elements of\n these arrays can be any type of lisp object.\n Fixnum-block and flonum-block arrays are res-\n tricted to fixnums and flonums respectively and\n are used mainly to communicate with foreign func-\n tions (see 8.5).\n\n NOTE: *_\ba_\br_\br_\ba_\by evaluates its arguments, _\ba_\br_\br_\ba_\by does not.\n\n\n\n 2.5.2. array predicate\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-24\n\n\n(arrayp 'g_arg)\n\n RETURNS: t iff g_arg is of type array.\n\n\n\n 2.5.3. array accessors\n\n\n(getaccess 'a_array)\n(getaux 'a_array)\n(getdelta 'a_array)\n(getdata 'a_array)\n(getlength 'a_array)\n\n RETURNS: the field of the array object a_array given by\n the function name.\n\n(arrayref 'a_name 'x_ind)\n\n RETURNS: the x_ind_\bt_\bh element of the array object\n a_name. x_ind of zero accesses the first ele-\n ment.\n\n NOTE: _\ba_\br_\br_\ba_\by_\br_\be_\bf uses the data, length and delta fields\n of a_name to determine which object to return.\n\n(arraycall s_type 'as_array 'x_ind1 ... )\n\n RETURNS: the element selected by the indices from the\n array a_array of type s_type.\n\n NOTE: If as_array is a symbol then the function binding\n of this symbol should contain an array object.\n s_type is ignored by _\ba_\br_\br_\ba_\by_\bc_\ba_\bl_\bl but is included\n for compatibility with Maclisp.\n\n(arraydims 's_name)\n\n RETURNS: a list of the type and bounds of the array\n s_name.\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-25\n\n\n(listarray 'sa_array ['x_elements])\n\n RETURNS: a list of all of the elements in array\n sa_array. If x_elements is given, then only\n the first x_elements are returned.\n\n\n\n ____________________________________________________\n\n ; We will create a 3 by 4 array of general lisp objects\n -> (_\ba_\br_\br_\ba_\by _\be_\br_\bn_\bi_\be _\bt _\b3 _\b4)\n array[12]\n\n ; the array header is stored in the function definition slot of the\n ; symbol ernie\n -> (_\ba_\br_\br_\ba_\by_\bp (_\bg_\be_\bt_\bd '_\be_\br_\bn_\bi_\be))\n t\n -> (_\ba_\br_\br_\ba_\by_\bd_\bi_\bm_\bs (_\bg_\be_\bt_\bd '_\be_\br_\bn_\bi_\be))\n (t 3 4)\n\n ; store in ernie[2][2] the list (test list)\n -> (_\bs_\bt_\bo_\br_\be (_\be_\br_\bn_\bi_\be _\b2 _\b2) '(_\bt_\be_\bs_\bt _\bl_\bi_\bs_\bt))\n (test list)\n\n ; check to see if it is there\n -> (_\be_\br_\bn_\bi_\be _\b2 _\b2)\n (test list)\n\n ; now use the low level function _\ba_\br_\br_\ba_\by_\br_\be_\bf to find the same element\n ; arrays are 0 based and row-major (the last subscript varies the fastest)\n ; thus element [2][2] is the 10th element , (starting at 0).\n -> (_\ba_\br_\br_\ba_\by_\br_\be_\bf (_\bg_\be_\bt_\bd '_\be_\br_\bn_\bi_\be) _\b1_\b0)\n (ptr to)(test list) ; the result is a value cell (thus the (ptr to))\n ____________________________________________________\n\n\n\n\n\n\n 2.5.4. array manipulation\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-26\n\n\n(putaccess 'a_array 'su_func)\n(putaux 'a_array 'g_aux)\n(putdata 'a_array 'g_arg)\n(putdelta 'a_array 'x_delta)\n(putlength 'a_array 'x_length)\n\n RETURNS: the second argument to the function.\n\n SIDE EFFECT: The field of the array object given by the\n function name is replaced by the second\n argument to the function.\n\n(store 'l_arexp 'g_val)\n\n WHERE: l_arexp is an expression which references an\n array element.\n\n RETURNS: g_val\n\n SIDE EFFECT: the array location which contains the ele-\n ment which l_arexp references is changed\n to contain g_val.\n\n(fillarray 's_array 'l_itms)\n\n RETURNS: s_array\n\n SIDE EFFECT: the array s_array is filled with elements\n from l_itms. If there are not enough ele-\n ments in l_itms to fill the entire array,\n then the last element of l_itms is used to\n fill the remaining parts of the array.\n\n\n\n 2.6. Hunks\n\n Hunks are vector-like objects whose size can\n range from 1 to 128 elements. Internally, hunks are\n allocated in sizes which are powers of 2. In order to\n create hunks of a given size, a hunk with at least\n that many elements is allocated and a distinguished\n symbol EMPTY is placed in those elements not\n requested. Most hunk functions respect those dis-\n tinguished symbols, but there are two (*_\bm_\ba_\bk_\bh_\bu_\bn_\bk and\n *_\br_\bp_\bl_\ba_\bc_\bx) which will overwrite the distinguished sym-\n bol.\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-27\n\n\n 2.6.1. hunk creation\n\n(hunk 'g_val1 ['g_val2 ... 'g_val_\bn])\n\n RETURNS: a hunk of length n whose elements are initial-\n ized to the g_val_\bi.\n\n NOTE: the maximum size of a hunk is 128.\n\n EXAMPLE: (_\bh_\bu_\bn_\bk _\b4 '_\bs_\bh_\ba_\br_\bp '_\bk_\be_\by_\bs) = {4 sharp keys}\n\n(makhunk 'xl_arg)\n\n RETURNS: a hunk of length xl_arg initialized to all\n nils if xl_arg is a fixnum. If xl_arg is a\n list, then we return a hunk of size\n (_\bl_\be_\bn_\bg_\bt_\bh '_\bx_\bl__\ba_\br_\bg) initialized to the elements\n in xl_arg.\n\n NOTE: (_\bm_\ba_\bk_\bh_\bu_\bn_\bk '(_\ba _\bb _\bc)) is equivalent to\n (_\bh_\bu_\bn_\bk '_\ba '_\bb '_\bc).\n\n EXAMPLE: (_\bm_\ba_\bk_\bh_\bu_\bn_\bk _\b4) = {_\bn_\bi_\bl _\bn_\bi_\bl _\bn_\bi_\bl _\bn_\bi_\bl}\n\n(*makhunk 'x_arg)\n\n RETURNS: a hunk of size 2[x_arg] initialized to EMPTY.\n\n NOTE: This is only to be used by such functions as _\bh_\bu_\bn_\bk\n and _\bm_\ba_\bk_\bh_\bu_\bn_\bk which create and initialize hunks for\n users.\n\n\n\n 2.6.2. hunk accessor\n\n(cxr 'x_ind 'h_hunk)\n\n RETURNS: element x_ind (starting at 0) of hunk h_hunk.\n\n(hunk-to-list 'h_hunk)\n\n RETURNS: a list consisting of the elements of h_hunk.\n\n\n\n 2.6.3. hunk manipulators\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-28\n\n\n(rplacx 'x_ind 'h_hunk 'g_val)\n(*rplacx 'x_ind 'h_hunk 'g_val)\n\n RETURNS: h_hunk\n\n SIDE EFFECT: Element x_ind (starting at 0) of h_hunk is\n set to g_val.\n\n NOTE: _\br_\bp_\bl_\ba_\bc_\bx will not modify one of the distinguished\n (EMPTY) elements whereas *_\br_\bp_\bl_\ba_\bc_\bx will.\n\n(hunksize 'h_arg)\n\n RETURNS: the size of the hunk h_arg.\n\n EXAMPLE: (_\bh_\bu_\bn_\bk_\bs_\bi_\bz_\be (_\bh_\bu_\bn_\bk _\b1 _\b2 _\b3)) = 3\n\n\n\n 2.7. Bcds\n\n A bcd object contains a pointer to compiled code\n and to the type of function object the compiled code\n represents.\n\n(getdisc 'y_bcd)\n(getentry 'y_bcd)\n\n RETURNS: the field of the bcd object given by the func-\n tion name.\n\n(putdisc 'y_func 's_discipline)\n\n RETURNS: s_discipline\n\n SIDE EFFECT: Sets the discipline field of y_func to\n s_discipline.\n\n\n\n 2.8. Structures\n\n There are three common structures constructed out\n of list cells: the assoc list, the property list and\n the tconc list. The functions below manipulate these\n structures.\n\n\n\n 2.8.1. assoc list\n\n An `assoc list' (or alist) is a common lisp\n data structure. It has the form\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-29\n\n\n ((key1 . value1) (key2 . value2) (key3 . value3) ... (keyn . valuen))\n\n(assoc 'g_arg1 'l_arg2)\n(assq 'g_arg1 'l_arg2)\n\n RETURNS: the first top level element of l_arg2 whose\n _\bc_\ba_\br is _\be_\bq_\bu_\ba_\bl (with _\ba_\bs_\bs_\bo_\bc) or _\be_\bq (with _\ba_\bs_\bs_\bq) to\n g_arg1.\n\n NOTE: Usually l_arg2 has an _\ba-_\bl_\bi_\bs_\bt structure and g_arg1\n acts as key.\n\n(sassoc 'g_arg1 'l_arg2 'sl_func)\n\n RETURNS: the result of\n (_\bc_\bo_\bn_\bd ((_\ba_\bs_\bs_\bo_\bc '_\bg__\ba_\br_\bg '_\bl__\ba_\br_\bg_\b2) (_\ba_\bp_\bp_\bl_\by '_\bs_\bl__\bf_\bu_\bn_\bc _\bn_\bi_\bl)))\n\n NOTE: sassoc is written as a macro.\n\n(sassq 'g_arg1 'l_arg2 'sl_func)\n\n RETURNS: the result of\n (_\bc_\bo_\bn_\bd ((_\ba_\bs_\bs_\bq '_\bg__\ba_\br_\bg '_\bl__\ba_\br_\bg_\b2) (_\ba_\bp_\bp_\bl_\by '_\bs_\bl__\bf_\bu_\bn_\bc _\bn_\bi_\bl)))\n\n NOTE: sassq is written as a macro.\n\n\n\n ____________________________________________________\n\n ; _\ba_\bs_\bs_\bo_\bc or _\ba_\bs_\bs_\bq is given a key and an assoc list and returns\n ; the key and value item if it exists, they differ only in how they test\n ; for equality of the keys.\n\n -> (_\bs_\be_\bt_\bq _\ba_\bl_\bi_\bs_\bt '((_\ba_\bl_\bp_\bh_\ba . _\ba) ( (_\bc_\bo_\bm_\bp_\bl_\be_\bx _\bk_\be_\by) . _\bb) (_\bj_\bu_\bn_\bk . _\bx)))\n ((alpha . a) ((complex key) . b) (junk . x))\n\n ; we should use _\ba_\bs_\bs_\bq when the key is an atom\n -> (_\ba_\bs_\bs_\bq '_\ba_\bl_\bp_\bh_\ba _\ba_\bl_\bi_\bs_\bt)\n (alpha . a)\n\n ; but it may not work when the key is a list\n -> (_\ba_\bs_\bs_\bq '(_\bc_\bo_\bm_\bp_\bl_\be_\bx _\bk_\be_\by) _\ba_\bl_\bi_\bs_\bt)\n nil\n\n ; however _\ba_\bs_\bs_\bo_\bc will always work\n -> (_\ba_\bs_\bs_\bo_\bc '(_\bc_\bo_\bm_\bp_\bl_\be_\bx _\bk_\be_\by) _\ba_\bl_\bi_\bs_\bt)\n ((complex key) . b)\n ____________________________________________________\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-30\n\n\n(sublis 'l_alst 'l_exp)\n\n WHERE: l_alst is an _\ba-_\bl_\bi_\bs_\bt.\n\n RETURNS: the list l_exp with every occurrence of key_\bi\n replaced by val_\bi.\n\n NOTE: new list structure is returned to prevent modifi-\n cation of l_exp. When a substitution is made, a\n copy of the value to substitute in is not made.\n\n\n\n 2.8.2. property list\n\n A property list consists of an alternating\n sequence of keys and values. Normally a property\n list is stored on a symbol. A list is a 'disembo-\n died' property list if it contains an odd number of\n elements, the first of which is ignored.\n\n(plist 's_name)\n\n RETURNS: the property list of s_name.\n\n(setplist 's_atm 'l_plist)\n\n RETURNS: l_plist.\n\n SIDE EFFECT: the property list of s_atm is set to\n l_plist.\n\n\n(get 'ls_name 'g_ind)\n\n RETURNS: the value under indicator g_ind in ls_name's\n property list if ls_name is a symbol.\n\n NOTE: If there is no indicator g_ind in ls_name's pro-\n perty list nil is returned. If ls_name is a list\n of an odd number of elements then it is a disem-\n bodied property list. _\bg_\be_\bt searches a disembodied\n property list by starting at its _\bc_\bd_\br, and compar-\n ing every other element with g_ind, using _\be_\bq.\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-31\n\n\n(getl 'ls_name 'l_indicators)\n\n RETURNS: the property list ls_name beginning at the\n first indicator which is a member of the list\n l_indicators, or nil if none of the indicators\n in l_indicators are on ls_name's property\n list.\n\n NOTE: If ls_name is a list, then it is assumed to be a\n disembodied property list.\n\n\n(putprop 'ls_name 'g_val 'g_ind)\n(defprop ls_name g_val g_ind)\n\n RETURNS: g_val.\n\n SIDE EFFECT: Adds to the property list of ls_name the\n value g_val under the indicator g_ind.\n\n NOTE: _\bp_\bu_\bt_\bp_\br_\bo_\bp evaluates it arguments, _\bd_\be_\bf_\bp_\br_\bo_\bp does not.\n ls_name may be a disembodied property list, see\n _\bg_\be_\bt.\n\n(remprop 'ls_name 'g_ind)\n\n RETURNS: the portion of ls_name's property list begin-\n ning with the property under the indicator\n g_ind. If there is no g_ind indicator in\n ls_name's plist, nil is returned.\n\n SIDE EFFECT: the value under indicator g_ind and g_ind\n itself is removed from the property list\n of ls_name.\n\n NOTE: ls_name may be a disembodied property list, see\n _\bg_\be_\bt.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-32\n\n\n\n ____________________________________________________\n\n -> (_\bp_\bu_\bt_\bp_\br_\bo_\bp '_\bx_\bl_\ba_\bt_\be '_\ba '_\ba_\bl_\bp_\bh_\ba)\n a\n -> (_\bp_\bu_\bt_\bp_\br_\bo_\bp '_\bx_\bl_\ba_\bt_\be '_\bb '_\bb_\be_\bt_\ba)\n b\n -> (_\bp_\bl_\bi_\bs_\bt '_\bx_\bl_\ba_\bt_\be)\n (alpha a beta b)\n -> (_\bg_\be_\bt '_\bx_\bl_\ba_\bt_\be '_\ba_\bl_\bp_\bh_\ba)\n a\n ; use of a disembodied property list:\n -> (_\bg_\be_\bt '(_\bn_\bi_\bl _\bf_\ba_\bt_\be_\bm_\ba_\bn _\br_\bj_\bf _\bs_\bk_\bl_\bo_\bw_\be_\br _\bk_\bl_\bs _\bf_\bo_\bd_\be_\br_\ba_\br_\bo _\bj_\bk_\bf) '_\bs_\bk_\bl_\bo_\bw_\be_\br)\n kls\n ____________________________________________________\n\n\n\n\n\n\n 2.8.3. tconc structure\n\n A tconc structure is a special type of list\n designed to make it easy to add objects to the end.\n It consists of a list cell whose _\bc_\ba_\br points to a\n list of the elements added with _\bt_\bc_\bo_\bn_\bc or _\bl_\bc_\bo_\bn_\bc and\n whose _\bc_\bd_\br points to the last list cell of the list\n pointed to by the _\bc_\ba_\br.\n\n(tconc 'l_ptr 'g_x)\n\n WHERE: l_ptr is a tconc structure.\n\n RETURNS: l_ptr with g_x added to the end.\n\n(lconc 'l_ptr 'l_x)\n\n WHERE: l_ptr is a tconc structure.\n\n RETURNS: l_ptr with the list l_x spliced in at the end.\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-33\n\n\n\n ____________________________________________________\n\n ; A _\bt_\bc_\bo_\bn_\bc structure can be initialized in two ways.\n ; nil can be given to _\bt_\bc_\bo_\bn_\bc in which case _\bt_\bc_\bo_\bn_\bc will generate\n ; a _\bt_\bc_\bo_\bn_\bc structure.\n\n ->(_\bs_\be_\bt_\bq _\bf_\bo_\bo (_\bt_\bc_\bo_\bn_\bc _\bn_\bi_\bl _\b1))\n ((1) 1)\n\n ; Since _\bt_\bc_\bo_\bn_\bc destructively adds to\n ; the list, you can now add to foo without using _\bs_\be_\bt_\bq again.\n\n ->(_\bt_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\b2)\n ((1 2) 2)\n ->_\bf_\bo_\bo\n ((1 2) 2)\n\n ; Another way to create a null _\bt_\bc_\bo_\bn_\bc structure\n ; is to use (_\bn_\bc_\bo_\bn_\bs _\bn_\bi_\bl).\n\n ->(_\bs_\be_\bt_\bq _\bf_\bo_\bo (_\bn_\bc_\bo_\bn_\bs _\bn_\bi_\bl))\n (nil)\n ->(_\bt_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\b1)\n ((1) 1)\n\n ; now see what _\bl_\bc_\bo_\bn_\bc can do\n -> (_\bl_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\bn_\bi_\bl)\n ((1) 1) ; no change\n -> (_\bl_\bc_\bo_\bn_\bc _\bf_\bo_\bo '(_\b2 _\b3 _\b4))\n ((1 2 3 4) 4)\n ____________________________________________________\n\n\n\n\n\n\n 2.8.4. fclosures\n\n An fclosure is a functional object which\n admits some data manipulations. They are discussed\n in 8.4. Internally, they are constructed from vec-\n tors.\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-34\n\n\n(fclosure 'l_vars 'g_funobj)\n\n WHERE: l_vars is a list of variables, g_funobj is any\n object that can be funcalled (including, fclo-\n sures).\n\n RETURNS: A vector which is the fclosure.\n\n(fclosure-alist 'v_fclosure)\n\n RETURNS: An association list representing the variables\n in the fclosure. This is a snapshot of the\n current state of the fclosure. If the bind-\n ings in the fclosure are changed, any previ-\n ously calculated results of _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be-_\ba_\bl_\bi_\bs_\bt\n will not change.\n\n(fclosure-function 'v_fclosure)\n\n RETURNS: the functional object part of the fclosure.\n\n(fclosurep 'v_fclosure)\n\n RETURNS: t iff the argument is an fclosure.\n\n(symeval-in-fclosure 'v_fclosure 's_symbol)\n\n RETURNS: the current binding of a particular symbol in\n an fclosure.\n\n(set-in-fclosure 'v_fclosure 's_symbol 'g_newvalue)\n\n RETURNS: g_newvalue.\n\n SIDE EFFECT: The variable s_symbol is bound in the\n fclosure to g_newvalue.\n\n\n\n 2.9. Random functions\n\n The following functions don't fall into any of\n the classifications above.\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-35\n\n\n(bcdad 's_funcname)\n\n RETURNS: a fixnum which is the address in memory where\n the function s_funcname begins. If s_funcname\n is not a machine coded function (binary) then\n _\bb_\bc_\bd_\ba_\bd returns nil.\n\n(copy 'g_arg)\n\n RETURNS: A structure _\be_\bq_\bu_\ba_\bl to g_arg but with new list\n cells.\n\n(copyint* 'x_arg)\n\n RETURNS: a fixnum with the same value as x_arg but in a\n freshly allocated cell.\n\n(cpy1 'xvt_arg)\n\n RETURNS: a new cell of the same type as xvt_arg with\n the same value as xvt_arg.\n\n(getaddress 's_entry1 's_binder1 'st_discipline1 [... ...\n...])\n\n RETURNS: the binary object which s_binder1's function\n field is set to.\n\n NOTE: This looks in the running lisp's symbol table for\n a symbol with the same name as s_entry_\bi. It then\n creates a binary object whose entry field points\n to s_entry_\bi and whose discipline is\n st_discipline_\bi. This binary object is stored in\n the function field of s_binder_\bi. If\n st_discipline_\bi is nil, then \"subroutine\" is used\n by default. This is especially useful for _\bc_\bf_\ba_\bs_\bl\n users.\n\n(macroexpand 'g_form)\n\n RETURNS: g_form after all macros in it are expanded.\n\n NOTE: This function will only macroexpand expressions\n which could be evaluated and it does not know\n about the special nlambdas such as _\bc_\bo_\bn_\bd and _\bd_\bo,\n thus it misses many macro expansions.\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-36\n\n\n(ptr 'g_arg)\n\n RETURNS: a value cell initialized to point to g_arg.\n\n(quote g_arg)\n\n RETURNS: g_arg.\n\n NOTE: the reader allows you to abbreviate (quote foo)\n as 'foo.\n\n(kwote 'g_arg)\n\n RETURNS: (_\bl_\bi_\bs_\bt (_\bq_\bu_\bo_\bt_\be _\bq_\bu_\bo_\bt_\be) _\bg__\ba_\br_\bg).\n\n(replace 'g_arg1 'g_arg2)\n\n WHERE: g_arg1 and g_arg2 must be the same type of\n lispval and not symbols or hunks.\n\n RETURNS: g_arg2.\n\n SIDE EFFECT: The effect of _\br_\be_\bp_\bl_\ba_\bc_\be is dependent on the\n type of the g_arg_\bi although one will\n notice a similarity in the effects. To\n understand what _\br_\be_\bp_\bl_\ba_\bc_\be does to fixnum and\n flonum arguments, you must first under-\n stand that such numbers are `boxed' in\n FRANZ LISP. What this means is that if\n the symbol x has a value 32412, then in\n memory the value element of x's symbol\n structure contains the address of another\n word of memory (called a box) with 32412\n in it.\n\n Thus, there are two ways of changing the\n value of x: the first is to change the\n value element of x's symbol structure to\n point to a word of memory with a different\n value. The second way is to change the\n value in the box which x points to. The\n former method is used almost all of the\n time, the latter is used very rarely and\n has the potential to cause great confu-\n sion. The function _\br_\be_\bp_\bl_\ba_\bc_\be allows you to\n do the latter, i.e., to actually change\n the value in the box.\n\n You should watch out for these situations.\n If you do (_\bs_\be_\bt_\bq _\by _\bx), then both x and y\n will point to the same box. If you now\n (_\br_\be_\bp_\bl_\ba_\bc_\be _\bx _\b1_\b2_\b3_\b4_\b5), then y will also have\n the value 12345. And, in fact, there may\n\n\n Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-37\n\n\n be many other pointers to that box.\n\n Another problem with replacing fixnums is\n that some boxes are read-only. The fix-\n nums between -1024 and 1023 are stored in\n a read-only area and attempts to replace\n them will result in an \"Illegal memory\n reference\" error (see the description of\n _\bc_\bo_\bp_\by_\bi_\bn_\bt* for a way around this problem).\n\n For the other valid types, the effect of\n _\br_\be_\bp_\bl_\ba_\bc_\be is easy to understand. The fields\n of g_val1's structure are made eq to the\n corresponding fields of g_val2's struc-\n ture. For example, if x and y have\n lists as values then the effect of\n (_\br_\be_\bp_\bl_\ba_\bc_\be _\bx _\by) is the same as\n (_\br_\bp_\bl_\ba_\bc_\ba _\bx (_\bc_\ba_\br _\by)) and (_\br_\bp_\bl_\ba_\bc_\bd _\bx (_\bc_\bd_\br _\by)).\n\n(scons 'x_arg 'bs_rest)\n\n WHERE: bs_rest is a bignum or nil.\n\n RETURNS: a bignum whose first bigit is x_arg and whose\n higher order bigits are bs_rest.\n\n(setf g_refexpr 'g_value)\n\n NOTE: _\bs_\be_\bt_\bf is a generalization of setq. Information\n may be stored by binding variables, replacing\n entries of arrays, and vectors, or being put on\n property lists, among others. Setf will allow\n the user to store data into some location, by\n mentioning the operation used to refer to the\n location. Thus, the first argument may be par-\n tially evaluated, but only to the extent needed\n to calculate a reference. _\bs_\be_\bt_\bf returns g_value.\n (Compare to _\bd_\be_\bs_\be_\bt_\bq )\n\n\n ____________________________________________________\n\n (setf x 3) = (setq x 3)\n (setf (car x) 3) = (rplaca x 3)\n (setf (get foo 'bar) 3) = (putprop foo 3 'bar)\n (setf (vref vector index) value) = (vset vector index value)\n ____________________________________________________\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n\n\n\n\nData Structure Access 2-38\n\n\n(sort 'l_data 'u_comparefn)\n\n RETURNS: a list of the elements of l_data ordered by\n the comparison function u_comparefn.\n\n SIDE EFFECT: the list l_data is modified rather than\n allocated in new storage.\n\n NOTE: (_\bc_\bo_\bm_\bp_\ba_\br_\be_\bf_\bn '_\bg__\bx '_\bg__\by) should return something\n non-nil if g_x can precede g_y in sorted order;\n nil if g_y must precede g_x. If u_comparefn is\n nil, alphabetical order will be used.\n\n(sortcar 'l_list 'u_comparefn)\n\n RETURNS: a list of the elements of l_list with the\n _\bc_\ba_\br's ordered by the sort function\n u_comparefn.\n\n SIDE EFFECT: the list l_list is modified rather than\n copied.\n\n NOTE: Like _\bs_\bo_\br_\bt, if u_comparefn is nil, alphabetical\n order will be used.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u001b9\n\n\u001b9 Printed: January 31, 1984\n\n\n\n", "meta": {"hexsha": "a005b85a18e939c9ea8543225884af3538b69e30", "size": 62791, "ext": "r", "lang": "R", "max_stars_repo_path": "lisplib/manual/ch2.r", "max_stars_repo_name": "omasanori/franz-lisp", "max_stars_repo_head_hexsha": "64e037d26cd382c0b88e0a5dc261bd2c29191af8", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 35, "max_stars_repo_stars_event_min_datetime": "2016-11-03T05:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T06:10:55.000Z", "max_issues_repo_path": "lisplib/manual/ch2.r", "max_issues_repo_name": "omasanori/franz-lisp", "max_issues_repo_head_hexsha": "64e037d26cd382c0b88e0a5dc261bd2c29191af8", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-05-19T16:13:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T20:48:51.000Z", "max_forks_repo_path": "lisplib/manual/ch2.r", "max_forks_repo_name": "omasanori/franz-lisp", "max_forks_repo_head_hexsha": "64e037d26cd382c0b88e0a5dc261bd2c29191af8", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2016-11-09T16:41:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T20:56:43.000Z", "avg_line_length": 25.1465758911, "max_line_length": 153, "alphanum_fraction": 0.5700179962, "num_tokens": 20368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091277568224823, "lm_q2_score": 0.07369626767158909, "lm_q1q2_score": 0.018491335078900356}} {"text": "#' ---\r\n#' title: \"Module 3 examples - R code\" \r\n#' author: \" \"\r\n#' date: \"September 2019\"\r\n#' --- \r\n#' Examples illustrating the over-sampling of some demographic groups and demonstrating the importance of using weights in analyses\r\n\r\n\r\n\r\n# Load required packages\r\n#+ message = FALSE, warning=FALSE\r\nlibrary(survey)\r\nlibrary(dplyr)\r\n#'\r\n\r\n# Display Version Information \r\ncat(\"R package versions:\\n\")\r\nfor (p in c(\"base\", \"survey\",\"dplyr\")) { \r\n cat(p, \": \", as.character(packageVersion(p)), \"\\n\")\r\n}\r\n\r\n#' # Data preparation\r\n#' ## Download & Read SAS Transport Files \r\n\r\n# function to download the required survey cycles for a component file \r\ndownloadNHANES <- function(fileprefix){\r\n print (fileprefix)\r\n outdf <- data.frame(NULL)\r\n for (j in 1:length(letters)){\r\n urlstring <- paste('https://wwwn.cdc.gov/nchs/nhanes/',yrs[j],'/',fileprefix,letters[j],'.XPT', sep='')\r\n download.file(urlstring, tf <- tempfile(), mode=\"wb\")\r\n tmpframe <- foreign::read.xport(tf)\r\n outdf <- bind_rows(outdf, tmpframe)\r\n }\r\n return(outdf)\r\n}\r\n\r\n# Specify the survey cycles required, with corresponding file suffixes\r\nyrs <- c('2015-2016')\r\nletters <- c('_i')\r\n\r\n# Download data for each component\r\n# Demographic (DEMO)\r\nDEMO <- downloadNHANES('DEMO')\r\n# BPX blood pressure exam \r\nBPX <- downloadNHANES('BPX')\r\n# BPQ blood pressure questionnaire \r\nBPQ <- downloadNHANES('BPQ')\r\n\r\n\r\n# Merge component files\r\n# Keep all records in DEMO, even if that SEQN does not match to BPQ or BPX files\r\none_tmp <- left_join(DEMO, select(BPX, \"SEQN\", starts_with(\"BPXSY\"), starts_with(\"BPXDI\")), by=\"SEQN\") %>%\r\n left_join(., select(BPQ, \"SEQN\", \"BPQ050A\") , by=\"SEQN\")\r\n\r\n\r\n#' ## Create derived analysis variables (using dplyr functions)\r\ndf <- mutate(one_tmp, \r\n # create indicator for overall summary\r\n one = 1,\r\n # Hypertension prevalence\r\n # Count Number of Nonmissing SBPs & DBPs\r\n n_sbp=rowSums(!is.na(select(one_tmp, starts_with(\"BPXSY\")))),\r\n n_dbp=rowSums(!is.na(select(one_tmp, starts_with(\"BPXDI\"))))) %>%\r\n # Set DBP Values Of 0 To Missing For Calculating Average\r\n mutate_at(vars(starts_with(\"BPXDI\")), list(~na_if(., 0))) %>%\r\n mutate(\r\n # Calculate Mean Systolic and Diastolic (over non-missing values) \r\n mean_sbp=rowMeans(select(., starts_with(\"BPXSY\")), na.rm=TRUE),\r\n mean_dbp=rowMeans(select(., starts_with(\"BPXDI\")), na.rm=TRUE),\r\n # Create 0/1 indicator for hypertension\r\n # \"Old\" Hypertensive Category variable: taking medication or measured BP > 140/90 \r\n # as used in NCHS Data Brief No. 289\r\n # Variable bpq050a: now taking prescribed medicine for hypertension, 1 = yes \r\n htn_old=case_when( mean_sbp>=140 | mean_dbp>=90 | BPQ050A ==1 ~ 1,\r\n n_sbp > 0 & n_dbp > 0 ~ 0),\r\n # for reference: \"new\" definition of hypertension prevalence, based on taking medication or measured BP > 130/80 \r\n # From 2017 ACC/AHA hypertension guidelines \r\n # Not used in Data Brief No. 289\r\n htn_new=case_when( mean_sbp>=130 | mean_dbp>=80 | BPQ050A ==1 ~ 1,\r\n n_sbp > 0 & n_dbp > 0 ~ 0),\r\n # Create race and Hispanic ethnicity categories for oversampling analysis \r\n # combined Non-Hispanic white and Non-Hispanic other and multiple races, to approximate the sampling domains\r\n race1 = factor(c(3, 3, 4, 1, NA, 2, 4)[RIDRETH3],\r\n labels = c('NH Black','NH Asian', 'Hispanic', 'NH White and Other')),\r\n # Create race and Hispanic ethnicity categories for hypertension analysis \r\n raceEthCat= factor(c(4, 4, 1, 2, NA, 3, 5)[RIDRETH3],\r\n labels = c('NH White', 'NH Black', 'NH Asian', 'Hispanic', 'NH Other/Multiple')),\r\n # Create age categories for adults aged 18 and over: ages 18-39, 40-59, 60 and over\r\n ageCat_18 = cut(RIDAGEYR,\r\n breaks = c(17, 39, 59, Inf),\r\n labels = c('18-39','40-59','60+')), \r\n # Define subpopulation of interest: non-pregnant adults aged 18 and over who have at least 1 valid systolic OR diastolic BP measure \r\n inAnalysis= (RIDAGEYR >=18 & ifelse(is.na(RIDEXPRG), 0, RIDEXPRG) != 1 & (n_sbp > 0 | n_dbp > 0)) \r\n )\r\n\r\n#' ***\r\n#'\r\n#' # Estimates for graph - Distribution of race and Hispanic origin, NHANES 2015-2016 \r\n#' Module 3, Examples Demonstrating the Importance of Using Weights in Your Analyses \r\n#' Section \"Adjusting for oversampling\" \r\n\r\n\r\n#' Proportion of unweighted interview sample \r\ndf %>% count(race1) %>% \r\n mutate(prop= round(n / sum(n)*100, digits=1))\r\n\r\n#' Proportion of weighted interview sample\r\ndf %>% count(race1, wt=WTINT2YR) %>%\r\n mutate(prop= round(n / sum(n)*100, digits=1))\r\n\r\n\r\n#' Proportion of US population \r\n# Input population totals from the American Community Survey, 2015-2016\r\n# available on the NHANES website: https://wwwn.cdc.gov/nchs/nhanes/responserates.aspx#population-totals\r\n# counts from tab \"Both\" (for both genders), total row (for all ages)\r\n\r\ndata.frame(group=c('Non-Hispanic White and Other', 'Non-Hispanic Black', 'Non-Hispanic Asian', 'Hispanic'), n=c(194849491+10444206, 38418696, 17018259, 55750392 )) %>%\r\n mutate(prop = round(n / sum(n)* 100, digits=1))\r\n\r\n \r\n#' ***\r\n#'\r\n#' # Comparison of weighted and unweighed estimates for hypertension, NHANES 2015-2016\r\n#' Module 3, Examples Demonstrating the Importance of Using Weights in Your Analyses\r\n#' Section \"Why weight?\" \r\n#'\r\n\r\n#' ## Prevalence of hypertension among adults aged 18 and over, overall and by race and Hispanic origin group\r\n\r\n#' ### Unweighted estimates \r\n#' Unweighted estimate - for adults aged 18 and over \r\ndf %>% filter(inAnalysis==1) %>% summarize(mean=round(mean(htn_old)*100, digits=1))\r\n\r\n#' Unweighted estimate - for adults aged 18 and over, by race and Hispanic origin \r\ndf %>% filter(inAnalysis==1 ) %>% group_by(raceEthCat) %>% summarize(mean=mean(htn_old)*100, n=n())\r\n\r\n#' ### Weighted estimates \r\n\r\n#' ## **WARNING**\r\n#' The following commands are intended to demonstrate the importance of using the sample weight in your analyses.\r\n#' The weighted estimate produces the correct **point estimates** for the prevalence of hypertension.\r\n#' However, your analysis must account for the complex survey design of NHANES (e.g. stratification and clustering), \r\n#' in order to produce correct **standard errors** (and confidence intervals, statistical tests, etc.).\r\n#' Do not use this step as a model for producing your own analyses! \r\n#' See the Continuous NHANES tutorial Module 4: Variance Estimation for a complete explanation of how to properly account \r\n#' for the complex survey design using commands in the \"survey\" package\r\n#'\r\n#'\r\n#' Weighted estimates - for adults aged 18 and over\r\ndf %>% filter(inAnalysis==1) %>% summarize(mean=round(weighted.mean(htn_old, WTMEC2YR)*100, digits=1))\r\n\r\n#' Weighted estimate - for adults aged 18 and over, by race and Hispanic origin \r\ndf %>% filter(inAnalysis==1 ) %>% group_by(raceEthCat) %>% summarize(mean=weighted.mean(htn_old, WTMEC2YR)*100)\r\n\r\n\r\n#' ## Example of how to use the survey package to estimate the prevalence of hypertension, with correct standard errors \r\n#' See Module 4: Variance Estimation for details \r\n# Define survey design for overall dataset \r\nNHANES_all <- svydesign(data=df, id=~SDMVPSU, strata=~SDMVSTRA, weights=~WTMEC2YR, nest=TRUE)\r\n\r\n# Create a survey design object for the subset of interest \r\n# Subsetting the original survey design object ensures we keep the design information about the number of clusters and strata\r\nNHANES <- subset(NHANES_all, inAnalysis==1)\r\n\r\n#' Proportion and standard error, for adults aged 18 and over\r\nsvyby(~htn_old, ~one, NHANES, svymean) %>% mutate(htn_old = round(htn_old*100, digits=1), se=round(se*100, digits=1))\r\n\r\n#' Proportion and standard error, for adults aged 18 and over by race and Hispanic origin\r\nsvyby(~htn_old, ~raceEthCat, NHANES, svymean) %>% mutate(htn_old = round(htn_old*100, digits=1), se=round(se*100, digits=1))\r\n\r\n#' ***\r\n \r\n#' ## Age distribution among Hispanic adults, weighted and unweighted\r\n#' To support the statement in the tutorial text that the unweighted estimate over-represents Hispanic adults aged 60 and over,\r\n#' compared with their actual share of the Hispanic adult population. \r\n#' \r\n \r\n#' ### Unweighted age distribution among Hispanic adults in the analysis \r\ndf %>% filter(inAnalysis==1 & raceEthCat=='Hispanic') %>% \r\n count(ageCat_18) %>% \r\n mutate(prop= round(n / sum(n)*100, digits=1))\r\n#' Unweighted, Hispanic adults aged 60 and over comprise 33% of Hispanic adults in the analysis sample. \r\n#'\r\n#' ### Weighted age distribution among Hispanic adults in the analysis population\r\ndf %>% filter(inAnalysis==1 & raceEthCat=='Hispanic') %>% count(ageCat_18, wt=WTMEC2YR) %>%\r\n mutate(prop= round(n / sum(n)*100, digits=1))\r\n#' When properly weighted, Hispanic adults aged 60 and over comprise 15% of Hispanic adults in the US non-institutionalized civilian population\r\n ", "meta": {"hexsha": "d02f73363c2cd49f97a1d5d7b1f416285f58a441", "size": 9402, "ext": "r", "lang": "R", "max_stars_repo_path": "[Data] NHANES) Tutorial 0 download/module3_examples_R.r", "max_stars_repo_name": "mkim0710/NHANES", "max_stars_repo_head_hexsha": "3ce614112b609f969ed7bdbe6c2201e7bd42d24a", "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": "[Data] NHANES) Tutorial 0 download/module3_examples_R.r", "max_issues_repo_name": "mkim0710/NHANES", "max_issues_repo_head_hexsha": "3ce614112b609f969ed7bdbe6c2201e7bd42d24a", "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": "[Data] NHANES) Tutorial 0 download/module3_examples_R.r", "max_forks_repo_name": "mkim0710/NHANES", "max_forks_repo_head_hexsha": "3ce614112b609f969ed7bdbe6c2201e7bd42d24a", "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.746031746, "max_line_length": 168, "alphanum_fraction": 0.6512444161, "num_tokens": 2437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.04146227448806703, "lm_q1q2_score": 0.018312766785407865}} {"text": "#--------------------------------------------------------------------#\r\n# Analysis of dataset from Heller & Goldrick (2014) \r\n# As reported in Keshet, Adi, Cibelli, Gustafson, Clopper, & Goldrick \r\n\r\n# Note on terminology -\r\n# Terms for the algorithmic methods in this code are different than \r\n# those used in the paper. Their correspondences are:\r\n# HMM = Penn/FAVE (forced aligner)\r\n# DLM = SED (structured prediction)\r\n# DLM (no classifier) = SEDNC (structured prediction, no classifier)\r\n#-------------------------------------------------------------------#\r\n\r\n# Regression analysis package\r\nlibrary(lme4)\r\n\r\n# lme convenience function\r\n# Extracts estimated chi-sq stats p-values for each fixed effect \r\n# To be used with anova() comparing model with and without the fixed effect of interest\r\nchiReport.func <- function(a){\r\n\tifelse (\r\n\t\ta$\"Pr(>Chisq)\"[2] > .0001,\r\n\t\treturn(paste(\"chisq(\",a$\"Chi Df\"[2],\")=\",round(a$Chisq[2],2),\", p = \",round(a\t$\"Pr(>Chisq)\"[2],4),sep=\"\")), # return chisq, p\r\n\t\treturn(paste(\"chisq(\",a$\"Chi Df\"[2],\")=\",round(a$Chisq[2],2),\", p < .0001\"))) # return p < .0001 for very small values of p\r\n}\r\n\r\n# Bootstrap analysis package\r\nlibrary(boot)\r\n\r\n# Bootstrap function for mean differences in paired observations\r\nboot.mean.dif.fnc <- function (data,indices){\r\n # get difference at each index\r\n d <- (data$Obs1[indices]-data$Obs2[indices])\r\n # calculate mean\r\n return(mean(d))\r\n}\r\n\r\n# Read in manual data \r\ndataMANUAL <- read.delim(\"durationData.txt\",as.is=T)\r\n\r\n# Read in aligned datasets and remove extraneous columns \r\ndataSED <- read.csv(\"structed_classifier_DL.csv\",as.is=T)\r\ndataSED = dataSED[,c(\"file_name\",\"predicted_duration\")]\r\ndataSEDNC <- read.csv(\"structed_no_classifier_DL.csv\", as.is=T)\r\ndataSEDNC = dataSEDNC[,c(\"file_name\",\"predicted_duration\")]\r\ndataPENN <- read.csv(\"fave_jordana.csv\",as.is=T)\r\ndataPENN = dataPENN[,c(\"file_name\", \"predicted_duration\")]\r\n\r\n# Make filename columns are consistent\r\ndataMANUAL$File = gsub(\".wav\", \"\", dataMANUAL$File)\r\ndataSED$file_name = tolower(gsub(\".TextGrid\", \"\", dataSED$file_name))\r\ndataSEDNC$file_name = tolower(gsub(\".TextGrid\", \"\", dataSEDNC$file_name))\r\ndataPENN$file_name = gsub(\".textgrid\", \"\", dataPENN$file_name)\r\n\r\n# Exclude subjects 001, 008, 031 \r\n# (These subjects did not give permission for data use beyond the original project)\r\nexcludeSubj = c(\"s001\", \"s008\", \"s031\")\r\ndataMANUAL = dataMANUAL[!(dataMANUAL$subj %in% excludeSubj),]\r\ndataSED = dataSED[-(grep(\"008\", dataSED$file_name, fixed = TRUE)),] \r\ndataSEDNC = dataSEDNC[-(grep(\"008\", dataSEDNC$file_name, fixed = TRUE)),]\r\n\r\n# Remove \"lock\", \"hat\" observations from the two data frames they appeared in\r\ndataSED = dataSED[-(grep(\"lock\", dataSED$file_name)),]\r\ndataSED = dataSED[-(grep(\"hat\", dataSED$file_name)),]\r\ndataSEDNC = dataSEDNC[-(grep(\"lock\", dataSEDNC$file_name)),]\r\ndataSEDNC = dataSEDNC[-(grep(\"hat\", dataSEDNC$file_name)),]\r\n\r\n# total observations\r\nnrow(dataMANUAL)\r\n# 2395\r\n\r\n# Failure rates for each\r\n# (Data points which could not be algorithmically aligned)\r\n1-(nrow(dataSED)/nrow(dataMANUAL))\r\n# -0.002505219\r\n1-(nrow(dataSEDNC)/nrow(dataMANUAL))\r\n# -0.002505219\r\n1-(nrow(dataPENN)/nrow(dataMANUAL))\r\n# 0\r\n\r\n# Find observations common to all\r\nMP <- intersect(dataMANUAL$File, dataSED$file_name)\r\nMPS <- intersect(MP, dataSED$file_name)\r\nMPS2 <- intersect(MPS, dataSED$file_name)\r\n\r\n# Select common observations and sort by filename\r\n# Rename duration column to be specific to each data source\r\ndataMANUAL.matched <- dataMANUAL[is.element(dataMANUAL$File,MPS2),]\r\ncolnames(dataMANUAL.matched)[13] <- \"duration.Manual\"\r\ndataMANUAL.matched <- dataMANUAL.matched[order(dataMANUAL.matched$File),]\r\n\r\ndataSED.matched <- dataSED[is.element(dataSED$file_name,MPS2),]\r\ncolnames(dataSED.matched)[1] <- \"File\"\r\ncolnames(dataSED.matched)[2] <- \"duration.SED\"\r\ndataSED.matched <- dataSED.matched[order(dataSED.matched$File),]\r\n\r\ndataSEDNC.matched = dataSEDNC[is.element(dataSEDNC$file_name,MPS2),]\r\ncolnames(dataSEDNC.matched)[1] <- \"File\"\r\ncolnames(dataSEDNC.matched)[2] = \"duration.SEDNC\"\r\ndataSEDNC.matched = dataSEDNC.matched[order(dataSEDNC.matched$File),]\r\n\r\ndataPENN.matched <- dataPENN[is.element(dataPENN$file_name,MPS2),]\r\ncolnames(dataPENN.matched)[1] <- \"File\"\r\ncolnames(dataPENN.matched)[2] <- \"duration.PENN\"\r\ndataPENN.matched <- dataPENN.matched[order(dataPENN.matched$File),]\r\n\r\n# Merge datasets into one frame\r\ndataMP <- merge(dataMANUAL.matched,dataPENN.matched,by=\"File\")\r\ndataMP2 <- merge(dataMP,dataSED.matched,by=\"File\")\r\ndataFull = merge(dataMP2, dataSEDNC.matched, by=\"File\")\r\n\r\n# Size of common set - make sure this equals the value reported above for nrow(dataMANUAL)\r\nnrow(dataFull)\r\n# 2395\r\n\r\n# --------------------------------------------------------------------------------------------\r\n## Density plot\r\n\r\n# Compare the distribution of deviance of each algorithmic model to the manual model, and \r\n# plot that distribution\r\n\r\npdf(file=\"figures/HellerDensity.pdf\", width = 5.25, height = 5)\r\ncexStandard = 1.25\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Baseline text size\r\naxisMaxMin = max(abs((c(\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Find good axis values \r\n\tdataFull$duration.Manual - dataFull$duration.SED, \r\n\tdataFull$duration.Manual - dataFull$duration.SEDNC, \r\n\tdataFull$duration.Manual - dataFull$duration.PENN))))\r\naxisMaxMin = axisMaxMin + (0.1* axisMaxMin)\t\r\nplot(density(dataFull$duration.Manual - dataFull$duration.SED), lwd = 2, col = \"blue\",\t\t\t\t# Plot SED (DLM) deviance in blue\r\n\tmain = \"\",\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Suppress main title\r\n\tcex.main = cexStandard+.25, cex.axis = cexStandard, cex.lab = cexStandard,\t\t\t\t\t\t# Set text sizes\r\n\txlim = c(-axisMaxMin, axisMaxMin), ylim = c(0, 30))\t\t\t\t\t\t\t\t\t\t\t\t# Set x-axis limits\r\nlines(density(dataFull$duration.Manual - dataFull$duration.SEDNC), lwd = 2, col = \"red\", lty = 2) \t# Plot SEDNC deviance in red\r\nlines(density(dataFull$duration.Manual - dataFull$duration.PENN), lwd = 2, col = \"black\", lty = 4) \t# Plot Penn (HMM) deviance in black\r\nlegend(\"topright\", c(\"DLM\", \"DLM (no classifier)\", \"HMM\"), col = c(\"blue\", \"red\", \"black\"),\t\t\t# Legend\r\n lwd = 2, lty = c(1, 2, 4), cex = 0.85)\r\ndev.off()\r\n\r\n# ---------------------------------------------------------------------------------------\r\n\r\n## Metrics of error (MSE)\r\n\r\n#Mean squared error of predictions: Structured Prediction\r\nmean((dataFull$duration.SED - dataFull$duration.Manual)^2)*1000\r\n# 1.561764\r\n\r\n#Mean squared error of predictions: Structured Prediction (no classifier)\r\nmean((dataFull$duration.SEDNC - dataFull$duration.Manual)^2)*1000\r\n# 2.336025\r\n\r\n#Mean squared error of predictions: Penn aligner\r\nmean((dataFull$duration.PENN - dataFull$duration.Manual)^2)*1000\r\n# 1.853601\r\n\r\n#Compare MSE: Structured prediction vs. Penn aligner\r\n#bootstrap 95% CI\r\npairedObs<- data.frame((dataFull$duration.PENN-dataFull$duration.Manual)^2,(dataFull$duration.SED-dataFull$duration.Manual)^2)\r\ncolnames(pairedObs) <-c(\"Obs1\",\"Obs2\")\r\nboot.results <- boot(data=pairedObs,statistic = boot.mean.dif.fnc,R=1000) #1000 bootstrap replicates\r\n\r\n# Mean squared error of predictions\r\n# Note: these and all bootstrap predictions will vary slightly from run to run\r\nmean((dataFull$duration.PENN - dataFull$duration.Manual)^2 - (dataFull$duration.SED - dataFull$duration.Manual)^2 )\r\n# 0.0002918373\r\n# this is the mean difference in squared error across the two methods.\r\n\r\nboot.ci(boot.results,type=\"perc\")$perc[,5] # upper 95th percentile\r\n# 0.0005405129 \r\nboot.ci(boot.results,type=\"perc\")$perc[,4] # lower 95th percentile\r\n# 4.535996e-05 \r\n# Interpretation: Interval does not include 0, so Penn (HMM) has significantly higher MSE than SED (DLM)\r\n\r\n#Compare MSE: Structured prediction vs. without classifier\r\n#bootstrap 95% CI\r\npairedObs<- data.frame((dataFull$duration.SEDNC-dataFull$duration.Manual)^2,(dataFull$duration.SED-dataFull$duration.Manual)^2)\r\ncolnames(pairedObs) <-c(\"Obs1\",\"Obs2\")\r\nboot.results <- boot(data=pairedObs,statistic = boot.mean.dif.fnc,R=1000) #1000 bootstrap replicates\r\n\r\n#Mean squared error of predictions\r\nmean((dataFull$duration.SEDNC - dataFull$duration.Manual)^2 - (dataFull$duration.SED - dataFull$duration.Manual)^2 )\r\n# 0.0007742605\r\n# this is the mean difference in squared error across the two methods.\r\n\r\nboot.ci(boot.results,type=\"perc\")$perc[,5] # upper 95th percentile\r\n# 0.001009028 \r\nboot.ci(boot.results,type=\"perc\")$perc[,4] # lower 95th percentile\r\n# 0.0005153437 \r\n# Interpretation: Interval does not contain 0; SEDNC (DLM NC) has significantly higher MSE than SED (DLM)\r\n\r\n#Compare MSE: Structured prediction without classifier vs. Penn aligner\r\n#bootstrap 95% CI\r\npairedObs<- data.frame((dataFull$duration.SEDNC-dataFull$duration.Manual)^2,(dataFull$duration.PENN-dataFull$duration.Manual)^2)\r\ncolnames(pairedObs) <-c(\"Obs1\",\"Obs2\")\r\nboot.results <- boot(data=pairedObs,statistic = boot.mean.dif.fnc,R=1000) #1000 bootstrap replicates\r\n\r\n#Mean squared error of predictions\r\nmean((dataFull$duration.SEDNC - dataFull$duration.Manual)^2 - (dataFull$duration.PENN - dataFull$duration.Manual)^2 )\r\n# 0.0004824232\r\n# this is the mean difference in squared error across the two methods.\r\n\r\nboot.ci(boot.results,type=\"perc\")$perc[,5] # upper 95th percentile\r\n# 0.0007918015 \r\nboot.ci(boot.results,type=\"perc\")$perc[,4] # lower 95th percentile\r\n# 0.0001562128 \r\n# Interpretation: Interval does not contain 0; SEDNC (DLM NC) has significantly higher MSE than Penn (HMM)\r\n\r\n# ------------------------------------------------------------------------------------------\r\n## Regression analyses\r\n\r\n# For regressions: follow method of Sonderegger & Keshet (2012)\r\n# Test 1: after trimming outliers, compare model parameters (for fit on training set)\r\n# Test 2: compare predictions of models using leave-one-out method\r\n\r\n# Prep regression analysis\r\n# center/log transform density predictor\r\ndataFull$logDur.Manual = log(dataFull$duration.Manual)\r\ndataFull$logDur.SED = log(dataFull$duration.SED)\r\ndataFull$logDur.SEDNC = log(dataFull$duration.SEDNC)\r\ndataFull$logDur.PENN = log(dataFull$duration.PENN)\r\n\r\n# For each algorithmic measure:\r\n# Fit a regression model, then re-fit excluding observations where model residuals exceed 2.5 standard deviations from mean\r\n# Assess significance of each fixed effect term using model comparison\r\n\r\n# Basic model structure: \r\n# data.lmer = lmer(logDur~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n\r\n# Manual fit\r\ndataManual.lmer = lmer(logDur.Manual~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\nmanualTrim = dataFull[abs(scale(resid(dataManual.lmer)))<2.5,] # Trim outlier residuals and then refit model\r\ndataManualTrim.lmer = lmer(logDur.Manual~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=manualTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n\r\nsummary(dataManualTrim.lmer)\r\n# Fixed effects:\r\n# \t\t\t Estimate \tStd. Error t value\r\n# (Intercept) -1.72217 0.04721 -36.48\r\n# ContextCode -0.05741 0.01747 -3.29\r\n# BlockCode 0.01181 0.01642 0.72\r\n\r\n# Assess fixed effects by re-fitting model without predictor, anova() to compare model with and without predictor\r\nchiReport.func(anova(dataManualTrim.lmer,update(dataManualTrim.lmer,.~.-ContextCode)))\r\n# \"chisq(1)=10, p = 0.0016\"\r\nchiReport.func(anova(dataManualTrim.lmer,update(dataManualTrim.lmer,.~.-BlockCode)))\r\n# \"chisq(1)=0.52, p = 0.473\"\r\n\r\n# Structured prediction fit\r\ndataSED.lmer = lmer(logDur.SED~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\nsedTrim = dataFull[abs(scale(resid(dataSED.lmer)))<2.5,]\r\ndataSEDTrim.lmer = lmer(logDur.SED~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=sedTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n\r\nsummary(dataSEDTrim.lmer)\r\n# Estimate Std. Error t value\r\n# (Intercept) -1.79041 0.04453 -40.20\r\n# ContextCode -0.07180 0.01879 -3.82\r\n# BlockCode 0.01608 0.01770 0.91\r\n\r\nchiReport.func(anova(dataSEDTrim.lmer,update(dataSEDTrim.lmer,.~.-ContextCode)))\r\n# \"chisq(1)=13.11, p = 3e-04\"\r\nchiReport.func(anova(dataSEDTrim.lmer,update(dataSEDTrim.lmer,.~.-BlockCode)))\r\n#\"chisq(1)=0.82, p = 0.3651\"\r\n\r\n# Structured prediction (no classifier) fit\r\ndataSEDNC.lmer = lmer(logDur.SEDNC~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\nsedncTrim = dataFull[abs(scale(resid(dataSEDNC.lmer)))<2.5,]\r\ndataSEDNCTrim.lmer = lmer(logDur.SEDNC~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=sedncTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n\r\nsummary(dataSEDNCTrim.lmer)\r\n# Estimate Std. Error t value\r\n# (Intercept) -1.80015 0.04262 -42.24\r\n# ContextCode -0.05861 0.01754 -3.34\r\n# BlockCode 0.01515 0.01680 0.90\r\n\r\nchiReport.func(anova(dataSEDNCTrim.lmer,update(dataSEDNCTrim.lmer,.~.-ContextCode)))\r\n# \"chisq(1)=10.2, p = 0.0014\"\r\nchiReport.func(anova(dataSEDNCTrim.lmer,update(dataSEDNCTrim.lmer,.~.-BlockCode)))\r\n# \"chisq(1)=0.81, p = 0.3688\"\r\n\r\n# Penn aligner fit\r\ndataPENN.lmer = lmer(logDur.PENN~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\npennTrim = dataFull[abs(scale(resid(dataPENN.lmer)))<2.5,]\r\ndataPENNTrim.lmer = lmer(logDur.PENN~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=pennTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n\r\nsummary(dataPENNTrim.lmer)\r\n# # Estimate Std. Error t value\r\n# (Intercept) -1.775437 0.046181 -38.45\r\n# ContextCode -0.057771 0.018471 -3.13\r\n# BlockCode 0.007923 0.014283 0.55\r\n\r\nchiReport.func(anova(dataPENNTrim.lmer,update(dataPENNTrim.lmer,.~.-ContextCode)))\r\n# \"chisq(1)=8.81, p = 0.003\"\r\nchiReport.func(anova(dataPENNTrim.lmer,update(dataPENNTrim.lmer,.~.-BlockCode)))\r\n# \"chisq(1)=0.31, p = 0.5795\"\r\n\r\n## ---------------------------------------------------------------------------------\r\n## Leave-one-out model predictions \r\n\r\n# Comparison 2: Predictions using leave-one-out method\r\n\r\n# Generate predictions for test set\r\nobs = c(1:length(dataFull$File))\r\ndataFull2 = cbind(dataFull, obs)\r\n\r\n# Predictions (these will be time-intensive)\r\nmanualPredict = double(length(dataFull$File))\r\nfor(i in 1:length(dataFull$File)){\r\n dataFull3 = subset(dataFull2, obs!=i)\r\n dataManual.lmer = lmer(logDur.Manual~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull3,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n manualTrim = dataFull3[abs(scale(resid(dataManual.lmer)))<2.5,]\r\n dataManualTrim.lmer = lmer(logDur.Manual~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=manualTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n manPred = predict(dataManualTrim.lmer, newdata = dataFull2)\r\n manualPredict[i] = manPred[i]\r\n}\r\n\r\nsedPredict = double(length(dataFull$File))\r\nfor(i in 1:length(dataFull$File)){\r\n dataFull3 = subset(dataFull2, obs!=i)\r\n dataSED.lmer = lmer(logDur.SED~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull3,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n sedTrim = dataFull3[abs(scale(resid(dataSED.lmer)))<2.5,]\r\n dataSEDTrim.lmer = lmer(logDur.SED~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=sedTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n sedPred = predict(dataSEDTrim.lmer, newdata = dataFull2)\r\n sedPredict[i] = sedPred[i]\r\n}\r\n\r\nsedncPredict = double(length(dataFull$File))\r\nfor(i in 1:length(dataFull$File)){\r\n dataFull3 = subset(dataFull2, obs!=i)\r\n dataSEDNC.lmer = lmer(logDur.SEDNC~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull3,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n sedncTrim = dataFull[abs(scale(resid(dataSEDNC.lmer)))<2.5,]\r\n dataSEDNCTrim.lmer = lmer(logDur.SEDNC~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=sedncTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n sedncPred = predict(dataSEDNCTrim.lmer, newdata = dataFull2)\r\n sedncPredict[i] = sedncPred[i]\r\n}\r\n\r\npennPredict = double(length(dataFull$File))\r\nfor(i in 1:length(dataFull$File)){\r\n dataFull3 = subset(dataFull2, obs!=i)\r\n dataPENN.lmer = lmer(logDur.PENN~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=dataFull3,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n pennTrim = dataFull[abs(scale(resid(dataPENN.lmer)))<2.5,]\r\n dataPENNTrim.lmer = lmer(logDur.PENN~ContextCode+BlockCode+(1+ContextCode||subject)+(1+ContextCode||word),data=pennTrim,control = lmerControl(optimizer = \"bobyqa\"),REML=F)\r\n pennPred = predict(dataPENNTrim.lmer, newdata = dataFull2)\r\n pennPredict[i] = pennPred[i]\r\n}\r\n\r\n#MSE for Structured Prediction\r\nmean((exp(manualPredict)-exp(sedPredict))^2)*1000\r\n# 0.4785495\r\n\r\n#MSE for Structured Prediction (no classifier)\r\nmean((exp(manualPredict)-exp(sedncPredict))^2) *1000\r\n# 0.9351113\r\n\r\n#MSE for penn aligner\r\nmean((exp(manualPredict)-exp(pennPredict))^2) *1000\r\n# 0.8345711\r\n\r\n#Compare MSE: Structured prediction vs. Penn aligner\r\n#bootstrap 95% CI\r\npairedObs<- data.frame((exp(pennPredict) - exp(manualPredict))^2,(exp(sedPredict) - exp(manualPredict))^2)\r\ncolnames(pairedObs) <-c(\"Obs1\",\"Obs2\")\r\nboot.results <- boot(data=pairedObs,statistic = boot.mean.dif.fnc,R=1000) #1000 bootstrap replicates\r\n\r\nboot.ci(boot.results,type=\"perc\")$perc[,5] # upper 95th percentile\r\n# 0.0004278912 \r\nboot.ci(boot.results,type=\"perc\")$perc[,4] # lower 95th percentile\r\n# 0.0002945042 \r\n# Interpretation: Interval does not contain 0, so PENN(HMM) has a higher MSE than SED (DLM)\r\n\r\n#Compare MSE: Structured prediction vs. structured prediction (no classifier)\r\n#bootstrap 95% CI\r\npairedObs<- data.frame((exp(sedncPredict) - exp(manualPredict))^2,(exp(sedPredict) - exp(manualPredict))^2)\r\ncolnames(pairedObs) <-c(\"Obs1\",\"Obs2\")\r\nboot.results <- boot(data=pairedObs,statistic = boot.mean.dif.fnc,R=1000) #1000 bootstrap replicates\r\n\r\nboot.ci(boot.results,type=\"perc\")$perc[,5] # upper 95th percentile\r\n# 0.0005468904 \r\nboot.ci(boot.results,type=\"perc\")$perc[,4] # lower 95th percentile\r\n# 0.0003740818\r\n# Interpretation: Interval does not contain 0, so SEDNC (DLM NC) has a higher MSE than SED (DLM)\r\n\r\n#Compare MSE: Structured prediction (no classifier) vs. Penn aligner\r\n#bootstrap 95% CI\r\npairedObs<- data.frame((exp(pennPredict) - exp(manualPredict))^2,(exp(sedncPredict) - exp(manualPredict))^2)\r\ncolnames(pairedObs) <-c(\"Obs1\",\"Obs2\")\r\nboot.results <- boot(data=pairedObs,statistic = boot.mean.dif.fnc,R=1000) #1000 bootstrap replicates\r\n\r\n#Mean squared error of predictions\r\nboot.ci(boot.results,type=\"perc\")$perc[,5] # upper 95th percentile\r\n# 1.51538e-06 \r\nboot.ci(boot.results,type=\"perc\")$perc[,4] # lower 95th percentile\r\n# -0.0002047568 \r\n# Interpretation: Interval contains 0, so we cannot be confident in a difference between SED (DLM) and SEDNC (DLM-NC)\r\n\r\n# ---------------------------------------------------------------------------------------\r\n## Plot leave-one-out model predictions\r\n\r\n# Compare the distribution of deviance of each algorithmic model's preditions to the manual model's predictions, and plot that distribution\r\n\r\npdf(file=\"figures/HellerDensityPredictions.pdf\", width = 5.25, height = 5)\r\ncexStandard = 1.25\r\n# Set axis min-max to contain data points from all four sets of predictions\r\naxisMaxMin = max(abs((c(\r\n\tmanualPredict - sedPredict, \r\n\tmanualPredict - sedncPredict, \r\n\tmanualPredict - pennPredict))))\r\naxisMaxMin = axisMaxMin + (0.3* axisMaxMin)\t\r\nplot(density(manualPredict - sedPredict), lwd = 2, col = \"blue\",\r\n\tmain = \"\",\r\n\tcex.main = cexStandard+.25, cex.axis = cexStandard, cex.lab = cexStandard,\r\n\txlim = c(-axisMaxMin, axisMaxMin), ylim = c(0, 6))\t\r\nlines(density(manualPredict - sedncPredict), lwd = 2, col = \"red\", lty = 2)\r\nlines(density(manualPredict - pennPredict), lwd = 2, col = \"black\", lty = 4)\r\nlegend(\"topright\", c(\"DLM\", \"DLM (no classifier)\", \"HMM\"), col = c(\"blue\", \"red\", \"black\"),\r\n lwd = 2, lty = c(1, 2, 4), cex = 0.85)\r\ndev.off()\r\n", "meta": {"hexsha": "28923298f8af77e00502fa0f15e2bb17a2399492", "size": 20286, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/hellerAnalysisForSubmission.r", "max_stars_repo_name": "adiyoss/AutoVowelDuration", "max_stars_repo_head_hexsha": "609451c686f30a189e2b73e8ab726bf2d01a2a7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12, "max_stars_repo_stars_event_min_datetime": "2016-06-17T21:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T14:54:16.000Z", "max_issues_repo_path": "analysis/hellerAnalysisForSubmission.r", "max_issues_repo_name": "adiyoss/AutoVowelDuration", "max_issues_repo_head_hexsha": "609451c686f30a189e2b73e8ab726bf2d01a2a7e", "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/hellerAnalysisForSubmission.r", "max_forks_repo_name": "adiyoss/AutoVowelDuration", "max_forks_repo_head_hexsha": "609451c686f30a189e2b73e8ab726bf2d01a2a7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-27T15:02:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-07T09:12:03.000Z", "avg_line_length": 49.0, "max_line_length": 180, "alphanum_fraction": 0.7017647639, "num_tokens": 6060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.04401864516002746, "lm_q1q2_score": 0.0172701357103359}} {"text": "##\n# @file\n# This file is part of SeisSol.\n#\n# @author Alex Breuer (breuer AT mytum.de, http://www5.in.tum.de/wiki/index.php/Dipl.-Math._Alexander_Breuer)\n#\n# @section LICENSE\n# Copyright (c) 2014, SeisSol Group\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# \n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# @section DESCRIPTION\n# Performance model for SeisSol setups.\n\ncomputeMeshStatistics <- function( i_meshName,\n i_pathToCsvFile,\n i_performanceParameters,\n i_outputFileTable,\n i_outputFilePlot ) {\n message( 'reading mesh', i_pathToCsvFile )\n l_meshStatistics <- read.csv( file = i_pathToCsvFile,\n header = TRUE )\n\n #\n # compute data to send and receive in MPI-communication\n #\n # mpi-information per time step in GB, regular mpi faces\n l_meshStatistics$mpi_send <- l_meshStatistics$mpi_faces*i_performanceParameters$dofs_size/1024^3\n\n # mpi-information per time step in GB, dr mpi face come on top\n l_meshStatistics$mpi_send <- l_meshStatistics$mpi_send + (l_meshStatistics$mpi_dr_faces*i_performanceParameters$dofs_size/1024^3)\n\n # so far everything is the same\n l_meshStatistics$mpi_receive <- l_meshStatistics$mpi_send\n\n #\n # compute ratios\n #\n l_meshStatistics$ratio_dynamic_rupture_faces_elements <- l_meshStatistics$dynamic_rupture_faces / l_meshStatistics$elements\n\n # compute timings for\n # * time integraton of all elements\n # * volume integration of all elements\n # * boundary integration of all elements\n # * additional flux computation for dunamic rupture faces\n # * time integration of MPI-elements\n # * communication of MPI-elements\n # * computation of volume integration and non-MPI time integration\n if( !i_performanceParameters$mic ) {\n l_meshStatistics$time_integration <- l_meshStatistics$elements*i_performanceParameters$time_integration\n l_meshStatistics$volume_integration <- l_meshStatistics$elements*i_performanceParameters$volume_integration\n }\n \n l_meshStatistics$boundary_integration <- l_meshStatistics$elements*i_performanceParameters$boundary_integration \n l_meshStatistics$time_communication <- (l_meshStatistics$mpi_send + l_meshStatistics$mpi_receive) / i_performanceParameters$network_bandwidth \n l_meshStatistics$dynamic_rupture_fluxes <- l_meshStatistics$dynamic_rupture_faces*i_performanceParameters$dynamic_rupture \n\n if( i_performanceParameters$mic ) {\n l_meshStatistics$time_integration_mpi <- l_meshStatistics$mpi_elements*i_performanceParameters$time_integration\n l_meshStatistics$pci_communication <- ( (l_meshStatistics$mpi_faces*i_performanceParameters$dofs_size*2 + l_meshStatistics$mpi_dr_faces*i_performanceParameters$dofs_size) /1024^3) / i_performanceParameters$pci_bandwidth\n l_meshStatistics$volume_time_integration_interior <- l_meshStatistics$elements*i_performanceParameters$volume_integration + l_meshStatistics$interior_elements*i_performanceParameters$time_integration \n\n l_meshStatistics$overlapped_comm_time_volume <- pmax( l_meshStatistics$time_communication + l_meshStatistics$pci_communication, l_meshStatistics$volume_time_integration_interior )\n l_meshStatistics$cpu_dynamic_rupture <- l_meshStatistics$dynamic_rupture_fluxes - pmax( l_meshStatistics$volume_time_integration_interior - l_meshStatistics$overlapped_comm_time_volume, 0 )\n l_meshStatistics$overlapped_dyn_rupture_fluxes <- pmax( l_meshStatistics$cpu_dynamic_rupture + (l_meshStatistics$dynamic_rupture_faces*i_performanceParameters$dofs_size/1024^3) / i_performanceParameters$pci_bandwidth,\n l_meshStatistics$boundary_integration )\n }\n\n#new overlap\n# if( i_performanceParameters$mic ) {\n# l_meshStatistics$time_integration_mpi <- l_meshStatistics$mpi_elements*i_performanceParameters$time_integration\n# l_meshStatistics$pci_communication <- ( (l_meshStatistics$mpi_faces*i_performanceParameters$dofs_size*2 + l_meshStatistics$mpi_dr_faces*i_performanceParameters$dofs_size) /1024^3) / i_performanceParameters$pci_bandwidth\n# l_meshStatistics$volume_time_integration_interior <- l_meshStatistics$elements*i_performanceParameters$volume_integration + l_meshStatistics$interior_elements*i_performanceParameters$time_integration + l_meshStatistics$interior_elements*i_performanceParameters$boundary_integration\n# \n# l_meshStatistics$overlapped_comm_time_volume <- pmax( l_meshStatistics$time_communication + l_meshStatistics$pci_communication, l_meshStatistics$volume_time_integration_interior )\n# l_meshStatistics$cpu_dynamic_rupture <- l_meshStatistics$dynamic_rupture_fluxes - pmax( l_meshStatistics$volume_time_integration_interior - l_meshStatistics$overlapped_comm_time_volume, 0 )\n# l_meshStatistics$overlapped_dyn_rupture_fluxes <- pmax( l_meshStatistics$cpu_dynamic_rupture + (l_meshStatistics$dynamic_rupture_faces*i_performanceParameters$dofs_size/1024^3) / i_performanceParameters$pci_bandwidth,\n# l_meshStatistics$mpi_elements*i_performanceParameters$boundary_integration )\n# }\n \n if( !i_performanceParameters$mic ) {\n l_meshStatistics$time_total <- l_meshStatistics$time_integration + l_meshStatistics$volume_integration + l_meshStatistics$boundary_integration + l_meshStatistics$dynamic_rupture_fluxes + l_meshStatistics$time_communication\n }\n else {\n l_meshStatistics$time_total <- l_meshStatistics$time_integration_mpi + l_meshStatistics$overlapped_comm_time_volume + l_meshStatistics$overlapped_dyn_rupture_fluxes\n }\n message( 'summary mesh statistics')\n print( summary( l_meshStatistics ) )\n\n message( 'writing csv' )\n write.csv( x=l_meshStatistics, file=i_outputFileTable)\n \n message( 'plotting information' )\n pdf( file = i_outputFilePlot,\n paper = 'a4r',\n width=20,\n height=10)\n\n # print title page\n plot(0:10, type = \"n\", xaxt=\"n\", yaxt=\"n\", bty=\"n\", xlab = \"\", ylab = \"\")\n text(5, 8, i_meshName)\n text(5, 7, Sys.time())\n\n # overview boxplots\n if( !i_performanceParameters$mic ) {\n par( mfrow=c(1,6) )\n boxplot(l_meshStatistics$time_integration, main='time integration' )\n boxplot(l_meshStatistics$volume_integration, main='volume integration' )\n boxplot(l_meshStatistics$boundary_integration, main='boundary integration' )\n boxplot(l_meshStatistics$dynamic_rupture_fluxes, main='dyn. rupt. fluxes' )\n boxplot(l_meshStatistics$time_communication, main='communication' )\n boxplot(l_meshStatistics$time_total, main='total time' )\n }\n else {\n par( mfrow=c(1,6) )\n boxplot( l_meshStatistics$time_integration_mpi, main='time integration of copy layer' )\n boxplot( l_meshStatistics$volume_time_integration_interior, main='time & volume int.' )\n boxplot( l_meshStatistics$overlapped_comm_time_volume, main='overlapped comm., int. time and vol. integration' )\n boxplot( l_meshStatistics$boundary_integration, main='boundary integration' )\n boxplot( l_meshStatistics$overlapped_dyn_rupture_fluxes, main='overlapped dyn. rupt. and bnd. intgration' )\n boxplot( l_meshStatistics$time_total, main='total time' )\n }\n \n # detailed plot of every characteristic value\n #for( l_name in names(l_meshStatistics[-1]) ) {\n # layout( matrix(c(1,2), 2, 2, byrow = TRUE), \n # widths=c(4,1) )\n # plot( x=l_meshStatistics$partition,\n # y=l_meshStatistics[,l_name],\n # xlab=\"partition\",\n # ylab=l_name )\n # boxplot(l_meshStatistics[l_name])\n #}\n dev.off()\n \n return( median(l_meshStatistics$time_total) )\n}\n\nl_config = list ( mesh_names = list( 'statistics_cube320_400_640_1024',\n 'statistics_cube400_640_640_2048',\n 'statistics_cube640_640_800_4096',\n 'statistics_cube640_900_1280_9216',\n 'statistics_Landers191M_02_05_02_512',\n 'statistics_Landers191M_02_05_02_768',\n 'statistics_Landers191M_02_05_02_1024',\n 'statistics_Landers191M_02_05_02_1536',\n 'statistics_Landers191M_02_05_02_3072',\n 'statistics_Landers191M_02_05_02_2048',\n 'statistics_Landers191M_02_05_02_4096',\n 'statistics_Landers191M_02_05_02_6144',\n 'statistics_Landers191M_02_05_02_9216',\n 'statistics_Landers191M_02_05_02_12288',\n 'statistics_Landers191M_02_05_02_24756'),\n \n statistics_directory = 'mesh_statistics_gb',\n \n performance_parameters = list( supermuc = list( basisFunctions = 56,\n quantities = 9,\n dofs_size = 56*9*8,\n network_bandwidth = 0.8, # TODO: missing reference point\n mic = FALSE,\n boundary_integration = 389.68 * 1024 / 191098540 / 1000, # reference, landers_1024\n time_integration = 169.04 * 1024 / 191098540 / 1000, # reference, landers_1024\n volume_integration = 126.88 * 1024 / 191098540 / 1000, # reference, landers_1024\n #boundary_integration = 43.26 * 9216 / 191098540 / 1000, # reference, landers_9216\n #time_integration = 18.86 * 9216 / 191098540 / 1000, # reference, landers_9216\n #volume_integration = 14.06 * 9216 / 191098540 / 1000, # reference, landers_9216\n #time_integration = 36.33 / 400000 / 100, # reference, cubes_9216\n #volume_integration = 27.18 / 400000 / 100, # reference, cubes_9216\n #boundary_integration = 84.86 / 400000 / 100, # reference, cubes_9216\n dynamic_rupture = 109.33 / 22798 / 1000 ), # TODO: missing reference point\n stampede = list( basisFunctions = 56,\n quantities = 9,\n dofs_size = 56*9*8,\n network_bandwidth = 0.8,\n mic = TRUE,\n pci_bandwidth = 6.3,\n boundary_integration = 230.68 * 2 / 386518 / 1000 * 56 / 60, # extrapolated from LOH1_2\n time_integration = 131.84 * 2 / 386518 / 1000 * 56 / 60, # extrapolated frpm LOH1_2\n volume_integration = 88.51 * 2 / 386518 / 1000 * 56 / 60, # extrapolated from LOH1_2\n dynamic_rupture = 109.33 / 22798 / 1000 ), # same as SuperMUC, but not relevant here; no impact on TH-2\n tianhe = list( basisFunctions = 56,\n quantities = 9,\n dofs_size = 56*9*8,\n #network_bandwidth = 0.367, # fitted via cube-runtimes of ~100.25 seconds\n #network_bandwidth = 0.61, # fitted via landers_2048, 3 cards\n network_bandwidth = 0.525, #fitted via landers_2048, rank 2474: 4582 mpi-facesm 65.56s comm. time\n mic = TRUE,\n pci_bandwidth = 3.2,\n boundary_integration = 230.68 * 2 / 386518 / 1000, # extrapolated from LOH1_2\n time_integration = 131.84 * 2 / 386518 / 1000, # extrapolated from LOH1_2\n volume_integration = 88.51 * 2 / 386518 / 1000, # extrapolated from LOH1_2\n dynamic_rupture = 26.79 / 2800 / 1000 ) # rank 2931 for 6144 ranks on TH-2\n )\n )\n\nl_expectedSimulationTime = list()\n\nmessage( 'lets go' )\nfor( l_machine in list('supermuc', 'stampede', 'tianhe') ) {\n for( l_meshName in l_config$mesh_names ) {\n message( 'analyzing: ', l_meshName )\n l_expectedSimulationTime[[paste(l_meshName,'_',l_machine, sep='')]] =\n computeMeshStatistics( i_meshName = l_meshName,\n i_pathToCsvFile = paste(l_config$statistics_directory,'/',l_meshName,'.csv', sep=''),\n i_performanceParameters = (l_config$performance_parameters)[[l_machine]],\n i_outputFileTable = paste(l_meshName,'_',l_machine,'.csv', sep=''),\n i_outputFilePlot = paste(l_meshName,'_',l_machine,'.pdf', sep='') )\n }\n}\n\nl_expectedSimulationTime$statistics_Landers191M_02_05_02_768_tianhe = 0.581\n\nfor( l_machine in list('supermuc', 'stampede', 'tianhe') ) {\n l_strongScalingNodes = list(768, 1024, 1536, 2048, 3072, 4096, 6144, 9216, 12288, 24756 )\n l_runtime = list()\n for( l_nodes in l_strongScalingNodes ) {\n l_runtime = c( l_runtime, l_expectedSimulationTime[[paste('statistics_Landers191M_02_05_02_', l_nodes, '_', l_machine, sep='')]] * ( l_nodes / l_strongScalingNodes[[1]]) )\n }\n l_runtime <- l_runtime[[1]] / unlist(l_runtime)\n \n print(l_machine)\n print(unlist(l_strongScalingNodes))\n print(l_runtime)\n \n plot( x=l_strongScalingNodes, l_runtime, ylab='parallel efficiency', main=l_machine )\n}\n", "meta": {"hexsha": "71adfa00d72a2a398be03eda01b0e417011b8ea5", "size": 17021, "ext": "r", "lang": "R", "max_stars_repo_path": "postprocessing/performance/model/gb14/mesh_based_model_gb.r", "max_stars_repo_name": "fabian-kutschera/SeisSol", "max_stars_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2015-01-30T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:22:14.000Z", "max_issues_repo_path": "postprocessing/performance/model/gb14/mesh_based_model_gb.r", "max_issues_repo_name": "fabian-kutschera/SeisSol", "max_issues_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 351, "max_issues_repo_issues_event_min_datetime": "2015-10-06T15:06:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:23:13.000Z", "max_forks_repo_path": "postprocessing/performance/model/gb14/mesh_based_model_gb.r", "max_forks_repo_name": "fabian-kutschera/SeisSol", "max_forks_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 96, "max_forks_repo_forks_event_min_datetime": "2015-07-27T15:13:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T19:19:32.000Z", "avg_line_length": 67.2766798419, "max_line_length": 286, "alphanum_fraction": 0.5891545738, "num_tokens": 3688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.042087729267329864, "lm_q1q2_score": 0.01714373786267408}} {"text": "#Italy Invert Figs\n#The following code is for the figures presented in the manuscript. \n#For all other code use for analysis see ItalyInvertRmarkdownJune8.rmd or ItalyInvertRmarkdownJune8.html for precomputed output\n#Joe Receveur Email: josephreceveur[at] gmail.com\n#######\n#Import\n#######\n\nlibrary(vegan)\nlibrary(MASS)\nlibrary(ggplot2)\nlibrary(plyr)\nlibrary(dplyr)\nlibrary(magrittr)\nlibrary(scales)\nlibrary(grid)\nlibrary(reshape2)\nlibrary(phyloseq)\nlibrary(randomForest)\nlibrary(knitr)\nlibrary(ape)\nlibrary(ggpubr)\nlibrary(multcompView)\nlibrary(Rmisc)\nlibrary(tiff)\n\nset.seed(27)\ncbPalette <- c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#000000\",\"#CC79A7\",\"#E12D00\")\ntheme_set(theme_bw(base_size = 18)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\nbiom=import_biom(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert2018WTax.biom\",parseFunction= parse_taxonomy_greengenes)\n#tax_table(biom) <- tax_table(biom)[,-c(5:10,14)]#remove dummy ranks\n\nmetadata=read.csv(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvertMetadataWDiversity3.5.2019.csv\",header = TRUE)\nhead(metadata)\n\ntree=read_tree(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert11.29.18Tree.nwk\")\n\nsampdat=sample_data(metadata)\nsample_names(sampdat)=metadata$id\nphyseq=merge_phyloseq(biom,sampdat,tree)\nphyseq=rarefy_even_depth(physeq, 3000, replace = TRUE, trimOTUs = TRUE, verbose = TRUE)\nphyseq\n\n\n\n\n#######\n#Figure 3A Weights by station\n#######\n\nTrtdata <- ddply(metadata, c(\"Sampling_station\", \"FFG\",\"Taxon_name\"), summarise,\n N = length(id),\n meanWeight = mean(Mass),\n sd = sd(Mass),\n se = sd / sqrt(N)\n)\nTrtdata\n\nScrapers<-subset(metadata, FFG==\"Scraper\")\nt.test( Mass~ Sampling_station, data=Scrapers)\n#t-test,t=4.219,P = 0.0047\n\nShredders<-subset(metadata, FFG==\"Shredder\")\nt.test( Mass~ Sampling_station, data=Shredders)\n#t=1.81,P = 0.2095\n\nMassPlot<-ggplot(metadata,aes(x=Sampling_station,y=Mass,fill=Sampling_station))+geom_boxplot()+ #Write in labels from posthoc\n scale_fill_manual(values=cbPalette)+xlab(\"\")+ylab(\"Mass (mg)\")+labs(fill=\"FFG\")+guides(fill=FALSE)+facet_wrap(~FFG,scales = \"free_y\")+\n theme_bw(base_size = 10)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())\n#+theme(axis.text.x = element_text(angle = 45, \nMassPlot\n\ntiff(\"Figures/MassPlot.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nMassPlot\ndev.off()\n\n#######\n#Figure 3B Phylum level stacked bar graph \n#######\ntheme_set(theme_bw(base_size = 9)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nPhylumAll=tax_glom(GPr, \"Phylum\")\n\nPhylumLevel = filter_taxa(PhylumAll, function(x) mean(x) > 1e-2, TRUE) #filter out any taxa lower tha 0.1%\n\ndf <- psmelt(PhylumLevel)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Phylum\", \"FFG\",\"Sampling_station\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\nTrtdata\n\n\nRelAbuAllSamples <- ddply(df, c(\"Phylum\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\nRelAbuAllSamples#Mean relative abundance for all samples\n\nTrtdata<-read.csv(\"PhylumLevelRelAbu.csv\", header=T) #Added in other category to reach 100%\nTrtdata$Phylum = factor(Trtdata$Phylum, levels = c(\"Actinobacteria\",\"Bacteroidetes\",\"Firmicutes\",\"Planctomycetes\",\"Proteobacteria\",\"Tenericutes\",\"Verrucomicrobia\",\"Other\")) #fixes x-axis labels\n\nPhylumAbu=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = Phylum),colour=\"black\", stat=\"identity\")+\n xlab(\"FFG\")+ylab(\"Relative Abundance (%)\")+theme(axis.title.x=element_blank())+ theme(axis.text.x = element_text(angle = 45, hjust = 1))+ \n scale_fill_manual(values=cbPalette)+facet_wrap(~Sampling_station,scale=\"free_x\")+ theme(legend.key.size = unit(0.4, \"cm\"))+\n theme(legend.text = element_text(size = 8))+ theme(legend.background=element_blank())\nPhylumAbu\ndev.off()\ntiff(\"Figures/PhylumLevelRelAbu.tiff\", width = 3.5, height = 3.2, units = 'in', res = 300)\nPhylumAbu\ndev.off()\n\n\n#######\n#Figure 3C Phylum level facet plot\n#######\n#Phylum level comparisons between sites \n\ntheme_set(theme_bw(base_size = 14)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nPhylumAll=tax_glom(GPr, \"Phylum\")\nPhylumLevel = filter_taxa(PhylumAll, function(x) mean(x) > 1e-2, TRUE) #filter out any taxa lower tha 0.1%\n\ndf <- psmelt(PhylumLevel)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Phylum\", \"FFG\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\n\ndfStatsPlot<-subset(Trtdata,Phylum!=\"Actinobacteria\"&Phylum!= \"Planctomycetes\"&Phylum!=\"Tenericutes\")\nvec<-c(\"a\",\"a\",\"b\",\"a\",\"a\",\"b\",\"b\",\"c\",\"ab\",\"a\",\"a\",\"b\",\"ab\",\"a\",\"bc\",\"c\") #From plot above\ndfStatsPlot # Only show significant taxa \ncdataplot=ggplot(dfStatsPlot, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_grid(~Family)+xlab(\"FFG\")+ylab(\"Relative Abundance (SEM)\") + theme(axis.text.x = element_text(angle = 0, hjust = 0.5))+\n theme(axis.title.x=element_blank())+facet_wrap(~Phylum)+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=FFG, y=mean+se+10,label=vec),size=3)+\n scale_fill_manual(values=cbPalette)+theme(legend.justification=c(0.05,0.95), legend.position=c(0.75,0.45))+ theme(legend.title = element_blank()) + theme(axis.text.x = element_text(angle = 45, hjust = 1))+\n guides(fill=F)#+ theme(legend.text=element_text(size=rel(0.5)))#+ annotate(\"text\", label = \"KW, adj-P = 0.0014\", x = 2, y = 15, size = 8)\n\nlabel = c(\" KW, adj-P = 0.0014\", \" adj-P = 0.0014\", \"adj-P = 0.021\",\" adj-P = 0.0043\")\n\n\ncdataplot<-cdataplot + annotate(\"text\",x=1.5, y=75,label=label,size=2.5)\n\n\nPhylumFacet<-cdataplot\n\ntheme_set(theme_bw(base_size = 12)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\n\ntiff(\"Figures/PhylumFacet.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nPhylumFacet\ndev.off()\ndev.off()\n\n#######\n#Figure 3D Family level facet plot\n######\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nFamilyAll=tax_glom(GPr, \"Family\")\nFamilyLevel = filter_taxa(FamilyAll, function(x) mean(x) > 3e-2, TRUE) #filter out any taxa lower tha 0.1%\n\ndf <- psmelt(FamilyLevel)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Family\", \"FFG\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\n\ndfStatsPlot<-subset(Trtdata,Family!=\"Enterobacteriaceae\"&Family!= \"Rhodobacteraceae\"&Family!=\"Aeromonadaceae\")\n#dfStatsPlot\n\nvec<-c(\"a\",\"a\",\"b\",\"c\",\"a\",\"b\",\"c\",\"a\",\"a\",\"b\",\"b\",\"a\",\"a\",\"b\",\"b\",\"a\")\n#dfStatsPlot # Only show significant taxa \ncdataplot=ggplot(dfStatsPlot, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_grid(~Family)+xlab(\"FFG\")+ylab(\"Relative Abundance (SEM)\") + theme(axis.text.x = element_text(angle = 0, hjust = 0.5))+\n theme(axis.title.x=element_blank())+facet_wrap(~Family)+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=FFG, y=mean+se+2,label=vec),size=3)+\n scale_fill_manual(values=cbPalette)+theme(legend.justification=c(0.05,0.95), legend.position=c(0.64,0.4))+ theme(legend.title = element_blank()) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1))+ theme(legend.key.size = unit(0.35, \"cm\"))+\n theme(legend.text = element_text(size = 8))+ theme(legend.background=element_blank())#+ annotate(\"text\", label = \"KW, adj-P = 0.0014\", x = 2, y = 15, size = 8)\n\nlabel = c(\" KW\\n adj-P < 0.001\", \"adj-P < 0.001\", \"adj-P < 0.001\",\" adj-P\\n < 0.001\")\n\n\ncdataplot<-cdataplot + annotate(\"text\",x=3.5, y=18,label=label,size=2.5)\n\ntheme_set(theme_bw(base_size = 12)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\nFamilyFacet<-cdataplot\ndev.off()\ntiff(\"Figures/FamilyFacet.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nFamilyFacet\ndev.off()\n\n\n\n\n\n######\n#Join together Figure 3\n######\n\nMassPlot\nPhylumAbu\nPhylumFacet\nFamilyFacet\n\n\ndev.off()\ntiff(\"Figures/Figure3.tiff\", width = 6.85, height = 6.85, units = 'in', res = 300)\nggarrange(MassPlot, PhylumAbu, PhylumFacet,FamilyFacet,\n labels = c(\"a\", \"b\", \"c\",\"d\"),\n ncol = 2, nrow = 2)\ndev.off()\n\n\n\n\n\n#####\n#Figure 4\n#####\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nGenusAll=tax_glom(GPr,\"Genus\")\nGenusAllStats<-GenusAll\n\nForestData=GenusAllStats#Change this one so you dont have to rewrite all variables\npredictors=t(otu_table(ForestData))\nresponse <- as.factor(sample_data(ForestData)$FFG)\nrf.data <- data.frame(response, predictors)\nMozzieForest <- randomForest(response~., data = rf.data, ntree = 1000)\nprint(MozzieForest)#returns overall Random Forest results\nimp <- importance(MozzieForest)#all the steps that are imp or imp. are building a dataframe that contains info about the taxa used by the Random Forest testto classify treatment \nimp <- data.frame(predictors = rownames(imp), imp)\nimp.sort <- arrange(imp, desc(MeanDecreaseGini))\nimp.sort$predictors <- factor(imp.sort$predictors, levels = imp.sort$predictors)\nimp.20 <- imp.sort[1:19, ]#22\n\nggplot(imp.20, aes(x = predictors, y = MeanDecreaseGini)) +\n geom_bar(stat = \"identity\", fill = \"indianred\") +\n coord_flip() +\n ggtitle(\"Most important genera for classifying samples\\n by FFG\")#\\n in a string tells it to start a new line\n#imp.20$MeanDecreaseGini\notunames <- imp.20$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n\nGenusRandomForestSubset = subset_taxa(GenusAll, row.names(tax_table(GenusAll))%in% otunames)\nGenusRandomForestSubset\n\ndf <- psmelt(GenusRandomForestSubset)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Genus\", \"FFG\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_grid(~Genus)+xlab(\"Feeding Group\")+ylab(\"Relative Abundance\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+facet_wrap(~Genus,scales = \"free_y\")+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+scale_fill_manual(values=cbPalette)\ncdataplot\n\ncompare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\",method=\"kruskal.test\")\n\nMeans<-compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nMeans\nMeans=compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nSigList<-length(unique(Trtdata$Genus))\nfor (i in levels(Means$Genus)){\n Tax<-i\n TaxAbundance<-subset(Means,Genus==i )\n Hyphenated<-as.character(paste0(TaxAbundance$group1,\"-\",TaxAbundance$group2))\n difference<-TaxAbundance$p.adj\n names(difference)<-Hyphenated\n Letters<-multcompLetters(difference)\n #print(Letters)\n SigList[i]<-Letters\n \n}\nvec<-unlist(SigList)\nvec<-vec[-1]\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_wrap(~Genus)+xlab(\"FFG\")+\n ylab(\"Relative Abundance (%)\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+\n geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=FFG, y=mean+se+2,label=vec))+ scale_fill_manual(values=cbPalette)+\n theme_set(theme_bw(base_size = 9)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))+\n theme(legend.justification=c(0.05,0.95), legend.position=c(0.64,0.2))+ theme(legend.title = element_blank()) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1))+ theme(legend.key.size = unit(0.35, \"cm\"))+\n theme(legend.text = element_text(size = 10))+ theme(legend.background=element_blank())+ theme(axis.title.x=element_blank())\n#scale_x_discrete(labels=c(\"0 hrs\", \"24 hrs\", \"48 hrs\",\"72 hrs\"))+ theme(axis.text.x = element_text(angle = 45, hjust = 1))#+ scale_fill_manual(values=cbPalette)\ncdataplot\n\ndev.off()\ntiff(\"Figures/Figure4.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\ncdataplot\ndev.off()\n\n\n\n#######\n#Figure 5A Faith's Div by FFG \n#######\nFaithByFFG<-ggplot(metadata,aes(x=Sampling_station,y=faith_pd,fill=FFG))+\n geom_boxplot()+ scale_fill_manual(values=cbPalette)+xlab(\"\")+ylab(\"Faith's Phylogenetic Diversity\")+labs(fill=\"FFG\")+\n guides(fill=FALSE)+facet_wrap(~FFG)+theme(axis.title.x=element_blank())#+geom_text(aes(x=FFG, y=shannon+se+1,label=Letters$Letters2), position=position_dodge(width=0.9), size=8,color=\"black\")#+ \nFaithByFFG\ntheme_set(theme_bw(base_size = 11)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\ndev.off()\ntiff(\"Figures/FaithByFFG.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nFaithByFFG\ndev.off()\n\n#Figure 5B Shannon Div by FFG \n#######\nShannonByFFG<-ggplot(metadata,aes(x=Sampling_station,y=shannon,fill=FFG))+\n geom_boxplot()+ scale_fill_manual(values=cbPalette)+xlab(\"\")+ylab(\"Shannon Diversity\")+labs(fill=\"FFG\")+\n guides(fill=FALSE)+facet_wrap(~FFG)+theme(axis.title.x=element_blank())#+geom_text(aes(x=FFG, y=shannon+se+1,label=Letters$Letters2), position=position_dodge(width=0.9), size=8,color=\"black\")#+ \nShannonByFFG\ntheme_set(theme_bw(base_size = 11)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\ndev.off()\ntiff(\"Figures/ShannonByFFG.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nShannonByFFG\ndev.off()\n\n#####\n#Figure 5C PCOA taxonomy jaccard\n#####\n\nord=ordinate(physeq,\"PCoA\", \"jaccard\")\nordplot=plot_ordination(physeq, ord,\"samples\", color=\"FFG\",shape =\"FFG\")+scale_colour_manual(values=cbPalette)+scale_fill_manual(values=cbPalette)\nordplotTax<-ordplot+ stat_ellipse(type= \"norm\",geom = \"polygon\", alpha = 0, aes(fill = FFG))+theme(legend.justification=c(0.05,0.95), legend.position=c(0.71,0.36))+ theme(legend.title = element_blank()) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1))+#+ theme(legend.key.size = unit(0.35, \"cm\"))\n theme(legend.text = element_text(size = 8))+ theme(legend.background=element_blank())+geom_point(size=2.5)\nordplotTax\ndev.off()\ntiff(\"Figures/PCoATax.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nordplotTax\ndev.off()\n\n#####\n#Figure 5D PCOA PICRUSt jaccard\n#####\nPiCRUST<-import_biom(\"C:\\\\Users\\\\Joe Receveur\\\\Downloads\\\\ItalyInvertPiCRUST2.20.19.biom\")\nPiCRUST<-merge_phyloseq(PiCRUST,sampdat)\nPiCRUST=rarefy_even_depth(PiCRUST, 750000, replace = TRUE, trimOTUs = TRUE, verbose = TRUE,rngseed = TRUE)\n\n\nGPdist=phyloseq::distance(PiCRUST, \"jaccard\")\nadonis(GPdist ~ FFG*Sampling_station, as(sample_data(PiCRUST), \"data.frame\"))\n\n\nord=ordinate(PiCRUST,\"PCoA\", \"jaccard\")\nordplot=plot_ordination(physeq, ord,\"samples\", color=\"FFG\",shape=\"FFG\")+geom_point(size=2.5)+scale_colour_manual(values=cbPalette)+scale_fill_manual(values=cbPalette)\nordplotFunction<-ordplot+ stat_ellipse(type= \"norm\",geom = \"polygon\", alpha = 0, aes(fill = FFG))+theme(legend.justification=c(0.05,0.95), legend.position=c(0.71,0.36))+ theme(legend.title = element_blank()) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1))+#+ theme(legend.key.size = unit(0.35, \"cm\"))\n theme(legend.text = element_text(size = 8))+ theme(legend.background=element_blank())+geom_point(size=2.5)\n\n\nordplotFunction\ndev.off()\ntiff(\"Figures/PCoAFunction.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nordplotFunction\ndev.off()\n\n#####\n#Join together figure 5\n#####\n\n\ndev.off()\ntiff(\"Figures/Figure5.tiff\", width = 6.85, height = 6.85, units = 'in', res = 300)\nggarrange(FaithByFFG, ShannonByFFG, ordplotTax,ordplotFunction,\n labels = c(\"a\", \"b\", \"c\",\"d\"),\n ncol = 2, nrow = 2)\ndev.off()\n\n\n\n\n\n\n##########\n#Figure Supplemental Random Forest indicator taxa Forest\n############\n#rm(list=ls())\nset.seed(27)\ncbPalette <- c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#000000\",\"#CC79A7\",\"#E12D00\")\ntheme_set(theme_bw(base_size = 18)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\nbiom=import_biom(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert2018WTax.biom\",parseFunction= parse_taxonomy_greengenes)\n#tax_table(biom) <- tax_table(biom)[,-c(5:10,14)]#remove dummy ranks\n\nmetadata=read.csv(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvertMetadataWDiversity3.5.2019.csv\",header = TRUE)\nhead(metadata)\n\ntree=read_tree(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert11.29.18Tree.nwk\")\n\nsampdat=sample_data(metadata)\nsample_names(sampdat)=metadata$id\nphyseq=merge_phyloseq(biom,sampdat,tree)\n\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nGenusAll=tax_glom(GPr,\"Genus\")\nGenusAllOstanaStats<-subset_samples(GenusAll, Sampling_station==\"Forest\")\nGenusAllOstanaStats<-subset_samples(GenusAllOstanaStats, FFG!=\"Predator\")\n\nForestData=GenusAll#Change this one so you dont have to rewrite all variables\n#tax_table(ForestData)[,6]\npredictors=t(otu_table(ForestData))\n\nresponse <- as.factor(sample_data(ForestData)$FFG)\nrf.data <- data.frame(response, predictors)\nMozzieForest <- randomForest(response~., data = rf.data, ntree = 1000,importance=TRUE)\nvarImpPlot(MozzieForest)\nprint(MozzieForest)#returns overall Random Forest results\nimp <- importance(MozzieForest)#all the steps that are imp or imp. are building a dataframe that contains info about the taxa used by the Random Forest testto classify treatment \nhead((imp))\n\nimp <- data.frame(predictors = row.names(imp), imp)\n#imp\nimp.sort <- arrange(imp, desc(MeanDecreaseGini))\nhead(imp.sort)#imp.sort$predictors <- factor(imp.sort$predictors, levels = imp.sort$predictors)\nimp.sort$predictors <- factor(imp.sort$predictors, levels = imp.sort$predictors)\nimp.20 <- imp.sort[1:20,]\nimp.20\n\nggplot(imp.20, aes(x = predictors, y = MeanDecreaseGini)) +\n geom_bar(stat = \"identity\", fill = \"indianred\") +\n coord_flip() +\n ggtitle(\"Most important genera for classifying samples\\n by FFG\")#\\n in a string tells it to start a new line\n#imp.20$MeanDecreaseGini\notunames <- imp.20$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n\n\nGenusRandomForestSubset = subset_taxa(GenusAllOstanaStats, row.names(tax_table(GenusAllOstanaStats))%in% otunames)\nGenusRandomForestSubset\n\ndf <- psmelt(GenusRandomForestSubset)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Genus\", \"FFG\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_grid(~Genus)+xlab(\"Feeding Group\")+ylab(\"Relative Abundance\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+facet_wrap(~Genus,scales = \"free_y\")+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+scale_fill_manual(values=cbPalette)\ncdataplot\n\ncompare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\",method=\"kruskal.test\")\n\nMeans<-compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nMeans\nMeans=compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nSigList<-length(unique(Trtdata$Genus))\nfor (i in levels(Means$Genus)){\n Tax<-i\n TaxAbundance<-subset(Means,Genus==i )\n Hyphenated<-as.character(paste0(TaxAbundance$group1,\"-\",TaxAbundance$group2))\n difference<-TaxAbundance$p.adj\n names(difference)<-Hyphenated\n Letters<-multcompLetters(difference)\n #print(Letters)\n SigList[i]<-Letters\n \n}\nvec<-unlist(SigList)\nvec<-vec[-1]\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_wrap(~Genus)+xlab(\"FFG\")+ylab(\"Relative Abundance (%) Forest\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+\n theme(axis.title.x=element_blank())+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=FFG, y=mean+se+1,label=vec))+\n scale_fill_manual(values=cbPalette)+guides(fill=F)\ncdataplot\n#scale_x_discrete(labels=c(\"0 hrs\", \"24 hrs\", \"48 hrs\",\"72 hrs\"))+ theme(axis.text.x = element_text(angle = 45, hjust = 1))#+ scale_fill_manual(values=cbPalette)\ntiff(\"Figures/RandomForestIndicatorsForest.tiff\", width = 6.85, height = 6.85, units = 'in', res = 300)\ncdataplot\ndev.off()\n\n##########\n#Figure Supplemental Random Forest indicator taxa Alpine\n############\nrm(list=ls())\nset.seed(27)\ncbPalette <- c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#000000\",\"#CC79A7\",\"#E12D00\")\ntheme_set(theme_bw(base_size = 18)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\nbiom=import_biom(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert2018WTax.biom\",parseFunction= parse_taxonomy_greengenes)\n#tax_table(biom) <- tax_table(biom)[,-c(5:10,14)]#remove dummy ranks\n\nmetadata=read.csv(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvertMetadataWDiversity3.5.2019.csv\",header = TRUE)\nhead(metadata)\n\ntree=read_tree(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert11.29.18Tree.nwk\")\n\nsampdat=sample_data(metadata)\nsample_names(sampdat)=metadata$id\nphyseq=merge_phyloseq(biom,sampdat,tree)\n#physeq=rarefy_even_depth(physeq, 3000, replace = TRUE, trimOTUs = TRUE, verbose = TRUE)\n\n\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nGenusAll=tax_glom(GPr,\"Genus\")\n\nGenusAllOstanaStats<-subset_samples(GenusAll, Sampling_station!=\"Forest\")\n\n\nForestData=GenusAllOstanaStats#Change this one so you dont have to rewrite all variables\npredictors=t(otu_table(ForestData))\nresponse <- as.factor(sample_data(ForestData)$FFG)\nrf.data <- data.frame(response, predictors)\nMozzieForest <- randomForest(response~., data = rf.data, ntree = 1000)\nprint(MozzieForest)#returns overall Random Forest results\nimp <- importance(MozzieForest)#all the steps that are imp or imp. are building a dataframe that contains info about the taxa used by the Random Forest testto classify treatment \nimp <- data.frame(predictors = rownames(imp), imp)\nimp.sort <- arrange(imp, desc(MeanDecreaseGini))\nimp.sort$predictors <- factor(imp.sort$predictors, levels = imp.sort$predictors)\nimp.20 <- imp.sort[1:22, ]#22\nggplot(imp.20, aes(x = predictors, y = MeanDecreaseGini)) +\n geom_bar(stat = \"identity\", fill = \"indianred\") +\n coord_flip() +\n ggtitle(\"Most important genera for classifying samples\\n by FFG\")#\\n in a string tells it to start a new line\n#imp.20$MeanDecreaseGini\notunames <- imp.20$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n\n\nGenusRandomForestSubset = subset_taxa(GenusAllOstanaStats, row.names(tax_table(GenusAllOstanaStats))%in% otunames)\nGenusRandomForestSubset\n\ndf <- psmelt(GenusRandomForestSubset)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Genus\", \"FFG\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_grid(~Genus)+xlab(\"Feeding Group\")+ylab(\"Relative Abundance\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+facet_wrap(~Genus,scales = \"free_y\")+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+scale_fill_manual(values=cbPalette)\ncdataplot\n\ncompare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\",method=\"kruskal.test\")\n\nMeans<-compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nMeans\nMeans=compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nSigList<-length(unique(Trtdata$Genus))\nfor (i in levels(Means$Genus)){\n Tax<-i\n TaxAbundance<-subset(Means,Genus==i )\n Hyphenated<-as.character(paste0(TaxAbundance$group1,\"-\",TaxAbundance$group2))\n difference<-TaxAbundance$p.adj\n names(difference)<-Hyphenated\n Letters<-multcompLetters(difference)\n #print(Letters)\n SigList[i]<-Letters\n \n}\nvec<-unlist(SigList)\nvec<-vec[-1]\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_wrap(~Genus)+xlab(\"FFG\")+\n ylab(\"Relative Abundance (%) Alpine Prairie\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+\n geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=FFG, y=mean+se+1,label=vec))+ scale_fill_manual(values=cbPalette)+\n guides(fill=F)\n#scale_x_discrete(labels=c(\"0 hrs\", \"24 hrs\", \"48 hrs\",\"72 hrs\"))+ theme(axis.text.x = element_text(angle = 45, hjust = 1))#+ scale_fill_manual(values=cbPalette)\ncdataplot\ntiff(\"Figures/RandomForestIndicatorsAlpine.tiff\", width = 6.85, height = 6.85, units = 'in', res = 300)\ncdataplot\ndev.off()\n\n\n#####################\n#Supplemental Fig Random Forest FFG Mean Decrease Accuracy\n####################\nset.seed(27)\ncbPalette <- c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#000000\",\"#CC79A7\",\"#E12D00\")\ntheme_set(theme_bw(base_size = 18)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\nbiom=import_biom(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert2018WTax.biom\",parseFunction= parse_taxonomy_greengenes)\n#tax_table(biom) <- tax_table(biom)[,-c(5:10,14)]#remove dummy ranks\n\nmetadata=read.csv(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvertMetadataWDiversity3.5.2019.csv\",header = TRUE)\nhead(metadata)\n\ntree=read_tree(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert11.29.18Tree.nwk\")\n\nsampdat=sample_data(metadata)\nsample_names(sampdat)=metadata$id\nphyseq=merge_phyloseq(biom,sampdat,tree)\n\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nGenusAll=tax_glom(GPr,\"Genus\")\nGenusAllOstanaStats<-subset_samples(GenusAll, Sampling_station==\"Forest\")\nGenusAllOstanaStats<-subset_samples(GenusAllOstanaStats, FFG!=\"Predator\")\n\nForestData=GenusAll#Change this one so you dont have to rewrite all variables\n#tax_table(ForestData)[,6]\npredictors=t(otu_table(ForestData))\n#head(predictors)[,1:6]\n\n#tax_table(ForestData)[,5:6]\n#head(taxa_names(ForestData))\n#colnames(predictors)<-tax_table(ForestData)[,6]\n#head(predictors)\nresponse <- as.factor(sample_data(ForestData)$FFG)\nrf.data <- data.frame(response, predictors)\nMozzieForest <- randomForest(response~., data = rf.data, ntree = 1000,importance=TRUE)\nvarImpPlot(MozzieForest)\nprint(MozzieForest)#returns overall Random Forest results\nimp <- importance(MozzieForest)#all the steps that are imp or imp. are building a dataframe that contains info about the taxa used by the Random Forest testto classify treatment \nhead((imp))\n#(tax_table(ForestData)[,7])<-\n\npredictors<-paste0(tax_table(ForestData)[,6],\":\")\n\nimp <- data.frame(predictors =tax_table(ForestData)[,6], imp)\nimp <- data.frame(predictors =tax_table(ForestData)[,5], imp)\nimp <- data.frame(predictors =row.names(tax_table(ForestData)), imp)\n\nhead(imp)\nimp.sort <- arrange(imp, desc(MeanDecreaseAccuracy))\n#imp.sort$predictors <- factor(imp.sort$predictors, levels = imp.sort$predictors)\nhead(imp.sort)\n\nimp.20 <- imp.sort[1:20,]\nimp.20$FamilyGenus<-paste0(imp.20$Family,\": \",imp.20$Genus)\nimp.20\nRandomForestFFGMeanAccuracy<-ggplot(imp.20, aes(x = reorder(FamilyGenus,-MeanDecreaseAccuracy), y = MeanDecreaseAccuracy)) +\n geom_bar(stat = \"identity\", fill = \"indianred\") +\n coord_flip() +xlab(\"Family: Genus\")+ylab(\"Mean Decrease Accuracy\")\n#imp.20$MeanDecreaseGini\n\ndev.off()\ntiff(\"Figures/FigureSupplmentalRandomForestFFGMeanAccuracyPlot.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nRandomForestFFGMeanAccuracy\ndev.off()\n\notunames <- imp.20$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n#Top 10 genera for plotting\nimp.10<-imp.20[1:10,]\nimp.10 #\notunames <- imp.10$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n\nGenusRandomForestSubset = subset_taxa(GenusAll, row.names(tax_table(GenusAll))%in% otunames)\nGenusRandomForestSubset\n\ndf <- psmelt(GenusRandomForestSubset)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Genus\", \"FFG\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_grid(~Genus)+xlab(\"Feeding Group\")+ylab(\"Relative Abundance\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+facet_wrap(~Genus,scales = \"free_y\")+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+scale_fill_manual(values=cbPalette)\ncdataplot\n\ncompare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\",method=\"kruskal.test\")\n\nMeans<-compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nMeans\nMeans=compare_means(Abundance ~ FFG, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nSigList<-length(unique(Trtdata$Genus))\nfor (i in levels(Means$Genus)){\n Tax<-i\n TaxAbundance<-subset(Means,Genus==i )\n Hyphenated<-as.character(paste0(TaxAbundance$group1,\"-\",TaxAbundance$group2))\n difference<-TaxAbundance$p.adj\n names(difference)<-Hyphenated\n Letters<-multcompLetters(difference)\n #print(Letters)\n SigList[i]<-Letters\n \n}\nvec<-unlist(SigList)\nvec<-vec[-1]\ncdataplot=ggplot(Trtdata, aes(x=FFG,y=mean))+geom_bar(aes(fill = FFG),colour=\"black\", stat=\"identity\")+ facet_wrap(~Genus)+xlab(\"FFG\")+\n ylab(\"Relative Abundance (%)\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+\n geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=FFG, y=mean+se+2,label=vec))+ scale_fill_manual(values=cbPalette)+\n theme_set(theme_bw(base_size = 9)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))+\n theme(legend.justification=c(0.05,0.95), legend.position=c(0.64,0.2))+ theme(legend.title = element_blank()) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1))+ theme(legend.key.size = unit(0.35, \"cm\"))+\n theme(legend.text = element_text(size = 10))+ theme(legend.background=element_blank())+ theme(axis.title.x=element_blank())\n#scale_x_discrete(labels=c(\"0 hrs\", \"24 hrs\", \"48 hrs\",\"72 hrs\"))+ theme(axis.text.x = element_text(angle = 45, hjust = 1))#+ scale_fill_manual(values=cbPalette)\ncdataplot\n\ndev.off()\ntiff(\"Figures/FigureSupplmentalRandomForestFFGMeanAccuracy.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\ncdataplot\ndev.off()\n\n###############\n#Supplemental Fig Random Forest Location Mean Decrease Accuracy\n##############\nset.seed(27)\ncbPalette <- c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#000000\",\"#CC79A7\",\"#E12D00\")\ntheme_set(theme_bw(base_size = 18)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\nbiom=import_biom(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert2018WTax.biom\",parseFunction= parse_taxonomy_greengenes)\n\nmetadata=read.csv(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvertMetadataWDiversity3.5.2019.csv\",header = TRUE)\nhead(metadata)\n\ntree=read_tree(\"C:\\\\Users\\\\Joe Receveur\\\\Documents\\\\MSU data\\\\ItalyInverts\\\\ItalyInvert11.29.18Tree.nwk\")\n\nsampdat=sample_data(metadata)\nsample_names(sampdat)=metadata$id\nphyseq=merge_phyloseq(biom,sampdat,tree)\n\n\nGPr = transform_sample_counts(physeq, function(x) x / sum(x) ) #transform samples based on relative abundance\nGPr = filter_taxa(GPr, function(x) mean(x) > 1e-5, TRUE)\nGenusAll=tax_glom(GPr,\"Genus\")\n\nForestData=GenusAll#Change this one so you dont have to rewrite all variables\npredictors=t(otu_table(ForestData))\n\nresponse <- as.factor(sample_data(ForestData)$Sampling_Station)\nrf.data <- data.frame(response, predictors)\nMozzieForest <- randomForest(response~., data = rf.data, ntree = 1000,importance=TRUE)\nvarImpPlot(MozzieForest)\nprint(MozzieForest)#returns overall Random Forest results\nimp <- importance(MozzieForest)#all the steps that are imp or imp. are building a dataframe that contains info about the taxa used by the Random Forest testto classify treatment \nhead((imp))\n#(tax_table(ForestData)[,7])<-\n\n#predictors<-paste0(tax_table(ForestData)[,6],\":\")\n\nimp <- data.frame(predictors =tax_table(ForestData)[,6], imp)\nimp <- data.frame(predictors =tax_table(ForestData)[,5], imp)\nimp <- data.frame(predictors =row.names(tax_table(ForestData)), imp)\n\nhead(imp)\nimp.sort <- arrange(imp, desc(MeanDecreaseAccuracy))\n#imp.sort$predictors <- factor(imp.sort$predictors, levels = imp.sort$predictors)\nhead(imp.sort)\n\nimp.20 <- imp.sort[1:20,]\nimp.20$FamilyGenus<-paste0(imp.20$Family,\": \",imp.20$Genus)\nimp.20\nRandomForestStationMeanAccuracy<-ggplot(imp.20, aes(x = reorder(FamilyGenus,-MeanDecreaseAccuracy), y = MeanDecreaseAccuracy)) +\n geom_bar(stat = \"identity\", fill = \"indianred\") +\n coord_flip() +xlab(\"Family: Genus\")+ylab(\"Mean Decrease Accuracy\")\n#imp.20$MeanDecreaseGini\ntheme_set(theme_bw(base_size = 8)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))\n\ndev.off()\ntiff(\"Figures/FigureSupplmentalRandomForestLocationMeanAccuracyPlot.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\nRandomForestStationMeanAccuracy\ndev.off()\n\notunames <- imp.20$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n#Top 10 genera for plotting\nimp.10<-imp.20[1:10,]\nimp.10 #\notunames <- imp.10$predictors\nr <- rownames(tax_table(ForestData)) %in% otunames\notunames\nPredictorTable<-kable(tax_table(ForestData)[r, ])#returns a list of the most important predictors for Random Forest Classification\nPredictorTable\n\nGenusRandomForestSubset = subset_taxa(GenusAll, row.names(tax_table(GenusAll))%in% otunames)\nGenusRandomForestSubset\n\ndf <- psmelt(GenusRandomForestSubset)\ndf$Abundance=df$Abundance*100\nTrtdata <- ddply(df, c(\"Genus\", \"Sampling_station\"), summarise,\n N = length(Abundance),\n mean = mean(Abundance),\n sd = sd(Abundance),\n se = sd / sqrt(N)\n)\ncdataplot=ggplot(Trtdata, aes(x=Sampling_station,y=mean))+geom_bar(aes(fill = Sampling_station),colour=\"black\", stat=\"identity\")+ facet_grid(~Genus)+xlab(\"Sampling Station\")+\n ylab(\"Relative Abundance\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+facet_wrap(~Genus,scales = \"free_y\")+geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+scale_fill_manual(values=cbPalette)\ncdataplot\n\ncompare_means(Abundance ~ Sampling_station, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\",method=\"kruskal.test\")\n\nMeans<-compare_means(Abundance ~ Sampling_station, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nMeans\nMeans=compare_means(Abundance ~ Sampling_station, data = df, group.by = \"Genus\", p.adjust.method = \"fdr\")\nSigList<-length(unique(Trtdata$Genus))\nfor (i in levels(Means$Genus)){\n Tax<-i\n TaxAbundance<-subset(Means,Genus==i )\n Hyphenated<-as.character(paste0(TaxAbundance$group1,\"-\",TaxAbundance$group2))\n difference<-TaxAbundance$p.adj\n names(difference)<-Hyphenated\n Letters<-multcompLetters(difference)\n #print(Letters)\n SigList[i]<-Letters\n \n}\nvec<-unlist(SigList)\nvec<-vec[-1]\ncdataplot=ggplot(Trtdata, aes(x=Sampling_station,y=mean))+geom_bar(aes(fill = Sampling_station),colour=\"black\", stat=\"identity\")+ facet_wrap(~Genus)+xlab(\"Sampling Station\")+\n ylab(\"Relative Abundance (%)\") + theme(axis.text.x = element_text(angle = 45, hjust = 1))+theme(axis.title.x=element_blank())+\n geom_errorbar(aes(ymin=mean-se,ymax=mean+se))+geom_text(aes(x=Sampling_station, y=mean+se+2,label=vec))+ scale_fill_manual(values=cbPalette)+\n theme_set(theme_bw(base_size = 9)+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()))+\n theme(legend.justification=c(0.05,0.95), legend.position=c(0.64,0.2))+ theme(legend.title = element_blank()) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1))+ theme(legend.key.size = unit(0.35, \"cm\"))+\n theme(legend.text = element_text(size = 10))+ theme(legend.background=element_blank())+ theme(axis.title.x=element_blank())\n#scale_x_discrete(labels=c(\"0 hrs\", \"24 hrs\", \"48 hrs\",\"72 hrs\"))+ theme(axis.text.x = element_text(angle = 45, hjust = 1))#+ scale_fill_manual(values=cbPalette)\ncdataplot\n\ndev.off()\ntiff(\"Figures/FigureSupplmentalRandomForestSampling_StationMeanAccuracy.tiff\", width = 3.3, height = 3.3, units = 'in', res = 300)\ncdataplot\ndev.off()", "meta": {"hexsha": "5eda8f2ca632e84c361ed48bf9a4d95a840177f9", "size": 38781, "ext": "r", "lang": "R", "max_stars_repo_path": "ManuscriptFigures.r", "max_stars_repo_name": "BenbowLab/AlpineStreamMicrobiome", "max_stars_repo_head_hexsha": "9d9d90bab0dd052d5f8544905a71b7a8ddddd420", "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": "ManuscriptFigures.r", "max_issues_repo_name": "BenbowLab/AlpineStreamMicrobiome", "max_issues_repo_head_hexsha": "9d9d90bab0dd052d5f8544905a71b7a8ddddd420", "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": "ManuscriptFigures.r", "max_forks_repo_name": "BenbowLab/AlpineStreamMicrobiome", "max_forks_repo_head_hexsha": "9d9d90bab0dd052d5f8544905a71b7a8ddddd420", "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.9490521327, "max_line_length": 385, "alphanum_fraction": 0.7183930275, "num_tokens": 12049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.03461883908817703, "lm_q1q2_score": 0.017038981871628056}} {"text": "#Jenny Smith\n\n#Differential Expression Analysis pipeline\n\n#Purpose: Given matrix of RNA-seq raw counts and clinical annoations, \n#create a series of differential expression Analyses for two group comparisions. \n#Annotate DEGs with TM information, provide Heatmaps and PCA/MDS clustering.\n#Heatmaps have option for additional color bars \n\n\n\n#For the Heatmaps \n# source(\"~/scripts/RNAseq_Analysis/DifferentialExpn_PathwayAnalysis/Heatmaps_Function.r\")\n\n#Function to create a gene ID map for ensembl gene_id, and transcript_ids \ngetIDmap <- function(GTF){\n library(dplyr)\n library(tibble)\n options(stringsAsFactors = FALSE)\n \n #standard ensembl GTF format and gencode GTF.\n tx <- GTF %>%\n filter(grepl(\"transcript\", V3)) %>%\n dplyr::select(V9) %>%\n unlist(.) %>%\n str_split(., pattern = \"; \") %>% \n lapply(., function(x) t(str_split(x, pattern = \" \", simplify = TRUE))) %>%\n sapply(., function(x) set_colnames(x, value = x[1,])[-1,]) %>%\n sapply(., function(x) data.frame(as.list(x))) %>% \n bind_rows(.)\n \n return(tx)\n}\n\n\n#custom GGPlot theme \nlibrary(pryr)\nlibrary(ggplot2)\ntheme_numX %% \n as.data.frame() %>%\n rownames_to_column(\"gene\") %>%\n mutate_if(is.numeric, function(x) 2^x) %>%\n # mutate_if(is.numeric, \n # function(x) ifelse(x >= prior.count, x-prior.count, 0)) %>% #worked for the Gtex dataset. not so well here. \n column_to_rownames(\"gene\")\n \n return(df)\n}\n\n\n#Function to collapse duplicate rows so that all information is retain and seperated by a semi-colon.\ncollapseRows <- function(col, uniq=FALSE, split=FALSE,sep=\"\"){\n #designed for dplyr so that \"col\" paramter is a vector of that column. \n #Similar to collapseDuplicates(), but for fewer columns, plus preselection of columns. Where are collapseDuplicates() you don't need to know the exact column names before hand. \n require(stringr)\n \n if (uniq){\n if(split){\n col <- str_split(col, pattern = sep) %>% unlist() %>% unique()\n }else{\n col <- unique(col)\n }\n }\n collapsed <- ifelse(all(is.na(col)), NA, paste(col, collapse = \"; \"))\n return(collapsed)\n}\n\n#Voom DE with Batch effect in the Model\nvoom_DE_BE <- function(expnData,clinData,col,percent=0.05, \n trend=FALSE, logCPM=FALSE,\n normalization=FALSE,\n GOI=NULL){\n library(edgeR)\n library(limma)\n \n ##ensure correct order\n expnData <- expnData[,match(rownames(clinData), colnames(expnData))] \n \n if (!all(complete.cases(expnData))){\n print(\"Names DO NOT match in between phenovector and colnames of expression matrix\")\n return(list(expnData=expnData,pheno=clinData))\n }\n \n #NOTE ClinData MUST BE already factor leveled! \n dge <- DGEList(counts = expnData, samples = clinData[,col])\n \n \n #remove low count genes. This is to allow for 2/3 samples must have 1 cpm. Since 3 is the minimum # of samples I will allow for DE analysis. \n AML <- ! grepl(\"BM[0-9]|R[O0][0-9]\", colnames(expnData))\n AMLsamples <- sum(AML)\n #X% of AML samples has cpm of at least 1 for a gene\n keep.dge <- rowSums(cpm(dge)[,AML] >= 1) >= max(2,(percent*AMLsamples)) \n dge <- dge[keep.dge,] #subset for those genes with cmp >= 1 per gene in AML samples\n dge <- calcNormFactors(dge) #Do TMM normalization\n \n \n #Create a design and contrasts with the groups to compare and the co-variate/batch effect variable \n #since the columns in dge$samples dataframe are already factor leveled - the ref is in the first column in the design\n design <- model.matrix(formula(paste(c(\"~0\", col), collapse=\"+\")), \n data=dge$samples) #~0 means no intercept. \n colnames(design) <- c(\"Ref\",\"Comparitor\",\"BatchEffect\") \n \n \n #contrast is the comparison-referenceGroup, or Pos-Neg, or Mut-WT \n cont.matrix <- makeContrasts(contrasts = paste(c(\"Comparitor\",\"Ref\"),collapse = \"-\"), \n levels = design)\n \n \n if (is.null(GOI)){ \n GOI <- 1:nrow(dge)\n }else{\n GOI <- intersect(rownames(dge), GOI)\n print(paste0(\"Length of GOI: \", length(GOI)))\n }\n \n \n if (logCPM){\n dge.norm <- cpm(dge, log=TRUE, prior.count = 1) #log2 + 1 CPM transformatio for normalization for sample to sample comparisons. \n NormFactors <- \"TMMCPM\"\n \n }else if (all(!logCPM & !normalization)){\n dge.norm <- voom(dge, design, plot = TRUE) #can I use voom transformed values like CPM? yes\n NormFactors <- \"Voom\" #voom transformed counts for sample to sample comparisons.\n \n }else if(all(!logCPM & normalization==\"qt\")){\n dge.norm <- voom(dge, design, plot = FALSE, normalize.method = \"quantile\")\n NormFactors <- \"Voom.quantile\" #voom and quantilte normalized counts for sample to sample comparisons.\n }\n \n print(NormFactors) #to confirm which type of DE is performed, trend or voom\n \n #fit the linear model. \n fit <- lmFit(dge.norm, design)\n fit <- contrasts.fit(fit, contrasts = cont.matrix)\n \n #compute moderated t-statistics using empirical bayes moderation. \n if(all(trend & logCPM)){ #only use limma trend method with CPM values, as per manual. \n fit2 <- eBayes(fit,trend = trend)[GOI,]\n }else{\n fit2 <- eBayes(fit)[GOI,] \n }\n \n # select differentially expressed genes.\n DE <-topTable(fit2,adjust.method=\"BH\",sort.by=\"P\",\n number=20000,p.value=0.05, lfc=1) #abs(logFC) >= 1 for all genes\n \n list <- list(dge.norm,fit2, DE)\n names(list) <- c(NormFactors,\"eBayesFit\", \"DE\")\n \n \n return(list)\n}\n\n\n#Function for Limma Voom differential expression \nvoom_DE <- function(expnData, pheno,ref,percent,\n logCPM=FALSE,trend=FALSE,\n normalization=FALSE,GOI=NULL,\n eBayesRobust=FALSE,\n lmMethod=\"ls\") {\n # expnData is a matrix or data frame with the raw counts. Patient IDs as colnames, genes as rownames\n # pheno is a character vector with patient IDs as names, and the status for each in each group(eg pos,neg)\n #ref is a chacter vector of the reference level for DE. for example ref=\"No\". \n # percent is the fraction (0-1 numberic) of AML samples to include when setting an expression threshold. eg 5% of AMLs, percent=0.05. \n #trend is for using limma trend method with log2 CPMs\n #normalization is for an extra method of normalization such as quantile if necessary. should be either FALSE or \"qt\" so far\n #GOI is a character vector of genes (or numeric vector of row indices) of interest to subset at the end. keeps BH adjuted p-values more accurate. \n\n library(limma)\n library(edgeR)\n \n expnData <- expnData[,match(names(pheno), colnames(expnData))] ##ensure correct order\n \n if (!all(complete.cases(expnData))){\n print(\"Names DO NOT match in between phenovector and colnames of expression matrix\")\n return(list(expnData=expnData,pheno=pheno))\n }\n \n groups <- unique(pheno)\n groups <- c(groups[groups != ref], ref) #order so that reference is second \n pheno.f <- factor(pheno, levels=groups)\n\n \n dge <- DGEList(counts = expnData, group = pheno.f)\n \n AML <- ! grepl(\"BM[0-9]|R[O0][0-9]\", colnames(expnData))\n AMLsamples <- sum(AML)\n \n #This is to allow for 2/3 samples must have 1 cpm. Since 3 is the minimum # of samples I will allow for DE analysis. \n keep.dge <- rowSums(cpm(dge)[,AML] >= 1) >= max(2,(percent*AMLsamples)) #X% of AML samples has cpm of at least 1 for a gene\n \n dge <- dge[keep.dge,] #subset for those genes with cmp >= 1 per gene in AML samples\n dge <- calcNormFactors(dge) #Do TMM normalization\n \n design <- model.matrix(~0 + pheno.f, data=dge$samples)#~0 means no intercept. \n colnames(design) <- levels(pheno.f)\n \n cont.matrix <- makeContrasts(contrasts = paste(groups, collapse = \"-\"), levels = design) #contrast is approx. log2(mean(Pos)) - log2(mean(Neg)) per gene. \n \n if (is.null(GOI)){ \n GOI <- 1:nrow(dge)\n }else{\n GOI <- intersect(rownames(dge), GOI)\n print(paste0(\"Length of GOI: \", length(GOI)))\n }\n \n \n if (logCPM){\n dge.norm <- cpm(dge, log=TRUE, prior.count = 1) #log2 + 1 CPM transformatio for normalization for sample to sample comparisons. \n NormFactors <- \"TMMCPM\"\n \n }else if (all(!logCPM & !normalization)){\n dge.norm <- voom(dge, design, plot = FALSE) #can I use voom transformed values like CPM? yes\n NormFactors <- \"Voom\" #voom transformed counts for sample to sample comparisons.\n \n }else if(all(!logCPM & normalization==\"qt\")){\n dge.norm <- voom(dge, design, plot = FALSE, normalize.method = \"quantile\")\n NormFactors <- \"Voom.quantile\" #voom and quantilte normalized counts for sample to sample comparisons.\n }\n\n print(NormFactors) #to confirm which type of DE is performed, trend or voom\n \n #fit the linear model. \n print(lmMethod)\n fit <- lmFit(dge.norm, design,method=lmMethod)\n fit <- contrasts.fit(fit, contrasts = cont.matrix)\n \n #compute moderated t-statistics using empirical bayes moderation. \n if(all(trend & logCPM)){ #only use limma trend method with CPM values, as per manual. \n fit2 <- eBayes(fit,trend = trend, robust=eBayesRobust)[GOI,]\n }else{\n fit2 <- eBayes(fit, robust=eBayesRobust)[GOI,] \n }\n\n # select differentially expressed genes.\n DE <-topTable(fit2,adjust.method=\"BH\",sort.by=\"P\",\n number=20000,p.value=0.05, lfc=1) #abs(logFC) >= 1 for all genes\n\n list <- list(dge.norm,fit2, DE)\n names(list) <- c(NormFactors,\"eBayesFit\", \"DE\")\n \n\n return(list)\n}\n\n\ngene_protein_anno <- function(df,gene.name.col=\"gene\", \n ids2symbols=NULL,\n mart.37=NULL,\n mart.38=NULL,\n makeQuery=TRUE,\n attempts=5){\n #Modified by J.Smith to include more on the Compartments. \n \n #df is a dataframe with genes as rows. May be expression dataset or DE genes list. \n #ids2symbols can be NULL, NA, or a file path. NULL is for BCCA id mapping + backwards compatibility. \n #while NA is for forwards compatibility if you don't need a ID map like with Kallisto counts. \n #NOTE: ids2symbols must have the gene_names column be the first column!!\n #gene.name.col is if any dataframe has an alternative column name for gene symbols (eg BCL2,TP53)\n #gene.name.col CANNOT be gene_id.\n \n library(dplyr)\n library(stringr)\n library(tidyr)\n suppressPackageStartupMessages(library(rDGIdb))\n library(biomaRt) \n options(stringsAsFactors = FALSE)\n \n #Function for mining certain keywords from the compartemnts data\n matchCompartment <- function(protein, gene, geneStableID, ref.df, keywords.regex){\n \n \n if (any(protein %in% ref.df$V1)){ #if a ENSP ID is matched, then use that information preferentially\n comp <- ref.df %>%\n filter(V1 %in% protein ) %>% \n filter(grepl(keywords.regex, V4, ignore.case = TRUE)) %>%\n #confidence score must be greater than or equal to 3 to be considered for annotation. add 3.14.19\n filter(V7 >= 3) %>%\n dplyr::select(V4)\n \n res <- rep(\"\",length(protein))\n res[protein %in% ref.df$V1] <- paste(unlist(unique(comp)),collapse=\"; \") \n \n }else{ #if not, search for the gene symbol and ENSG ID\n comp <- ref.df %>%\n filter( V2 %in% toupper(gene) | V2 %in% geneStableID ) %>% \n filter(grepl(keywords.regex, V4, ignore.case = TRUE)) %>%\n #confidence score must be greater than or equal to 3 to be considered for annotation. add 3.14.19\n filter(V7 >= 3) %>%\n dplyr::select(V4)\n \n res <- paste(unlist(unique(comp)),collapse=\"; \")\n }\n return(res)\n }\n \n #Read in the external database information \n compartment_knowledge_data <- read.delim(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo/Compartments_database\",\"human_compartment_knowledge_full_3.5.21.tsv\"),\n sep = \"\\t\",as.is = TRUE, header = FALSE)\n \n ADCs <- read.csv(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo/ADC_and_CARTcell_Targets_Database_ADCReview_rmDups_clinicaltrialsGov.csv\"), \n as.is=TRUE)\n \n if(is.null(ids2symbols)){\n # First, converts gene symbols present in data to gene stable IDs\n ids2symbols <- read.csv(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo\",\"GeneSymbol_Ensembl_ID_Conversion_GRCh37.69_FromBCCA.csv\"),\n header = TRUE)\n \n }else if (is.na(ids2symbols)){\n ids2symbols <- NA\n \n }else{\n #if want a custom gene name to ensemble gene ID file. Can contain additional annotation like ADCs or drug targets. \n ids2symbols <- read.csv(ids2symbols,header = TRUE)\n \n }\n \n \n # #rename the column containing the gene symbols/names \n # #this avoid conficlts with column names that are commonly used like gene_id, gene_name, etc\n df <- df %>%\n dplyr::select(geneSymbol=all_of(gene.name.col),everything())\n \n #if df already has ENSG ids for rownames, just rename the ENSG ID column\n if(all(is.na(ids2symbols))){\n print(paste(\"No ID mapping is performed, ids2symbols is \", ids2symbols))\n \n }else{\n #merge in the ensembl gene IDs to the input DEGs dataframe\n col <- colnames(ids2symbols)[1]\n df <- df %>%\n left_join(., ids2symbols, \n by=c(geneSymbol=col))\n }\n \n #find which column has the ensemble IDs \n ensCol <- sapply(df, function(x) any(grep(pattern=\"^ENSG\", x)))\n ensCol <- names(which(ensCol))\n \n #Create a new column called geneStableID which contains the Ensembl gene IDs \n #this allows one to not re-name any columns in the input dataframe \n df <- df %>% \n mutate( geneStableID := !! as.name(ensCol))\n \n \n #Check that the ENSG ID doesnt have NAs if using a provided gene ID map. \n if(any(is.na(df$geneStableID) | is.null(df$geneStableID))){\n print(\"NAs introduced in ID mapping. Check Reference is correct\")\n return(list(\"reference_used\"=ids2symbols))\n }\n \n \n if(is.null(mart.37) & makeQuery){\n # Uses gene stable IDs to query Ensembl for further info about the gene & associated transcripts, proteins etc.\n # mart.92 <- mart2 <- biomaRt::useMart(biomart = \"ensembl\", dataset = \"hsapiens_gene_ensembl\",host = \"http://apr2018.archive.ensembl.org\")\n mart.37 <- useEnsembl(biomart = \"ENSEMBL_MART_ENSEMBL\",\n dataset = \"hsapiens_gene_ensembl\",\n GRCh = 37) #GRCh37 does not have TSL (transcript support level ). Can't use mirror with this GRCh parameter\n #if biomartr still cannot load\n if(!exists(\"mart.37\")){\n mart.37 <- readRDS(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo/biomaRt.GRCh37.RDS\"))\n message(\"Cannot load GRCh37 from BiomaRt currently. Loaded older local version.\")\n }\n }\n \n \n if(is.null(mart.38) & makeQuery){\n #try to load the database. Having a ton of SSL errors, but oddly sometimes it works\n #the errors are new the Rstudio server and R v4.0.4\n #I need to find a way to avoid this query step. its just too buggy and unreliable...\n # https://github.com/grimbough/biomaRt/issues/31\n #ugh honestly fuck biomaRt. I'm going to need to just use the rest API apparently. Which will take time to figure out. \n #I cant even get it to reliably load the goddamn mart object.... \n httr::set_config(httr::config(ssl_verifypeer = FALSE))\n for(i in 1:attempts){\n try(mart.38 <- useEnsembl(\"ensembl\", \n mirror = \"uswest\",\n dataset = \"hsapiens_gene_ensembl\"), silent = T)\n }\n \n #if biomartr still cannot loaded load an older saved version\n if(is.null(mart.38)){\n mart.38 <- readRDS(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo/biomaRt.GRCh38.RDS\"))\n message(\"Cannot load GRCh38 from BiomaRt currently. Loaded older local version.\")\n }\n }\n \n #Query Biomart for protein information. \n attr.mart <- c(\"ensembl_gene_id\",\n \"external_gene_name\",\n \"transcript_count\",\n \"ensembl_transcript_id\", \n \"ensembl_peptide_id\",\n \"tmhmm\", \"tmhmm_start\", \"tmhmm_end\") #\"transcript_tsl\",\n \n if(makeQuery){\n #GRCh38 results\n res.anno1 <- getBM(attributes = attr.mart,\n filters = \"ensembl_gene_id\",\n values = df$geneStableID,\n mart = mart.38)\n #GRCh37 results\n res.anno2 <- getBM(attributes = attr.mart,\n filters = \"ensembl_gene_id\",\n values = df$geneStableID,\n mart = mart.37)\n }else{\n #due to getBM() time-outs and useEnsembl() memory errors, the above query in real-time has become too burdensom\n #instead use these files as the default for now on and will need to periodically update them.\n \n #This was not finished clearly.. Need to save a stable copy for use on Rhino/Gizmo due to SSL cert issues for everything...\n # res.anno1 <- readRDS(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo/\")) %>% \n # filter(ensemble_gene_id %in% df$geneStableID)\n # \n # \n # res.anno2 <- readRDS(file.path(PROJHOME,\"0000.00.02_Reference_GeneInfo/\")) %>% \n # filter(ensemble_gene_id %in% df$geneStableID)\n }\n \n #gene_id's which are in GRCh37 but NOT GRCh38 \n g.idx <- which(! res.anno2$ensembl_gene_id %in% res.anno1$ensembl_gene_id)\n \n #update results by adding GRCh37 results to the GRCh38 dataframe\n final.res <- res.anno1 %>%\n bind_rows(., res.anno2[g.idx,])\n \n #protein_id's which are in GRCh37 but NOT GRCh38 \n p.idx <- which(! res.anno2$ensembl_peptide_id %in% final.res$ensembl_peptide_id)\n \n #final update for protien ID by adding GRCh37 results to the GRCh38 dataframe (since CompartmentsDB uses ENSP IDs from GRCh37)\n final.res <- final.res %>% \n bind_rows(.,res.anno2[p.idx,]) %>% \n arrange(ensembl_gene_id)\n \n #Rename columns for clarity\n colnames(final.res) <- c(\"geneStableID\",\n \"external_gene_name\",\n \"Number_of_Transcripts\",\n \"Transcript_ID\",\n \"Ensembl_ProteinID\",\n \"Predicted_Transmembrane_Structure\",\n \"Start_TM_Region\", \"End_TM_Region\") #\"Ensembl_TSL\",\n \n # groups by gene_id, then concatenates the start and stop positions of each transmembrane protein into 1 column\n results_by_gene <- final.res %>%\n mutate_at(vars(Start_TM_Region:End_TM_Region), ~as.character(.)) %>%\n unite(TM_Protein_Regions, Start_TM_Region, End_TM_Region, sep = \"-\") %>%\n \n #combine TM regions by protien\n group_by(geneStableID,Ensembl_ProteinID) %>%\n mutate_at(vars(TM_Protein_Regions), ~collapseRows(., uniq = FALSE)) %>%\n ungroup() %>%\n \n mutate_at(vars(TM_Protein_Regions), funs(gsub(\"NA-NA\",NA, .))) %>% \n mutate_at(vars(Number_of_Transcripts:TM_Protein_Regions), ~gsub(\"^$\", NA, .)) %>% \n unique(.)\n \n # Adds expression data back onto the newly queried data and Annotate cellular compartments. \n results <- df %>% \n left_join(., results_by_gene, by = \"geneStableID\") %>%\n group_by(geneSymbol) %>%\n mutate(Cellular.Compartment_Membrane=matchCompartment(protein = Ensembl_ProteinID,\n gene = geneSymbol, \n geneStableID = geneStableID,\n ref.df=compartment_knowledge_data,\n keywords.regex = c(\"extracellular|plasma membrane|transmembrane|Cell periphery\")),\n \n Cellular.Compartment_Receptors=matchCompartment(protein = Ensembl_ProteinID,\n gene = geneSymbol,\n geneStableID = geneStableID,\n ref.df=compartment_knowledge_data,\n keywords.regex = c(\"receptor|EGFR\"))) %>%\n ungroup() %>% \n #change the original column name back \n dplyr::select(!! as.name(gene.name.col) := geneSymbol, everything()) #revert to original column name \n \n #Identify small molecule inhibitors if available\n DGI_Filter <- queryDGIdb(pull(results,gene.name.col), \n geneCategories = c(\"CLINICALLY ACTIONABLE\")) #for now, only this filter since no filters has soo many drugs that are not relevant\n DGI_Final <- detailedResults(DGI_Filter) \n \n \n #Append ADCs and Small Molecular Inhibitors to the results\n #https://stackoverflow.com/questions/28399065/dplyr-join-on-by-a-b-where-a-and-b-are-variables-containing-strings\n if(nrow(DGI_Final) < 1 ){\n print(\"No Interactions in Drug Gene Database\")\n \n #Merge in the ADC drugs\n results <- results %>% \n left_join(., ADCs, \n by=setNames(\"Gene.symbol.of.target..Final.\",gene.name.col)) %>% \n dplyr::select(gene.name.col, \n everything())\n \n }else{\n \n #Collapse multiple drugs for 1 gene-target into a single row per gene-target. \n DGI_Final <- DGI_Final %>% \n group_by(Gene) %>% \n #collapse genes with multiple drugs into a single row\n mutate_at(vars(Drug:PMIDs),\n ~collapseRows(col = ., uniq = FALSE, sep=\"; \")) %>% \n ungroup() %>%\n dplyr::select(-SearchTerm) %>%\n unique()\n \n #Merge in the ADC and Drug-Gene interactions\n results <- results %>% \n left_join(., ADCs, \n by=setNames(\"Gene.symbol.of.ADC.target..Final.\",gene.name.col)) %>% \n left_join(.,DGI_Final, \n by=setNames(\"Gene\",gene.name.col)) %>% \n dplyr::select(gene.name.col, \n everything())\n }\n \n \n \n return(results)\n}\n\n################### Pipeline DE Analysis Function #########################\n\ntwoGroups_DEGs <- function(expnData, clinData, col, ref,\n percent.cutoff=0.05,logCPM=FALSE,\n BM=FALSE,GOI=NULL,\n anno=TRUE, ids2symbols=NULL,\n gene.name.col=\"gene\",\n method=\"ward.D2\", \n Add.Anno.Col=NULL, \n Custom.Cols=NULL,\n SkipPlots=FALSE){\n # expnData is a matrix or data frame with the raw counts. Patient IDs as colnames, genes as rownames\n #clindata has patient IDs as rownames. \n #col is a character string of the factor column of interest\n #ref is the character strign of the reference group level (eg BM, Neg, or control)\n #anno is for the annotation of the DEGs with TM and cell localization patterns. \n #Add.Anno.Col is to add one or two more columns for heatmap annotation color bars \n #Anno.Cols is to use entirely custom annotation cols. \n \n library(magrittr)\n library(gtools)\n library(tibble)\n \n #remove unknown categories from the datasets since only want yes/no or 0/1 groups\n rmUnknowns <- function(clinData, cols){\n removeUnknowns <- clinData\n \n for (i in 1:length(cols)){\n idx <- ! grepl(\"Unknown\",removeUnknowns[, cols[i]], ignore.case=TRUE)\n removeUnknowns <- removeUnknowns[idx, ] \n }\n return(removeUnknowns)\n }\n \n #For file names\n variantName <- col\n \n #Remove unknowns from clindata\n print(col)\n clinData <- rmUnknowns(clinData, col)\n groups <- GroupIDs(clinData, col) #list of patient IDs, one for each group\n \n #Define Groups to compare based on group IDs from clinical data. Intersect with expression matrix to subset. \n if (BM == TRUE){\n BM <- grep(\"BM[0-9]|R[O0][0-9]\", colnames(expnData), value = TRUE)\n GroupB <- BM #select the reference group \n print(head(GroupB))\n \n GroupA <- groups[[which(names(groups) != ref)]] %>% \n intersect(. , colnames(expnData)) #the second group (mutant, AML, treated, etc)\n \n }else{\n GroupB <- groups[[ref]] %>% \n intersect(. , colnames(expnData)) #select the reference group (eg No, normal, wt, control, etc.) Must be a character(level) from the column of clinData selected. \n \n GroupA <- groups[[which(names(groups) != ref)]] %>% \n intersect(. , colnames(expnData)) #the second group (mutant, AML, treated, etc)\n }\n \n #Only analyze at least 3x3 comparisons at minimum\n if (any(lapply(list(GroupA,GroupB), length) < 3)){\n list <- list(expnData, clinData, GroupA,GroupB)\n names(list) <- c(\"InputExpnMatrix\",\"InputClinData\", \"GroupA\",\"GroupB\")\n return(list)\n }\n \n #Define the pheno vector \n phenoVector <- phenoVectors(GroupA, GroupB)\n \n #update clinical data \n if (identical(GroupB,BM)){\n \n clinData <- clinData %>% \n dplyr::select(-one_of(\"Group\")) %>% #generic colname that can cause issues here \n right_join(., data.frame(Group=phenoVector,\n USI=names(phenoVector)),\n by=\"USI\") %>%\n mutate_if(is.character, ~ifelse(is.na(.) & Group==\"GroupB\", \"NBM\", .)) %>%\n set_rownames(.$USI)\n \n }else{\n clinData = clinData\n }\n \n #subset and order the dataframe.\n expnData <- expnData[ ,match(names(phenoVector), colnames(expnData))] #mutant (groupA), then WT (groupB)\n clinData <- clinData[intersect(names(phenoVector),rownames(clinData)), ]\n \n print(dim(expnData))\n print(dim(clinData))\n \n # Check that No NAs introduced with the match)() function.\n if (any(is.na(expnData))){print(\"NAs Introduced. Check Rownames and colnames of inputs\")}\n \n # Calculate Differential Expression\n #check why I use trend = TRUE here? it looks like its for logCPM switch so that if its true, do limma trend else voom. \n DE <- voom_DE(expnData = expnData, \n pheno = phenoVector, #mutant - wild type. logCPM and voom transform the counts\n ref=\"GroupB\",\n percent=percent.cutoff,\n logCPM=logCPM, \n normalization=FALSE,\n GOI=GOI)\n \n #add column for linear scale fold-changes\n DE$DE$FoldChange <- gtools::logratio2foldchange(DE$DE$logFC) \n \n #Add Protein Annotations to the DEGs, if there are any DEGs \n if(nrow(DE$DE) == 0){print(\"No DEGs identified\")}\n if(anno & nrow(DE$DE) > 0){\n DE[[\"DE.Anno\"]] <- gene_protein_anno(df=rownames_to_column(DE$DE, \"gene\"),\n gene.name.col = gene.name.col,\n ids2symbols = ids2symbols)\n }\n \n #begin list of results to return\n res <- list(\"phenovector\"=phenoVector, \"DE\"=DE)\n \n #to avoid PCA/Heatmaps when not needed. \n if(SkipPlots){\n return(res)\n }\n \n if (nrow(DE$DE) <= 9){\n cc <- c(\"GroupB\"=\"black\", \"GroupA\"=\"firebrick\")\n eigen <- PCA(expnData, phenoVector,colorCode=cc, title=variantName)\n \n res[c(\"InputClinData\", \"InputExpnMatrix\",\"PCA\")] <- list(clinData, expnData, eigen)\n return(res)\n \n }else{\n\n\n #Unsupervised Heirachrach clustering\n cols.colorbar <- c(\"Cytogenetic.Category.1\",\"Cytogenetic.Category.2\", \"SNVs\",\"Rare.Fusions\", col) #\"Cytogenetic.Category.2\"\n\n if(!is.null(Add.Anno.Col)){\n cols.colorbar <- c(cols.colorbar, Add.Anno.Col)\n # print(c(\"Annotation Columns\", cols.colorbar))\n\n }else if (!is.null(Custom.Cols)){\n cols.colorbar <- c(Custom.Cols)\n }\n\n if(all(cols.colorbar %in% colnames(clinData))){\n cc <- colorCodes_aheatmap(df=clinData[,cols.colorbar])\n \n #90th percentile absolute logFC \n mostDE <- quantile(abs(DE$DE$logFC), probs = seq(0,1,length.out = 11))[10] \n genes.to.plot <- DE$DE[order(abs(DE$DE$logFC),decreasing=TRUE), ]\n genes.to.plot <- rownames(genes.to.plot)[abs(genes.to.plot$logFC) >= mostDE] \n genes.to.plot <- genes.to.plot[seq_len(min(30, length(genes.to.plot)))]\n \n \n #Dendrogram (for easier pulling out \"like\" groups that cluster together and clustering is done on log2 valuies that are not scaled before hand)\n dends_DE <- dge_dendrograms(expnData = expnData , #expnData can be counts or TMM normalized (but set createDGE=FALSE)\n pheno = phenoVector,\n genelist = rownames(DE$DE), #subset for only DEGs\n createDGE=TRUE,\n add.count=0.01,\n method=method)\n \n #annotation color bars\n HA <- create_HA_Labs_Hmap(expn=dends_DE$TMMCPM,\n geneList=rownames(DE$DE),\n CDE=clinData,\n cols=cols.colorbar,\n goi=genes.to.plot,\n cc=cc) #warning: `annotation_height` is set with length of one while with multiple annotations, `annotation_height` is treated as `height`.\"\n #heatmap\n heatmap <- ComplexHmap(mat=dends_DE$TMMCPM,\n hmap_anno_obj=HA$annoColumn,\n dge_dendrograms.res=dends_DE,\n hmap_anno_obj_genes=HA$geneLabels)\n\n }else{\n print(paste0(\"Default Column Names not in Clinical Data Frame - check Input CDEs or provide a vector of column names.\\n\",\n \"Default Cols: \", cols.colorbar))\n return(res)\n # heatmap <- figure out how to skip teh annotation object in complex heatmap\n }\n\n #PCA Clustering\n cc <- c(\"GroupB\"=\"grey50\", \"GroupA\"=\"firebrick\")\n eigen <- PCA(expnData, phenoVector, PC3=TRUE, colorCodes=cc, title=variantName, GOI=GOI) # PCA on top 500 varied genes in dataset.\n \n \n #Unconstrained Cluster Analysis/ PCoA\n genes <- rownames(DE$DE)\n MDS <- plotPCoA(assay(eigen$vst),phenoVector,geneList=genes, colorCode=cc, title=variantName) \n \n #return the objects\n res[c( \"dendrogram\", \"Heatmap\", \"MDS\", \"PCA\")] <- list( dends_DE, heatmap, MDS, eigen)\n\n return(res)\n }\n}\n\n\n\n\n\n####### Extraction methods to get items of interest. ############\n\n\nextract_DEGs <- function(twoGroups_DEGs.res, filter=FALSE,goi=NULL,anno=FALSE, geneLevel=FALSE){\n library(dplyr)\n\n #function to extract gene level annotation infromation. Added 3/22/19\n extract_anno_subset <- function(extract_DEGs.res){\n #for use after extracting all the DEGs with Annotations. \n \n if(is.null(dim(extract_DEGs.res))){\n return(\"No DEGs\")\n }else{\n df <- extract_DEGs.res %>%\n dplyr::select(-Number_of_Transcripts,-Transcript_ID, -TM_Protein_Regions) %>% \n \n #any gene with at least 1 TMhelix detected for any of its transcripts, has a TMhelix.\n group_by(gene) %>%\n mutate(Predicted_Transmembrane_Structure = case_when(\n any(grepl(\"TM\", Predicted_Transmembrane_Structure)) ~ \"TMhelix\",\n TRUE ~ Predicted_Transmembrane_Structure)) %>%\n arrange(Cellular.Compartment_Membrane) %>%\n filter( grepl(\"^[A-Z].+\", Cellular.Compartment_Membrane) | (!duplicated(gene, fromLast = TRUE) )) %>%\n ungroup() %>% \n \n group_by(gene) %>% \n mutate_at(vars(Ensembl_ProteinID:Cellular.Compartment_Receptors),\n ~collapseRows(., uniq = TRUE, split = TRUE, sep=\"; \")) %>% \n filter(!duplicated(gene)) %>%\n ungroup() %>% \n arrange(desc(logFC))\n \n return(df)\n }\n } \n \n #If statement to avoid errors whenDEGs is empty\n if(length(nrow(twoGroups_DEGs.res$DE$DE)) < 1 | ! grepl(\"phenovector|DE\", names(twoGroups_DEGs.res))){\n return(\"No DEGs or object is not from twoGroups_DEGs()\")\n }else{\n \n if(anno){\n DE <- twoGroups_DEGs.res$DE$DE.Anno\n \n if(geneLevel){\n DE <- extract_anno_subset(DE)\n }\n \n }else{\n DE <- twoGroups_DEGs.res$DE$DE %>%\n mutate(gene=rownames(.)) \n }\n \n DE <- DE %>% \n arrange(dplyr::desc(logFC)) %>%\n dplyr::select(gene, everything())\n \n if (filter){\n DE <- DE %>%\n filter(gene %in% goi)\n }\n \n return(DE)\n }\n}\n\n\nextract_MDS <- function(twoGroups_DEGs.res){\n twoGroups_DEGs.res$MDS$plot\n}\n\n\nextract_PCA <- function(twoGroups_DEGs.res){\n twoGroups_DEGs.res$PCA$pca_plot\n}\n\nextract_N.DE_NormFact <- function(twoGroups_DEGs.res){\n library(magrittr)\n # cytogenetics <- names(twoGroups_DEGs.res)\n \n N.DE <- nrow(twoGroups_DEGs.res$DE$DE)\n NormFactors <- range(twoGroups_DEGs.res$DE$NormFactors$norm.factors) %>% paste(., collapse=\"-\")\n N.DE_NormFactor <- cbind(N.DE, NormFactors) \n return(N.DE_NormFactor)\n}\n\n\n\n\n# for file in $(echo $(ls -1 *.Rd) $(ls -1 man/*.Rd | sed -E 's|man/||') | tr \" \" \"\\n\" | sort | uniq -d) ; do rm $file ; done\n\n\n\n", "meta": {"hexsha": "670a9e800a1424e39512ca5c399ddec6b6c95cf0", "size": 33539, "ext": "r", "lang": "R", "max_stars_repo_path": "R/DifferentialExpressionPipeline_01.07.19.r", "max_stars_repo_name": "Meshinchi-Lab/DeGSEA", "max_stars_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "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/DifferentialExpressionPipeline_01.07.19.r", "max_issues_repo_name": "Meshinchi-Lab/DeGSEA", "max_issues_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "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/DifferentialExpressionPipeline_01.07.19.r", "max_forks_repo_name": "Meshinchi-Lab/DeGSEA", "max_forks_repo_head_hexsha": "09a95f006114b78181cf6b5c5a62df5f5ac705d7", "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.022673031, "max_line_length": 179, "alphanum_fraction": 0.6253317034, "num_tokens": 9072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.03514484349535461, "lm_q1q2_score": 0.017023462254181287}} {"text": "#' @exportClass Link\n#' @name Link \n#' @rdname Link\n#' @aliases Link-class \n#' @title The Link class\n#' \n#' @description\n#' This class is part of the \\pkg{HNUORTools}. It represents the connection of two \\code{\\link{Node}s} in an\n#' \\dfn{Operations-Research (OR)}-context.\n#' \n#' @details Find here the defined slots for this class.\n#' @section Slots defined: \n#' \\describe{\n#' \\item{\\code{id}:}{\n#' Object of class \\code{\"character\"}, containing data from id.\n#' \\strong{Should be unique}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{label}:}{\n#' Object of class \\code{\"character\"}, containing the label of \n#' the \\code{\\link{Node}}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{origin}:}{\n#' Object of class \\code{\"Node\"}, containing the origin \\code{\\link{Link}}. This value is REQUIRED. \n#' }\n#' \\item{\\code{destination}:}{\n#' Object of class \\code{\"Node\"}, containing the destination \\code{\\link{Link}}. This value is REQUIRED. \n#' }\n#' \\item{\\code{costs}:}{\n#' Object of class \\code{\"numeric\"}, containing the costs for using this \\code{\\link{Link}}.\n#' The default value will be caluclated automatically (if not provided during creation).\n#' }\n#' \\item{\\code{distance}:}{\n#' Object of class \\code{\"numeric\"}, containing the distance for using this \\code{\\link{Link}}.\n#' The default value will be caluclated automatically (if not provided during creation).\n#' }\n#' \\item{\\code{oneway}:}{\n#' Object of class \\code{\"logical\"}, indicating if this \\code{\\link{Link}} can be accessed both directions.\n#' The default value will is \\code{FALSE}.\n#' }\n#' \\item{\\code{used}:}{\n#' Object of class \\code{\"logical\"}, \n#' Usually automatically assigned when solving the \\dfn{Shortest-Path-Problem (SPP)}\n#' with the \\code{SPP.Dijkstra}.\n#' The default value will is \\code{FALSE}.\n#' }\n#' } \n#' @section Methods:\n#' \\describe{\n#' \\item{\\code{$}}{\n#' getting the value of a slot\n#' }\n#' \\item{\\code{$<-}}{\n#' assinging a value to of the slots\n#' }\n#' }\n#' @section To be used for:\n#' \\describe{ \n#' \\item{SPP}{\n#' Shortest-Path-Problem\n#' }\n#' \\item{TSP}{\n#' Travelling Salesman Problem\n#' }\n#' } \n#' \n#' @seealso \\code{\\link{Node}}\n#' @note \n#' for citing use: Felix Lindemann (2014). HNUORTools: Operations Research Tools. R package version 1.1-0. \\url{http://felixlindemann.github.io/HNUORTools/}.\n#' \n#' @author Dipl. Kfm. Felix Lindemann \\email{felix.lindemann@@hs-neu-ulm.de} \n#' \n#' Wissenschaftlicher Mitarbeiter\n#' Kompetenzzentrum Logistik\n#' Buro ZWEI, 17\n#'\n#' Hochschule fur angewandte Wissenschaften \n#' Fachhochschule Neu-Ulm | Neu-Ulm University \n#' Wileystr. 1 \n#' \n#' D-89231 Neu-Ulm \n#' \n#' \n#' Phone +49(0)731-9762-1437 \n#' Web \\url{www.hs-neu-ulm.de/felix-lindemann/} \n#' \\url{http://felixlindemann.blogspot.de}\n#' @examples \n#' # demo(HNULink01) \n#'\nsetClass(\n Class = \"Link\",\n representation=representation(\n id = \"character\",\n label = \"character\",\n origin = \"Node\",\n destination = \"Node\",\n costs = \"numeric\",\n distance = \"numeric\",\n oneway = \"logical\",\n used = \"logical\"\n ),\n prototype=prototype(\n list(\n id = character(),\n label = character(),\n origin = NA,\n destination = NA,\n costs = numeric(),\n distance = numeric(),\n oneway = logical() ,\n used = logical()\n )\n ),\n validity = function(object){\n \n \n if( sum(is.null(object@origin)) + sum(length(object@origin) ==0) > 0 ) {\n return(paste(\"Error with value origin: origin is not initialized\", class(object@origin)))\n } \n if( sum(is.null(object@destination)) + sum( length(object@destination) ==0) > 0) {\n return(paste(\"Error with value destination: destination is not initialized\", class(object@destination)))\n } \n if( !is.Node(object@origin) ) {\n return(paste(\"Error with value origin: expected Node, but obtained\", class(object@origin)))\n } \n if( !is.Node(object@destination) ) {\n return(paste(\"Error with value destination: expected Node, but obtained\", class(object@destination)))\n } \n if( length(object@origin ) != 1 ){ \n return(paste(\"Error with value origin: expected value of length 1, but obtained\", length(object@origin)))\n } \n if( length(object@destination ) != 1 ){ \n return(paste(\"Error with value destination: expected value of length 1, but obtained\", length(object@destination)))\n } \n if( length(object@distance ) != 1 ){ \n return(paste(\"Error with value distance: expected value of length 1, but obtained\", length(object@distance)))\n } \n if( length(object@costs ) != 1 ){ \n return(paste(\"Error with value costs: expected value of length 1, but obtained\", length(object@costs)))\n } \n if( object@distance < 0 ){ \n return(paste(\"Error with value distance: expected non-negative value, but obtained\", object@distance))\n } \n if( object@costs < 0 ){ \n return(paste(\"Error with value costs: expected non-negative value, but obtained\", object@costs))\n } \n return(TRUE)\n } \n)\n################################### initialize - Method ###################################################\n#' @title initialize Method\n#' @name initialize\n#' @aliases initialize,Link-method \n#' @rdname initialize-methods \n#' @param n1 Origin-\\code{\\link{Node}}\n#' @param n2 Destination-\\code{\\link{Node}}\nsetMethod(\"initialize\", \"Link\", function(.Object, n1,n2,... ) {\n \n li <- list(...)\n \n if(is.null(li$showwarnings)) li$showwarnings <- FALSE\n \n \n if(is.null(n1)) stop(\"No Origin node is provided.\") \n if(is.null(n2)) stop(\"No Destination node is provided.\") \n \n if(length(n1) !=1 ) stop(\"Incorrect Number of objects for Origin-Node. Expected is one.\")\n if(length(n2) !=1 ) stop(\"Incorrect Number of objects for Destination-Node. Expected is one.\")\n \n if(!is.Node(n1)) stop(\"The value for the origin Node is not of type Node\")\n if(!is.Node(n2)) stop(\"The value for the destination Node is not of type Node\")\n \n .Object@origin <- n1\n .Object@destination <- n2\n if(is.null(li$oneway)) {\n li$oneway <- FALSE \n w <- paste(\"Attribute oneway set to default: FALSE.\")\n if(li$showwarnings) warning(w) \n }else{\n if(length(li$oneway)!=1){\n stop(\"only 1 item for attribute oneway accepted.\")\n } \n }\n if(is.null(li$used)) {\n li$used <- FALSE \n w <- paste(\"Attribute used set to default: FALSE.\")\n if(li$showwarnings) warning(w) \n }else{\n if(length(li$used)!=1){\n stop(\"only 1 item for attribute used accepted.\")\n } \n }\n if(is.null(li$distance)) {\n li$distance <- getDistance(n1,n2, ...)\n w <- paste(\"automatic distance (\",li$distance,\") calculated.\")\n if(li$showwarnings) warning(w) \n }else{\n if(length(li$distance)!=1){\n stop(\"only 1 item for attribute distance accepted.\")\n } \n }\n if(is.null(li$costs)) { \n li$costs <- li$distance \n w <- paste(\"automatic costs (\",li$costs,\") calculated.\")\n if(li$showwarnings) warning(w) \n }else{\n if(length(li$costs)!=1){\n stop(\"only 1 item for attribute costs accepted.\")\n } \n }\n \n if(is.null(li$id)) { \n tmp.id <- UUIDgenerate()\n li$id <- tmp.id\n w <- paste(\"Random ID (\",li$id,\") provided. Uniqueness should be given.\")\n if(li$showwarnings) warning(w) \n }\n if(is.null(li$label)) {\n li$label <- li$id \n }\n if(is.null(li$label)) {\n li$label <- li$id\n w <- paste(\"Random label (\",li$label,\") provided. Uniqueness may not be given.\")\n if(li$showwarnings) warning(w) \n }else{\n if(length(li$label)!=1){\n stop(\"only 1 item for attribute label accepted.\")\n } \n }\n \n .Object@used <- as.logical(li$used)\n .Object@oneway <- as.logical(li$oneway)\n .Object@distance <- as.numeric(li$distance)\n .Object@costs <- as.numeric(li$costs)\n .Object@label <- as.character(li$label) \n .Object@id <- as.character(li$id) \n \n \n if(validObject(.Object)) {\n return(.Object )\n }\n})\n\n################################### Extract - Method ###################################################\n#' @title Extract Method\n#' @name $\n#' @aliases $,Link-method \n#' @rdname Extract-methods-1 \nsetMethod(\"$\",\"Link\",function(x,name) {return(slot(x,name))})\n################################### Set - Method ###################################################\n#' @title Set Method \n#' @name $<-\n#' @aliases $<-,Link-method \n#' @rdname Set-methods-1\nsetMethod(\"$<-\",\"Link\",function(x,name,value) {\n slot(x,name,check=TRUE) <- value\n valid<-validObject(x)\n return(x)\n}) \n#' @title show Method\n#' @name show\n#' @aliases show,Link-method \n#' @description Object can be of type \\code{\\link{Link}} \n#' @param object Object can be of type \\code{\\link{Link}} \n#' @rdname show-methods \nsetMethod (\"show\", \"Link\", function(object){\n cat(\"S4 class Link: (\",object@id,\" '\",object@label,\"')\\n\")\n cat(\"\\tOrigin:\", object@origin@label)\n if(!object@oneway) cat(\"<-\")\n cat(\"-> Destination:\", object@destination@label) \n cat(\"\\tdistance:\", object@distance)\n cat(\"\\tcosts:\", object@costs) \n cat(\"\\n\")\n}\n) # end show method\n################################### as... - Method ###################################################\n\nas.Link.list = function(x, ...){return(new(\"Link\", x))}\nas.list.Link = function(x, ...){\n li<-list(\n id=x@id, label = x@label, \n origin= x@origin$id, \n destination = x@destination$id, \n costs = x@costs,\n distance = x@distance,\n oneway = x@oneway,\n used = x@used)\n return(li)\n}\nas.Link.data.frame = function(x, ...){return(new(\"Link\", x))}\nas.data.frame.Link = function(x, ...){\n li<-list(...)\n if(is.null(li$withrownames)) li$withrownames <- FALSE\n df<-data.frame(\n id=x@id, label = x@label, \n origin= x@origin$id, \n destination = x@destination$id, \n costs = x@costs,\n distance = x@distance,\n oneway = x@oneway,\n used = x@used)\n if(li$withrownames) rownames(df)<-x@id\n return (df)\n} \n#\n#\nsetGeneric(\"as.Link\", function(x, ...) standardGeneric( \"as.Link\")) \nsetGeneric(\"is.Link\", function(x, ...) standardGeneric( \"is.Link\")) \n\nsetMethod(\"as.Link\", signature(x = \"list\"), as.Link.list) \nsetMethod(\"as.Link\", signature(x = \"data.frame\"), as.Link.data.frame) \nsetMethod(\"as.list\", signature(x = \"Link\"), as.list.Link) \nsetMethod(\"as.data.frame\", signature(x = \"Link\"), as.data.frame.Link) \n# \nsetAs(\"data.frame\", \"Link\", def=function(from){ return(as.Link.data.frame(from))})\nsetAs(\"list\", \"Link\", def=function(from){return(as.Link.list(from))})\n################################### is... - Method ###################################################\nsetMethod( \"is.Link\", \"Link\", function(x, ...){return(is(x ,\"Link\"))})\n\n", "meta": {"hexsha": "0d1b0650820ccb01e59322436205d6eb4720348c", "size": 10970, "ext": "r", "lang": "R", "max_stars_repo_path": "R/02Link.r", "max_stars_repo_name": "felixlindemann/HNUORTools", "max_stars_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/02Link.r", "max_issues_repo_name": "felixlindemann/HNUORTools", "max_issues_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/02Link.r", "max_forks_repo_name": "felixlindemann/HNUORTools", "max_forks_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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.1744548287, "max_line_length": 162, "alphanum_fraction": 0.5862351869, "num_tokens": 2993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405053215160816, "lm_q2_score": 0.05419872714970429, "lm_q1q2_score": 0.017021139103304446}} {"text": "#############################################################################################\n######## calibration.sets() ############\n######## The function takes (1) an input phylogenetic tree (NEWICK), (2) a data ############\n######## frame with a list of species with information on clade (subfamily), ############\n######## family, and order (*.csv), and (3) a list of calibrations as produced ############ \n######## by PROTEUS (*.csv). Informal clades or higher taxa (above order) are ############\n######## accepted, prompting the user to input two family (or subfamily) names ############\n######## to obtain an MRCA for these calibrations. ############\n######## The code works directly with the output from PROTEUS. ############\n######## The function generates a PDF file of the tree with all calibrated ############\n######## nodes depicted with the PROTEUS fossil number, the name of the fossil, ############\n######## and the age used as minimum age. ############\n######## Currently there are two ways to generate taxa sets with the ############\n######## 'beast.treepl' option: ############\n######## -- \"beast\": produce a taxa sets block (NEXUS) with full tip labels for ############\n######## each calibrated clade. This is ready to paste into the NEXUS file ############\n######## for reading in BEAUTI. ############\n######## -- \"treepl\": produces a text file for use in treepl, with alist of two ############\n######## two tip labels (MRCA) for each calibrated clade. This file only ############\n######## needs the final running options implemented in treepl. ############\n#############################################################################################\n\n# 163,114,117,169,177,147,12,183,182,360,336,195,19,251,345,244,346,361,2,215,286,285,288,312,339,124\ninput= \"Data1_RAxMLTree.tre\" # available as Supplementary Data in Ramírez-Barahona et al. (2020)\nspecies.table = \"Tree_TIPS.csv\" # file in data folder\nPROTEUS.cal = \"PROTEUS_INCLUDED_24-4-18.csv\" # available as Supplementary Data in Ramírez-Barahona et al. (2020)\nsetwd(\"~/Documents/\")\nrename.tree.nex <- function (input,species.table,output){\n if(length(grep(\".tre\",input))==1){\n tre <- read.tree(input)\n tre <- ladderize(tre, TRUE)\n tre$tip.label[which(tre$tip.label==\"Lauraceae_Hypodaphniszenkeri\")]<-\"Lauraceae_Hypodaphnis_zenkeri\"\n tre$tip.label[which(tre$tip.label==\"Batidaceae_Batis_maritima\")]<-\"Bataceae_Batis_maritima\"\n tre$tip.label[which(tre$tip.label==\"Didieraceae_Alluaudia_spp\")]<-\"Didiereaceae_Alluaudia_spp\"\n tre$tip.label[which(tre$tip.label==\"Didieraceae_Portulacaria_afra\")]<-\"Didiereaceae_Portulacaria_afra\"\n tre$tip.label[which(tre$tip.label==\"Gerrardiniaceae_Gerrardina_foliosa\")]<-\"Gerrardinaceae_Gerrardina_foliosa\"\n tre$tip.label[which(tre$tip.label==\"Petenaceae_Petenaea_cordata\")]<-\"Petenaeaceae_Petenaea_cordata\"\n tre$tip.label[which(tre$tip.label==\"Petermaniaceae_Petermannia_cirrosa\")]<-\"Petermanniaceae_Petermannia_cirrosa\"\n tre$tip.label[which(tre$tip.label==\"Rhipogonaceae_Rhipogonum_elseyanum\")]<-\"Ripogonaceae_Ripogonum_elseyanum\"\n tre$tip.label[which(tre$tip.label==\"Rhipogonaceae_Ripogonum_scandens\")]<-\"Ripogonaceae_Ripogonum_scandens\"\n tre$tip.label[which(tre$tip.label==\"Rhipogonaceae_Rhipogonum_elseyanum\")]<-\"Ripogonaceae_Ripogonum_elseyanum\"\n tre$tip.label[which(tre$tip.label==\"Strelitiziaceae_Ravenala_madagascariensis\")]<-\"Strelitziaceae_Ravenala_madagascariensis\"\n tre$tip.label[which(tre$tip.label==\"Strelitiziaceae_Strelitizia_spp\")]<-\"Strelitziaceae_Strelitzia_spp\"\n tre$tip.label[which(tre$tip.label==\"Stylidaceae_Donatia_spp\")]<-\"Stylidiaceae_Donatia_spp\"\n tre$tip.label[which(tre$tip.label==\"Stylidaceae_Stylidium_spp\")]<-\"Stylidiaceae_Stylidium_spp\"\n list<-tre$tip.label\n list_fams<-foreach(i=1:length(list),.combine=c) %do% {strsplit(list,\"_\")[[i]][1]}\n list_fams_un<-unique(list_fams)\n newlist<-read.table(species.table,sep=\",\",header=T)\n if(length(which(is.na(match(list,newlist$SPECIES))==TRUE))!=0) {\n cat(red(\"ERROR: Names in phylogeny do not match names in list !\"),\"\\n\")}\n newlist$NEW<-paste(newlist$Order,\"_\",newlist$SPECIES,\"_\",newlist$Clade_new,sep=\"\")\n if(length(which((list==newlist$SPECIES[match(list,newlist$SPECIES)])==FALSE))!=0) {\n cat(red(\"ERROR: Names in phylogeny do not match names in list !\"),\"\\n\")}\n list_new<-newlist$NEW[match(list,newlist$SPECIES)]\n tre$tip.label<-as.character(list_new)\n tre$tip.label[grep(\"_$\",tre$tip.label)] <- gsub('.{1}$', '', tre$tip.label[grep(\"_$\",tre$tip.label)])\n write.tree(tre,file=output)}\n if(length(grep(\".nex\",input))==1){ \n nexus<-read.nexus.data(input)\n list <- names(nexus)\n if(length(which(is.na(match(list,newlist$SPECIES))==TRUE))!=0) {\n cat(red(\"ERROR: Names in nexus do not match names in list !\"),\"\\n\")}\n newlist$NEW<-paste(newlist$Order,\"_\",newlist$SPECIES,\"_\",newlist$Clade_clean,sep=\"\")\n if(length(which((list==newlist$SPECIES[match(list,newlist$SPECIES)])==FALSE))!=0) {\n cat(red(\"ERROR: Names in phylogeny do not match names in list !\"),\"\\n\")}\n list_new<-newlist$NEW[match(list,newlist$SPECIES)]\n names(nexus)<- list_new\n write.nexus.data(nexus,file=output,format=\"dna\",interleaved = F,gap=\"-\",missing=\"?\")\n }\n}\n\ncalibration.sets<-function(input.tre,species.table,PROTEUS.cal,max_age=154,beast.treepl=\"beast\",output=\"input_treePL.tre\"){\n suffix<-beast.treepl\n cat(\"Reading phylo tree and changing tip.labels to match species list\",\"\\n\")\n tre <- read.tree(input.tre)\n tre <- ladderize(tre, TRUE)\n tre$tip.label[which(tre$tip.label==\"Lauraceae_Hypodaphniszenkeri\")]<-\"Lauraceae_Hypodaphnis_zenkeri\"\n tre$tip.label[which(tre$tip.label==\"Batidaceae_Batis_maritima\")]<-\"Bataceae_Batis_maritima\"\n tre$tip.label[which(tre$tip.label==\"Didieraceae_Alluaudia_spp\")]<-\"Didiereaceae_Alluaudia_spp\"\n tre$tip.label[which(tre$tip.label==\"Didieraceae_Portulacaria_afra\")]<-\"Didiereaceae_Portulacaria_afra\"\n tre$tip.label[which(tre$tip.label==\"Gerrardiniaceae_Gerrardina_foliosa\")]<-\"Gerrardinaceae_Gerrardina_foliosa\"\n tre$tip.label[which(tre$tip.label==\"Petenaceae_Petenaea_cordata\")]<-\"Petenaeaceae_Petenaea_cordata\"\n tre$tip.label[which(tre$tip.label==\"Petermaniaceae_Petermannia_cirrosa\")]<-\"Petermanniaceae_Petermannia_cirrosa\"\n tre$tip.label[which(tre$tip.label==\"Rhipogonaceae_Rhipogonum_elseyanum\")]<-\"Ripogonaceae_Ripogonum_elseyanum\"\n tre$tip.label[which(tre$tip.label==\"Rhipogonaceae_Ripogonum_scandens\")]<-\"Ripogonaceae_Ripogonum_scandens\"\n tre$tip.label[which(tre$tip.label==\"Rhipogonaceae_Rhipogonum_elseyanum\")]<-\"Ripogonaceae_Ripogonum_elseyanum\"\n tre$tip.label[which(tre$tip.label==\"Strelitiziaceae_Ravenala_madagascariensis\")]<-\"Strelitziaceae_Ravenala_madagascariensis\"\n tre$tip.label[which(tre$tip.label==\"Strelitiziaceae_Strelitizia_spp\")]<-\"Strelitziaceae_Strelitzia_spp\"\n tre$tip.label[which(tre$tip.label==\"Stylidaceae_Donatia_spp\")]<-\"Stylidiaceae_Donatia_spp\"\n tre$tip.label[which(tre$tip.label==\"Stylidaceae_Stylidium_spp\")]<-\"Stylidiaceae_Stylidium_spp\"\n list<-tre$tip.label\n list_fams<-foreach(i=1:length(list),.combine=c) %do% {strsplit(list,\"_\")[[i]][1]}\n list_fams_un<-unique(list_fams)\n newlist<-read.table(species.table,sep=\",\",header=T)\n if(length(which(is.na(match(list,newlist$SPECIES))==TRUE))!=0) {\n cat(red(\"ERROR: Names in phylogeny do not match names in list !\"),\"\\n\")}\n newlist$NEW<-paste(newlist$Order,\"_\",newlist$SPECIES,\"_\",newlist$Clade_new,sep=\"\")\n if(length(which((list==newlist$SPECIES[match(list,newlist$SPECIES)])==FALSE))!=0) {\n cat(red(\"ERROR: Names in phylogeny do not match names in list !\"),\"\\n\")}\n list_new<-newlist$NEW[match(list,newlist$SPECIES)]\n tre$tip.label<-as.character(list_new)\n tre$tip.label[grep(\"_$\",tre$tip.label)] <- gsub('.{1}$', '', tre$tip.label[grep(\"_$\",tre$tip.label)])\n write.tree(drop.tip(tre,\"_Ophioglossaceae_Ophioglossum_spp\",trim.internal = T),file=output)\n proteus<- read.table(PROTEUS.cal,sep=\",\",header=T,quote=\"\\\"\");head(proteus);names(proteus)\n proteus$Node.calibrated <- sub(\"The\",\"\",proteus$Node.calibrated)\n proteus$Node.calibrated <- sub(\" \",\" \",proteus$Node.calibrated)\n dima<- dim(proteus)[1]\n if(readline(\"Exclude calibrations? (y/n):\") == \"y\") { \n cat(\"Which Nfos to exclude? (numbers separated by a comma)\",\"\\n\")\n exc <- readline()\n exc <- unlist(strsplit(exc,\",\"))\n proteus <- proteus[-which(proteus$NFos %in% exc),]\n }\n cat(\"Excluding:\",dima-dim(proteus)[1],\"fossils\",\"\\n\")\n cat(\"Re-formatting PROTEUS csv output\",\"\\n\")\n #proteus$Family..of.clade.calibrated. <- rep(\"\",dim(proteus)[1])\n proteus$Clade.calibrated <- rep(\"\",dim(proteus)[1])\n proteus$INFORMAL <- rep(\"\",dim(proteus)[1])\n \n major <- which(proteus$Order..of.clade.calibrated.==\"\")\n family <- strsplit(as.character(proteus$Node.calibrated),split = \" \")\n proteus$Crown.or.stem. <- unlist(lapply(family,\"[\",1))\n #fams <- unlist(family)[grep(\"ceae\",unlist(family))]\n #proteus$Family..of.clade.calibrated.[grep(\"ceae\",family)] <- fams\n ##fams <- sub(\"\\\\(\",\"\",fams); fams <- sub(\",\",\"\",fams)\n subfams <- unlist(lapply(family,\"[\",2))[grep(\"ideae\",unlist(lapply(family,\"[\",2)))]\n proteus$Clade.calibrated[match(subfams,unlist(lapply(family,\"[\",2)))] <- subfams\n duplas<-unique(subfams[duplicated(match(subfams,unlist(lapply(family,\"[\",2))))])\n for (i in 1:length(duplas)){ \n proteus$Clade.calibrated[which(unlist(lapply(family,\"[\",2))==duplas[i])]<-duplas[i]}\n which(grepl(paste(c(\"core\",\"\\\\+\",\"neae\",\"polles\",\"clade\"), collapse=\"|\"),proteus$Node.calibrated)==TRUE)\n \n iden <- c(major,which(grepl(paste(c(\"core\",\"\\\\+\",\"neae\",\"polles\",\"clade\"), collapse=\"|\"),proteus$Node.calibrated)==TRUE))\n iden<-unique(iden)\n proteus$INFORMAL[iden] <- \"informal\"\n proteus$NAME <- paste(unlist(lapply(family,\"[\",1)),unlist(lapply(family,\"[\",2)),sep=\" \")\n \n iden <- c(major,which(grepl(paste(c(\"core\",\"\\\\+\",\"neae\",\"polles\",\"clade\",\"ideae\"), collapse=\"|\"),proteus$Node.calibrated)==TRUE))\n subfams <- unlist(lapply(family,\"[\",2))[-iden]\n proteus$INFORMAL[grep(paste(subfams[-grep(paste(c(\"ales\",\"ceae\"), collapse=\"|\"),subfams)],collapse = \"|\"),proteus$Node.calibrated)]<-\"informal\"\n \n \n if (beast.treepl == \"treepl\") {\n cat(\"Generating output format for treepl\",\"\\n\")\n ff<-matrix(ncol=9,nrow=dim(proteus)[1])\n ff[,1] <- \"mrca =\"; ff[,4] <- \"min =\"; ff[,7] <- \"max =\";ff[,9]<-max_age\n colnames(ff)<-c(\"mrca =\",\"Calibration\",\"tips\",\"Calibration\",\"min =\",\"Min_Age\",\"max =\",\"Calibration\",\"Max_Age\")\n head(ff)\n pdf(file=paste(input.tre,\"_NODES.pdf\",sep=\"\"),width=20,height=180,onefile=F,\n useDingbats=FALSE)\n plot(tre,show.tip.label = T,cex=0.8,no.margin = T,edge.color=\"grey\",\n edge.width = 1,use.edge.length = F,\"phylo\",node.pos=1,node.depth=2)\n for (i in 1:dim(proteus)[1]) { \n fos.tax <- str_sub(proteus$Fossil.taxon, 2)\n names <- paste(\"Nfos.\",proteus$NFos,\":\",\"\\u2020\",fos.tax,\"(\",proteus$Safe.minimum.age,\"Mya)\")\n names <- sub(\" \",\" \",names);names <- sub(\" \",\" \",names);\n cat(i,\"Searching clade for\",as.character(proteus$Fossil.taxon[i]),\"\\n\")\n ff[i,2] <- as.character(paste(\"Nfos\",proteus$NFos[i],sep=\"_\"));\n ff[i,5] <- as.character(paste(\"Nfos\",proteus$NFos[i],sep=\"_\"));\n ff[i,8] <- as.character(paste(\"Nfos\",proteus$NFos[i],sep=\"_\"));\n ff[i,6] <- proteus$Safe.minimum.age[i];\n if(proteus$INFORMAL[i]==\"informal\") {\n cat(green(i,\"Specify family (or subfamily) names for MRCA (case sensitive):\",as.character(proteus$Fossil.taxon[i]),\"\\n\"))\n cat(green(i,\"Calibrated clade\",as.character(proteus$Node.calibrated[i]),\"\\n\"))\n names.in<- readline()\n names.in2<- readline()\n names.in<- c(names.in,names.in2)\n cat(green(i,\"Specify whether crown (c) or stem (s):\",as.character(proteus$Crown.or.stem.[i]),as.character(proteus$Fossil.taxon[i]),\"\\n\"))\n cr.st<- readline()\n tipas<- unique(grep(paste(names.in,collapse=\"|\"),tre$tip.label,value=TRUE));tipas\n #### this one was added on the latest update!!\n if(length(tipas)==1){ancestor <- Ancestors(tre,node=which(tre$tip.label==tipas),\"parent\")\n subtre<-extract.clade(tre,node=ancestor)\n nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,3]<-stri_flatten(c(child1,child2),\" \") \n next\n }\n Nnode<- getMRCA(tre,tipas)\n if(cr.st==\"c\"){\n nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \") \n next}\n if (cr.st==\"s\"){ \n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=ancestor)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next\n }\n } else { \n if (proteus$Clade.calibrated[i] != \"\"){ \n tipas<- grep(proteus$Clade.calibrated[i],tre$tip.label,fixed=T)\n if(length(tipas)== 0) next\n if (length(tipas)==1) {\n Nnode <- tre$edge[which(tre$edge[,2]==tipas),1] \n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n next}\n if(length(tipas) > 1) {Nnode<- getMRCA(tre,tipas)\n if(proteus$Crown.or.stem.[i] == \"crown\") {\n subtre<- extract.clade(tre,node=Nnode)\n nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \") \n next}\n if(proteus$Crown.or.stem.[i] == \"stem\") {\n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=ancestor)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n }} \n else { \n if (proteus$Family..of.clade.calibrated.[i] != \"\"){ \n tipas<- grep(proteus$Family..of.clade.calibrated.[i],tre$tip.label,fixed=T);tipas\n if(length(tipas)== 0) next\n if (length(tipas)==1) {\n Nnode <- tre$edge[which(tre$edge[,2]==tipas),1] \n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n if(length(tipas)>1) {Nnode<- getMRCA(tre,tipas)\n if(proteus$Crown.or.stem.[i] == \"crown\") {\n subtre<- extract.clade(tre,node=Nnode)\n nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n if(proteus$Crown.or.stem.[i] == \"stem\"){\n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=ancestor)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n }}\n else { \n if (proteus$Order..of.clade.calibrated.[i] != \"\"){ \n tipas<- grep(proteus$Order..of.clade.calibrated.[i],tre$tip.label,fixed=T)\n if(length(tipas)== 0) next\n if (length(tipas)==1) {\n Nnode <- tre$edge[which(tre$edge[,2]==tipas),1] \n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n if(length(tipas)>1) {Nnode<- getMRCA(tre,tipas)\n if(proteus$Crown.or.stem.[i] == \"crown\") {\n subtre<- extract.clade(tre,node=Nnode)\n nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=Nnode)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n if(proteus$Crown.or.stem.[i] == \"stem\"){\n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n childs<-Children(tre,node=ancestor)\n if(length(Descendants(tre,childs[1])[[1]])==1) {child1<-tre$tip.label[childs[1]]}\n if(length(Descendants(tre,childs[1])[[1]])>1) {child1<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[1])$tip.label[1]]}\n if(length(Descendants(tre,childs[2])[[1]])==1) {child2<-tre$tip.label[childs[2]]}\n if(length(Descendants(tre,childs[2])[[1]])>1) {child2<-tre$tip.label[tre$tip.label==extract.clade(tre,node=childs[2])$tip.label[1]]}\n ff[i,3]<-stri_flatten(c(child1,child2),\" \")\n next}\n } }\n }\n }}}\n for (i in 1:dim(ff)[1]){\n cat(stri_flatten(c(ff[i,1:3]),\" \"),sep=\"\",\"\\n\")\n nodelabels(node=getMRCA(tre,tip = unlist(strsplit(ff[i,3],\" \")[1])),frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"red\",adj=1.1)\n }\n sink(paste(\"Calibration_set_\",suffix,\".txt\",sep=\"\"))\n cat(\"treefile = input_treePL.tre\",sep=\"\",\"\\n\")\n cat(\"smooth = 0.001\",sep=\"\",\"\\n\")\n cat(\"numsites = 11395\",sep=\"\",\"\\n\")\n for (i in 1:dim(ff)[1]){\n nodelabels(node=getMRCA(tre,tip = unlist(strsplit(ff[i,3],\" \")[1])),frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"red\",adj=1.1)\n \n cat(stri_flatten(c(ff[i,1:3]),\" \"),sep=\"\",\"\\n\")\n cat(stri_flatten(c(ff[i,4:6]),\" \"),sep=\"\",\"\\n\")\n cat(stri_flatten(c(ff[i,7:9]),\" \"),sep=\"\",\"\\n\")\n }\n cat(\"outfile = treePL_dated.tre\",sep=\"\",\"\\n\")\n cat(\"thorough\",sep=\"\",\"\\n\")\n cat(\"opt = 4\",sep=\"\",\"\\n\")\n cat(\"moredetail\",sep=\"\",\"\\n\")\n cat(\"optad = 4\",sep=\"\",\"\\n\")\n cat(\"moredetailad\",sep=\"\",\"\\n\")\n cat(\"optcvad = 1\",sep=\"\",\"\\n\")\n sink()\n dev.off()\n write.table(ff,\"Calibrations_raw.csv\",sep=\",\",row.names=F,col.names=T)\n }\n if (beast.treepl == \"beast\") {\n cat(\"Generating output format for beast\",\"\\n\")\n ff<-matrix(ncol=4,nrow=dim(proteus)[1])\n ff[,1] <- \"taxset\"; ff[,3] <- \"=\"\n colnames(ff)<-c(\"taxset\",\"Name\",\"=\",\"taxa\")\n sub(\"Data1\",input.tre,\"Data4\") -> out_name\n pdf(file=paste(out_name,\"_NODES.pdf\",sep=\"\"),width=20,height=180,onefile=F,\n useDingbats=FALSE)\n plot(tre,show.tip.label = T,cex=0.8,no.margin = T,edge.color=\"grey\",\n edge.width = 1,use.edge.length = F,\"phylo\",node.pos=1,node.depth=2)\n for (i in 1:dim(proteus)[1]) {\n fos.tax <- str_sub(proteus$Fossil.taxon, 2)\n names <- paste(\"Nfos.\",proteus$NFos,\":\",\"\\u2020\",fos.tax,\"(\",proteus$Safe.minimum.age,\"Mya)\")\n names <- sub(\" \",\" \",names);names <- sub(\" \",\" \",names)\n cat(i,\"Searching clade for\",as.character(proteus$Fossil.taxon[i]),\"\\n\")\n ff[i,2] <- as.character(paste(\"Nfos\",proteus$NFos[i],sep=\"_\"));\n if(proteus$INFORMAL[i]==\"informal\") {\n cat(green(i,\"Specify family (or subfamily) names for MRCA (case sensitive):\",as.character(proteus$Fossil.taxon[i]),\"\\n\"))\n cat(green(i,\"Calibrated clade\",as.character(proteus$Node.calibrated[i]),\"\\n\"))\n names.in<- readline()\n names.in2<- readline()\n names.in<- c(names.in,names.in2)\n cat(green(i,\"Specify whether crown (c) or stem (s):\",as.character(proteus$Crown.or.stem.[i]),as.character(proteus$Fossil.taxon[i]),\"\\n\"))\n cr.st<- readline()\n tipas<- grep(paste(names.in,collapse=\"|\"),tre$tip.label,value=TRUE);tipas\n #### this one was added on the latest update!!\n if(length(tipas)==1){ancestor <- Ancestors(tre,node=which(tre$tip.label==tipas),\"parent\")\n subtre<-extract.clade(tre,node=ancestor)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=ancestor,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next\n }\n Nnode<- getMRCA(tre,tipas)\n if(cr.st==\"c\"){\n subtre<- extract.clade(tre,node=Nnode)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next}\n if (cr.st==\"s\"){ \n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n subtre<- extract.clade(tre,node=ancestor)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=ancestor,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next\n }\n }\n if (proteus$Clade.calibrated[i] != \"\"){ \n tipas<- grep(proteus$Clade.calibrated[i],tre$tip.label,fixed=T);tipas\n if(length(tipas) == 0) next\n if (length(tipas) == 1) {Nnode <- tre$edge[which(tre$edge[,2]==tipas),1] \n subtre<- extract.clade(tre,node=Nnode)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \")\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n \n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n next}\n if(length(tipas) > 1) {Nnode<- getMRCA(tre,tipas)\n if(proteus$Crown.or.stem.[i] == \"crown\") {\n subtre<- extract.clade(tre,node=Nnode)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n \n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next}\n if(proteus$Crown.or.stem.[i] == \"stem\") {\n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=ancestor,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")}\n \n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n subtre<- extract.clade(tre,node=ancestor)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next}}\n } else { \n if (proteus$Family..of.clade.calibrated.[i] != \"\"){ \n tipas<- grep(proteus$Family..of.clade.calibrated.[i],tre$tip.label,fixed=T);tipas\n if(length(tipas)== 0) next\n if (length(tipas)==1) {Nnode <- tre$edge[which(tre$edge[,2]==tipas),1] \n subtre<- extract.clade(tre,node=Nnode)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \")\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n next}\n if(length(tipas)>1) {Nnode<- getMRCA(tre,tipas)\n if(proteus$Crown.or.stem.[i] == \"crown\") {\n subtre<- extract.clade(tre,node=Nnode)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next}\n if(proteus$Crown.or.stem.[i] == \"stem\"){\n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n subtre<- extract.clade(tre,node=ancestor)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=ancestor,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next}}\n } else { \n if (proteus$Order..of.clade.calibrated.[i] != \"\"){ \n tipas<- grep(proteus$Order..of.clade.calibrated.[i],tre$tip.label,fixed=T);tipas\n if(length(tipas) == 0) next\n if (length(tipas) == 1) {Nnode <- tre$edge[which(tre$edge[,2]==tipas),1] \n subtre<- extract.clade(tre,node=Nnode)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \")\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n next}\n if(length(tipas)>1) {Nnode<- getMRCA(tre,tipas)\n if(proteus$Crown.or.stem.[i] == \"crown\") {\n subtre<- extract.clade(tre,node=Nnode)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=Nnode,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=Nnode,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=Nnode,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \") \n next}\n if(proteus$Crown.or.stem.[i] == \"stem\"){\n ancestor<-Ancestors(tre,node=Nnode,\"parent\")\n subtre<- extract.clade(tre,node=ancestor)\n if(proteus$Node.assignment.quality.score.and.method[i] == \"5 / phylogenetic analysis\") {nodelabels(node=ancestor,frame=\"none\",pch=21,cex=2,bg=\"white\")} else {nodelabels(node=ancestor,frame=\"none\",pch=19,cex=2,col=\"black\")}\n nodelabels(node=ancestor,frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"black\",adj=1.1)\n ff[i,4]<-stri_flatten(subtre$tip.label,\" \")\n next}}\n } \n }\n }}\n for (i in 1:dim(ff)[1]){\n cat(i,names[i],sep=\" \",\"--\")\n nodelabels(node=getMRCA(tre,tip = unlist(strsplit(ff[i,4],\" \")[1])),frame=\"none\",text=as.character(names[i]),cex=0.5,col=\"red\",adj=1.1)\n cat(\"OK\",\"\\n\")\n }\n sink(paste(\"Calibration_set_\",suffix,\".txt\",sep=\"\"))\n cat(\"begin sets;\",\"\\n\")\n for (i in 1:dim(ff)[1]){ \n cat(stri_flatten(c(ff[i,1:4]),\" \"),\"\\n\")\n }\n sink()\n dev.off()\n }}\n", "meta": {"hexsha": "c505b91268484a7e2fddec75abb7be53eefa2d77", "size": 33427, "ext": "r", "lang": "R", "max_stars_repo_path": "code/preprocessing/CalibrationSets.r", "max_stars_repo_name": "spiritu-santi/angiosperm-time-tree-2.0", "max_stars_repo_head_hexsha": "d1a8a14edadd15834ccba052991886853f4c852a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-14T03:29:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-14T03:29:42.000Z", "max_issues_repo_path": "code/preprocessing/CalibrationSets.r", "max_issues_repo_name": "spiritu-santi/angiosperm-time-tree-2.0", "max_issues_repo_head_hexsha": "d1a8a14edadd15834ccba052991886853f4c852a", "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/preprocessing/CalibrationSets.r", "max_forks_repo_name": "spiritu-santi/angiosperm-time-tree-2.0", "max_forks_repo_head_hexsha": "d1a8a14edadd15834ccba052991886853f4c852a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-06T15:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-06T15:43:48.000Z", "avg_line_length": 69.2070393375, "max_line_length": 236, "alphanum_fraction": 0.6128877853, "num_tokens": 10736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03358950843143849, "lm_q1q2_score": 0.016139042607416595}} {"text": "### Coastal Phenology Trend Analysis in Phenology Observations and Environmental\n### Predictors by Jakob Assmann 13 March 2018\n\n# Dependencies\nlibrary(dplyr)\nlibrary(MCMCglmm)\nlibrary(ggplot2)\nlibrary(parallel)\nlibrary(gridExtra)\n\n# Housekeeping\nscript_path <- \"scripts/users/jassmann/phenology/coastal_phenology/\"\nload(file =paste0(script_path, \"coastal_phen.Rda\"))\n\n# Site names\nsite_names <- unique(as.character(coastal_phen$site_name))\n\n# Site spp phen combos\nsite_spp_phen_combos <- unique(coastal_phen$site_spp_phen)\n\n# Spp phen combos\nspp_phen_combos <- sort(unique(coastal_phen$site_spp_phen))\n\n# Set colours\ncolour_theme_sites <- data.frame(site_name = c(site_names),\n name_pretty = c(\"Alexandra Fiord\", \n \"Utqiaġvik\",\n \"Qikiqtaruk\",\n \"Zackenberg\"),\n colour = c(\"#324D5CFF\", \n \"#46B29DFF\", \n \"#C2A33EFF\",\n \"#E37B40FF\")) # 5th colour #F53855FF\n\ncolour_theme_spp_phen <- data.frame(site_name = c(rep(site_names[1], 8), \n rep(site_names[2], 7),\n rep(site_names[3], 3),\n rep(site_names[4], 6)),\n site_spp_phen = spp_phen_combos,\n spp_phen = c(unique(sort(as.character(coastal_phen[coastal_phen$site_name == site_names[1],]$spp_phen))),\n unique(sort(as.character(coastal_phen[coastal_phen$site_name == site_names[2],]$spp_phen))),\n unique(sort(as.character(coastal_phen[coastal_phen$site_name == site_names[3],]$spp_phen))),\n unique(sort(as.character(coastal_phen[coastal_phen$site_name == site_names[4],]$spp_phen)))),\n colour = c(\n colorRampPalette(c(\"#19262EFF\",\"#84CBF2FF\"), \n interpolate = \"linear\")(8), # ALEXFIIORD\n colorRampPalette(c(\"#112B26FF\",\"#5BE8CDFF\"), \n interpolate = \"linear\")(7), # BARROW\n colorRampPalette(c(\"#382F12FF\",\"#C2A33EFF\"), \n interpolate = \"linear\")(3), # QHI\n colorRampPalette(c(\"#422413FF\",\"#FF8A48FF\"), \n interpolate = \"linear\")(6) # ZACKENBERG\n ), stringsAsFactors = F)\n\n# Helper function that returns ylab only for Alexfiord (first site)\nylab_filter <- function(label, site_to_plot){\n if(site_to_plot == \"ALEXFIORD\") {\n return(label)\n } else {\n return(\"\")\n }\n}\n\n### Quality Control Phenology data----\n\n## Check for NAs and quality in predictors and responses\n\n# Phenology observations, upper and lower bounds\nunique(coastal_phen$doy)\nunique(coastal_phen$prior_visit)\nsum(is.na(coastal_phen$doy))\nsum(is.na(coastal_phen$prior_visit))\n# remove NAs (211 values)\ncoastal_phen <- coastal_phen[!is.na(coastal_phen$doy),]\n# nice!\n\n# Snowmelt dates\nunique(coastal_phen$snowmelt)\nsum(is.na(coastal_phen$snowmelt))\n# Some NAs in there (153)\ncoastal_phen <- coastal_phen[!is.na(coastal_phen$snowmelt),]\n# Nice!\n\n# Remaining predictors\nunique(coastal_phen$phase_temp)\nunique(coastal_phen$spring_temp)\nunique(coastal_phen$apr_temp)\nunique(coastal_phen$may_temp)\nunique(coastal_phen$jun_temp)\nunique(coastal_phen$onset_ice_melt)\nunique(coastal_phen$spring_extent)\n\nsum(is.na(coastal_phen$phase_temp))\nsum(is.na(coastal_phen$spring_temp))\nsum(is.na(coastal_phen$apr_temp))\nsum(is.na(coastal_phen$may_temp))\nsum(is.na(coastal_phen$jun_temp))\nsum(is.na(coastal_phen$onset_ice_melt))\nsum(is.na(coastal_phen$spring_extent))\n# Okay. All good.\n\n\n### Trend analysis fro phenological observations ----\n\n# If previously run load from this file:\n# load(paste0(script_path, \"models/phen_trend_models.Rda\"))\n\n# Define function to run MCMCglmm models\ntrend_model <- function(site_spp_sphen_select){\n cphen_subset <- coastal_phen %>% \n filter(site_spp_phen == site_spp_sphen_select) \n model <- MCMCglmm(cbind(prior_visit, doy) ~ year, \n random = ~ year_fac + plot_id,\n data = as.data.frame(cphen_subset),\n family = \"cengaussian\",\n nitt = 1000000)\n return(model)\n}\n\n# Execute over all site_spp_phen_combinations with parallel processing\n# models <- mclapply(site_spp_phen_combos, trend_model, mc.cores = 4)\n# names(models) <- make.names(paste0(site_spp_phen_combos, \"_model\"))\n# list2env(models, envir = .GlobalEnv)\n\n# Dont'r run in parallel, as we will not know which model will be associated\n# with which output afterwards. Better run linearly.\nmodel_list <- lapply(site_spp_phen_combos, trend_model)\nnames(model_list) <- make.names(paste0(site_spp_phen_combos, \"_model\"))\nlist2env(model_list, envir = .GlobalEnv) \n\n### Gather outputs \n## Prep data frame\nphen_trends <- data.frame(site_spp_phen = site_spp_phen_combos,\n intercept = NA,\n intercept_l95 = NA,\n intercept_u95 = NA, \n intercept_esmpl = NA,\n intercept_pMCMC = NA,\n slope = NA,\n slope_l95 = NA,\n slope_u95 = NA,\n slope_esmpl = NA,\n slope_pMCMC = NA)\n## Define funciton to extract slope parameters and estimates \nextr_outputs <- function(site_spp_sphen_select){\n model <- get(paste0(site_spp_sphen_select, \"_model\"))\n model_sum <- summary(model)\n # retrive row index for output dataframe\n row_no <- which(phen_trends$site_spp_phen == site_spp_sphen_select)\n # use one liners to extract intersept and slope estimators\n phen_trends[row_no,2:6] <<- model_sum$solutions[1,]\n phen_trends[row_no,7:11] <<- model_sum$solutions[2,]\n}\n\n## Apply to all site_spp_phen combos\nlapply(site_spp_phen_combos, extr_outputs)\n\n### Claculate predictions\n# prep data frame\nphen_predicts <- data.frame(site_spp_phen = coastal_phen %>% \n select(site_spp_phen, year) %>%\n distinct(site_spp_phen, year) %>%\n select(site_spp_phen) %>%\n unlist() %>% \n as.character(),\n year = coastal_phen %>% \n select(site_spp_phen, year) %>%\n distinct(site_spp_phen, year) %>%\n select(year) %>%\n unlist() %>% \n as.numeric(),\n pred = NA,\n pred_l95 = NA,\n pred_u95 = NA)\n\n# Define function to extract predicitons\nextract_pred <- function(site_spp_phen_select){\n model <- get(paste0(site_spp_phen_select, \"_model\"))\n row_nos <- which(phen_predicts$site_spp_phen == site_spp_phen_select)\n preds <- predict.MCMCglmm(model, interval = \"confidence\", type = \"response\")\n preds <- unique(data.frame(preds, year = as.numeric(model$X[,2])))\n preds <- preds[,c(4,1,2,3)]\n phen_predicts[row_nos, 3:5] <<- preds[,2:4]\n paste0(\"Done with: \", site_spp_phen_select, \" ;\")\n}\nlapply(site_spp_phen_combos, extract_pred)\n\n# create site name and spp_phen columns\nphen_predicts$site_name <- gsub(\"_.*\", \"\", phen_predicts$site_spp_phen) \nphen_predicts$spp_phen <- gsub(\"^[A-Z]*_\", \"\", phen_predicts$site_spp_phen) \n\n### Plot phenology data with trends ----\n# First without ZACK SILACA due to large errors\ncolour_theme_sites$start_year <- c(1989,1993,1999,1994)\ncolour_theme_sites$end_year <- c(2016,2016,2016,2011)\ncolour_theme_sites$early_doy <- c(130,130,130,130)\ncolour_theme_sites$late_doy <- c(220,220,220,220)\n\nplot_phen <- function(site_to_plot){\n\n site_colours <- colour_theme_spp_phen[colour_theme_spp_phen$site_name == site_to_plot,]$colour\n site_colour <- colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$colour\n name_pretty <- colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$name_pretty\n site_phen <- coastal_phen %>% filter(site_name == site_to_plot) %>% \n group_by(spp_phen, year) %>% mutate(int_mean = (prior_visit + doy) /2) %>% \n summarise(phen_mean = round(mean(int_mean, na.rm = T)))\n site_phen$spp_phen <- factor(as.character(site_phen$spp_phen))\n site_preds <- phen_predicts %>%\n filter(site_name == site_to_plot)\n site_preds$spp_phen <- factor(site_preds$spp_phen)\n ribbon_alpha <- 0.5\n site_colours_ribbon <- site_colours\n if(site_to_plot == \"ZACKENBERG\"){\n site_phen$spp_phen <- factor(site_phen$spp_phen, levels = rev(levels(site_phen$spp_phen)))\n site_preds$spp_phen <- factor(site_preds$spp_phen, levels = rev(levels(site_preds$spp_phen)))\n site_colours <- rev(site_colours)\n # Exclude SILACA due to large error bars\n site_colours_ribbon <- c(\"#FF8A4800\", \"#D9753D80\", \"#B3613280\", \"#8D4C2880\", \"#67381D80\", \"#42241380\")\n \n ribbon_alpha <- NA\n \n }\n \n ggplot() +\n geom_ribbon(data = site_preds[,], #-which(site_preds$spp_phen == \"SILACA_flowering\")\n mapping = aes(x = year,\n ymin = pred_l95,\n ymax = pred_u95,\n fill = spp_phen,\n group = spp_phen),\n alpha = ribbon_alpha,\n inherit.aes = FALSE) +\n geom_point(data = site_phen, \n mapping = aes(x = year, \n y = phen_mean, \n colour = spp_phen, \n fill= spp_phen, \n group = spp_phen),\n size = 4) +\n geom_line(data = site_preds,\n mapping = aes(x = year,\n y = pred,\n colour = spp_phen,\n group = spp_phen),\n inherit.aes = FALSE,\n size = 1) +\n scale_colour_manual(values = site_colours) +\n scale_fill_manual(values = site_colours_ribbon) +\n\n scale_x_continuous(limits= c(colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$start_year, \n colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$end_year), \n breaks = seq(1990, 2016, 5)) +\n scale_y_continuous(limits = c(colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$early_doy, \n colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$late_doy), \n breaks = seq(100, 240, 20)) +\n xlab(label = \"\") +\n ylab(label = ylab_filter(\"Mean Phenology (DoY)\", site_to_plot)) +\n annotate(\"text\", x = (colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$end_year + \n colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$start_year) / 2, \n y = colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$late_doy, \n label = name_pretty, \n colour = site_colour, size = 7, hjust = 0.5) +\n theme_bw() +\n theme(panel.border = element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n axis.line = element_line(colour = \"black\"),\n axis.text = element_text(colour = \"black\", size = 15),\n axis.title = element_text(size = 15),\n legend.position = \"none\") \n}\n# plot all sites\nlist2env(lapply(setNames(site_names, \n make.names(paste0(site_names,\n \"_phen_plot\"))),\n plot_phen), \n envir = .GlobalEnv)\n\n# Set panel layout\npanel_layout <- rbind(c(1,2,3,4))\n\n# Combine plots and export\nplot_grob <- grid.arrange(ALEXFIORD_phen_plot, \n BARROW_phen_plot, \n QHI_phen_plot, \n ZACKENBERG_phen_plot,\n layout_matrix = panel_layout)\nggsave(filename = paste0(script_path, \"/coastal_phen_plot_MCMCglmm_intmeans.png\"), \n plot = plot_grob, scale = 1.7, \n width = 10, \n height = (10/3), \n dpi = 600)\n\n# Second with ZACK SILACA due to large errors\nplot_phen <- function(site_to_plot){\n \n site_colours <- colour_theme_spp_phen[colour_theme_spp_phen$site_name == site_to_plot,]$colour\n site_colour <- colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$colour\n name_pretty <- colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$name_pretty\n site_phen <- coastal_phen %>% filter(site_name == site_to_plot) %>% \n group_by(spp_phen, year) %>% mutate(int_mean = (prior_visit + doy) /2) %>% \n summarise(phen_mean = round(mean(int_mean, na.rm = T)))\n site_phen$spp_phen <- factor(as.character(site_phen$spp_phen))\n site_preds <- phen_predicts %>%\n filter(site_name == site_to_plot)\n site_preds$spp_phen <- factor(site_preds$spp_phen)\n ribbon_alpha <- 0.5\n site_colours_ribbon <- site_colours\n if(site_to_plot == \"ZACKENBERG\"){\n site_phen$spp_phen <- factor(site_phen$spp_phen, levels = rev(levels(site_phen$spp_phen)))\n site_preds$spp_phen <- factor(site_preds$spp_phen, levels = rev(levels(site_preds$spp_phen)))\n site_colours <- rev(site_colours)\n # Exclude SILACA due to large error bars\n site_colours_ribbon <- c(\"#FF8A4880\", \"#D9753D80\", \"#B3613280\", \"#8D4C2880\", \"#67381D80\", \"#42241380\")\n \n ribbon_alpha <- NA\n }\n \n ggplot() +\n geom_ribbon(data = site_preds[,], #-which(site_preds$spp_phen == \"SILACA_flowering\")\n mapping = aes(x = year,\n ymin = pred_l95,\n ymax = pred_u95,\n fill = spp_phen,\n group = spp_phen),\n alpha = ribbon_alpha,\n inherit.aes = FALSE) +\n geom_point(data = site_phen, \n mapping = aes(x = year, \n y = phen_mean, \n colour = spp_phen, \n fill= spp_phen, \n group = spp_phen),\n size = 4) +\n geom_line(data = site_preds,\n mapping = aes(x = year,\n y = pred,\n colour = spp_phen,\n group = spp_phen),\n inherit.aes = FALSE,\n size = 1) +\n scale_colour_manual(values = site_colours) +\n scale_fill_manual(values = site_colours_ribbon) +\n \n scale_x_continuous(limits= c(colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$start_year, \n colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$end_year), \n breaks = seq(1990, 2016, 5)) +\n scale_y_continuous(limits = c(colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$early_doy, \n colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$late_doy), \n breaks = seq(100, 240, 20)) +\n xlab(label = \"\") +\n ylab(label = ylab_filter(\"Mean Phenology (DoY)\", site_to_plot)) +\n annotate(\"text\", x = (colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$end_year + \n colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$start_year) / 2, \n y = colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$late_doy, \n label = name_pretty, \n colour = site_colour, size = 7, hjust = 0.5) +\n theme_bw() +\n theme(panel.border = element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n axis.line = element_line(colour = \"black\"),\n axis.text = element_text(colour = \"black\", size = 15),\n axis.title = element_text(size = 15),\n legend.position = \"none\") \n}\n# plot all sites\nlist2env(lapply(setNames(site_names, \n make.names(paste0(site_names,\n \"_phen_plot\"))),\n plot_phen), \n envir = .GlobalEnv)\n\n# Set panel layout\npanel_layout <- rbind(c(1,2,3,4))\n\n# Combine plots and export\nplot_grob <- grid.arrange(ALEXFIORD_phen_plot, \n BARROW_phen_plot, \n QHI_phen_plot, \n ZACKENBERG_phen_plot,\n layout_matrix = panel_layout)\nggsave(filename = paste0(script_path, \"/coastal_phen_plot_MCMCglmm_intmeans_with_SILACA.png\"), \n plot = plot_grob, scale = 1.7, \n width = 10, \n height = (10/3), \n dpi = 600)\n### Calculate decadal advance ---- \nphen_trends <- phen_trends %>% mutate(adv_per_dec = slope * 10)\n\n# Min and max advance\nphen_trends %>% summarise(min_adv_per_dec = round(min(adv_per_dec),2), \n max_adv_per_dec = round(max(adv_per_dec),2))\n\n# Export\nwrite.csv(phen_trends, file = paste0(script_path, \"coastal_phen_trends.csv\"), row.names = F)\n\n\n# And safe the model files for the record\n\nmodel_names <- ls()[grep(\"_model\", ls())][-19] # excluding the model function\nsave(list = model_names, file = paste0(script_path, \"models/phen_trend_models.Rda\"))\n\n# Check Convergance\nlapply(model_names, function(x) { \n \n png(file = paste0(script_path, \"../quality_control/phen_trends/\", x, \"_sol.png\"))\n par(ask = F)\n plot(get(x)$Sol)\n dev.off()\n \n png(file = paste0(script_path, \"../quality_control/phen_trends/\", x, \"_vcv.png\"))\n par(ask = F)\n plot(get(x)$VCV)\n dev.off()\n \n }\n )\n# Check summaries\nfor(x in 1:length(model_names)){\n print(model_names[x])\n print(summary(get(model_names[x])))\n readline(\"Hit button to see next summary:\")\n }\nsummary(get(model_names[1]))\n\n# \n# ####### Aditional calcs: 1) Begining of season data -5 instead of -10 ----\n# \n# rm(list = ls())\n# # Housekeeping\n# script_path <- \"scripts/users/jassmann/phenology/coastal_phenology/\"\n# load(file =paste0(script_path, \"coastal_phen.Rda\"))\n# \n# # remove NAs (211 values)\n# coastal_phen <- coastal_phen[!is.na(coastal_phen$doy),]\n# \n# # Site names\n# site_names <- unique(as.character(coastal_phen$site_name))\n# \n# # Site spp phen combos\n# site_spp_phen_combos <- unique(coastal_phen$site_spp_phen)\n# \n# # Spp phen combos\n# spp_phen_combos <- sort(unique(coastal_phen$site_spp_phen))\n# \n# # Set colours\n# colour_theme_sites <- data.frame(site_name = c(site_names),\n# colour = c(\"#324D5CFF\", \n# \"#46B29DFF\", \n# \"#C2A33EFF\",\n# \"#E37B40FF\")) # 5th colour #F53855FF\n# colour_theme_spp_phen <- data.frame(site_name = c(rep(site_names[1], 8), \n# rep(site_names[2], 7),\n# rep(site_names[3], 3),\n# rep(site_names[4], 6)),\n# site_spp_phen = spp_phen_combos,\n# spp_phen = c(unique(as.character(coastal_phen[coastal_phen$site_name == site_names[1],]$spp_phen)),\n# unique(as.character(coastal_phen[coastal_phen$site_name == site_names[2],]$spp_phen)),\n# unique(as.character(coastal_phen[coastal_phen$site_name == site_names[3],]$spp_phen)),\n# unique(as.character(coastal_phen[coastal_phen$site_name == site_names[4],]$spp_phen))),\n# colour = c(\n# colorRampPalette(c(\"#19262EFF\",\"#84CBF2FF\"), \n# interpolate = \"linear\")(8), # ALEXFIIORD\n# colorRampPalette(c(\"#112B26FF\",\"#5BE8CDFF\"), \n# interpolate = \"linear\")(7), # BARROW\n# colorRampPalette(c(\"#382F12FF\",\"#C2A33EFF\"), \n# interpolate = \"linear\")(3), # QHI\n# colorRampPalette(c(\"#422413FF\",\"#FF8A48FF\"), \n# interpolate = \"linear\")(6) # ZACKENBERG\n# ), stringsAsFactors = F)\n# \n# # Helper function that returns ylab only for Alexfiord (first site)\n# ylab_filter <- function(label, site_to_plot){\n# if(site_to_plot == \"ALEXFIORD\") {\n# return(label)\n# } else {\n# return(\"\")\n# }\n# }\n# \n# \n# # adjust data set\n# coastal_phen[(coastal_phen$doy - coastal_phen$prior_visit) == 10,\n# ]$prior_visit <- \n# coastal_phen[(coastal_phen$doy - coastal_phen$prior_visit) == 10,\n# ]$doy - 5\n# # Define function to run MCMCglmm models\n# trend_model <- function(site_spp_sphen_select){\n# cphen_subset <- coastal_phen %>% \n# filter(site_spp_phen == site_spp_sphen_select) \n# model <- MCMCglmm(cbind(prior_visit, doy) ~ year, data = as.data.frame(cphen_subset),\n# family = \"cengaussian\",\n# nitt = 20000)\n# return(model)\n# }\n# \n# # Execute over all site_spp_phen_combinations\n# model_list <- lapply(site_spp_phen_combos, trend_model)\n# names(model_list) <- make.names(paste0(site_spp_phen_combos, \"_model\"))\n# list2env(model_list, envir = .GlobalEnv) \n# \n# ### Gather outputs \n# ## Prep data frame\n# phen_trends <- data.frame(site_spp_phen = site_spp_phen_combos,\n# intercept = NA,\n# intercept_l95 = NA,\n# intercept_u95 = NA, \n# intercept_esmpl = NA,\n# intercept_pMCMC = NA,\n# slope = NA,\n# slope_l95 = NA,\n# slope_u95 = NA,\n# slope_esmpl = NA,\n# slope_pMCMC = NA)\n# ## Define funciton to extract slope parameters and estimates \n# extr_outputs <- function(site_spp_sphen_select){\n# model <- get(paste0(site_spp_sphen_select, \"_model\"))\n# model_sum <- summary(model)\n# # retrive row index for output dataframe\n# row_no <- which(phen_trends$site_spp_phen == site_spp_sphen_select)\n# # use one liners to extract intersept and slope estimators\n# phen_trends[row_no,2:6] <<- model_sum$solutions[1,]\n# phen_trends[row_no,7:11] <<- model_sum$solutions[2,]\n# }\n# \n# ## Apply to all site_spp_phen combos\n# lapply(site_spp_phen_combos, extr_outputs)\n# \n# ### Claculate predictions\n# # prep data frame\n# phen_predicts <- data.frame(site_spp_phen = coastal_phen %>% \n# select(site_spp_phen, year) %>%\n# distinct(site_spp_phen, year) %>%\n# select(site_spp_phen) %>%\n# unlist() %>% \n# as.character(),\n# year = coastal_phen %>% \n# select(site_spp_phen, year) %>%\n# distinct(site_spp_phen, year) %>%\n# select(year) %>%\n# unlist() %>% \n# as.numeric(),\n# pred = NA,\n# pred_l95 = NA,\n# pred_u95 = NA)\n# \n# # Define function to extract predicitons\n# extract_pred <- function(site_spp_phen_select){\n# model <- get(paste0(site_spp_phen_select, \"_model\"))\n# row_nos <- which(phen_predicts$site_spp_phen == site_spp_phen_select)\n# preds <- predict.MCMCglmm(model, interval = \"confidence\", type = \"response\")\n# preds <- unique(data.frame(preds, year = as.numeric(model$X[,2])))\n# preds <- preds[,c(4,1,2,3)]\n# phen_predicts[row_nos, 3:5] <<- preds[,2:4]\n# paste0(\"Done with: \", site_spp_phen_select, \" ;\")\n# }\n# lapply(site_spp_phen_combos, extract_pred)\n# \n# # create site name and spp_phen columns\n# phen_predicts$site_name <- gsub(\"_.*\", \"\", phen_predicts$site_spp_phen) \n# phen_predicts$spp_phen <- gsub(\"^[A-Z]*_\", \"\", phen_predicts$site_spp_phen) \n# \n# ### Plot phenology data with trends ----\n# plot_phen <- function(site_to_plot){\n# \n# site_colours <- colour_theme_spp_phen[colour_theme_spp_phen$site_name == site_to_plot,]$colour\n# site_colour <- colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$colour\n# site_phen <- coastal_phen %>% filter(site_name == site_to_plot) %>% \n# group_by(spp_phen, year) %>% summarise(phen_mean = round(mean(doy, na.rm = T)))\n# \n# site_preds <- phen_predicts %>%\n# filter(site_name == site_to_plot)\n# \n# ggplot(data = site_phen, aes(x = year, \n# y = phen_mean, \n# colour = spp_phen, \n# fill= spp_phen, \n# group = spp_phen)) +\n# scale_colour_manual(values = site_colours) +\n# scale_fill_manual(values = site_colours) +\n# geom_point(size = 4) +\n# geom_ribbon(data = site_preds,\n# mapping = aes(x = year,\n# ymin = pred_l95,\n# ymax = pred_u95,\n# fill = spp_phen,\n# group = spp_phen),\n# alpha = 0.5,\n# inherit.aes = FALSE) +\n# geom_line(data = site_preds,\n# mapping = aes(x = year,\n# y = pred,\n# colour = spp_phen,\n# group = spp_phen),\n# inherit.aes = FALSE,\n# size = 1) +\n# scale_x_continuous(limits= c(1990, 2016), breaks = seq(1990, 2016, 5)) +\n# scale_y_continuous(limits = c(90, 250), breaks = seq(100, 240, 20)) +\n# xlab(label = \"\") +\n# ylab(label = ylab_filter(\"Mean Phenology (DoY)\", site_to_plot)) +\n# annotate(\"text\", x = 2014, y = 245, label = site_to_plot, \n# colour = site_colour, size = 7, hjust = 1) +\n# theme_bw() +\n# theme(panel.border = element_blank(),\n# panel.grid.major = element_blank(),\n# panel.grid.minor = element_blank(),\n# axis.line = element_line(colour = \"black\"),\n# axis.text = element_text(colour = \"black\", size = 15),\n# axis.title = element_text(size = 15),\n# legend.position = \"none\") \n# }\n# # plot all sites\n# list2env(lapply(setNames(site_names, \n# make.names(paste0(site_names,\n# \"_phen_plot\"))),\n# plot_phen), \n# envir = .GlobalEnv)\n# \n# # Set panel layout\n# panel_layout <- rbind(c(1,2,3,4))\n# \n# # Combine plots and export\n# plot_grob <- grid.arrange(ALEXFIORD_phen_plot, \n# BARROW_phen_plot, \n# QHI_phen_plot, \n# ZACKENBERG_phen_plot,\n# layout_matrix = panel_layout)\n# ggsave(filename = paste0(script_path, \"/coastal_phen_plot_MCMCglmm_5d.png\"), \n# plot = plot_grob, scale = 1.7, \n# width = 10, \n# height = (10/3), \n# dpi = 600)\n# \n# ### Calculate decadal advance ---- \n# phen_trends <- phen_trends %>% mutate(adv_per_dec = slope * 10)\n# \n# # Min and max advance\n# phen_trends %>% summarise(min_adv_per_dec = round(min(adv_per_dec),2), \n# max_adv_per_dec = round(max(adv_per_dec),2))\n# \n# # Export\n# write.csv(phen_trends, file = paste0(script_path, \"coastal_phen_trends_5d.csv\"), row.names = F)\n# \n# \n# \n# \n# ####### Aditional calcs: 2) Begining of season data -20 instead of -10 ----\n# \n# rm(list = ls())\n# # Housekeeping\n# script_path <- \"scripts/users/jassmann/phenology/coastal_phenology/\"\n# load(file =paste0(script_path, \"coastal_phen.Rda\"))\n# \n# # remove NAs (211 values)\n# coastal_phen <- coastal_phen[!is.na(coastal_phen$doy),]\n# \n# # Site names\n# site_names <- unique(as.character(coastal_phen$site_name))\n# \n# # Site spp phen combos\n# site_spp_phen_combos <- unique(coastal_phen$site_spp_phen)\n# \n# # Spp phen combos\n# spp_phen_combos <- sort(unique(coastal_phen$site_spp_phen))\n# \n# # Set colours\n# colour_theme_sites <- data.frame(site_name = c(site_names),\n# colour = c(\"#324D5CFF\", \n# \"#46B29DFF\", \n# \"#C2A33EFF\",\n# \"#E37B40FF\")) # 5th colour #F53855FF\n# colour_theme_spp_phen <- data.frame(site_name = c(rep(site_names[1], 8), \n# rep(site_names[2], 7),\n# rep(site_names[3], 3),\n# rep(site_names[4], 6)),\n# site_spp_phen = spp_phen_combos,\n# spp_phen = c(unique(as.character(coastal_phen[coastal_phen$site_name == site_names[1],]$spp_phen)),\n# unique(as.character(coastal_phen[coastal_phen$site_name == site_names[2],]$spp_phen)),\n# unique(as.character(coastal_phen[coastal_phen$site_name == site_names[3],]$spp_phen)),\n# unique(as.character(coastal_phen[coastal_phen$site_name == site_names[4],]$spp_phen))),\n# colour = c(\n# colorRampPalette(c(\"#19262EFF\",\"#84CBF2FF\"), \n# interpolate = \"linear\")(8), # ALEXFIIORD\n# colorRampPalette(c(\"#112B26FF\",\"#5BE8CDFF\"), \n# interpolate = \"linear\")(7), # BARROW\n# colorRampPalette(c(\"#382F12FF\",\"#C2A33EFF\"), \n# interpolate = \"linear\")(3), # QHI\n# colorRampPalette(c(\"#422413FF\",\"#FF8A48FF\"), \n# interpolate = \"linear\")(6) # ZACKENBERG\n# ), stringsAsFactors = F)\n# \n# # Helper function that returns ylab only for Alexfiord (first site)\n# ylab_filter <- function(label, site_to_plot){\n# if(site_to_plot == \"ALEXFIORD\") {\n# return(label)\n# } else {\n# return(\"\")\n# }\n# }\n# \n# # Define function to run MCMCglmm models\n# trend_model <- function(site_spp_sphen_select){\n# cphen_subset <- coastal_phen %>% \n# filter(site_spp_phen == site_spp_sphen_select) \n# model <- MCMCglmm(cbind(prior_visit, doy) ~ year, data = as.data.frame(cphen_subset),\n# family = \"cengaussian\",\n# nitt = 20000)\n# return(model)\n# }\n# \n# \n# # adjust data set\n# # NB re-run begining of script to re-load data\n# coastal_phen[(coastal_phen$doy - coastal_phen$prior_visit) == 10,\n# ]$prior_visit <- \n# coastal_phen[(coastal_phen$doy - coastal_phen$prior_visit) == 10,\n# ]$doy - 20\n# \n# # Execute over all site_spp_phen_combinations\n# model_list <- lapply(site_spp_phen_combos, trend_model)\n# names(model_list) <- make.names(paste0(site_spp_phen_combos, \"_model\"))\n# list2env(model_list, envir = .GlobalEnv) \n# \n# ### Gather outputs \n# ## Prep data frame\n# phen_trends <- data.frame(site_spp_phen = site_spp_phen_combos,\n# intercept = NA,\n# intercept_l95 = NA,\n# intercept_u95 = NA, \n# intercept_esmpl = NA,\n# intercept_pMCMC = NA,\n# slope = NA,\n# slope_l95 = NA,\n# slope_u95 = NA,\n# slope_esmpl = NA,\n# slope_pMCMC = NA)\n# ## Define funciton to extract slope parameters and estimates \n# extr_outputs <- function(site_spp_sphen_select){\n# model <- get(paste0(site_spp_sphen_select, \"_model\"))\n# model_sum <- summary(model)\n# # retrive row index for output dataframe\n# row_no <- which(phen_trends$site_spp_phen == site_spp_sphen_select)\n# # use one liners to extract intersept and slope estimators\n# phen_trends[row_no,2:6] <<- model_sum$solutions[1,]\n# phen_trends[row_no,7:11] <<- model_sum$solutions[2,]\n# }\n# \n# ## Apply to all site_spp_phen combos\n# lapply(site_spp_phen_combos, extr_outputs)\n# \n# ### Claculate predictions\n# # prep data frame\n# phen_predicts <- data.frame(site_spp_phen = coastal_phen %>% \n# select(site_spp_phen, year) %>%\n# distinct(site_spp_phen, year) %>%\n# select(site_spp_phen) %>%\n# unlist() %>% \n# as.character(),\n# year = coastal_phen %>% \n# select(site_spp_phen, year) %>%\n# distinct(site_spp_phen, year) %>%\n# select(year) %>%\n# unlist() %>% \n# as.numeric(),\n# pred = NA,\n# pred_l95 = NA,\n# pred_u95 = NA)\n# \n# # Define function to extract predicitons\n# extract_pred <- function(site_spp_phen_select){\n# model <- get(paste0(site_spp_phen_select, \"_model\"))\n# row_nos <- which(phen_predicts$site_spp_phen == site_spp_phen_select)\n# preds <- predict.MCMCglmm(model, interval = \"confidence\", type = \"response\")\n# preds <- unique(data.frame(preds, year = as.numeric(model$X[,2])))\n# preds <- preds[,c(4,1,2,3)]\n# phen_predicts[row_nos, 3:5] <<- preds[,2:4]\n# paste0(\"Done with: \", site_spp_phen_select, \" ;\")\n# }\n# lapply(site_spp_phen_combos, extract_pred)\n# \n# # create site name and spp_phen columns\n# phen_predicts$site_name <- gsub(\"_.*\", \"\", phen_predicts$site_spp_phen) \n# phen_predicts$spp_phen <- gsub(\"^[A-Z]*_\", \"\", phen_predicts$site_spp_phen) \n# \n# ### Plot phenology data with trends ----\n# plot_phen <- function(site_to_plot){\n# \n# site_colours <- colour_theme_spp_phen[colour_theme_spp_phen$site_name == site_to_plot,]$colour\n# site_colour <- colour_theme_sites[colour_theme_sites$site_name == site_to_plot,]$colour\n# site_phen <- coastal_phen %>% filter(site_name == site_to_plot) %>% \n# group_by(spp_phen, year) %>% summarise(phen_mean = round(mean(doy, na.rm = T)))\n# \n# site_preds <- phen_predicts %>%\n# filter(site_name == site_to_plot)\n# \n# ggplot(data = site_phen, aes(x = year, \n# y = phen_mean, \n# colour = spp_phen, \n# fill= spp_phen, \n# group = spp_phen)) +\n# scale_colour_manual(values = site_colours) +\n# scale_fill_manual(values = site_colours) +\n# geom_point(size = 4) +\n# geom_line(data = site_preds,\n# mapping = aes(x = year,\n# y = pred,\n# colour = spp_phen,\n# group = spp_phen),\n# inherit.aes = FALSE,\n# size = 1) +\n# geom_ribbon(data = site_preds,\n# mapping = aes(x = year,\n# ymin = pred_l95,\n# ymax = pred_u95,\n# fill = spp_phen,\n# group = spp_phen),\n# alpha = 0.5,\n# inherit.aes = FALSE) +\n# scale_x_continuous(limits= c(1990, 2016), breaks = seq(1990, 2016, 5)) +\n# scale_y_continuous(limits = c(90, 250), breaks = seq(100, 240, 20)) +\n# xlab(label = \"\") +\n# ylab(label = ylab_filter(\"Mean Phenology (DoY)\", site_to_plot)) +\n# annotate(\"text\", x = 2014, y = 245, label = site_to_plot, \n# colour = site_colour, size = 7, hjust = 1) +\n# theme_bw() +\n# theme(panel.border = element_blank(),\n# panel.grid.major = element_blank(),\n# panel.grid.minor = element_blank(),\n# axis.line = element_line(colour = \"black\"),\n# axis.text = element_text(colour = \"black\", size = 15),\n# axis.title = element_text(size = 15),\n# legend.position = \"none\") \n# }\n# # plot all sites\n# list2env(lapply(setNames(site_names, \n# make.names(paste0(site_names,\n# \"_phen_plot\"))),\n# plot_phen), \n# envir = .GlobalEnv)\n# \n# # Set panel layout\n# panel_layout <- rbind(c(1,2,3,4))\n# \n# # Combine plots and export\n# plot_grob <- grid.arrange(ALEXFIORD_phen_plot, \n# BARROW_phen_plot, \n# QHI_phen_plot, \n# ZACKENBERG_phen_plot,\n# layout_matrix = panel_layout)\n# ggsave(filename = paste0(script_path, \"/coastal_phen_plot_MCMCglmm_20d.png\"), \n# plot = plot_grob, scale = 1.7, \n# width = 10, \n# height = (10/3), \n# dpi = 600)\n# \n# ### Calculate decadal advance ---- \n# phen_trends <- phen_trends %>% mutate(adv_per_dec = slope * 10)\n# \n# # Min and max advance\n# phen_trends %>% summarise(min_adv_per_dec = round(min(adv_per_dec),2), \n# max_adv_per_dec = round(max(adv_per_dec),2))\n# \n# # Export\n# write.csv(phen_trends, file = paste0(script_path, \"coastal_phen_trends_20d.csv\"), row.names = F)\n# \n", "meta": {"hexsha": "1e02cf77321fdbf8dce3c2b02e9ef42c89e9e35e", "size": 38490, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/coastal_phen_trends.r", "max_stars_repo_name": "jakobjassmann/coastalphenology", "max_stars_repo_head_hexsha": "cebfcd97002bb497dd5b8d67722e709b46ae7df4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2019-04-12T15:40:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-07T19:42:28.000Z", "max_issues_repo_path": "analysis/coastal_phen_trends.r", "max_issues_repo_name": "jakobjassmann/coastalphenology", "max_issues_repo_head_hexsha": "cebfcd97002bb497dd5b8d67722e709b46ae7df4", "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": "analysis/coastal_phen_trends.r", "max_forks_repo_name": "jakobjassmann/coastalphenology", "max_forks_repo_head_hexsha": "cebfcd97002bb497dd5b8d67722e709b46ae7df4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-10T15:59:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T15:59:12.000Z", "avg_line_length": 44.3944636678, "max_line_length": 142, "alphanum_fraction": 0.5458300857, "num_tokens": 9723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.033589507584945354, "lm_q1q2_score": 0.0157464463088135}} {"text": "#########################################################################################\n# License Agreement\n# \n# THIS WORK IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE \n# (\"CCPL\" OR \"LICENSE\"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER \n# APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE \n# OR COPYRIGHT LAW IS PROHIBITED.\n# \n# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE \n# BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED \n# TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN \n# CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.\n#\n# BASELIne: Bayesian Estimation of Antigen-Driven Selection in Immunoglobulin Sequences\n# Coded by: Mohamed Uduman & Gur Yaari\n# Copyright 2012 Kleinstein Lab\n# Version: 1.3 (01/23/2014)\n#########################################################################################\n\nop <- options();\noptions(showWarnCalls=FALSE, showErrorCalls=FALSE, warn=-1)\nlibrary('seqinr')\nif( F & Sys.info()[1]==\"Linux\"){\n library(\"multicore\")\n}\n\n# Load functions and initialize global variables\nsource(\"Baseline_Functions.r\")\n\n# Initialize parameters with user provided arguments\n arg <- commandArgs(TRUE) \n #arg = c(2,1,5,5,0,1,\"1:26:38:55:65:104:116\", \"test.fasta\",\"\",\"sample\")\n #arg = c(1,1,5,5,0,1,\"1:38:55:65:104:116:200\", \"test.fasta\",\"\",\"sample\")\n #arg = c(1,1,5,5,1,1,\"1:26:38:55:65:104:116\", \"/home/mu37/Wu/Wu_Cloned_gapped_sequences_D-masked.fasta\",\"/home/mu37/Wu/\",\"Wu\")\n testID <- as.numeric(arg[1]) # 1 = Focused, 2 = Local\n species <- as.numeric(arg[2]) # 1 = Human. 2 = Mouse\n substitutionModel <- as.numeric(arg[3]) # 0 = Uniform substitution, 1 = Smith DS et al. 1996, 5 = FiveS\n mutabilityModel <- as.numeric(arg[4]) # 0 = Uniform mutablity, 1 = Tri-nucleotide (Shapiro GS et al. 2002) , 5 = FiveS\n clonal <- as.numeric(arg[5]) # 0 = Independent sequences, 1 = Clonally related, 2 = Clonally related & only non-terminal mutations\n fixIndels <- as.numeric(arg[6]) # 0 = Do nothing, 1 = Try and fix Indels\n region <- as.numeric(strsplit(arg[7],\":\")[[1]]) # StartPos:LastNucleotideF1:C1:F2:C2:F3:C3\n inputFilePath <- arg[8] # Full path to input file\n outputPath <- arg[9] # Full path to location of output files\n outputID <- arg[10] # ID for session output \n \n\n if(testID==5){\n traitChangeModel <- 1\n if( !is.na(any(arg[11])) ) traitChangeModel <- as.numeric(arg[11]) # 1 <- Chothia 1998\n initializeTraitChange(traitChangeModel) \n }\n \n# Initialize other parameters/variables\n \n # Initialzie the codon table ( definitions of R/S )\n computeCodonTable(testID) \n\n # Initialize \n # Test Name\n testName<-\"Focused\"\n if(testID==2) testName<-\"Local\"\n if(testID==3) testName<-\"Imbalanced\" \n if(testID==4) testName<-\"ImbalancedSilent\" \n \n # Indel placeholders initialization\n indelPos <- NULL\n delPos <- NULL\n insPos <- NULL\n\n # Initialize in Tranistion & Mutability matrixes\n substitution <- initializeSubstitutionMatrix(substitutionModel,species)\n mutability <- initializeMutabilityMatrix(mutabilityModel,species)\n \n # FWR/CDR boundaries\n flagTrim <- F\n if( is.na(region[7])){\n flagTrim <- T\n region[7]<-region[6]\n }\n readStart = min(region,na.rm=T)\n readEnd = max(region,na.rm=T)\n if(readStart>1){\n region = region - (readStart - 1)\n }\n region_Nuc = c( (region[1]*3-2) , (region[2:7]*3) )\n region_Cod = region\n \n readStart = (readStart*3)-2\n readEnd = (readEnd*3)\n \n FWR_Nuc <- c( rep(TRUE,(region_Nuc[2])),\n rep(FALSE,(region_Nuc[3]-region_Nuc[2])),\n rep(TRUE,(region_Nuc[4]-region_Nuc[3])),\n rep(FALSE,(region_Nuc[5]-region_Nuc[4])),\n rep(TRUE,(region_Nuc[6]-region_Nuc[5])),\n rep(FALSE,(region_Nuc[7]-region_Nuc[6]))\n )\n CDR_Nuc <- (1-FWR_Nuc)\n CDR_Nuc <- as.logical(CDR_Nuc)\n FWR_Nuc_Mat <- matrix( rep(FWR_Nuc,4), ncol=length(FWR_Nuc), nrow=4, byrow=T)\n CDR_Nuc_Mat <- matrix( rep(CDR_Nuc,4), ncol=length(CDR_Nuc), nrow=4, byrow=T)\n \n FWR_Codon <- c( rep(TRUE,(region[2])),\n rep(FALSE,(region[3]-region[2])),\n rep(TRUE,(region[4]-region[3])),\n rep(FALSE,(region[5]-region[4])),\n rep(TRUE,(region[6]-region[5])),\n rep(FALSE,(region[7]-region[6]))\n )\n CDR_Codon <- (1-FWR_Codon)\n CDR_Codon <- as.logical(CDR_Codon)\n\n\n# Read input FASTA file\n tryCatch(\n inputFASTA <- baseline.read.fasta(inputFilePath, seqtype=\"DNA\",as.string=T,set.attributes=F,forceDNAtolower=F)\n , error = function(ex){\n cat(\"Error|Error reading input. Please enter or upload a valid FASTA file.\\n\")\n q()\n }\n )\n \n if (length(inputFASTA)==1) {\n cat(\"Error|Error reading input. Please enter or upload a valid FASTA file.\\n\")\n q()\n }\n\n # Process sequence IDs/names\n names(inputFASTA) <- sapply(names(inputFASTA),function(x){trim(x)})\n \n # Convert non nucleotide characters to N\n inputFASTA[length(inputFASTA)] = gsub(\"\\t\",\"\",inputFASTA[length(inputFASTA)])\n inputFASTA <- lapply(inputFASTA,replaceNonFASTAChars)\n\n # Process the FASTA file and conver to Matrix[inputSequence, germlineSequence]\n processedInput <- processInputAdvanced(inputFASTA)\n matInput <- processedInput[[1]]\n germlines <- processedInput[[2]]\n lenGermlines = length(unique(germlines))\n groups <- processedInput[[3]]\n lenGroups = length(unique(groups))\n rm(processedInput)\n rm(inputFASTA)\n\n# # remove clones with less than 2 seqeunces\n# tableGL <- table(germlines)\n# singletons <- which(tableGL<8)\n# rowsToRemove <- match(singletons,germlines)\n# if(any(rowsToRemove)){ \n# matInput <- matInput[-rowsToRemove,]\n# germlines <- germlines[-rowsToRemove] \n# groups <- groups[-rowsToRemove]\n# }\n# \n# # remove unproductive seqs\n# nonFuctionalSeqs <- sapply(rownames(matInput),function(x){any(grep(\"unproductive\",x))})\n# if(any(nonFuctionalSeqs)){\n# if(sum(nonFuctionalSeqs)==length(germlines)){\n# write.table(\"Unproductive\",file=paste(outputPath,outputID,\".txt\",sep=\"\"),quote=F,sep=\"\\t\",row.names=F,col.names=T)\n# q() \n# }\n# matInput <- matInput[-which(nonFuctionalSeqs),]\n# germlines <- germlines[-which(nonFuctionalSeqs)]\n# germlines[1:length(germlines)] <- 1:length(germlines)\n# groups <- groups[-which(nonFuctionalSeqs)]\n# }\n# \n# if(class(matInput)==\"character\"){\n# write.table(\"All unproductive seqs\",file=paste(outputPath,outputID,\".txt\",sep=\"\"),quote=F,sep=\"\\t\",row.names=F,col.names=T)\n# q() \n# }\n# \n# if(nrow(matInput)<10 | is.null(nrow(matInput))){\n# write.table(paste(nrow(matInput), \"seqs only\",sep=\"\"),file=paste(outputPath,outputID,\".txt\",sep=\"\"),quote=F,sep=\"\\t\",row.names=F,col.names=T)\n# q()\n# }\n\n# replace leading & trailing \"-\" with \"N:\n matInput <- t(apply(matInput,1,replaceLeadingTrailingDashes,readEnd))\n \n # Trim (nucleotide) input sequences to the last codon\n #matInput[,1] <- apply(matrix(matInput[,1]),1,trimToLastCodon) \n\n# # Check for Indels\n# if(fixIndels){\n# delPos <- fixDeletions(matInput)\n# insPos <- fixInsertions(matInput)\n# }else{\n# # Check for indels\n# indelPos <- checkForInDels(matInput)\n# indelPos <- apply(cbind(indelPos[[1]],indelPos[[2]]),1,function(x){(x[1]==T & x[2]==T)})\n# }\n \n # If indels are present, remove mutations in the seqeunce & throw warning at end\n #matInput[indelPos,] <- apply(matrix(matInput[indelPos,],nrow=sum(indelPos),ncol=2),1,function(x){x[1]=x[2]; return(x) })\n \n colnames(matInput)=c(\"Input\",\"Germline\")\n\n # If seqeunces are clonal, create effective sequence for each clone & modify germline/group definitions\n germlinesOriginal = NULL\n if(clonal){\n germlinesOriginal <- germlines\n collapseCloneResults <- tapply(1:nrow(matInput),germlines,function(i){\n collapseClone(matInput[i,1],matInput[i[1],2],readEnd,nonTerminalOnly=(clonal-1))\n })\n matInput = t(sapply(collapseCloneResults,function(x){return(x[[1]])}))\n names_groups = tapply(groups,germlines,function(x){names(x[1])}) \n groups = tapply(groups,germlines,function(x){array(x[1],dimnames=names(x[1]))}) \n names(groups) = names_groups\n \n names_germlines = tapply(germlines,germlines,function(x){names(x[1])}) \n germlines = tapply( germlines,germlines,function(x){array(x[1],dimnames=names(x[1]))} )\n names(germlines) = names_germlines\n matInputErrors = sapply(collapseCloneResults,function(x){return(x[[2]])}) \n }\n\n\n# Selection Analysis\n\n \n# if (length(germlines)>sequenceLimit) {\n# # Code to parallelize processing goes here\n# stop( paste(\"Error: Cannot process more than \", Upper_limit,\" sequences\",sep=\"\") )\n# }\n\n# if (length(germlines)1){\n groups <- c(groups,lenGroups+1)\n names(groups)[length(groups)] = \"All sequences combined\"\n bayesPDF_groups_cdr[[lenGroups+1]] = groupPosteriors(bayesPDF_groups_cdr,length_sigma=4001)\n bayesPDF_groups_fwr[[lenGroups+1]] = groupPosteriors(bayesPDF_groups_fwr,length_sigma=4001)\n }\n \n #Bayesian Outputs\n bayes_cdr = t(sapply(bayesPDF_cdr,calcBayesOutputInfo))\n bayes_fwr = t(sapply(bayesPDF_fwr,calcBayesOutputInfo))\n bayes_germlines_cdr = t(sapply(bayesPDF_germlines_cdr,calcBayesOutputInfo))\n bayes_germlines_fwr = t(sapply(bayesPDF_germlines_fwr,calcBayesOutputInfo))\n bayes_groups_cdr = t(sapply(bayesPDF_groups_cdr,calcBayesOutputInfo))\n bayes_groups_fwr = t(sapply(bayesPDF_groups_fwr,calcBayesOutputInfo))\n \n #P-values\n simgaP_cdr = sapply(bayesPDF_cdr,computeSigmaP)\n simgaP_fwr = sapply(bayesPDF_fwr,computeSigmaP)\n \n simgaP_germlines_cdr = sapply(bayesPDF_germlines_cdr,computeSigmaP)\n simgaP_germlines_fwr = sapply(bayesPDF_germlines_fwr,computeSigmaP)\n \n simgaP_groups_cdr = sapply(bayesPDF_groups_cdr,computeSigmaP)\n simgaP_groups_fwr = sapply(bayesPDF_groups_fwr,computeSigmaP)\n \n \n #Format output\n \n # Round expected mutation frequencies to 3 decimal places\n matMutationInfo[germlinesOriginal[indelPos],] = NA\n if(nrow(matMutationInfo)==1){\n matMutationInfo[5:8] = round(matMutationInfo[,5:8]/sum(matMutationInfo[,5:8],na.rm=T),3)\n }else{\n matMutationInfo[,5:8] = t(round(apply(matMutationInfo[,5:8],1,function(x){ return(x/sum(x,na.rm=T)) }),3))\n }\n \n listPDFs = list()\n nRows = length(unique(groups)) + length(unique(germlines)) + length(groups)\n \n matOutput = matrix(NA,ncol=18,nrow=nRows)\n rowNumb = 1\n for(G in unique(groups)){\n #print(G)\n matOutput[rowNumb,c(1,2,11:18)] = c(\"Group\",names(groups)[groups==G][1],bayes_groups_cdr[G,],bayes_groups_fwr[G,],simgaP_groups_cdr[G],simgaP_groups_fwr[G])\n listPDFs[[rowNumb]] = list(\"CDR\"=bayesPDF_groups_cdr[[G]],\"FWR\"=bayesPDF_groups_fwr[[G]])\n names(listPDFs)[rowNumb] = names(groups[groups==paste(G)])[1]\n #if(names(groups)[which(groups==G)[1]]!=\"All sequences combined\"){\n gs = unique(germlines[groups==G])\n rowNumb = rowNumb+1\n if( !is.na(gs) ){\n for( g in gs ){\n matOutput[rowNumb,c(1,2,11:18)] = c(\"Germline\",names(germlines)[germlines==g][1],bayes_germlines_cdr[g,],bayes_germlines_fwr[g,],simgaP_germlines_cdr[g],simgaP_germlines_fwr[g])\n listPDFs[[rowNumb]] = list(\"CDR\"=bayesPDF_germlines_cdr[[g]],\"FWR\"=bayesPDF_germlines_fwr[[g]])\n names(listPDFs)[rowNumb] = names(germlines[germlines==paste(g)])[1]\n rowNumb = rowNumb+1\n indexesOfInterest = which(germlines==g)\n numbSeqsOfInterest = length(indexesOfInterest)\n rowNumb = seq(rowNumb,rowNumb+(numbSeqsOfInterest-1))\n matOutput[rowNumb,] = matrix( c( rep(\"Sequence\",numbSeqsOfInterest),\n rownames(matInput)[indexesOfInterest],\n c(matMutationInfo[indexesOfInterest,1:4]),\n c(matMutationInfo[indexesOfInterest,5:8]),\n c(bayes_cdr[indexesOfInterest,]),\n c(bayes_fwr[indexesOfInterest,]),\n c(simgaP_cdr[indexesOfInterest]),\n c(simgaP_fwr[indexesOfInterest]) \n ), ncol=18, nrow=numbSeqsOfInterest,byrow=F)\n increment=0\n for( ioi in indexesOfInterest){\n listPDFs[[min(rowNumb)+increment]] = list(\"CDR\"=bayesPDF_cdr[[ioi]] , \"FWR\"=bayesPDF_fwr[[ioi]])\n names(listPDFs)[min(rowNumb)+increment] = rownames(matInput)[ioi]\n increment = increment + 1\n }\n rowNumb=max(rowNumb)+1\n\n }\n }\n }\n colsToFormat = 11:18\n matOutput[,colsToFormat] = formatC( matrix(as.numeric(matOutput[,colsToFormat]), nrow=nrow(matOutput), ncol=length(colsToFormat)) , digits=3)\n matOutput[matOutput== \" NaN\"] = NA\n \n \n \n colnames(matOutput) = c(\"Type\", \"ID\", \"Observed_CDR_R\", \"Observed_CDR_S\", \"Observed_FWR_R\", \"Observed_FWR_S\",\n \"Expected_CDR_R\", \"Expected_CDR_S\", \"Expected_FWR_R\", \"Expected_FWR_S\",\n paste( rep(testName,6), rep(c(\"Sigma\",\"CIlower\",\"CIupper\"),2),rep(c(\"CDR\",\"FWR\"),each=3), sep=\"_\"),\n paste( rep(testName,2), rep(\"P\",2),c(\"CDR\",\"FWR\"), sep=\"_\")\n )\n fileName = paste(outputPath,outputID,\".txt\",sep=\"\")\n write.table(matOutput,file=fileName,quote=F,sep=\"\\t\",row.names=T,col.names=NA)\n fileName = paste(outputPath,outputID,\".RData\",sep=\"\")\n save(listPDFs,file=fileName)\n\nindelWarning = FALSE\nif(sum(indelPos)>0){\n indelWarning = \"

Warning: The following sequences have either gaps and/or deletions, and have been ommited from the analysis.\";\n indelWarning = paste( indelWarning , \"

    \", sep=\"\" )\n for(indels in names(indelPos)[indelPos]){\n indelWarning = paste( indelWarning , \"
  • \", indels, \"
  • \", sep=\"\" )\n }\n indelWarning = paste( indelWarning , \"

\", sep=\"\" )\n}\n\ncloneWarning = FALSE\nif(clonal==1){\n if(sum(matInputErrors)>0){\n cloneWarning = \"

Warning: The following clones have sequences of unequal length.\";\n cloneWarning = paste( cloneWarning , \"

    \", sep=\"\" )\n for(clone in names(matInputErrors)[matInputErrors]){\n cloneWarning = paste( cloneWarning , \"
  • \", names(germlines)[as.numeric(clone)], \"
  • \", sep=\"\" )\n }\n cloneWarning = paste( cloneWarning , \"

\", sep=\"\" )\n }\n}\ncat(paste(\"Success\",outputID,indelWarning,cloneWarning,sep=\"|\"))\n", "meta": {"hexsha": "abb8c5ca05eb1a8a04a7e2e2d039093137d79d80", "size": 17368, "ext": "r", "lang": "R", "max_stars_repo_path": "baseline/Baseline_Main.r", "max_stars_repo_name": "ESehlhoff/shm_csr", "max_stars_repo_head_hexsha": "78ace939ed7437b8b360588032449a99aad949eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-20T12:39:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T12:39:30.000Z", "max_issues_repo_path": "baseline/Baseline_Main.r", "max_issues_repo_name": "ESehlhoff/shm_csr", "max_issues_repo_head_hexsha": "78ace939ed7437b8b360588032449a99aad949eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-09-10T14:28:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-10T14:28:41.000Z", "max_forks_repo_path": "baseline/Baseline_Main.r", "max_forks_repo_name": "ESehlhoff/shm_csr", "max_forks_repo_head_hexsha": "78ace939ed7437b8b360588032449a99aad949eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-09-28T11:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T11:16:11.000Z", "avg_line_length": 44.64781491, "max_line_length": 187, "alphanum_fraction": 0.6080723169, "num_tokens": 4944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.03161877000619939, "lm_q1q2_score": 0.01506886237661713}} {"text": "## Created on Friday, August 27, 2021 at 7:14pm EDT by Weekend Editor on WeekendEditorMachine.\n## Copyright (c) 2021, SomeWeekendReading.blog. All rights reserved. As if you care.\n\ntoolsDir <- \"../../tools\" # Various tools available from author\nsource(file.path(toolsDir, \"graphics-tools.r\")) # Various graphics hacks\n\n##\n## After accounting for age and vax status to evade Simpson's paradox, show vaccine efficacy\n## in Israel (which has much better medical records than the US!) vs age cohort.\n##\n\ndoit <- function(cohorts = c(\"12-15\", \"16-19\", \"20-29\", \"30-39\", \"40-49\", \"50-59\",\n \"60-69\", \"70-79\", \"80-89\", \"90+\"),\n efficacies = c(100.0, 100.0, 100.0, 96.8, 93.9, 92.8,\n 88.7, 89.6, 81.1, 92.4),\n plotFile = \"./2021-08-29-covid-simpson-ve-by-age.png\") {\n ## *** IWBNI we knew 95% cl bars on the efficacies, say by posterior Beta + Monte Carlo method\n withPNG(plotFile, 400, 400, FALSE, function() { # Capture graphics to file\n withPars(function() { # Save/restore graphics params\n plot(x = 1 : length(cohorts), y = efficacies, # Plot points & lines\n type = \"b\", pch = 21, col = \"black\", bg = \"blue\",\n xaxt = \"n\", xlab = NA, ylab = \"Vaccine Efficacy (%)\", ylim = c(0, 100),\n main = \"Vaccine efficacy by age cohort\") # Horizontal axis done manually\n axis(side = 1, at = 1 : length(cohorts), labels = cohorts)\n title(xlab = \"Age Cohort\", line = 3.5) # Horizontal axis title\n }, pty = \"m\", # Maximal plotting area\n bg = \"white\", # White background\n mar = c(5, 3, 2, 1), # Margins for axis labels, title\n mgp = c(1.7, 0.5, 0), # Axis title, labels, ticks\n ps = 16, # Larger type size for file capture\n las = 2) # Axis labels always perp to axis\n }) # Done!\n} #\n", "meta": {"hexsha": "832222347f6943acdd5e8dbc8180a8730c8c2b68", "size": 2257, "ext": "r", "lang": "R", "max_stars_repo_path": "assets/2021-08-29-covid-simpson-ve-by-age.r", "max_stars_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_stars_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "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": "assets/2021-08-29-covid-simpson-ve-by-age.r", "max_issues_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_issues_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-10-14T16:09:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-18T21:01:06.000Z", "max_forks_repo_path": "assets/2021-08-29-covid-simpson-ve-by-age.r", "max_forks_repo_name": "SomeWeekendReading/SomeWeekendReading.github.io", "max_forks_repo_head_hexsha": "e9b63e1668a0c267dd053bbd0e3357e4c38142e0", "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.3823529412, "max_line_length": 96, "alphanum_fraction": 0.4847142224, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.0316187652154802, "lm_q1q2_score": 0.014945667868498392}} {"text": "#' Matching Estimators with Network Data\n#'\n#' \\strong{WARNING}: This function is still in development and has not been tested throughly.\n#' Following Aral et al. (2009), \\code{netmatch} computes matching\n#' estimators for network data. The function \\code{netmatch_prepare}, which\n#' prepares the data to be used with \\code{\\link[MatchIt:matchit]{matchit}} from\n#' the \\pkg{\\link[MatchIt:MatchIt]{MatchIt}} package, is called by \\code{netmatch}.\n#'\n#' @param dat \\code{data.frame} with dynamic data. Must be of\n#' \\code{nrow(dat)==nslices(graph)*nnodes(graph)}.\n#' @param graph List with sparse matrices.\n#' @param timevar Character scalar. Name of time variable\n#' @param depvar Character scalar. Name of the dependent variable\n#' @param covariates Character vector. Name(s) of the control variable(s).\n#' @param adopt_thr Either a numeric scalar or vector of length \\code{nslices(graph)}.\n#' Sets the threshold of \\code{depvar} at which it is considered that an observation\n#' has adopted a behavior.\n#' @param treat_thr Either a numeric scalar or vector of length \\code{nslices(graph)}.\n#' Sets the threshold of \\code{exposure} at which it is considered that an\n#' observation is treated.\n#' @param expo_pcent Logical scalar. When \\code{TRUE}, exposure is computed\n#' non-normalized (so it is a count rather than a percentage).\n#' @param expo_lag Integer scalar. Number of lags to consider when computing\n#' exposure. \\code{expo_lag=1} defines exposure in T considering behavior and\n#' network at T-1.\n#' @param ... Further arguments to be passed to \\code{\\link[MatchIt:matchit]{matchit}}.\n#' @return In the case of \\code{netmatch_prepare}\n#' \\item{dat}{A \\code{data.frame} with the original data (covariates), plus the\n#' following new variables: \\code{treat}, \\code{adopt}, \\code{exposure}.\n#' }\n#' \\item{match_model}{A formula to be passed to \\code{netmatch}}\n#'\n#' \\code{netmatch} returns the following:\n#' \\item{fATT}{A numeric vector of length \\eqn{N_1}{N1} (number of treated used\n#' in the matching process). Treatment effects on the treated at the individual\n#' level}\n#' \\item{match_obj}{The output from \\code{matchit}.}\n#' @name netmatch\n#' @author\n#' George G. Vega Yon\n#' @references\n#' Aral, S., Muchnik, L., & Sundararajan, A. (2009). Distinguishing\n#' influence-based contagion from homophily-driven diffusion in dynamic networks.\n#' Proceedings of the National Academy of Sciences of the United States of America,\n#' 106(51), 21544–21549. \\doi{10.1073/pnas.0908800106}\n#'\n#' Imbens, G. W., & Wooldridge, J. M. (2009). Recent Developments in the\n#' Econometrics of Program Evaluation. Journal of Economic Literature, 47(1),\n#' 5–86. \\doi{10.1257/jel.47.1.5}\n#'\n#' King, G., & Nielsen, R. (2015). Why Propensity Scores Should Not Be Used for.\n#'\n#' Sekhon, J. S. (2008). The Neyman-Rubin Model of Causal Inference and Estimation\n#' Via Matching Methods. The Oxford Handbook of Political Methodology.\n#' \\doi{10.1093/oxfordhb/9780199286546.003.0011}\n#' @details\n#'\n#' In Aral et al. (2009), the matching estimator is used as a response to the\n#' fact that the observed network is homophilous. Essentially, using exposure\n#' as a treatment indicator, which is known to be endogenous, we can apply the\n#' same principle of matching estimators in which, after controlling for characteristics\n#' (covariates), individuals from the treated group (exposed to some behavior)\n#' can be compared to individuals from the control group (not exposed to that\n#' behavior), as the only difference between the two is the exposure.\n#'\n#' As pointed out in King & Nielsen (2015), it is suggested that, contrary to\n#' what Aral et al. (2009), the matching is not performed over propensity score\n#' since it is know that the later can increase imbalances in the data and thus\n#' obtaining exactly the opposed outcome that matching based estimators pursue.\n#'\n#' A couple of good references for matching estimators are Imbens and Wooldridge\n#' (2009), and Sekhon (2008).\nNULL\n\n#' @export\n#' @rdname netmatch\nnetmatch_prepare <- function (\n dat, graph, timevar, depvar, covariates,\n treat_thr = rep(1L, length(graph)),\n adopt_thr = rep(1L, length(graph)),\n expo_pcent = FALSE,\n expo_lag = 0L\n) {\n\n # Subset\n Y <- as.matrix(dat[, depvar, drop=FALSE])\n X <- as.matrix(dat[, covariates, drop=FALSE])\n Time <- as.matrix(dat[, timevar, drop=FALSE])\n\n # Checking thresholds\n if (length(treat_thr)==1)\n treat_thr <- rep(treat_thr, length(graph))\n if (length(adopt_thr)==1)\n adopt_thr <- rep(adopt_thr, length(graph))\n\n # Obtaining constants\n pers <- sort(unique(Time))\n npers <- length(pers)\n n <- length(Y)/npers\n\n if (expo_lag >= npers)\n stop(\"Not enought time points for such lag.\")\n\n # Generating exposures and treatment\n expo <- matrix(NA, ncol=npers, nrow=n)\n adopt <- matrix(NA, ncol=npers, nrow=n)\n treat <- matrix(NA, ncol=npers, nrow=n)\n ans <- vector(\"list\", npers)\n for (i in seq_along(pers)) {\n\n # Subset data\n per <- pers[i]\n y <- Y[Time == per,, drop=FALSE]\n x <- X[Time == per,, drop=FALSE]\n\n # Computing exposure and seting treatment\n adopt[,i] <- as.integer(y >= adopt_thr[i])\n\n # Skiping lags\n if (i <= expo_lag) next\n\n # Computing exposure (and normalizing if required)\n expo[,i] <- as.vector(graph[[i-expo_lag]] %*% adopt[,i-expo_lag,drop=FALSE])\n if (expo_pcent)\n expo[,i] <- expo[,i]/(Matrix::rowSums(graph[[i-expo_lag]]) + 1e-20)\n\n # Assigning regime\n treat[,i] <- as.integer(expo[,i] >= treat_thr[i])\n\n # Creating dataset\n ans[[i]] <- data.frame(Y=y, X=x, treat=treat[,i],\n adopt = adopt[,i-expo_lag],\n expo = expo[,i], check.names = FALSE)\n colnames(ans[[i]]) <-\n c(\"Y\", covariates, \"treat\", \"adopt\", \"expo\")\n\n }\n\n # Model\n match_model <- as.formula(paste(\"treat ~\", paste0(covariates, collapse=\" + \")))\n\n # Returning outcome\n return(list(dat=ans, match_model=match_model))\n}\n\n\n#' @rdname netmatch\n#' @export\nnetmatch <- function(\n dat, graph, timevar, depvar, covariates,\n treat_thr = rep(1L, length(graph)),\n adopt_thr = rep(1L, length(graph)),\n expo_pcent = FALSE,\n expo_lag = 0L, ...) {\n\n # No so good for now.\n if (nslices(graph) != 2)\n stop(\"-netmatch- is currently supported only for nslices(graph) == 2.\")\n\n # Preparing the data\n ans <- netmatch_prepare(dat=dat, graph = graph, timevar = timevar,\n depvar = depvar, covariates = covariates,\n treat_thr = treat_thr, adopt_thr = adopt_thr,\n expo_pcent = expo_pcent, expo_lag = expo_lag)\n\n # print(str(ans[[1]]))\n # Processing the data so we can use it with -matchit-\n dat <- ans$dat[[2]]\n rownames(dat) <- 1:nrow(dat)\n\n # Matching (with replacement)\n match_obj <- MatchIt::matchit(ans$match_model, data=dat, ...)\n\n mmethod <- match_obj$call$method\n if (length(mmethod) && (\"cem\" %in% mmethod)) {\n\n # Retrieving sub classes\n dat1 <- MatchIt::match.data(match_obj, \"treat\")\n dat0 <- MatchIt::match.data(match_obj, \"control\")\n\n # Computing effect. At the end CEM gives weights (very simple)\n # coef(lm(Y~treat, data=match.data(match_obj), weights=weights))[\"treat\"]\n fATT <- with(dat1, sum(Y*weights)/sum(weights)) -\n with(dat0, sum(Y*weights)/sum(weights))\n\n } else {\n match_index <- match_obj$match.matrix\n\n # Computing feasible Average Treatment Effect on the Treated\n fATT <- dat[,\"Y\"]\n\n matched_control <- lapply(1:nrow(match_index), function(x) {\n x <- match_index[x,,drop=TRUE]\n as.integer(x[!is.na(x)])\n })\n\n # Computing differences\n fATT <-Map(function(i1, i0) mean(fATT[i1] - fATT[i0]),\n i0=as.integer(rownames(match_index)),\n i1=matched_control\n )\n\n fATT <- mean(unlist(fATT, recursive = TRUE), na.rm=TRUE)\n }\n\n\n # Wrapping up\n return(list(\n fATT = fATT,\n match_obj = match_obj,\n exposures = dat$expo\n )\n )\n\n}\n", "meta": {"hexsha": "532fc37b6b7f855137914e3a96248626c2ad4bbd", "size": 7972, "ext": "r", "lang": "R", "max_stars_repo_path": "R/netmatch.r", "max_stars_repo_name": "USCCANA/netdiffuseR", "max_stars_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2015-12-15T02:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T02:48:37.000Z", "max_issues_repo_path": "R/netmatch.r", "max_issues_repo_name": "USCCANA/netdiffuseR", "max_issues_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30, "max_issues_repo_issues_event_min_datetime": "2015-12-17T03:43:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T18:50:22.000Z", "max_forks_repo_path": "R/netmatch.r", "max_forks_repo_name": "USCCANA/netdiffuseR", "max_forks_repo_head_hexsha": "4cda66a4381c2df3ee2d738f6c97ac0b2916a5c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-12-28T21:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-22T19:48:08.000Z", "avg_line_length": 36.9074074074, "max_line_length": 93, "alphanum_fraction": 0.6714751631, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.034618837220668094, "lm_q1q2_score": 0.01423218026159579}} {"text": "#' @export\n#' @title coordinates.db\n#' @description this is an assortment of coordinates for commonly used objects\n#' @param \\code{item} the desired object. Valid values are 'gully','nens.ss.6-7','nens.ss.5-6','nens.ss.4-5','nens.ss.3-4','nens.ss.2-3','nens.ss.1-2','nens.ss.outside.1','nens.ss.outside.2','gulf-ss','nens-sens','cfa23.inshore-offshore','cfa23-cfa24','sens-cfa4x','shrimp.nw.sable','shrimp.louisburg','shrimp.bad.neighbours'\n#' @return \\code{} \n#' @examples\n#' coordinates.db('gully')\n#' @note It is tempting to mark this as deprecated, as it is not clear that these objects will be updated to reflect a more definitive source \n#' @author unknown, \\email{@@dfo-mpo.gc.ca}\n#' @export\n coordinates.db = function( item ) {\n \n if ( item==\"gully\" ) {\n a = as.data.frame( matrix( c( \n -59.10051192315181,44.21678274656149,\n -59.33516115171256,44.10057784448195,\n -59.13782200164582,43.91718619192973,\n -59.13430015596633,43.58357892651157,\n -58.58296879641245,43.58284385250472,\n -58.58345034613519,43.78360045129342,\n -59.10051192315181,44.21678274656149\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.6-7\" ) {\n a = as.data.frame( matrix( c( \n -59.8669459147477,46.61829003097517,\n -59.86714927555937,46.1903922915425\n ), ncol=2, byrow=T ) )\n \n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n\n if ( item==\"nens.ss.5-6\" ) {\n a = as.data.frame( matrix( c( \n -60.15013169910874,46.61686051036362,\n -60.15070296987705,46.25403077923779\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.4-5\" ) {\n a = as.data.frame( matrix( c( \n -58.57169296505639,46.61743715738334,\n -60.35101630484722,46.61743036291101\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.3-4\" ) {\n a = as.data.frame( matrix( c( \n -60.32934961857659,46.73377402095574,\n -58.70455622211595,46.73425821633046\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.2-3\" ) {\n a = as.data.frame( matrix( c( \n -60.29739776341232,46.8490837267233,\n -58.83935581691834,46.8522334225455\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.1-2\" ) {\n a = as.data.frame( matrix( c( \n -60.39965967598059,47.00047832780142,\n -59.01461782671211,47.00028076937365\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.outside.1\" ) {\n a = as.data.frame( matrix( c( \n -59.99891390682926,47.83103013198976,\n -58.56775382241514,46.61649379280151\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens.ss.outside.2\" ) {\n a = as.data.frame( matrix( c( \n -57.78591208190541,46.00109962205628,\n -58.56775382241514,46.61649379280151\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"gulf-ss\" ) {\n a = as.data.frame( matrix( c( \n -60.41568418984078,47.03853523297152,\n -60.00014897319883,47.83408958793515 \n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"nens-sens\" ) {\n a = as.data.frame( matrix( c( \n -59.85247480316924,46.00291960992756,\n -57.78560987011954,46.00106076110973\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"cfa23.inshore-offshore\" ) {\n a = as.data.frame( matrix( c( \n -59.92853837122961,44.69774735070251,\n -58.41005287016962,46.00038380222262\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"cfa23-cfa24\" ) {\n a = as.data.frame( matrix( c( \n -60.66040620990439,45.58083805201212,\n -59.11881785180857,43.67610276909335\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"sens-cfa4x\" ) {\n a = as.data.frame( matrix( c( \n -63.52502801857509,44.5005704612574,\n -63.33296001561555,44.33343763428088,\n -63.33161397633095,42.50186912534272\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"shrimp.nw.sable\" ) {\n a = as.data.frame( matrix( c( \n -60.53348522264675,44.16713857065227,\n -59.83402446317178,44.16674842805921,\n -59.8337724318864,44.35020211840867,\n -60.53437630895549,44.35056350439965,\n -60.53348522264675,44.16713857065227\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"shrimp.louisburg\" ) {\n a = as.data.frame( matrix( c( \n -59.16722567748156,45.50037490107675,\n -58.11756232854311,45.50029678441212,\n -58.11736586354162,45.91675134337378,\n -59.16724395727103,45.91694991968841,\n -59.16722567748156,45.50037490107675\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"shrimp.eastern\" ) {\n a = as.data.frame( matrix( c( \n -60.99983106518073,44.58360971012488,\n -58.0005005513048,44.58361575122798,\n -58.00112052095971,44.9165492050831,\n -58.66697123168657,44.91801611900925,\n -58.66586013724016,45.00054787436935,\n -61.00063058037657,45.00080688407766,\n -60.99983106518073,44.58360971012488\n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n if ( item==\"shrimp.bad.neighbours\" ) {\n a = as.data.frame( matrix( c( \n -60.95065555250798,45.31550857725852,\n -60.08311721156429,45.46714417665778,\n -60.08371925586215,45.80040191216285 \n ), ncol=2, byrow=T ) )\n a$elevation = 0\n names( a ) = c(\"lon\", \"lat\", \"elevation\" )\n return( a )\n }\n \n }\n\n\n", "meta": {"hexsha": "d6f47b1b927d84f5351530f9c14621af46302e1e", "size": 6834, "ext": "r", "lang": "R", "max_stars_repo_path": "R/coordinates.db.r", "max_stars_repo_name": "AtlanticR/bio.utilities", "max_stars_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "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/coordinates.db.r", "max_issues_repo_name": "AtlanticR/bio.utilities", "max_issues_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "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/coordinates.db.r", "max_forks_repo_name": "AtlanticR/bio.utilities", "max_forks_repo_head_hexsha": "aaa52cf86afa4ee9e6f46c4516a48d27cc0bfed9", "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.7860465116, "max_line_length": 326, "alphanum_fraction": 0.5570676032, "num_tokens": 2528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423539898095244, "lm_q2_score": 0.042722195108838804, "lm_q1q2_score": 0.013852047976456444}} {"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# Read GNU MathProg model \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# Read GNU MathProg model\n# based on Rglpk_read_file, modified to eliminate objective fn from constraint matrix\n#' @export \n############################################################################### \nRglpk.read.model <- function(file, type = c(\"MPS_fixed\", \"MPS_free\", \"CPLEX_LP\", \"MathProg\"), ignore_first_row = FALSE, verbose = FALSE){\n\tif(!file.exists(file)) stop(paste(\"There is no file called\", file, \"!\"))\n\t\n \ttype_db <- c(\"MPS_fixed\" = 1L, \"MPS_free\" = 2L, \"CPLEX_LP\" = 3L, \"MathProg\" = 4L)\n \tobj <- list(file = tools::file_path_as_absolute(file), type = type_db[match.arg(type)])\n \t\n\tmeta_data <- Rglpk:::glp_get_meta_data_from_file(obj, verbose)\n\tmilp_data <- Rglpk:::glp_retrieve_MP_from_file(meta_data, ignore_first_row, verbose)\n\tMP_data <- Rglpk:::glp_merge_MP_data(meta_data, milp_data)\n\t\n\tdir_db <- c(\"free\" = 1L, \">=\" = 2L, \"<=\" = 3L, \"DB\" = 4L, \"==\" = 5L)\n \tMP_data$direction_of_constraints <- names(dir_db[MP_data$direction_of_constraints])\n \t\n\ttypes <- rep(\"C\", length.out = MP_data$n_objective_vars)\n \tif(any(MP_data$objective_var_is_integer)) types[MP_data$objective_var_is_integer] <- \"I\" \t\n \tif(any(MP_data$objective_var_is_binary)) types[MP_data$objective_var_is_binary] <- \"B\" \t\n \tMP_data$types = types\n \t\n\t# remove objective fn from constraints\n\tindex = which(MP_data$direction_of_constraints == 'free')\n\tif( length(index) > 0 ) {\n\t\tMP_data$constraint_matrix = as.matrix(MP_data$constraint_matrix)[-index,]\n\t\tMP_data$direction_of_constraints = MP_data$direction_of_constraints[-index]\n\t\tMP_data$right_hand_side = MP_data$right_hand_side[-index]\t\n\t} \n\tMP_data\n}\n\n\n###############################################################################\n# Create constraints structure from model data (Rglpk.read.model)\n#' @export \n############################################################################### \nRglpk.create.constraints <- function( prob ) \n{ \n\t#--------------------------------------------------------------------------\n\t# Create constraints\n\t#--------------------------------------------------------------------------\n\tn = prob$n_objective_vars\n\t\n\tlb = rep(NA,n)\n\t\tlb[prob$bounds$lower$ind] = prob$bounds$lower$val\n\tub = rep(NA,n)\n\t\tub[prob$bounds$upper$ind] = prob$bounds$upper$val\n\tconstraints = new.constraints(n, lb = lb, ub = ub)\n\t\n\t# binary variables\n\tconstraints$binary.index = which(prob$objective_var_is_binary == 1)\t\n\tif(len(constraints$binary.index) == 0) constraints$binary.index = 0\n\t\t\t\t\t\n\t#constraints\n\tif(is.null(dim(prob$constraint_matrix))) {\n\t\tprob$constraint_matrix = matrix(prob$constraint_matrix)\n\t} else {\n\t\tprob$constraint_matrix = t(prob$constraint_matrix)\n\t}\n\t\n\tindex = which(prob$direction_of_constraints == '==') \n\tif(len(index)>0) constraints = add.constraints(prob$constraint_matrix[,index], type = '=', b = prob$right_hand_side[index], constraints)\n\t\n\tindex = which(prob$direction_of_constraints == '<=') \n\tif(len(index)>0) constraints = add.constraints(prob$constraint_matrix[,index], type = '<=', b = prob$right_hand_side[index], constraints)\n\n\tindex = which(prob$direction_of_constraints == '>=') \n\tif(len(index)>0) constraints = add.constraints(prob$constraint_matrix[,index], type = '>=', b = prob$right_hand_side[index], constraints)\n\t\n\t# objective function\n\tf.obj = prob$objective_coefficients\n\tdir = ifelse(prob$maximize, 'max', 'min')\n\n \tprob$names = prob$objective_vars_names\n \tprob$tickers = prob$objective_vars_names\n\t\n # find tickers wgt[AAPL]\n if(len(grep('\\\\[',prob$objective_vars_names)) > 0) {\n temp = matrix(spl(gsub(']','', prob$objective_vars_names),'\\\\['), nr=2)\n \tprob$names = temp[1,]\n \tprob$tickers = temp[2,]\n }\n\t\n\treturn(list(constraints=constraints, f.obj=f.obj, dir=dir, prob=prob))\n}\n \n\n\n\n###############################################################################\n# Parse Views / Constraints using GNU Mathprog specifications\n#' @export \n############################################################################### \nparse.views = function(symbolnames, views) {\n\tload.packages('Rglpk')\n\n\tviews = parse.expr(views)\n\tif (len(views)==0)\n\t\treturn(list(\n\t\t\tA = matrix(0, nr=0, nc=len(symbolnames)),\n\t\t\tb = c(),\n\t\t\tmeq = 0\n\t\t))\t\n\t\nmodel.file = tempfile('temp.model')\non.exit(unlink(model.file))\t\n\t\n\t# create GNU MathProg model\n\tcat(\"\t\n###############################################################################\t\n# Define Variables\n\", join(paste0('var ', symbolnames, '>=0;'),'\\n'), \"\n\n# Define Objective\nminimize objective : \", join(symbolnames, '+'), \";\n\n# Define Constraints\n\", join(paste0('V', 1:len(views), ':', views,';'),'\\n'), \"\n \n###############################################################################\n\t\", file = model.file, append = FALSE)\n\t\n\t#--------------------------------------------------------------------------\n\t# Read GNU MathProg model/Setup constraints/Solve QP problem\n\t#--------------------------------------------------------------------------\t\n\t# read model\n\tmodel = Rglpk.read.model(model.file,type = 'MathProg') \t\n\n\t# convert GNU MathProg model to constraint used in solve.QP\n\ttemp = Rglpk.create.constraints(model)$constraints\t\n\t\n\tA = t(as.matrix(temp$A))\n\t\tcolnames(A) = symbolnames\n\t\n\tlist(\n\t\tA = A,\n\t\tb = temp$b,\n\t\tmeq = temp$meq\n\t)\n}\t\n\t\n\n\n###############################################################################\n# Helper function to find Minimum Variance Portfolio\n#' @export \n############################################################################### \nmin.var.portfolio.gmpl <- function(ia, constraints)\n{\n\t#--------------------------------------------------------------------------\n\t# Adjust Covariance matrix\n\t#--------------------------------------------------------------------------\n\tload.packages('quadprog,corpcor')\n\t\n\tcov.temp = ia$cov\n\t\n\t# check if there are dummy variables\n\tn0 = ia$n\n\tn = nrow(constraints$A)\t\t\t\n\tif( n != nrow(cov.temp) ) {\n\t\ttemp = matrix(0, n, n)\n\t\ttemp[1:n0, 1:n0] = cov.temp[1:n0, 1:n0]\n\t\tcov.temp = temp\n\t}\t\n\t\n\tif(!is.positive.definite(cov.temp)) {\n\t\tcov.temp <- make.positive.definite(cov.temp, 0.000000001)\n\t}\t\n\t\n\t#--------------------------------------------------------------------------\n\t# Solve QP problem\n\t#--------------------------------------------------------------------------\n\tbinary.vec = 0\n\tif(!is.null(constraints$binary.index)) binary.vec = constraints$binary.index\n\t\n\tsol = solve.QP.bounds(Dmat = cov.temp, dvec = rep(0, nrow(cov.temp)) , \n\t\tAmat=constraints$A, bvec=constraints$b, constraints$meq,\n\t\tlb = constraints$lb, ub = constraints$ub, binary.vec = binary.vec)\n\n\tif(binary.vec[1] != 0) cat(sol$counter,'QP calls made to solve problem with', len(binary.vec), 'binary variables using Branch&Bound', '\\n')\t\t\n\t\n\tx = sol$solution[1:ia$n]\n\t\tnames(x) = ia$symbols\n\n\treturn(x)\n}\t\t\n\n\n###############################################################################\n# Portfolio Optimization: Specify constraints with GNU MathProg language\n#\n# Examples:\n# http://en.wikibooks.org/wiki/GLPK/GMPL_%28MathProg%29\n# http://en.wikibooks.org/wiki/GLPK/Literature#Official_GLPK_documentation\n#\n# The GNU Linear Programming Kit (GLPK) : Resources, Tutorials\n# http://spokutta.wordpress.com/tag/gnu-mathprog/\n###############################################################################\nportopt.mathprog.test <- function( ) \n{\n\t#*****************************************************************\n\t# Load packages\n\t#****************************************************************** \n\tload.packages('quantmod,quadprog,corpcor')\n\t\t\t\n\t#--------------------------------------------------------------------------\n\t# Create historical input assumptions\n\t#--------------------------------------------------------------------------\n\ttickers = dow.jones.components()\n\tia = aa.test.create.ia.custom(tickers, dates = '2000::2010')\n\t\n\t#--------------------------------------------------------------------------\n\t# Create Constraints & Solve QP problem\n\t#--------------------------------------------------------------------------\n\tn = ia$n\t\t\n\n\t# 0 <= x.i <= 1 \n\tconstraints = new.constraints(n, lb = 0, ub = 1)\n\n\t# SUM x.i = 1\n\tconstraints = add.constraints(rep(1, n), 1, type = '=', constraints)\t\t\n\t\n\t# Solve QP problem\n\tx = min.var.portfolio.gmpl(ia, constraints)\t\n\t\n\t# plot weights\npng(filename = 'plot1.png', width = 600, height = 400, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tbarplot(100*x, las=2, main='Minimum Variance Portfolio')\ndev.off()\t\n\t\n\n\t\n\t\n\t\n\t\n\t#*****************************************************************\n\t# Load packages\n\t#****************************************************************** \n\t# load Rglpk to read GNU MathProg files\n\tload.packages('Rglpk')\n\t\t\n\t#--------------------------------------------------------------------------\n\t# Create Constraints: GNU MathProg model\n\t#--------------------------------------------------------------------------\n\tmodel.file = 'model1.mod'\n\t\n\t# create GNU MathProg model\n\tcat('\t\n###############################################################################\t\nset SYMBOLS ;\t\n\t\n# set min/max weights for individual stocks\nvar weight{i in SYMBOLS} >= 0, <= 1 ;\n \n# objective function, NOT USED\nminimize alpha : sum{i in SYMBOLS} weight[i] ;\n \n# weights must sum to 1 (fully invested)\nsubject to fully_invested : sum{i in SYMBOLS} weight[i] = 1 ;\n\ndata;\n\nset SYMBOLS := ', ia$symbols, ';\n###############################################################################\n\t', file = model.file, append = FALSE)\n\n\t#--------------------------------------------------------------------------\n\t# Read GNU MathProg model/Setup constraints/Solve QP problem\n\t#--------------------------------------------------------------------------\t\n\t# read model\n\tmodel = Rglpk.read.model(model.file,type = 'MathProg') \t\n\n\t# convert GNU MathProg model to constraint used in solve.QP\n\tconstraints = Rglpk.create.constraints(model)$constraints\t\n\t\t\n\t# Solve QP problem\n\tx = min.var.portfolio.gmpl(ia, constraints)\t\n\t\n\t# plot weights\npng(filename = 'plot2.png', width = 600, height = 400, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tbarplot(100*x, las=2, main='Minimum Variance Portfolio using GNU MathProg model')\ndev.off()\t\n\n\t\n\t#--------------------------------------------------------------------------\n\t# Create Constraints: GNU MathProg model\n\t# Control Minimum Investment and Number of Assets: Portfolio Cardinality Constraints\n\t# http://systematicinvestor.wordpress.com/2011/10/20/minimum-investment-and-number-of-assets-portfolio-cardinality-constraints/\n\t#--------------------------------------------------------------------------\n\tmodel.file = 'model2.mod'\n\t\n\t# create GNU MathProg model\n\tcat('\t\n###############################################################################\t\nset SYMBOLS ;\t\n\t\n# set min/max weights for individual stocks\nvar weight{i in SYMBOLS} >= 0, <= 1 ;\n \n# add binary, 1 if held, 0 if not held\nvar held{SYMBOLS} binary;\n\n# objective function, NOT USED\nminimize alpha : sum{i in SYMBOLS} weight[i] ;\n \n# weights must sum to 1 (fully invested)\nsubject to fully_invested : sum{i in SYMBOLS} weight[i] = 1 ;\n\n# min weight constraint for individual asset\nsubject to MinWgt {i in SYMBOLS} : weight[i] >= 0.025 * held[i];\n \n# max weight constraint for individual asset\nsubject to MaxWgt {i in SYMBOLS} : weight[i] <= .20 * held[i] ;\n\n# number of stocks in portfolio\nsubject to MaxAssetsLB : 0 <= sum {i in SYMBOLS} held[i] ;\nsubject to MaxAssetsUB : sum {i in SYMBOLS} held[i] <= 6 ;\n \ndata;\n\nset SYMBOLS := ', ia$symbols, ';\n###############################################################################\n\t', file = model.file, append = FALSE)\n\t\n\t#--------------------------------------------------------------------------\n\t# Read GNU MathProg model/Setup constraints/Solve QP problem\n\t#--------------------------------------------------------------------------\t\n\t# read model\n\tmodel = Rglpk.read.model(model.file,type = 'MathProg') \t\n\n\t# convert GNU MathProg model to constraint used in solve.QP\n\tconstraints = Rglpk.create.constraints(model)$constraints\t\n\t\t\n\t# Solve QP problem\n\tx = min.var.portfolio.gmpl(ia, constraints)\t\n\t\n\t# plot weights\npng(filename = 'plot3.png', width = 600, height = 400, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tbarplot(100*x, las=2, main='Minimum Variance Portfolio using GNU MathProg model \\n with Minimum Investment and Number of Assets Constraints')\ndev.off()\t\n\n\t\n\t#--------------------------------------------------------------------------\n\t# Create Constraints: GNU MathProg model\n\t# Control Long and Short positions based on 130/30 Portfolio Construction\n\t# http://systematicinvestor.wordpress.com/2011/10/18/13030-porfolio-construction/\n\t#--------------------------------------------------------------------------\n\tmodel.file = 'model3.mod'\n\n\t# create GNU MathProg model\n\tcat('\t\n###############################################################################\t\nset SYMBOLS ;\t\n\t\n# set min/max weights for individual stocks\nvar long {i in SYMBOLS} >= 0, <= 0.8 ;\nvar short{i in SYMBOLS} >= 0, <= 0.5 ;\n \n# add binary, 1 if long, 0 if short\nvar islong{SYMBOLS} binary;\n\n# objective function, NOT USED\nminimize alpha : sum{i in SYMBOLS} long[i] ;\n \n# weights must sum to 1 (fully invested)\nsubject to fully_invested : sum{i in SYMBOLS} (long[i] - short[i]) = 1 ;\n\n# leverage is 1.6 = longs + shorts\nsubject to leverage : sum{i in SYMBOLS} (long[i] + short[i]) = 1.6 ;\n\n# force long and short to be mutually exclusive (only one of them is greater then 0 for each i)\nsubject to long_flag {i in SYMBOLS} : long[i] <= islong[i] ;\nsubject to short_flag {i in SYMBOLS} : short[i] <= (1 - islong[i]) ;\n \ndata;\n\nset SYMBOLS := ', ia$symbols, ';\n###############################################################################\n\t', file = model.file, append = FALSE)\n\t\n\t#--------------------------------------------------------------------------\n\t# Read GNU MathProg model/Setup constraints/Solve QP problem\n\t#--------------------------------------------------------------------------\t\n\t# read model\n\tmodel = Rglpk.read.model(model.file,type = 'MathProg') \t\n\n\t# convert GNU MathProg model to constraint used in solve.QP\n\tconstraints = Rglpk.create.constraints(model)$constraints\t\n\t\t\n\t# Solve QP problem, modify Input Assumptions to include short positions\n\tx = min.var.portfolio.gmpl(aa.test.ia.add.short(ia), constraints)\t\n\t\n\t# Compute total weight = longs - short\n\tx = x[1:ia$n] - x[-c(1:ia$n)]\n\t\n\t# plot weights\npng(filename = 'plot4.png', width = 600, height = 400, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tbarplot(100*x, las=2, main='Minimum Variance Portfolio using GNU MathProg model \\n with 130:30 Constraints')\ndev.off()\t\n\t\n\n\n\n\n\t# reduce problem size\n\tia = aa.test.create.ia.custom(tickers[1:15], dates = '2000::2010')\n\n\t#--------------------------------------------------------------------------\n\t# Create Constraints: GNU MathProg model\n\t# Turnover Constraints : Control Maximum Trade Size and Number of Trades\n\t#--------------------------------------------------------------------------\n\tmodel.file = 'model4.mod'\n\n\t# create parameters to hold Current Weight\n\tparam = ia$cov[,1,drop=F]\n\t\tcolnames(param) = 'CurWgt'\n\t\tparam[,'CurWgt'] = 1/ia$n\n\t\t\n\t\n\t# create GNU MathProg model\n\tcat('\t\n###############################################################################\t\nset SYMBOLS ;\t\n\t\nparam CurWgt{SYMBOLS} ;\n\n# set min/max weights for individual stocks\nvar weight{i in SYMBOLS} >= 0, <= 1 ;\n\n# TradePos[i] - TradeNeg[i] = CurWgt[i] - weight[i]\nvar TradePos{i in SYMBOLS} >= 0 ;\nvar TradeNeg{i in SYMBOLS} >= 0 ;\n\n# Only one of TradePos or TradeNeg is > 0\nvar TradeFlag{SYMBOLS} binary;\n\n# add binary, 1 if traded, 0 if not traded\nvar trade{SYMBOLS} binary;\n\n# objective function, NOT USED\nminimize alpha : sum{i in SYMBOLS} weight[i] ;\n \n# weights must sum to 1 (fully invested)\nsubject to fully_invested : sum{i in SYMBOLS} weight[i] = 1 ;\n\n# setup Trades for individual asset\nsubject to TradeRange {i in SYMBOLS} : (CurWgt[i] - weight[i]) = (TradePos[i] - TradeNeg[i]) ;\n\n# Only one of TradePos or TradeNeg is > 0\nsubject to TradeFlagPos {i in SYMBOLS} : TradePos[i] <= 100 * TradeFlag[i];\nsubject to TradeFlagNeg {i in SYMBOLS} : TradeNeg[i] <= 100 * (1 - TradeFlag[i]);\n\n# min trade size constraint for individual asset\nsubject to MinTradeSize {i in SYMBOLS} : (TradePos[i] + TradeNeg[i]) >= 0.01 * trade[i];\nsubject to MaxTradeSize {i in SYMBOLS} : (TradePos[i] + TradeNeg[i]) <= .90 * trade[i] ; \n\n# number of trades in portfolio\nsubject to MaxTrade : sum {i in SYMBOLS} trade[i] <= 48 ;\n \ndata;\n\nset SYMBOLS := ', ia$symbols, ';\n\nparam : CurWgt:=\n\t', file = model.file, append = FALSE)\n\t\nwrite.table(param, sep='\\t', quote = F, col.names = F, file = model.file, append = TRUE)\ncat('; \n###############################################################################\n\t', file = model.file, append = TRUE)\n\n\t\n\t#--------------------------------------------------------------------------\n\t# Read GNU MathProg model/Setup constraints/Solve QP problem\n\t#--------------------------------------------------------------------------\t\n\tmodel = Rglpk.read.model(model.file,type = 'MathProg') \t\n\tconstraints = Rglpk.create.constraints(model)$constraints\t\n\t\n\n\t# Solve QP problem\n\tx = min.var.portfolio.gmpl(ia, constraints)\t\n\t\tsqrt(x %*% ia$cov %*% x)\n\t\n\t\n\t# plot weights\npng(filename = 'plot5.png', width = 600, height = 400, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tbarplot(100*x, las=2, main='Minimum Variance Portfolio using GNU MathProg model \\n with Turnover Constraints')\ndev.off()\t\t\n\n\n\n\n\n\n\n\n\n\n# reduce problem size\nia = aa.test.create.ia.custom(tickers[1:10], dates = '2000::2010')\n\n\n\t#--------------------------------------------------------------------------\n\t# Create Constraints: GNU MathProg model\n\t# Turnover Constraints : Control Maximum Trade Size and Number of Trades\n\t#--------------------------------------------------------------------------\n\tmodel.file = 'model4.mod'\n\n\t# create parameters to hold Current Weight\n\tparam = ia$cov[,1,drop=F]\n\t\tcolnames(param) = 'CurWgt'\n\t\tparam[,'CurWgt'] = 1/ia$n\n\t\t\n\t\n\t# create GNU MathProg model\n\tcat('\t\n###############################################################################\t\nset SYMBOLS ;\t\n\t\nparam CurWgt{SYMBOLS} ;\n\n# set min/max weights for individual stocks\nvar weight{i in SYMBOLS} >= 0, <= 1 ;\n\n# TradePos[i] - TradeNeg[i] = CurWgt[i] - weight[i]\nvar TradePos{i in SYMBOLS} >= 0 ;\nvar TradeNeg{i in SYMBOLS} >= 0 ;\n\n# Only one of TradePos or TradeNeg is > 0\nvar TradeFlag{SYMBOLS} binary;\n\n# add binary, 1 if traded, 0 if not traded\nvar trade{SYMBOLS} binary;\n\n# objective function, NOT USED\nminimize alpha : sum{i in SYMBOLS} weight[i] ;\n \n# weights must sum to 1 (fully invested)\nsubject to fully_invested : sum{i in SYMBOLS} weight[i] = 1 ;\n\n# setup Trades for individual asset\nsubject to TradeRange {i in SYMBOLS} : (CurWgt[i] - weight[i]) = (TradePos[i] - TradeNeg[i]) ;\n\n# Only one of TradePos or TradeNeg is > 0\nsubject to TradeFlagPos {i in SYMBOLS} : TradePos[i] <= 100 * TradeFlag[i];\nsubject to TradeFlagNeg {i in SYMBOLS} : TradeNeg[i] <= 100 * (1 - TradeFlag[i]);\n\n# min trade size constraint for individual asset\nsubject to MinTradeSize {i in SYMBOLS} : (TradePos[i] + TradeNeg[i]) >= 0.05 * trade[i];\nsubject to MaxTradeSize {i in SYMBOLS} : (TradePos[i] + TradeNeg[i]) <= .20 * trade[i] ; \n\n# number of trades in portfolio\nsubject to MaxTrade : sum {i in SYMBOLS} trade[i] <= 8 ;\n \ndata;\n\nset SYMBOLS := ', ia$symbols, ';\n\nparam : CurWgt:=\n\t', file = model.file, append = FALSE)\n\t\nwrite.table(param, sep='\\t', quote = F, col.names = F, file = model.file, append = TRUE)\ncat('; \n###############################################################################\n\t', file = model.file, append = TRUE)\n\n\t\n\t#--------------------------------------------------------------------------\n\t# Read GNU MathProg model/Setup constraints/Solve QP problem\n\t#--------------------------------------------------------------------------\t\n\tmodel = Rglpk.read.model(model.file,type = 'MathProg') \t\n\tconstraints = Rglpk.create.constraints(model)$constraints\t\n\t\n\n\t# Solve QP problem\n\tx = min.var.portfolio.gmpl(ia, constraints)\t\n\t\tsqrt(x %*% ia$cov %*% x)\n\t\n\t\n\t# plot weights\npng(filename = 'plot6.png', width = 600, height = 400, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tbarplot(100*x, las=2, main='Minimum Variance Portfolio using GNU MathProg model \\n with Turnover Constraints')\ndev.off()\t\t\n\n\n\n\n\n}\n\n\n\n\t\t\t\t\t", "meta": {"hexsha": "8bb8c84a06925b6b9aa0977ff7add2ab0b3f55ff", "size": 21524, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/aa.gmpl.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/aa.gmpl.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/aa.gmpl.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": 34.8849270665, "max_line_length": 142, "alphanum_fraction": 0.5380040885, "num_tokens": 5092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.028436032118571066, "lm_q1q2_score": 0.013109487943725203}} {"text": "MetaAnalysis.RVE <- function(\r\n data, \r\n measureType = \"r\",\r\n measureCol = \"Corr\", \r\n n = \"n\", \r\n grping1, grping2,\r\n published = \"Published\",\r\n PA = NULL,\r\n zTrans = F,\r\n user_beta = NULL)\r\n{\r\n notes <- c()\r\n \r\n # Remove empty samples\r\n data$n <- data[[n]]\r\n data <- subset(data, data$n > 0)\r\n \r\n # Define grouping, effect-size and published columns\r\n data$grp1 <- data[[grping1]]\r\n data$grp2 <- data[[grping2]]\r\n data$Meas <- data[[measureCol]]\r\n MeasInit <- data$Meas\r\n data$published <- as.logical(data[[published]])\r\n grping1_lvls <- levels(data$grp1)\r\n \r\n nName <- n\r\n \r\n # Get sample variances\r\n if (zTrans) {\r\n data <- escalc(\r\n ri = Meas,\r\n ni = n, \r\n measure = \"ZCOR\",\r\n data = data,\r\n var.names = c(\"Meas\", \"Var\")\r\n )\r\n } else if (measureType == \"r\") {\r\n data <- escalc(\r\n ri = Meas,\r\n ni = n, \r\n measure = \"COR\",\r\n data = data,\r\n var.names = c(\"Meas\", \"Var\")\r\n )\r\n } else if (measureType == \"k\") {\r\n pci <- (data[[PA]] - data$Meas) / (1 - data$Meas)\r\n data$Var <- data[[PA]] * (1 - data[[PA]]) / ((1 - pci) ^ 2 * data$n)\r\n } else if (measureType == \"p\") {\r\n data$Var <- data$Meas * (1 - data$Meas) / (data$n + 1e-4)\r\n } else {\r\n stop(\"Unknown 'measureType' specified.\")\r\n }\r\n \r\n # Remove any undefined data (and take notes)\r\n if (any(is.na(data$Meas))) {\r\n notes <- c(notes, paste0(\r\n \"\\tThe following rows were removed because the effect-size was undefined:\\n\\n\"))\r\n notes <- c(notes, paste0(\r\n \"\\t * Grp 1 - \", data$grp1[is.na(data$Meas)], \", Grp 2 - \", data$grp2[is.na(data$Meas)],\r\n \" (Original effect-size: \", MeasInit[is.na(data$Meas)], \")\\n\"))\r\n notes <- c(notes, \"\\n\")\r\n data <- data[!is.na(data$Meas),]\r\n }\r\n \r\n # Make sure none of variances are 0, otherwise analysis will fail\r\n data$Var[data$Var == 0] <- 1e-9\r\n \r\n # Build random-effects models using Robust Variance Estimation\r\n # Also run sensitivity analysis on rho and conduct Egger's regression test for bias\r\n REModels <- list()\r\n rhoSensitivity <- list()\r\n eggersRegTest <- list()\r\n dataList <- list()\r\n for (grping in grping1_lvls) {\r\n if (sum(data$grp1 == grping) > 1)\r\n {\r\n data.grp = data[data$grp1 == grping,]\r\n \r\n # Calculate random effects model\r\n argList <- list(\r\n formula = Meas ~ 1,\r\n data = data.grp,\r\n studynum = data.grp$grp2,\r\n var.eff.size = data.grp$Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\"\r\n )\r\n REModels[[grping]] <- do.call(robu, argList)\r\n dataList[[grping]] <- data.grp\r\n \r\n if (!is.null(user_beta))\r\n {\r\n REModels[[grping]]$reg_table$b.r <- user_beta[[grping]]$b.r\r\n REModels[[grping]]$reg_table$SE <- user_beta[[grping]]$SE\r\n REModels[[grping]]$reg_table$CI.L <- user_beta[[grping]]$CI.L\r\n REModels[[grping]]$reg_table$CI.U <- user_beta[[grping]]$CI.U\r\n REModels[[grping]]$data.full$r.weights <- user_beta[[grping]]$mdlWeights\r\n }\r\n \r\n dataList[[grping]]$mdlWeights <- REModels[[grping]]$data.full$r.weights\r\n dataList[[grping]]$mdlWeights2 <- REModels[[grping]]$data.full$weights\r\n \r\n # Perform sensitivity analysis\r\n tmp <- capture.output(rhoSensitivity[[grping]] <- sensitivity(REModels[[grping]]))\r\n \r\n if (sum(data.grp$published) > 2 && measureType != \"p\") {\r\n # Conduct regression test\r\n eggersRegTest[[grping]] <- robu(\r\n formula = Meas ~ 1 + sqrt(Var),\r\n data = data.grp[data.grp$published,],\r\n studynum = grp2,\r\n var.eff.size = Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\",\r\n userweights = REModels[[grping]]$data.full$r.weights[data.grp$published]\r\n )\r\n } else {\r\n eggersRegTest[[grping]] <- list(reg_table = list(prob = c(NaN,NaN)))\r\n }\r\n } else {\r\n data.grp = data[data$grp1 == grping,]\r\n dataList[[grping]] <- data.grp\r\n if (nrow(data.grp) > 0) dataList[[grping]]$mdlWeights <- 1\r\n notes <- c(notes, paste0(\"\\tSkipped '\", grping, \"' - \", sum(data$grp1 == grping), \" studies.\\n\"))\r\n }\r\n }\r\n \r\n crossTab <- table(data$grp1)\r\n data.grp <- data[data$grp1 %in% names(crossTab)[crossTab > 0], ]\r\n argList <- list(\r\n formula = Meas ~ 1,\r\n data = data.grp,\r\n studynum = data.grp$grp2,\r\n var.eff.size = data.grp$Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\"\r\n )\r\n REModels$overall <- do.call(robu, argList)\r\n dataList$overall <- data.grp\r\n \r\n if (!is.null(user_beta))\r\n {\r\n REModels$overall$reg_table$b.r <- user_beta$overall$b.r\r\n REModels$overall$reg_table$SE <- user_beta$overall$SE\r\n REModels$overall$reg_table$CI.L <- user_beta$overall$CI.L\r\n REModels$overall$reg_table$CI.U <- user_beta$overall$CI.U\r\n REModels$overall$data.full$r.weights <- user_beta$overall$mdlWeights\r\n }\r\n \r\n dataList$overall$mdlWeights <- REModels$overall$data.full$r.weights\r\n\r\n tmp <- capture.output(rhoSensitivity$overall <- sensitivity(REModels$overall))\r\n \r\n if (measureType != \"p\")\r\n eggersRegTest$overall <- robu(\r\n formula = Meas ~ 1 + sqrt(Var),\r\n data = data.grp[data.grp$published,],\r\n studynum = grp2,\r\n var.eff.size = Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\",\r\n userweights = REModels$overall$data.full$r.weights[data.grp$published]\r\n )\r\n \r\n return(\r\n list(\r\n REModels = REModels,\r\n rhoSensitivity = rhoSensitivity,\r\n eggersRegTest = eggersRegTest,\r\n data = data,\r\n dataList = dataList,\r\n notes = notes,\r\n measureType = measureType,\r\n zTrans = zTrans\r\n )\r\n )\r\n}\r\n\r\nSummary.RVE <- function(\r\n RVEModel,\r\n fileName,\r\n studyName = \"Authors\"\r\n)\r\n{\r\n output <- c()\r\n \r\n # Unpack\r\n REModels <- RVEModel$REModels\r\n rhoSensitivity <- RVEModel$rhoSensitivity\r\n eggersRegTest <- RVEModel$eggersRegTest\r\n notes <- RVEModel$notes\r\n zTrans <- RVEModel$zTrans\r\n measureType <- RVEModel$measureType\r\n dataList <- RVEModel$dataList\r\n \r\n output <- c(output, \"Notes\\n-----\\n\", paste(notes, collapse = \"\"), \"\\n\")\r\n \r\n # Get first level groupings\r\n grping1_lvls <- names(REModels)\r\n \r\n for (grping in grping1_lvls)\r\n {\r\n # Print group heading\r\n output <- c(output, \"\\n\\n========\", grping, \"========\\n\\n\")\r\n \r\n # Print model statistics and tests\r\n Q <- t(REModels[[grping]]$data.full$e) %*% \r\n diag(REModels[[grping]]$data.full$weights) %*% \r\n REModels[[grping]]$data.full$e\r\n \r\n if (zTrans) {\r\n output <- c(output, \"\\tEffect-size (z): \\t\", REModels[[grping]]$reg_table$b.r, \"\\n\")\r\n output <- c(output, \"\\tEffect-size (eff-size): \\t\", tanh(REModels[[grping]]$reg_table$b.r), \"\\n\")\r\n output <- c(output, \"\\tStandard error (z): \\t\", REModels[[grping]]$reg_table$SE, \"\\n\")\r\n } else if (measureType == \"p\") {\r\n output <- c(output, \"\\tEffect-size (log-odds): \\t\", REModels[[grping]]$reg_table$b.r, \"\\n\")\r\n output <- c(output, \"\\tEffect-size (eff-size): \\t\", 1/(1+exp(-REModels[[grping]]$reg_table$b.r)), \"\\n\")\r\n output <- c(output, \"\\tStandard error (log-odds):\\t\", REModels[[grping]]$reg_table$SE, \"\\n\")\r\n } else {\r\n output <- c(output, \"\\tEffect-size (eff-size): \\t\", REModels[[grping]]$reg_table$b.r, \"\\n\")\r\n output <- c(output, \"\\tStandard error (eff-size):\\t\", REModels[[grping]]$reg_table$SE, \"\\n\")\r\n }\r\n output <- c(output, \"\\tk (ind. samples): \\t\", length(unique(dataList[[grping]]$grp2)), \"\\n\")\r\n output <- c(output, \"\\tn (participants): \\t\", sum(aggregate(n ~ grp2, data = dataList[[grping]], max)$n), \"\\n\")\r\n output <- c(output, \"\\tp-value: \\t\", REModels[[grping]]$reg_table$prob, \"\\n\")\r\n output <- c(output, \"\\tdf: \\t\", REModels[[grping]]$reg_table$dfs, \"\\n\")\r\n output <- c(output, \"\\tI.sq: \\t\", REModels[[grping]]$mod_info$I.2, \"\\n\")\r\n output <- c(output, \"\\tQ-test: \\t\", Q, \"\\n\")\r\n output <- c(output, \"\\tTau.sq: \\t\", REModels[[grping]]$mod_info$tau.sq, \"\\n\\n\")\r\n \r\n output <- c(output, \"\\tEgger's Regression Test for Bias\\n\\n\")\r\n \r\n if (is.nan(eggersRegTest[[grping]]$reg_table$prob[2])) {\r\n output <- c(output, \"\\t\\tEgger's test not defined (probably not enough data)\\n\\n\")\r\n } else {\r\n output <- c(output, \"\\t\\tp-value: \\t\", eggersRegTest[[grping]]$reg_table$prob[2], \r\n if (eggersRegTest[[grping]]$reg_table$prob[2] < 0.05) \"*\" else \"\", \"\\n\")\r\n output <- c(output, \"\\t\\tdf: \\t\", eggersRegTest[[grping]]$reg_table$dfs[2], \"\\n\\n\")\r\n }\r\n \r\n # Print sensitivity analysis\r\n output <- c(output, \"\\tIntra-study clustering sensitivity analysis:\\n\")\r\n output <- c(output, paste0(\"\\t\\t\", capture.output(rhoSensitivity[[grping]]), sep = \"\\n\"))\r\n }\r\n \r\n cat(output)\r\n capture.output(cat(output), file = fileName)\r\n \r\n flush.console()\r\n invisible()\r\n}\r\n\r\n\r\nforest.RVE <- function(\r\n RVEModel,\r\n studyNames,\r\n sampleNames,\r\n effSizeName,\r\n fileName,\r\n extraCol = NULL,\r\n extraColName = NULL,\r\n fullData = NULL\r\n) \r\n{\r\n # Unpack\r\n REModels <- RVEModel$REModels\r\n data <- RVEModel$data\r\n zTrans <-RVEModel$zTrans\r\n data$study <- as.character(data[[studyNames]])\r\n data$sample <- data[[sampleNames]]\r\n grping1_lvls <- levels(data$grp1)\r\n \r\n measScale <- 1\r\n if (RVEModel$measureType == \"p\")\r\n {\r\n measScale <- 100\r\n }\r\n data$Meas <- data$Meas * measScale\r\n \r\n if (!is.null(extraCol)) {\r\n data$extra <- data[[extraCol]]\r\n }\r\n \r\n if (zTrans) {\r\n transf <- tanh\r\n } else {\r\n transf <- function(x) {x}\r\n }\r\n \r\n # Get weights; summary effects and standard errors; and n sums for plotting\r\n effSize <- c()\r\n standErr <- c()\r\n ci.lb <- c()\r\n ci.ub <- c()\r\n nSum <- c()\r\n data$weight <- NA\r\n for (grping in grping1_lvls)\r\n {\r\n indx <- data$grp1 == grping & !is.na(data$n)\r\n if (sum(indx) > 1) {\r\n data$weight[indx] <- REModels[[grping]]$data.full$r.weights / \r\n sum(REModels[[grping]]$data.full$r.weights) * 100\r\n \r\n effSize[grping] <- REModels[[grping]]$reg_table$b.r\r\n standErr[grping] <- REModels[[grping]]$reg_table$SE\r\n ci.lb[grping] <- REModels[[grping]]$reg_table$CI.L\r\n ci.ub[grping] <- REModels[[grping]]$reg_table$CI.U\r\n nSum[grping] <- sum(aggregate(n ~ grp2, data = data[indx,], max)$n)\r\n } else {\r\n data$weight[indx] <- 100\r\n effSize[grping] <- NA\r\n standErr[grping] <- NA\r\n ci.lb[grping] <- NA\r\n ci.ub[grping] <- NA\r\n nSum[grping] <- NA\r\n }\r\n }\r\n \r\n # Sort data by level 1 and level 2 grouping and add an id\r\n data <- data %>% arrange(as.integer(grp1), study)\r\n data$ID <- 1:nrow(data)\r\n \r\n # Define headings for studies with multiple endpoints\r\n for (grping1 in grping1_lvls)\r\n {\r\n data.grp <- data[data$grp1 == grping1,]\r\n for (grping2 in unique(data.grp$grp2))\r\n {\r\n data.grp2 <- data.grp[data.grp$grp2 == grping2,]\r\n if (nrow(data.grp2) > 1) {\r\n minID <- min(data.grp2$ID)\r\n study <- data.grp2$study[1]\r\n indx <- data$grp1 == grping1 & data$grp2 == grping2\r\n data$study[indx] <- paste0(\" \", data$sample[indx])\r\n data <- rbindlist(\r\n list(data, \r\n data.frame(grp1 = grping1, grp2 = grping2, study = study, ID = minID - 0.5, \r\n n = max(data.grp2$n), weight = sum(data.grp2$weight), stringsAsFactors = F)),\r\n fill = T)\r\n }\r\n }\r\n }\r\n # Re-sort data\r\n data <- data %>% arrange(ID)\r\n \r\n # Define forest plot row formatting\r\n headingLocations <- c()\r\n summaryLocations <- c()\r\n sampleLocations <- c()\r\n \r\n for (grping in grping1_lvls)\r\n {\r\n if (length(headingLocations) == 0)\r\n {\r\n headingLocations <- 1\r\n }\r\n else\r\n {\r\n headingLocations <- c(headingLocations, max(c(sampleLocations, summaryLocations)) + 2)\r\n }\r\n sampleLocations <- c(\r\n sampleLocations, \r\n max(headingLocations) + seq(1,sum(data$grp1 == grping),length = sum(data$grp1 == grping))\r\n )\r\n # if (sum(data$grp1 == grping) != 1)\r\n summaryLocations <- c(summaryLocations, max(headingLocations) + sum(data$grp1 == grping) + 1)\r\n }\r\n maxLocations <- max(summaryLocations, sampleLocations, headingLocations)\r\n headingLocations <- maxLocations - headingLocations + 1\r\n sampleLocations <- maxLocations - sampleLocations + 1\r\n summaryLocations <- maxLocations - summaryLocations + 1\r\n \r\n # Add indent to study names for formatting\r\n data$study <- paste0(\" \", data$study)\r\n\r\n # Split out study headings and samples\r\n studyHeadingLocations <- sampleLocations[is.na(data$Meas)]\r\n sampleLocations <- sampleLocations[!is.na(data$Meas)]\r\n studyHeadings <- data$study[is.na(data$Meas)]\r\n studyHeadingsN <- data$n[is.na(data$Meas)]\r\n studyHeadingsWeight <- round(data$weight[is.na(data$Meas)], 2)\r\n data <- data[!is.na(data$Meas),]\r\n \r\n # Reset zero variances to zero and unity correlations to unity\r\n if (!zTrans) {\r\n data$Meas[data$Meas == 1] <- 1-1e-8\r\n data$Var[data$Var < 1e-8] <- 0\r\n }\r\n \r\n # Initialise forest plot with sample effect-sizes and CIs\r\n cex = 1.5\r\n op <- par(mar=c(4,4,0,2))\r\n ylim <- c(-1, maxLocations+3)\r\n efac <- 0.4\r\n digits <- if (RVEModel$measureType == \"p\") 1 else 2\r\n slab.col <- rep(\"black\", nrow(data))\r\n slab.col[grep(\" \", data$study)] <- \"dimgray\"\r\n anno.pos <- 2.5 * measScale\r\n if (is.null(extraCol)) {\r\n ilab = cbind(data$n, format(round(data$weight,2), trim = F))\r\n ilab.xpos <- c(-1.9, -1.2) * measScale + if (RVEModel$measureType == \"p\") measScale else 0\r\n ilab.pos <- 2\r\n xlim <- c(if (RVEModel$measureType == \"p\") -4 else -5, 2.5) * measScale\r\n colLabels <- c(\"N\", \"Weight\", paste(effSizeName, \"[95% CI]\"))\r\n } else {\r\n ilab = cbind(data$n, format(round(data$weight,2), trim = F), data$extra)\r\n ilab.xpos <- c(c(-1.9, -1.2) * measScale + if (RVEModel$measureType == \"p\") measScale else 0, 3 * measScale)\r\n ilab.pos <- 2\r\n xlim <- c(if (RVEModel$measureType == \"p\") -4 else -5, 3) * measScale\r\n colLabels <- c(\"N\", \"Weight\", extraColName, paste(effSizeName, \"[95% CI]\"))\r\n }\r\n \r\n \r\n tiff(filename = fileName,\r\n width=18, height = 3+25*maxLocations/75, units = \"cm\", res = 600,\r\n compression = \"lzw\", pointsize = 6)\r\n forest.col(\r\n x = data$Meas,\r\n vi = data$Var * measScale^2,\r\n xlim = xlim,\r\n alim = c(if (RVEModel$measureType == \"p\") 0 else -1, 1) * measScale,\r\n ylim = ylim,\r\n digits = digits,\r\n xlab = effSizeName,\r\n slab = data$study,\r\n ilab = ilab,\r\n ilab.xpos = ilab.xpos,\r\n ilab.pos = ilab.pos,\r\n transf = transf,\r\n rows = sampleLocations,\r\n efac = efac,\r\n cex = cex,\r\n slab.col = slab.col,\r\n anno.pos = anno.pos,\r\n refline = if (RVEModel$measureType == \"p\") c(0, 0.25, 0.5, 0.75, 1)*measScale else 0\r\n )\r\n \r\n # Add study headings (level 2 groupings)\r\n if (length(studyHeadings) > 0) {\r\n text(\r\n x = xlim[1],\r\n y = studyHeadingLocations,\r\n labels = studyHeadings,\r\n cex = cex,\r\n pos = 4\r\n )\r\n text(\r\n x = ilab.xpos[1],\r\n y = studyHeadingLocations,\r\n labels = studyHeadingsN,\r\n cex = cex,\r\n pos = 2\r\n )\r\n text(\r\n x = ilab.xpos[2],\r\n y = studyHeadingLocations,\r\n labels = format(studyHeadingsWeight),\r\n cex = cex,\r\n pos = 2\r\n )\r\n }\r\n \r\n # Add level 1 grouping headings\r\n text(\r\n x = xlim[1],\r\n y = headingLocations,\r\n labels = grping1_lvls,\r\n cex = cex,\r\n pos = 4,\r\n font = 4\r\n )\r\n \r\n # Add level 1 group summaries and overall summary\r\n grpIncl <- grping1_lvls %in% names(REModels)\r\n text(\r\n x = c(rep(ilab.xpos[1], sum(grpIncl)), rep(ilab.xpos[2], sum(grpIncl))),\r\n y = rep(summaryLocations[grpIncl], 2),\r\n labels = c(nSum[grpIncl], rep(\"100.00\", sum(grpIncl))),\r\n cex = cex,\r\n pos = ilab.pos,\r\n font = 2\r\n )\r\n text(\r\n x = c(ilab.xpos[1], ilab.xpos[2]),\r\n y = ylim[1],\r\n labels = c(sum(aggregate(n ~ grp2, data = data, max)$n), \"100.00\"),\r\n cex = cex,\r\n pos = ilab.pos,\r\n font = 2\r\n )\r\n \r\n if(sum(!grpIncl) > 0)\r\n text(\r\n x = c(rep(ilab.xpos[1], sum(!grpIncl)), rep(ilab.xpos[2], sum(!grpIncl))),\r\n y = rep(summaryLocations[!grpIncl], 2),\r\n labels = rep(\"N/A\", sum(!grpIncl)*2),\r\n cex = cex,\r\n pos = ilab.pos,\r\n font = 2\r\n )\r\n \r\n addpoly.col(\r\n x = effSize[grpIncl],\r\n ci.lb = ci.lb[grpIncl],\r\n ci.ub = ci.ub[grpIncl],\r\n rows = summaryLocations[grpIncl],\r\n cex = cex,\r\n mlab = rep(\" RE Model\", sum(grpIncl)),\r\n transf = transf,\r\n efac = efac, \r\n digits = digits,\r\n font = 2,\r\n anno.pos = anno.pos\r\n )\r\n addpoly.col(\r\n x = REModels$overall$reg_table$b.r,\r\n sei = REModels$overall$reg_table$SE,\r\n rows = ylim[1],\r\n cex = cex,\r\n mlab = \"Overall RE Model\",\r\n transf = transf,\r\n efac = efac, \r\n digits = digits,\r\n font = 2,\r\n anno.pos = anno.pos\r\n )\r\n \r\n # Add column labels\r\n text(\r\n x = c(ilab.xpos, anno.pos),\r\n y = maxLocations + 2,\r\n labels = colLabels,\r\n cex = cex,\r\n pos = ilab.pos,\r\n font = 2\r\n )\r\n \r\n dev.off()\r\n \r\n invisible()\r\n}\r\n\r\nfunnel.RVE <- function(\r\n RVEModel,\r\n fileName,\r\n trimnfill = T,\r\n plotReg = T,\r\n effSizeName = \"Cohen's kappa\"\r\n)\r\n{\r\n # Unpack\r\n data <- RVEModel$data\r\n zTrans <- RVEModel$zTrans\r\n REModels <- RVEModel$REModels\r\n eggersRegTest <- RVEModel$eggersRegTest\r\n grping1_lvls <- names(REModels)\r\n grpIncl <- grping1_lvls %in% levels(data$grp1)\r\n overallB <- REModels$overall$reg_table$b.r\r\n data$standErr <- sqrt(data$Var)\r\n maxStandErr <- max(data$standErr, na.rm = T)\r\n \r\n if (plotReg)\r\n {\r\n # Get Egger's regression line\r\n xEgg <- seq(-1,1,0.001)\r\n mdl <- REModels$overall\r\n egg <- eggersRegTest$overall\r\n intercept <- -egg$reg_table$b.r[1]/egg$reg_table$b.r[2]\r\n gradient <- 1/egg$reg_table$b.r[2]\r\n regLine <- xEgg * gradient + intercept\r\n print(paste0(\"Egger's regression p-value: \", egg$reg_table$prob[2]))\r\n \r\n if (zTrans)\r\n regLine <- tanh(regLine)\r\n }\r\n \r\n if (trimnfill)\r\n {\r\n tnf <- meta::trimfill.default(\r\n data$Meas[data$published], \r\n data$standErr[data$published],\r\n left = T,\r\n sm = if (zTrans) \"ZCOR\" else \"COR\",\r\n ma.fixed = F,\r\n type = \"L\"\r\n )\r\n \r\n tnf_Meas <- tnf$TE[tnf$trimfill]\r\n tnf_standErr <- tnf$seTE[tnf$trimfill]\r\n tnf_study <- tnf$studlab[tnf$trimfill]\r\n \r\n if (zTrans)\r\n {\r\n tnf_standErr <- (tanh(tnf_Meas + tnf_standErr) - tanh(tnf_Meas - tnf_standErr)) / 2\r\n tnf_Meas <- tanh(tnf_Meas)\r\n }\r\n }\r\n \r\n if (zTrans)\r\n {\r\n data$standErr <- (tanh(data$Meas + sqrt(data$Var)) - tanh(data$Meas - sqrt(data$Var))) / 2\r\n data$Meas <- tanh(data$Meas)\r\n maxStandErr <- max(data$standErr)\r\n overallB <- tanh(overallB)\r\n }\r\n \r\n op <- par(mar = c(4,4,1,2))\r\n tiff(filename = fileName,\r\n width = 15, height = 12, units = \"cm\", res = 600,\r\n compression = \"lzw\", pointsize = 8)\r\n \r\n funnel(\r\n x = c(-99, -99),\r\n vi = c(99, 99),\r\n yaxis = \"sei\",\r\n xlim = c(-1, 1),\r\n ylim = c(0, maxStandErr),\r\n xlab = effSizeName,\r\n back = \"white\",\r\n shade = F,\r\n hlines = \"white\",\r\n pch = 1,\r\n cex = 1,\r\n refline = overallB\r\n )\r\n box()\r\n \r\n points(\r\n x = data$Meas[data$published],\r\n y = data$standErr[data$published],\r\n # pch = as.integer(data$grp1[data$published]),\r\n pch = 1,\r\n cex = 1\r\n )\r\n points(\r\n x = data$Meas[!data$published],\r\n y = data$standErr[!data$published],\r\n pch = 16,\r\n cex = 1\r\n )\r\n\r\n if (plotReg)\r\n {\r\n lines(xEgg[regLine >= 0], regLine[regLine >= 0], lty = 2)\r\n }\r\n \r\n if (trimnfill && length(tnf_Meas)>0)\r\n {\r\n points(\r\n x = tnf_Meas,\r\n y = tnf_standErr,\r\n pch = 17,\r\n cex = 1\r\n )\r\n \r\n crossTab <- table(data$grp1)\r\n data.grp <- data[data$grp1 %in% names(crossTab)[crossTab > 0], ]\r\n tnf.data.grp <- data.frame(\r\n grp2 = tnf_study,\r\n Meas = tnf_Meas,\r\n n = data$n[as.numeric(gsub(\"Filled: \", \"\", tnf_study))]\r\n )\r\n data.grp <- rbind.fill(data.grp, tnf.data.grp)\r\n \r\n data.grp <- escalc(\r\n ri = Meas,\r\n ni = n, \r\n measure = if (zTrans) \"ZCOR\" else \"COR\",\r\n data = data.grp,\r\n var.names = c(\"Meas\", \"Var\")\r\n )\r\n argList <- list(\r\n formula = Meas ~ 1,\r\n data = data.grp,\r\n studynum = data.grp$grp2,\r\n var.eff.size = data.grp$Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\"\r\n )\r\n adjMdl <- do.call(robu, argList)\r\n lines(c(adjMdl$reg_table$b.r, adjMdl$reg_table$b.r), c(0, 10), lty = 2)\r\n }\r\n \r\n legend(\r\n x = \"topleft\",\r\n legend = eval(parse(text = \r\n paste0(\"expression('Published', 'Unpublished', 'Original estimate','Eggers regression line ('*italic('p')*' value = '*\", as.character(round(egg$reg_table$prob[2], 3)), \"*')')\"))),\r\n pch = c(1, 16, NA, NA),\r\n lty = c(0, 0, 1, 2),\r\n col = \"black\",\r\n pt.cex = 1,\r\n bty = \"n\"\r\n )\r\n \r\n dev.off()\r\n \r\n invisible()\r\n}\r\n\r\nSensitivityAnalysis.RVE <- function(\r\n data,\r\n measureType = \"r\",\r\n measureCol = \"Corr\",\r\n sensitivityCol,\r\n n = \"n\",\r\n grping1, grping2,\r\n PA = NULL,\r\n zTrans = F,\r\n grpd = T)\r\n{\r\n notes <- c()\r\n \r\n # Remove empty samples\r\n data$n <- data[[n]]\r\n data <- data[data$n > 0,]\r\n \r\n data$grp1 <- data[[grping1]]\r\n data$grp2 <- data[[grping2]]\r\n data$Meas <- data[[measureCol]]\r\n data$Sens <- data[[sensitivityCol]]\r\n IsBinary <- length(na.omit(unique(data$Sens))) <= 2\r\n MeasInit <- data$Meas\r\n SensInit <- data$Sens\r\n grping1_lvls <- levels(data$grp1)\r\n \r\n nName <- n\r\n \r\n # Get sample variances\r\n if (zTrans) {\r\n data <- escalc(\r\n ri = Meas,\r\n ni = n, \r\n measure = \"ZCOR\",\r\n data = data,\r\n var.names = c(\"Meas\", \"Var\")\r\n )\r\n } else if (measureType == \"r\") {\r\n data <- escalc(\r\n ri = Meas,\r\n ni = n, \r\n measure = \"COR\",\r\n data = data,\r\n var.names = c(\"Meas\", \"Var\")\r\n )\r\n data$Meas[data$Meas == 1] <- 1 - 1e-6\r\n data$Meas[data$Meas == 0] <- 1e-6\r\n } else if (measureType == \"k\") {\r\n pci <- (data[[PA]] - data$Meas) / (1 - data$Meas)\r\n data$Var <- data[[PA]] * (1 - data[[PA]]) / ((1 - pci) ^ 2 * data$n)\r\n } else if (measureType == \"p\") {\r\n data <- escalc(\r\n xi = Meas,\r\n ni = n,\r\n measure = \"PLO\",\r\n data = data,\r\n var.names = c(\"Meas\", \"Var\")\r\n )\r\n } else {\r\n stop(\"Unknown 'measureType' specified.\")\r\n }\r\n \r\n # Remove any undefined data (and take notes)\r\n if (any(is.na(data$Meas))) {\r\n notes <- c(notes, paste0(\r\n \"\\tThe following rows were removed because the effect-size was undefined:\\n\\n\"))\r\n notes <- c(notes, paste0(\r\n \"\\t * \", data$grp1[is.na(data$Meas)], \" - \", data$grp2[is.na(data$Meas)],\r\n \" (\", data$Meas[is.na(data$Meas)], \")\\n\"))\r\n notes <- c(notes, \"\\n\")\r\n data <- data[!is.na(data$Meas),]\r\n }\r\n if (any(is.na(data$Sens))) {\r\n notes <- c(notes, paste0(\r\n \"\\tThe following rows were removed because the sensitivity variable was undefined:\\n\\n\"))\r\n notes <- c(notes, paste0(\r\n \"\\t * \", data$grp1[is.na(data$Sens)], \" - \", data$grp2[is.na(data$Sens)],\r\n \" (\", data$Sens[is.na(data$Sens)], \")\\n\"))\r\n notes <- c(notes, \"\\n\")\r\n data <- data[!is.na(data$Sens),]\r\n }\r\n \r\n # Make sure none of variances are 0, otherwise analysis will fail\r\n data$Var[data$Var == 0] <- 1e-6\r\n \r\n # Remove first level groups with only 1 study\r\n for (grping in grping1_lvls)\r\n if (sum(data$grp1 == grping) < 1)\r\n {\r\n notes <- c(notes, paste0(\"\\tRemoved '\", grping, \"' - \", sum(data$grp1 == grping), \" studies.\\n\"))\r\n data <- data[data$grp1 != grping,]\r\n grping1_lvls <- grping1_lvls[grping1_lvls != grping]\r\n }\r\n \r\n # Build random-effects models using Robust Variance Estimation\r\n REModels <- list()\r\n dataList <- list()\r\n for (grping in grping1_lvls) {\r\n data.grp = data[data$grp1 == grping,]\r\n \r\n if ((!IsBinary || all(table(data.grp$Sens) >= 2)) && length(unique(data.grp$Sens)) > 1 && nrow(data.grp) > 2) {\r\n # Calculate random effects model\r\n argList <- list(\r\n formula = Meas ~ 1 + Sens,\r\n data = data.grp,\r\n studynum = data.grp$grp2,\r\n var.eff.size = data.grp$Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\"\r\n )\r\n REModels[[grping]] <- do.call(robu, argList)\r\n dataList[[grping]] <- data.grp\r\n dataList[[grping]]$mdlWeights <- REModels[[grping]]$data.full$r.weights\r\n } else {\r\n notes <- c(notes, paste0(\"\\tSkipped '\", grping, \"' due to lack of data (we require at least 1 per group and 2 overall)\\n\"))\r\n }\r\n }\r\n\r\n if (grpd)\r\n {\r\n formula <- as.formula(Meas ~ 1 + Sens + grp1)\r\n }\r\n else\r\n {\r\n formula <- as.formula(Meas ~ 1 + Sens)\r\n }\r\n res <- try(\r\n {\r\n dataOA <- data\r\n if ((!IsBinary || all(table(dataOA$Sens) >= 2)) && length(unique(dataOA$Sens)) > 1 && nrow(dataOA) >= 2) {\r\n argList <- list(\r\n formula = formula,\r\n data = dataOA,\r\n studynum = dataOA$grp2,\r\n var.eff.size = dataOA$Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\"\r\n )\r\n REModels$overall <- do.call(robu, argList)\r\n dataList$overall <- dataOA\r\n dataList$overall$mdlWeights <- REModels$overall$data.full$r.weights\r\n }\r\n }\r\n )\r\n if (inherits(res, \"try-error\") || any(is.nan(REModels$overall$reg_table$prob))) {\r\n crossTab <- table(data$grp1)\r\n dataOA <- data[data$grp1 %in% names(crossTab)[crossTab > 1],]\r\n if ((!IsBinary || all(table(dataOA$Sens) >= 2)) && length(unique(dataOA$Sens)) > 1 && nrow(dataOA) >= 2 &&\r\n length(REModels) > 0) {\r\n argList <- list(\r\n formula = formula,\r\n data = dataOA,\r\n studynum = dataOA$grp2,\r\n var.eff.size = dataOA$Var,\r\n rho = 0.8,\r\n small = T,\r\n modelweights = \"CORR\"\r\n )\r\n REModels$overall <- do.call(robu, argList)\r\n dataList$overall <- dataOA\r\n dataList$overall$mdlWeights <- REModels$overall$data.full$r.weights\r\n }\r\n }\r\n \r\n \r\n return(\r\n list(\r\n REModels = REModels,\r\n data = data,\r\n dataList = dataList,\r\n notes = notes,\r\n measureType = measureType,\r\n sensitivityCol = sensitivityCol,\r\n zTrans = zTrans\r\n )\r\n )\r\n}\r\n\r\nSensSummary.RVE <- function(\r\n RVEModel,\r\n fileName,\r\n isBinary = T,\r\n overallOnly = F,\r\n studyName = \"Authors\"\r\n)\r\n{\r\n output <- c()\r\n \r\n # Unpack\r\n REModels <- RVEModel$REModels\r\n notes <- RVEModel$notes\r\n zTrans <- RVEModel$zTrans\r\n measureType <- RVEModel$measureType\r\n sensCol <- RVEModel$sensitivityCol\r\n data <- RVEModel$data\r\n dataList <- RVEModel$dataList\r\n \r\n if (length(REModels) == 0) {\r\n output <- c(output, \"Notes\\n-----\\n\", paste(notes, collapse = \"\"), \"\\n\\n\")\r\n output <- c(output, \"No models built - see notes\\n\")\r\n \r\n cat(output)\r\n capture.output(cat(output), file = fileName)\r\n \r\n return(invisible())\r\n } \r\n \r\n output <- c(output, \"\\n\\n========\", sensCol, \"========\")\r\n output <- c(output, \"\\nNotes\\n-----\\n\", paste(notes, collapse = \"\"), \"\\n\")\r\n \r\n # Determine relvant levels\r\n if (isBinary) {\r\n factors <- c(0, 1)\r\n } else {\r\n factors <- c(\r\n min(data$Sens), \r\n (min(data$Sens) + max(data$Sens))/2, \r\n max(data$Sens)\r\n )\r\n output <- c(output, \"\\tLine of best fit estimations\\n\")\r\n }\r\n \r\n # Get first level groupings\r\n grping1_lvls <- names(REModels)\r\n if (overallOnly) {\r\n grping1_lvls <- \"overall\"\r\n }\r\n \r\n probVec <- c()\r\n for (grping in grping1_lvls)\r\n {\r\n # Print group heading\r\n output <- c(output, \"\\n\", grping, \"\\n-------\\n\\n\")\r\n \r\n regTable <- REModels[[grping]]$reg_table\r\n data.grp <- dataList[[grping]]\r\n if (is.character(data.grp$Sens)) {\r\n data.grp$Sens <- as.integer(as.factor(data.grp$Sens))\r\n }\r\n if (isBinary) {\r\n posGrp <- data.grp$Sens == 1\r\n } else {\r\n posGrp <- rep(T, nrow(data.grp))\r\n }\r\n \r\n output <- c(output, \"\\tk_total: \\t\", length(unique(data.grp$grp2)), \"\\n\")\r\n output <- c(output, \"\\tk_posGrp: \\t\", length(unique(data.grp$grp2[posGrp])), \"\\n\")\r\n output <- c(output, \"\\tn_total: \\t\", sum(aggregate(n ~ grp2, data = data.grp, max)$n), \"\\n\")\r\n output <- c(output, \"\\tn_posGrp: \\t\", sum(aggregate(n ~ grp2, data = data.grp[posGrp,], max)$n), \"\\n\")\r\n output <- c(output, \"\\tb_0: \\t\", regTable$b.r[1], \"\\n\")\r\n output <- c(output, \"\\tb_1: \\t\", regTable$b.r[2], \"\\n\")\r\n output <- c(output, \"\\tCI(b_0): \\t(\", regTable$CI.L[1], \", \", regTable$CI.U[1], \")\\n\")\r\n output <- c(output, \"\\tCI(b_1): \\t(\", regTable$CI.L[2], \", \", regTable$CI.U[2], \")\\n\")\r\n output <- c(output, \"\\tSE(b_0): \\t\", regTable$SE[1], \"\\n\")\r\n output <- c(output, \"\\tSE(b_1): \\t\", regTable$SE[2], \"\\n\")\r\n output <- c(output, \"\\tdf_0: \\t\", regTable$dfs[1], \"\\n\")\r\n output <- c(output, \"\\tdf_1: \\t\", regTable$dfs[2], \"\\n\")\r\n output <- c(output, \"\\tt_0: \\t\", regTable$t[1], \"\\n\")\r\n output <- c(output, \"\\tt_1: \\t\", regTable$t[2], \"\\n\")\r\n output <- c(output, \"\\tp_0: \\t\", regTable$prob[1], \"\\n\")\r\n output <- c(output, \"\\tp_1: \\t\", regTable$prob[2], \"\\n\")\r\n output <- c(output, \"\\tTauSq: \\t\", REModels[[grping]]$mod_info$tau.sq, \"\\n\")\r\n output <- c(output, \"\\tISq: \\t\", REModels[[grping]]$mod_info$I.2, \"\\n\\n\")\r\n \r\n roundDig <- 3\r\n if (is.na(regTable$prob[1]))\r\n {\r\n probString0 <- probString1 <- \"NA\"\r\n }\r\n else\r\n {\r\n probString0 <- paste0(round(regTable$prob[1],roundDig), if (regTable$prob[1] < 0.01) \"***\" else if (regTable$prob[1] < 0.05) \"**\" else if (regTable$prob[1] < 0.1) \"*\" else \"\")\r\n probString1 <- paste0(round(regTable$prob[2],roundDig), if (regTable$prob[2] < 0.01) \"***\" else if (regTable$prob[2] < 0.05) \"**\" else if (regTable$prob[2] < 0.1) \"*\" else \"\")\r\n }\r\n if (grping == \"overall\")\r\n {\r\n desc <- c(\r\n sensCol,\r\n length(unique(data.grp$grp2)),\r\n length(unique(data.grp$grp2[posGrp])),\r\n sum(aggregate(n ~ grp2, data = data.grp, max)$n),\r\n sum(aggregate(n ~ grp2, data = data.grp[posGrp,], max)$n),\r\n paste0(round(regTable$b.r[1],roundDig), \" [\", round(regTable$CI.L[1],roundDig), \", \", round(regTable$CI.U[1],roundDig), \"]\"),\r\n paste0(round(regTable$b.r[2],roundDig), \" [\", round(regTable$CI.L[2],roundDig), \", \", round(regTable$CI.U[2],roundDig), \"]\"),\r\n # round(regTable$SE[1],roundDig),\r\n # round(regTable$SE[2],roundDig),\r\n round(regTable$dfs[1],roundDig),\r\n round(regTable$dfs[2],roundDig),\r\n round(regTable$t[1],roundDig),\r\n round(regTable$t[2],roundDig),\r\n probString0,\r\n probString1,\r\n round(REModels[[grping]]$mod_info$tau.sq,roundDig),\r\n round(REModels[[grping]]$mod_info$I.2,roundDig)\r\n )\r\n }\r\n probVec[[grping]] <- probString1\r\n }\r\n \r\n \r\n cat(output)\r\n capture.output(cat(output), file = fileName)\r\n \r\n flush.console()\r\n return(list(text = output, matrix = probVec, desc = desc))\r\n}\r\n\r\nlogit <- function(p)\r\n{\r\n log(p / (1 - p))\r\n}\r\n\r\nsigmoid <- function(x)\r\n{\r\n 1 / (1 + exp(-x))\r\n}\r\n\r\n# Wilson score method\r\n#\r\n# Wilson, E. B. ‘Probable inference, the law of succession, and statistical inference’,\r\n# Journal of the AmericanStatistical Association\r\n# \r\np_CI <- function(n, p, z)\r\n{\r\n list(\r\n (2 * n * p + z^2 + z * sqrt(z^2 + 4 * n * p * (1 - p))) / (2 * (n + z^2)),\r\n (2 * n * p + z^2 - z * sqrt(z^2 + 4 * n * p * (1 - p))) / (2 * (n + z^2))\r\n )\r\n}", "meta": {"hexsha": "da292f5138ec545138aab5980a7ad527c1e8a5ac", "size": 32214, "ext": "r", "lang": "R", "max_stars_repo_path": "Code/Utilities/RVE.r", "max_stars_repo_name": "timesler/AttachmentStabilityMetaAnalysis_Opie2018", "max_stars_repo_head_hexsha": "b55a9a635e6a1669fce1a22e37ed0f39a026cd54", "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/Utilities/RVE.r", "max_issues_repo_name": "timesler/AttachmentStabilityMetaAnalysis_Opie2018", "max_issues_repo_head_hexsha": "b55a9a635e6a1669fce1a22e37ed0f39a026cd54", "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/Utilities/RVE.r", "max_forks_repo_name": "timesler/AttachmentStabilityMetaAnalysis_Opie2018", "max_forks_repo_head_hexsha": "b55a9a635e6a1669fce1a22e37ed0f39a026cd54", "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.1246376812, "max_line_length": 186, "alphanum_fraction": 0.5411622276, "num_tokens": 10221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.028007520403160235, "lm_q1q2_score": 0.012803265923579742}} {"text": "#!/usr/bin/Rscript\n\n## recombine.r -- carries out a simulated recombination of chromosomes\n\n## Author: David Eccles (gringer), 2008 \n\nusage <- function(){\n cat(\"usage: ./recombine.r\\n\");\n cat(\"\\nOther Options:\\n\");\n cat(\"-help : Only display this help message\\n\");\n cat(\"\\n\");\n}\n\nargLoc <- 1;\nwhile(!is.na(commandArgs(TRUE)[argLoc])){\n if(commandArgs(TRUE)[argLoc] == \"-help\"){\n usage();\n quit(save = \"no\", status=0);\n }\n argLoc <- argLoc + 1;\n}\n\nmakeUniformChromosome <- function(colour = \"NA\"){\n if(colour == \"NA\"){\n colour = sample(colors(),1);\n }\n return(data.frame(Block = colour, Points = 0));\n}\n\ndrawChromosome <- function(ChrX, xPos = 0.5, yPos = 0, scale = 1,\n yScale = 0.5, new = TRUE){\n xLeft = xPos;\n yBottom = yPos;\n xRight = xPos + 0.05 * scale;\n if(new){\n plot.new();\n }\n for(i in 1:(dim(ChrX)[1])){\n if(i == dim(ChrX)[1]){\n rect(xLeft,yBottom+ChrX[i,2]*scale*yScale,xRight,\n yBottom+1*scale*yScale,\n col=as.character(ChrX[i,1]));\n } else {\n rect(xLeft,yBottom+ChrX[i,2]*scale*yScale,xRight,\n yBottom+ChrX[i+1,2]*scale*yScale,\n col=as.character(ChrX[i,1]));\n }\n }\n}\n\nrecombine <- function(ChrX, ChrY, minPoints = 3, maxPoints = 4){\n result <- NULL;\n recombPoints <- sort(runif(sample(minPoints:maxPoints,1)));\n currentChr <- sample(c(0,1),1);\n startPos <- 0;\n newPoints <- NULL;\n for(endPos in c(recombPoints,1)){\n if(currentChr == 0){\n stopX <- c(ChrX$Points[-1],1);\n # list of recombination points on ChrX in the correct interval\n curPoints = which((ChrX$Points<=endPos) &\n (stopX >= startPos));\n newPoints <- ChrX[curPoints,];\n } else {\n stopY <- c(ChrY$Points[-1],1);\n # list of recombination points on ChrY in the correct interval\n curPoints = which((ChrY$Points<=endPos) &\n (stopY >= startPos));\n newPoints <- ChrY[curPoints,];\n }\n # set start recombination point to be where the recombination took place\n newPoints$Points[1] <- startPos;\n result <- rbind(result,newPoints);\n startPos <- endPos;\n currentChr <- (currentChr + 1) %% 2;\n }\n return(result);\n}\n\n# merges regions of the same colour\nchrClean <- function(ChrX){\n result <- ChrX[1,];\n oldColour <- ChrX$Block[1];\n for(pos in 2:(dim(ChrX)[1])){\n if(oldColour != ChrX$Block[pos]){\n## cat(oldColour, \"does not equal\", ChrX$Block[pos],\"\\n\");\n result <- rbind(result,ChrX[pos,]);\n oldColour <- ChrX$Block[pos];\n }\n }\n return(result);\n}\n\n# combines two chromosomes, so that regions of target colour common to\n# both input chromosomes are in the result chromosome\nchrUnion <- function(colourName, ChrX, ChrY, ChrOther = NULL, ...){\n if(is.null(ChrOther)){\n result <- rbind(ChrX, ChrY);\n result <- result[order(result$Points),];\n for(pos in 1:(dim(result)[1])){\n blockX <- ChrX$Block[max(which(ChrX$Points <= result$Points[pos]))];\n blockY <- ChrY$Block[max(which(ChrY$Points <= result$Points[pos]))];\n if(blockX == colourName){\n result$Block[pos] <- blockX;\n }\n if(blockY == colourName){\n result$Block[pos] <- blockY;\n }\n }\n result <- chrClean(result);\n return(result);\n } else {\n return(chrUnion(colourName, chrUnion(colourName, ChrX, ChrY), ChrOther, ...));\n }\n}\n\n## recombination descendancy, haplotype dilution\noc <- makeUniformChromosome(\"yellow\");\ng1 <- list(makeUniformChromosome(\"red\"));\ng2 <- list(\n chrClean(recombine(g1[[1]],oc)),\n chrClean(recombine(g1[[1]],oc))\n );\ng2u<- chrUnion(\"red\",g2[[1]],g2[[2]]);\ng3 <- list(\n chrClean(recombine(g2[[1]],oc)),\n chrClean(recombine(g2[[1]],oc)),\n chrClean(recombine(g2[[2]],oc)),\n chrClean(recombine(g2[[2]],oc))\n );\ng3u<- chrUnion(\"red\",g3[[1]],g3[[2]],g3[[3]],g3[[4]]);\ng4 <- list(\n chrClean(recombine(g3[[1]],oc)),\n chrClean(recombine(g3[[1]],oc)),\n chrClean(recombine(g3[[2]],oc)),\n chrClean(recombine(g3[[2]],oc)),\n chrClean(recombine(g3[[3]],oc)),\n chrClean(recombine(g3[[3]],oc)),\n chrClean(recombine(g3[[4]],oc)),\n chrClean(recombine(g3[[4]],oc))\n );\ng4u<- chrUnion(\"red\",g4[[1]],g4[[2]],g4[[3]],g4[[4]],\n g4[[5]],g4[[6]],g4[[7]],g4[[8]]);\ng5 <- list(\n chrClean(recombine(g4[[1]],oc)),\n chrClean(recombine(g4[[1]],oc)),\n chrClean(recombine(g4[[2]],oc)),\n chrClean(recombine(g4[[2]],oc)),\n chrClean(recombine(g4[[3]],oc)),\n chrClean(recombine(g4[[3]],oc)),\n chrClean(recombine(g4[[4]],oc)),\n chrClean(recombine(g4[[4]],oc)),\n chrClean(recombine(g4[[5]],oc)),\n chrClean(recombine(g4[[5]],oc)),\n chrClean(recombine(g4[[6]],oc)),\n chrClean(recombine(g4[[6]],oc)),\n chrClean(recombine(g4[[7]],oc)),\n chrClean(recombine(g4[[7]],oc)),\n chrClean(recombine(g4[[8]],oc)),\n chrClean(recombine(g4[[8]],oc))\n );\ng5u <- chrUnion(\"red\",g5[[1]],g5[[2]],g5[[3]],g5[[4]],\n g5[[5]],g5[[6]],g5[[7]],g5[[8]],\n g5[[9]],g5[[10]],g5[[11]],g5[[12]],\n g5[[13]],g5[[14]],g5[[15]],g5[[16]]);\n\npar(mar=c(0,0,0,0));\nplot.new();\nplot.window(xlim=c(0,1),ylim=c(0.2,1));\nfor(i in 1:8){\n drawChromosome(g5[[i*2-1]],xPos = (i-1)*0.125, yPos = 0.8,\n scale = 0.4, new = FALSE);\n drawChromosome(g5[[i*2]],xPos = (i-1)*0.125+0.05, yPos = 0.8,\n scale = 0.4, new = FALSE);\n}\ndrawChromosome(g5u,xPos = (7)*0.125+0.125, yPos = 0.8, scale = 0.4, new = FALSE);\nfor(i in 1:4){\n drawChromosome(g4[[i*2-1]],xPos = (i-1)*0.25+0.0625, yPos = 0.58,\n scale = 0.4, new = FALSE);\n drawChromosome(g4[[i*2]],xPos = (i-1)*0.25+0.0625+0.05, yPos = 0.58,\n scale = 0.4, new = FALSE);\n}\ndrawChromosome(g4u,xPos = (7)*0.125+0.095, yPos = 0.58, scale = 0.4, new = FALSE);\nfor(i in 1:2){\n drawChromosome(g3[[i*2-1]],xPos = (i-1)*0.5+0.1875, yPos = 0.4,\n scale = 0.4, new = FALSE);\n drawChromosome(g3[[i*2]],xPos = (i-1)*0.5+0.1875+0.05, yPos = 0.4,\n scale = 0.4, new = FALSE);\n}\ndrawChromosome(g3u,xPos = (7)*0.125+0.065, yPos = 0.4, scale = 0.4, new = FALSE);\ndrawChromosome(g2[[1]],xPos = 0.4375, yPos = 0.22,\n scale = 0.4, new = FALSE);\ndrawChromosome(g2[[2]],xPos = 0.4375+0.05, yPos = 0.22,\n scale = 0.4, new = FALSE);\ndrawChromosome(g2u,xPos = (7)*0.125+0.035, yPos = 0.22, scale = 0.4, new = FALSE);\ndrawChromosome(g1[[1]],xPos = 0.0875, yPos = 0.22, scale = 0.4, new = FALSE);\narrows(x1=seq(0.035,0.91,length.out=8),\n x0=seq(0.035,0.91,length.out=8) + rep(c(0.015,-0.015),4),\n y1=0.79, y0=0.68, length = 0.1);\narrows(x1=seq(0.0975,0.8475,length.out=4),\n x0=seq(0.0975,0.8475,length.out=4) + rep(c(0.08,-0.08),2),\n y1=0.57, y0=0.5, length = 0.1);\narrows(x1=seq(0.2225,0.7225,length.out=2),\n x0=seq(0.2225,0.7225,length.out=2) + rep(c(0.2,-0.2),2),\n y1=0.39, y0=0.32, length = 0.1);\narrows(x1 = 0.42, x0 = 0.1275, y1 = 0.30, y0 = 0.30, length = 0.1);\narrows(x1 = 0.975, x0 = 0.875, y1 = 1.01, y0 = 0.21, length = 0);\n\n## recombination ancestry, unbalanced haplotypes\ng1 <- list(\n makeUniformChromosome(\"black\"),\n makeUniformChromosome(\"red\"),\n makeUniformChromosome(\"magenta\"),\n makeUniformChromosome(\"blue\"),\n makeUniformChromosome(\"cyan\"),\n makeUniformChromosome(\"green\"),\n makeUniformChromosome(\"yellow\"),\n makeUniformChromosome(\"white\"));\ng2 <- list(\n recombine(g1[[1]],g1[[1]]),\n recombine(g1[[2]],g1[[2]]),\n recombine(g1[[3]],g1[[3]]),\n recombine(g1[[4]],g1[[4]]),\n recombine(g1[[5]],g1[[5]]),\n recombine(g1[[6]],g1[[6]]),\n recombine(g1[[7]],g1[[7]]),\n recombine(g1[[8]],g1[[8]]));\ng3 <- list(\n recombine(g2[[1]],g2[[2]]),\n recombine(g2[[3]],g2[[4]]),\n recombine(g2[[5]],g2[[6]]),\n recombine(g2[[7]],g2[[8]]));\ng4 <- list(\n recombine(g3[[1]],g3[[2]]),\n recombine(g3[[3]],g3[[4]]));\ng5 <- list(\n recombine(g4[[1]],g4[[2]]));\n\npdf(\"recombination_ancestry.pdf\",width=8,height=8);\npar(mar=c(0,0,0,0));\nplot.new();\nplot.window(xlim=c(0,1),ylim=c(0.2,1));\nfor(i in 1:8){\n drawChromosome(g1[[i]],xPos = (i-1)*0.125, yPos = 0.8,\n scale = 0.4, new = FALSE);\n drawChromosome(g1[[i]],xPos = (i-1)*0.125+0.05, yPos = 0.8,\n scale = 0.4, new = FALSE);\n}\nfor(i in 1:4){\n drawChromosome(g2[[i*2-1]],xPos = (i-1)*0.25+0.0625, yPos = 0.58,\n scale = 0.4, new = FALSE);\n drawChromosome(g2[[i*2]],xPos = (i-1)*0.25+0.0625+0.05, yPos = 0.58,\n scale = 0.4, new = FALSE);\n}\nfor(i in 1:2){\n drawChromosome(g3[[i*2-1]],xPos = (i-1)*0.5+0.1875, yPos = 0.4,\n scale = 0.4, new = FALSE);\n drawChromosome(g3[[i*2]],xPos = (i-1)*0.5+0.1875+0.05, yPos = 0.4,\n scale = 0.4, new = FALSE);\n}\ndrawChromosome(g4[[1]],xPos = 0.4375, yPos = 0.22,\n scale = 0.4, new = FALSE);\ndrawChromosome(g4[[2]],xPos = 0.4375+0.05, yPos = 0.22,\n scale = 0.4, new = FALSE);\ndrawChromosome(g5[[1]],xPos = 0.8375, yPos = 0.22, scale = 0.4, new = FALSE);\narrows(x0=seq(0.035,0.91,length.out=8),\n x1=seq(0.035,0.91,length.out=8) + rep(c(0.015,-0.015),4),\n y0=0.79, y1=0.68, length = 0.1);\narrows(x0=seq(0.0975,0.8475,length.out=4),\n x1=seq(0.0975,0.8475,length.out=4) + rep(c(0.08,-0.08),2),\n y0=0.57, y1=0.5, length = 0.1);\narrows(x0=seq(0.2225,0.7225,length.out=2),\n x1=seq(0.2225,0.7225,length.out=2) + rep(c(0.2,-0.2),2),\n y0=0.39, y1=0.32, length = 0.1);\narrows(x0 = 0.52, x1 = 0.82, y0 = 0.30, y1 = 0.30, length = 0.1);\ndummy <- dev.off();\n", "meta": {"hexsha": "1e9090d1a9446e71c0b3c008f208ce62d21a0513", "size": 9962, "ext": "r", "lang": "R", "max_stars_repo_path": "recombine.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": "recombine.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": "recombine.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": 35.963898917, "max_line_length": 82, "alphanum_fraction": 0.5410560128, "num_tokens": 3583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121585956185, "lm_q2_score": 0.03308597540928261, "lm_q1q2_score": 0.012735194214028522}} {"text": "# <-- encoding UTF-8 -->\n# Portal for the code of: Socioeconomic Status Inequality and Morbidity Rate Differences in China: Based on NHSS and CHARLS Data\n# Author: Y. Jiang, H. Zheng, T. Zhao\n# -------------------------------------------\n## DOC STRING\n# \n# The script is the portal of all programs of our submtted paper;\n# you may run this file, or follow the documentation, README, and comments to specific source files.\n# Please refer to README.md for more information.\n# and, all scripts & file I/O are encoded in UTF-8 (because Chinese charaters, in data and/or scripts, may be included & used)\n# \n# Tianhao Zhao (GitHub: Clpr)\n# Dec 2018\n# -------------------------------------------\n## DEPENDENCY\n#\n# 1. readxl: IO of xlsx files\n# 2. plm: panel data models\n# 3. nlme: GLS estimation of linear models\n# 4. car: VIFs, qqplots\n# 5. ggplot2, plyr, maptools, mapproj, Cairo: map drawing\n# 6. sqldf: api of firendly sql enqury\n# 7. nortest: normality tests\n# 8. purrr: std lib, to do function operations\n# 9. openxlsx: easy xlsx I/O, no dependency on rJava\n# 10. psych: easier APIs for PCA\n# -------------------------------------------\n\nrm(list=ls()) # clear\nsetwd(\"C:/Users/Lenovo/OneDrive/GitHubProj/HealthInequality2018Dec\") # working directory\n\n\n\n\n\n\n\n\n# -------------------------------------------\n# Section 1: NHSS data processing & variable selection\ncat(\"\\nScript 1: NHSS data processing & variable selection\")\n# MISSION:\n# 1. NHSS data I/O\n# 2. NHSS data processing, missing values\n# 3. collinearity between income & edu: resid(income ~ edu) --> income\n# 4. NHSS (control) variable selection I: through single-variable regressions\n# 5. NHSS (control) variable selection II: PCA\n# 6. VIFs of final specifications\nsource(\"./scripts/proc_1_NHSS.r\")\n# LEGACY IN WORKSPACE:\n# 1. df_NHSSraw: raw NHSS dataset, consisting of all potential vars & useless vars; as backup\n# 2. df_NHSS: processed NHSS dataset\n# 3. li_Dat_NHSS: datasets for every specification\n# 3. li_DatPlm_NHSS: panel-data for every specification\n# 4. li_PCAres_NHSS: PCA results\n# 5. li_PCAk_NHSS: numebr of components used in every specification\n# 5. li_VIF_NHSS: VIF results of final specifications\n# 6. li_Eq_NHSS: a list consisting of formula objects of final specifications\n# 7. li_Xnames_NHSS: a list of namelists of independents of every specification\n# 7. envNHSS: environment variables of NHSS dataset\n# NOTE: pls go to ./output/proc_1_NHSS/ for output results (if applicable)\n# ---------------------------------------------\n\n# ---------------------------------------------\n# Section 2: NHSS data, descriptive statistics (basic and advanced)\ncat(\"\\nScript 2: NHSS data descriptive statistics\")\n# DEPENDENCY: using legacy of proc_1_NHSS.r\n# MISSION:\n# 1. NHSS data, general descriptive stats (mean, sd etc)\n# 2. county-level (individual) Lorenz Curve & Gini coef of health outcomes\n# 3. county-level (individual) Theil-I, Theil-II\n# 4. county-level (individual) C.V., coefficient of variance\n# 5. county-level (individual) Variance\n# 6. NHSS data, the existence of the inequalities of health outcomes among areas in China (colored map)\n# 7. NHSS data, the difference of (income & edu) among areas in china (colored map)\nsource(\"./scripts/proc_2_NHSS.r\")\n# LEGACY IN WORKSPACE:\n# 1. li_Descript_NHSS: tables of the descriptive statistics of NHSS data (only income & edu, we do not do this on normalized+centered principle components!)\n# 2. df_InequalIdx_NHSS: a table of different kinds of inequality indices of NHSS data\n# 3. MapShapeCH: a dataset of Chinese GIS data; will be used later\n# 4. func_DescrStat: a function to do descriptive statistics\n# 5. func_MapProv: draws colored map based on Chinese GIS data; province level\n# 6. func_SaveMap2PDF: easy output method of the figures created by func_MapProv()\n# 7. LorenzCurve: easy function to compute Lorenz curve & Gini coef\n# 8. Theil: easy function to compute Theil-I/II index\n# 9. TrapeInt: easy function to compute trapezium integral\n# NOTE: pls go to ./output/proc_2_NHSS/ for output results (applicable)\n# ---------------------------------------------\n\n# ---------------------------------------------\n# Section 3: NHSS data, econometric analysis (pool, fix, random, Hausman)\ncat(\"\\nScript 3: NHSS data, econometric analysis (pool, fix, random, Hausman)\")\n# DEPENDENCY: using legacy of proc_1_NHSS.r\n# \n# IMPORTANT NOTE: please refer to PanelAnalysisLogic.md under the ./docs directory to help understand how we designed this section !!! :)\n# \n# MISSION:\n# 1. one-way fixed individual effect model & random individual effect model (FGLS estimators)\n# 2. Hausman test & robust Hausman test (Wooldridge, 2010)\n# 3. Residual QQplots & normality tests, one-way fixed individual effect model (only)\n# 4. ROBUST: two-ways fixed effect model & Haussman test (to see if one-way & two-ways are consistent)\n# 5. ROBUST: pooling, OLS\n# 6. ROBUST: pooling, FGLS\n# \n# 5. ROBUST: add possible independent: \nsource(\"./scripts/proc_3_NHSS.r\")\n# LEGACY IN WORKSPACE:\n# NOTE: pls go to ./output/proc_3_NHSS/ for output results (applicable)\n# -------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n# -------------------------------------------\n# Section 4: CHARLS data processing & variable selection\ncat(\"\\nScript 4: CHARLS data processing & variable selection\")\n# MISSION:\n# 1. CHARLS data I/O\n# 2. CHARLS data processing, missing values\n# 3. collinearity between income & edu: resid(income ~ edu) --> income\n# 4. CHARLS (control) variable selection I: through single-variable regressions\n# 5. CHARLS (control) variable selection II: AIC stepwise to FURTHER select control variables into final specifications\n# 6. VIFs of final specifications\nsource(\"./scripts/proc_1_CHARLS.r\")\n# LEGACY IN WORKSPACE:\n# 1. df_CHARLS_backup: raw CHARLS dataset, consisting of all potential vars & useless vars; as backup\n# 2. df_CHARLS: processed CHARLS dataset\n# 3. dfp_CHARLS: a panel-data-type dataframe (converted from df_NHSS, used in package plm)\n# 4. df_FinalSpecif_CHARLS: a dataframe marking which variables in the final specifications\n# 5. df_VIF_CHARLS: VIF results of final specifications\n# 6. li_Eq_CHARLS: a list consisting of formula objects of final specifications\n# 7. envCHARLS: environment variables of CHARLS dataset\n# NOTE: pls go to ./output/proc_1_CHARLS/ for output results (if applicable)\n# ---------------------------------------------\n\n# ---------------------------------------------\n# Section 5: CHARLS data, descriptive statistics (basic and advanced)\ncat(\"\\nScript 5: CHARLS data, descriptive statistics (basic and advanced)\")\n# DEPENDENCY: using legacy of proc_1_NHSS.r\n# MISSION:\n# 1. CHARLS data, general descriptive stats (mean, sd etc)\n# 2. county-level (individual) Lorenz Curve & Gini coef of health outcomes\n# 3. county-level (individual) Theil-I, Theil-II\n# 4. county-level (individual) C.V., coefficient of variance\n# 5. county-level (individual) Variance\n# 6. CHARLS data, the existence of the inequalities of health outcomes among areas in China (colored map)\n# 7. CHARLS data, the difference of (income & edu) among areas in china (colored map)\nsource(\"./scripts/proc_2_CHARLS.r\")\n# LEGACY IN WORKSPACE:\n# 1. df_Descript_CHARLS: a table of the descriptive statistics of NHSS data (final specification)\n# 2. df_InequalIdx_CHARLS: a table of different kinds of inequality indices of NHSS data\n# 3. MapShapeCH: a dataset of Chinese GIS data; will be used later\n# 4. func_DescrStat: a function to do descriptive statistics\n# 5. func_MapProv: draws colored map based on Chinese GIS data; province level\n# 6. func_SaveMap2PDF: easy output method of the figures created by func_MapProv()\n# 7. LorenzCurve: easy function to compute Lorenz curve & Gini coef\n# 8. Theil: easy function to compute Theil-I/II index\n# 9. TrapeInt: easy function to compute trapezium integral\n# NOTE: pls go to ./output/proc_2_CHARLS/ for output results (applicable)\n# ---------------------------------------------\n\n# ---------------------------------------------\n# Section 6: CHARLS data, econometric analysis (pool, fix, random, Hausman)\ncat(\"\\nScript 3: CHARLS data, econometric analysis (pool, fix, random, Hausman)\")\n# DEPENDENCY: using legacy of proc_1_CHARLS.r\n# \n# IMPORTANT NOTE: please refer to PanelAnalysisLogic.md under the ./docs directory to help understand how we designed this section !!! :)\n# \n# MISSION:\n# 1. one-way fixed individual effect model & random individual effect model (FGLS estimators)\n# 2. Hausman test & robust Hausman test (Wooldridge, 2010)\n# 3. Residual QQplots & normality tests, one-way fixed individual effect model (only)\n# 4. ROBUST: two-ways fixed effect model & Haussman test (to see if one-way & two-ways are consistent)\n# 5. ROBUST: pooling, OLS\n# 6. ROBUST: pooling, FGLS\n# \n# 5. ROBUST: add possible independent: \nsource(\"./scripts/proc_3_CHARLS.r\")\n# LEGACY IN WORKSPACE:\n# NOTE: pls go to ./output/proc_3_CHARLS/ for output results (applicable)\n# -------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e7246c505aff0f7030832c1b5d39f2f172e89cfa", "size": 9919, "ext": "r", "lang": "R", "max_stars_repo_path": "main.r", "max_stars_repo_name": "Clpr/HealthInequality2018Dec", "max_stars_repo_head_hexsha": "d88d80c97e46f3e0b10c2c15e83eb0932957e69d", "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": "main.r", "max_issues_repo_name": "Clpr/HealthInequality2018Dec", "max_issues_repo_head_hexsha": "d88d80c97e46f3e0b10c2c15e83eb0932957e69d", "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": "main.r", "max_forks_repo_name": "Clpr/HealthInequality2018Dec", "max_forks_repo_head_hexsha": "d88d80c97e46f3e0b10c2c15e83eb0932957e69d", "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.2333333333, "max_line_length": 173, "alphanum_fraction": 0.6282891421, "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.034618839959681236, "lm_q1q2_score": 0.012690911412598595}} {"text": "###############################################################################\r\n# \"Infection Rate Models for COVID-19: \r\n# Model Risk and Public Health News Sentiment Exposure Adjustments\"\r\n# \r\n# Ioannis Chalkiadakis, Kevin Hongxuan Yan, Gareth W. Peters, Pavel V. Shevchenko\r\n#\r\n# Kevin Hongxuan Yan\r\n# March 2021\r\n###############################################################################\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"./covid19modelrisk/data/covid19_infected/\")\r\n\r\n y_GM=read.csv(\"COVID-19_confirmed__Germany.csv\")[,2]\r\n y_IT=read.csv(\"COVID-19_confirmed__Italy.csv\")[,2]\r\n y_JP=read.csv(\"COVID-19_confirmed__Japan.csv\")[,2]\r\n y_SP=read.csv(\"COVID-19_confirmed__Spain.csv\")[,2]\r\n y_UK=read.csv(\"COVID-19_confirmed__United Kingdom.csv\")[,2]\r\n y_US=read.csv(\"COVID-19_confirmed__US.csv\")[,2]\r\n y_AU=read.csv(\"COVID-19_confirmed_Australia.csv\")[,2]\r\n\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\n\r\npdf(\"UK_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_UK,main=name[5],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_UK)), labels=c(\"Jan/31\",\"May/09\",\"Aug/06\")) ### UK\r\ndev.off()\r\n\r\n\r\npdf(\"GM_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_GM,main=name[1],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_GM)), labels=c(\"Jan/27\",\"May/05\",\"Aug/06\")) ### GM\r\ndev.off()\r\n\r\n\r\npdf(\"IT_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_IT,main=name[2],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_IT)), labels=c(\"Jan/31\",\"May/09\",\"Aug/06\")) ### IT\r\ndev.off()\r\n\r\n\r\npdf(\"SP_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_SP,main=name[4],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_SP)), labels=c(\"Feb/01\",\"May/10\",\"Aug/06\")) ### SP\r\ndev.off()\r\n\r\n\r\npdf(\"US_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_US,main=name[6],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_US)), labels=c(\"Jan/22\",\"Apr/30\",\"Aug/06\")) ### US\r\ndev.off()\r\n\r\n\r\npdf(\"JP_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_JP,main=name[3],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_JP)), labels=c(\"Jan/22\",\"Apr/30\",\"Aug/06\")) ### JP\r\ndev.off()\r\n\r\n\r\npdf(\"AU_tplot.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_AU,main=name[7],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,length(y_AU)), labels=c(\"Jan/26\",\"May/04\",\"Aug/06\")) ### AU\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#################### Violin plot \r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\nk=7\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M2 Rdata\")\r\nload(paste(\"M2_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_2=(res-mean(res))/(sd(res))\r\nR_2=cbind(Res_2,rep(\"M2\",length(Res_2)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M4 Rdata\")\r\nload(paste(\"M4_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_4=(res-mean(res))/(sd(res))\r\nR_4=cbind(Res_4,rep(\"M4\",length(Res_4)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M7 Rdata\")\r\nload(paste(\"M7_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_7=(res-mean(res))/(sd(res))\r\nR_7=cbind(Res_7,rep(\"M7\",length(Res_7)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M8 Rdata\")\r\nload(paste(\"M8_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_8=(res-mean(res))/(sd(res))\r\nR_8=cbind(Res_8,rep(\"M8\",length(Res_8)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M9 Rdata\")\r\nload(paste(\"M9_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_9=(res-mean(res))/(sd(res))\r\nR_9=cbind(Res_9,rep(\"M9\",length(Res_9)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M10 Rdata\")\r\nload(paste(\"M10_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_10=(res-mean(res))/(sd(res))\r\nR_10=cbind(Res_10,rep(\"M10\",length(Res_10)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M11 Rdata\")\r\nload(paste(\"M11_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(8+N):(7+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_11=(res-mean(res))/(sd(res))\r\nR_11=cbind(Res_11,rep(\"M11\",length(Res_11)))\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M12 Rdata\")\r\nload(paste(\"M12_\",abn[k],\".Rdata\", sep=\"\"))\r\nEpars_m <- apply( as.data.frame(fit@sim[[1]][[1]])[10001:100000,(7+N):(6+2*N)] , 2 , mean )\r\nres=Epars_m-y\r\nRes_12=(res-mean(res))/(sd(res))\r\nR_12=cbind(Res_12,rep(\"M12\",length(Res_12)))\r\n\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\final plot\")\r\n\r\npdf(paste(abn[k],\"_plot.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\nlibrary(\"vioplot\")\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nvioplot(Res_2,Res_4,Res_7,Res_8,Res_9,Res_10,Res_11,Res_12,names=c(\"M2\",\"M4\",\"M7\",\"M8\",\"M9\",\"M10\",\"M11\",\"M12\"))\r\ntitle(paste(\"Residual plots for \",name[k],sep=\"\"))\r\n\r\n\r\ndev.off()\r\n\r\n\r\n\r\n############## boxplot ########################################################################################################################################\r\n\r\n\r\n\r\n\r\n\r\n\r\nlibrary(methods)\r\nlibrary(rstan)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\nabn=c(\"GM\",\"IT\",\"JP\",\"SP\",\"UK\",\"US\",\"AU\")\r\n\r\n\r\n\r\nk=3\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\M2 Rdata\") ##### change\r\nload(paste(\"M2_\",abn[k],\".Rdata\", sep=\"\")) ##### change\r\nEpars <- as.data.frame(fit@sim[[1]][[1]])[10001:100000,(6+N):(5+2*N)]\r\n\r\n\r\nres_all=matrix(,nrow=dim(Epars)[1],ncol=dim(Epars)[2])\r\nY_m=matrix(rep(y,nrow=dim(Epars)[1]),nrow=dim(Epars)[1],ncol=dim(Epars)[2],byrow=T)\r\nres_all=as.matrix(Epars-Y_m)\r\n\r\n\r\nres_st=matrix(,nrow=dim(Epars)[1],ncol=dim(Epars)[2])\r\nfor (i in 1:dim(Epars)[1]){\r\nres_st[i,]=(res_all[i,]-mean(res_all[i,]))/(sd(res_all[i,]))\r\n}\r\n\r\n\r\n\r\n\r\n\r\nsetwd(\"C:\\\\Users\\\\yhx19\\\\Desktop\\\\NEW RUN\\\\final plot\")\r\n\r\n\r\npdf(paste(abn[k],\"_boxplot.pdf\",sep=\"\"), width = 16.5, height = 8.50) \r\n\r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nboxplot(res_st,xlab=\"time steps\")\r\ntitle(paste(\"M2 residual boxplots for \",name[k],sep=\"\")) ##### change\r\n\r\n\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n############## NEW plot ########################################################################################################################################\r\n############## NEW plot ########################################################################################################################################\r\n\r\n\r\n\r\n####### read new data Y\r\nsetwd(\"G:\\\\Covid paper\\\\additionalcountdataofinfectedcases\\\\new data\")\r\n\r\n y_GM=read.csv(\"COVID-19_confirmed__Germany_latest_Feb.csv\")[,2]\r\n y_IT=read.csv(\"COVID-19_confirmed__Italy_latest_Feb.csv\")[,2]\r\n y_JP=read.csv(\"COVID-19_confirmed__Japan_latest_Feb.csv\")[,2]\r\n y_SP=read.csv(\"COVID-19_confirmed__Spain_latest_Feb.csv\")[,2]\r\n y_UK=read.csv(\"COVID-19_confirmed__United Kingdom_latest_Feb.csv\")[,2]\r\n y_US=read.csv(\"COVID-19_confirmed__US_latest_Feb.csv\")[,2]\r\n y_AU=read.csv(\"COVID-19_confirmed_Australia_latest_Feb.csv\")[,2]\r\n\r\n\r\nD_GM=c(\"Jan/27\",\"May/05\",\"Aug/13\",\"Nov/21\",\"Jan/10\")\r\nD_IT=c(\"Jan/31\",\"May/09\",\"Aug/17\",\"Nov/25\",\"Jan/14\")\r\nD_JP=c(\"Jan/22\",\"Apr/30\",\"Aug/08\",\"Nov/16\",\"Jan/5\")\r\nD_SP=c(\"Feb/01\",\"May/10\",\"Aug/18\",\"Nov/26\",\"Jan/15\")\r\nD_UK=c(\"Jan/31\",\"May/09\",\"Aug/17\",\"Nov/25\",\"Jan/14\")\r\nD_US=c(\"Jan/22\",\"Apr/30\",\"Aug/08\",\"Nov/16\",\"Jan/5\")\r\nD_AU=c(\"Jan/26\",\"May/04\",\"Aug/12\",\"Nov/20\",\"Jan/9\")\r\n\r\nDate=c(D_GM,D_IT,D_JP,D_SP,D_UK,D_US,D_AU)\r\n\r\n\r\nname=c(\"Germany\",\"Italy\",\"Japan\",\"Spain\",\"U.K.\",\"U.S.\",\"Australia\")\r\n\r\nk=5\r\npdf(\"UK_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_UK,main=name[5],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Jan/31\",\"May/09\",\"Aug/17\",\"Nov/25\",\"Jan/14\")) \r\n ### UK\r\ndev.off()\r\n\r\n\r\nk=1\r\npdf(\"GM_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_GM,main=name[1],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Jan/27\",\"May/05\",\"Aug/13\",\"Nov/21\",\"Jan/10\")) \r\n ### GM\r\ndev.off()\r\n\r\nk=2\r\npdf(\"IT_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_IT,main=name[2],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Jan/31\",\"May/09\",\"Aug/17\",\"Nov/25\",\"Jan/14\")) \r\n ### IT\r\ndev.off()\r\n\r\nk=4\r\npdf(\"SP_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_SP,main=name[4],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Feb/01\",\"May/10\",\"Aug/18\",\"Nov/26\",\"Jan/15\")) \r\n ### SP\r\ndev.off()\r\n\r\nk=6\r\npdf(\"US_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_US,main=name[6],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Jan/22\",\"Apr/30\",\"Aug/08\",\"Nov/16\",\"Jan/5\")) \r\n ### US\r\ndev.off()\r\n\r\nk=3\r\npdf(\"JP_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_JP,main=name[3],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Jan/22\",\"Apr/30\",\"Aug/08\",\"Nov/16\",\"Jan/5\")) \r\n ### JP\r\ndev.off()\r\n\r\nk=7\r\npdf(\"AU_tplot_LONG.pdf\", width = 16.5, height = 8.50) \r\npar(cex.axis=2.5,cex.lab=2.5,cex.main=2.5,mar=c(5, 5, 3, 0.5))\r\nplot(y_AU,main=name[7],xlab=\"time\",ylab=\"count\",xaxt = 'n')\r\naxis(1, at=c(0,100,200,300,350), labels=c(\"Jan/26\",\"May/04\",\"Aug/12\",\"Nov/20\",\"Jan/9\")) \r\n ### AU\r\ndev.off()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "f90149b3ded43310f310e8d513cea10b9119a0c8", "size": 10603, "ext": "r", "lang": "R", "max_stars_repo_path": "R/final plot.r", "max_stars_repo_name": "ichalkiad/covid19modelrisk", "max_stars_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/final plot.r", "max_issues_repo_name": "ichalkiad/covid19modelrisk", "max_issues_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "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/final plot.r", "max_forks_repo_name": "ichalkiad/covid19modelrisk", "max_forks_repo_head_hexsha": "eaf14f373411c0122c73439f089e9626164c87d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-04-05T00:19:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T00:19:10.000Z", "avg_line_length": 29.9519774011, "max_line_length": 165, "alphanum_fraction": 0.5632368198, "num_tokens": 4116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.034618842698694585, "lm_q1q2_score": 0.012565573353238999}} {"text": "##\n# layer_class.r\n# Copyright (C) Jonathan Bramble 2011\n# \n# FBF-Optics is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# FBF-Optics is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License along\n# with this program. If not, see .\n#\n\n#' An S4 class to represent a thin dielectric or metallic layer.\n#'\n#' @slot d Thickness of the layer in m\n#' @slot eps The relative permittivity of the material as a complex number\n#' \n\nIsoLayer <- setClass(\"IsoLayer\", \n representation(\n fitd=\"logical\",\n dstart=\"numeric\",\n dend=\"numeric\",\n d=\"numeric\",\n eps=\"complex\"\n ),\n prototype(fitd=FALSE,dstart=0.0,dend=0.0,d=0.0,eps=0+0i)\n)\n\nsetGeneric(\"d<-\",function(x,value) standardGeneric(\"d<-\"))\nsetReplaceMethod(\"d\",\"IsoLayer\", function(x,value) {x@d <- value; validObject(x); x})\n\n#' An S4 class to represent anisotropic layer.\n#'\n#' @slot d Thickness of the layer in m\n#' @slot epsx The relative permittivity of the material in the x direction\n#' @slot epsy The relative permittivity of the material in the y direction\n#' @slot epsz The relative permittivity of the material in the z direction\n#' @slot theta angle of the molecular axis in relation to the prism axis - see diagram\n#' @slot phi angle of the molecular axis in relation to the prism axis - see diagram\n#' @slot S the order parameter for the layer\n#' \n\nAnisoLayer <- setClass(\"AnisoLayer\", \n representation(\n d=\"numeric\",\n epsx=\"numeric\",\n epsy=\"numeric\",\n epsz=\"numeric\",\n theta=\"numeric\",\n phi=\"numeric\",\n S=\"numeric\"\n )\n)\n\nsetMethod(\"show\", signature(object=\"IsoLayer\"),function(object){\n cat(\" Isotropic Layer data \\n\")\n})\n\nsetMethod(\"show\", signature(object=\"AnisoLayer\"),function(object){\n cat(\" Anisotropic Layer data \\n\")\n cat(\" Layer Thickness:\", object@d , \"\\n\")\n cat(\" eps along x:\", object@epsx , \"\\n\")\n cat(\" eps along y:\", object@epsy , \"\\n\")\n cat(\" eps along z:\", object@epsz , \"\\n\")\n cat(\" Theta angle:\", object@theta, \"\\n\")\n cat(\" Phi angle:\", object@phi , \"\\n\")\n cat(\" Order Parameter S:\", object@S , \"\\n\")\n})\n", "meta": {"hexsha": "f5ce08a3ab48e1262892b083f0a3439d0dcfe2e9", "size": 2713, "ext": "r", "lang": "R", "max_stars_repo_path": "R/layer_class.r", "max_stars_repo_name": "jonbramble/RFBFoptics", "max_stars_repo_head_hexsha": "db7768b0e2f0e7defe3cf572292bd4f0c16c08ce", "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/layer_class.r", "max_issues_repo_name": "jonbramble/RFBFoptics", "max_issues_repo_head_hexsha": "db7768b0e2f0e7defe3cf572292bd4f0c16c08ce", "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": "R/layer_class.r", "max_forks_repo_name": "jonbramble/RFBFoptics", "max_forks_repo_head_hexsha": "db7768b0e2f0e7defe3cf572292bd4f0c16c08ce", "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": 35.6973684211, "max_line_length": 86, "alphanum_fraction": 0.6343531146, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.030214589468852714, "lm_q1q2_score": 0.012535998734039962}} {"text": "#functions used to calculate diversity statistics within populations\n# make sure the output file is already written in format (header):\n# population1 population2 statistic chromosome start end number_sites number_variable_sites calculated_stat\n# e.g., write(c(\"pop1\", \"pop2\", \"stat\", \"chr\", \"start\", \"end\", \"number_sites\", \"number_variable_sites\", \"calculated_stat\"), ncolumns=9, file=outname, sep=\"\\t\")\n\n# input is simplified vcf (entire vcf) and 3-column popmap (ordered the same as the vcf) and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only calculate for invariant sites and biallelic snps\nheterozygosity <- function(xxx, popmap, outname, filename) {\n options(scipen=999)\n xxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n for(a in 1:nrow(popmap)) {\n output_rep <- c(popmap[a,1], \"none\", \"heterozygosity\", strsplit(filename, \":\")[[1]][1], \n as.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n as.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]))\n # select this individual\n a_rep <- xxx[,a+3]\n # remove missing genotypes\n a_rep <- a_rep[a_rep != \"./.\"]\n # count number of sites\n a_total <- length(a_rep)\n # remove phasing information\n a_rep <- gsub(\"\\\\|\", \"/\", a_rep)\n # find number of heterozygous sites\n a_het <- length(a_rep[a_rep == \"0/1\"])\n # add to output\n output_rep <- c(output_rep, a_total, a_het, a_het/a_total)\n write(output_rep, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n }\n}\n\n# helper function to identify transition variants from biallelic alleles in rows (used in titv function)\ntransitions <- function(x1) {\n\ta_rep <- sort(x1)\n\tif(a_rep[1] == \"A\" & a_rep[2] == \"G\") {\n\t\treturn(1)\n\t} else if(a_rep[1] == \"C\" & a_rep[2] == \"T\") {\n\t\treturn(1)\n\t} else {\n\t\treturn(0)\n\t}\n}\n\n\n\n# input is simplified vcf (entire vcf) and other files as in heterozygosity calcs, to calculate transition transversion ratio\ntitv <- function(xxx, popmap, outname, filename) {\n options(scipen=999)\n xxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n # filter to variable sites\n xxx <- xxx[xxx[,3] != \".\", ]\n \n # sites used for titv \n # total sites used same as het sites\n a_total <- nrow(xxx)\n a_het <- a_total\n \n # find number of transitions using helper function\n total_transitions <- sum(apply(xxx[,2:3], 1, transitions))\n # calculate transition / transversion ratio\n titv_ratio <- total_transitions / (a_total - total_transitions)\n \n # output info\n output_rep <- c(\"all_inds\", \"none\", \"titv\", strsplit(filename, \":\")[[1]][1], \n as.numeric(strsplit(strsplit(filename, \":\")[[1]][2], \"-\")[[1]][1]),\n as.numeric(strsplit(strsplit(filename, \"-\")[[1]][2], \".simple\")[[1]][1]))\n \n output_rep <- output_rep <- c(output_rep, a_total, a_het, titv_ratio)\n write(output_rep, file=outname, append=T, ncolumns=9, sep=\"\\t\")\n \n}\n\n\n\n\n# input is one simplified vcfs, \n# the popmap, and output file name\n# and the input simple vcf file name that contains the chr and start and end information\n# only for invariant sites and biallelic snps\n# lastly, input number of sites needed to write file\n\ncreate_fasta_from_vcf <- function(xxx, popmap, outname, filename, num_sites_needed) {\n options(scipen=999)\n # remove sites that are not either invariant or bi-allelic SNPs\n xxx <- xxx[nchar(xxx[,2]) == 1 & nchar(xxx[,3]) == 1, ]\n \n # keep going only if enough sites\n if(num_sites_needed <= nrow(xxx)) {\n # remove phasing information\n for(a in 4:ncol(xxx)) {\n xxx[,a] <- gsub(\"\\\\|\", \"/\", xxx[,a])\n }\n \n # define names of individuals in output fasta\n output_names_fasta <- paste(\">\", popmap[,1], sep=\"\")\n \n # subset the genotypes from the allele info\n allele_info <- xxx[,2:3]\n genotypes <- xxx[,4:ncol(xxx)]\n \n # convert all numbers in genotypes to actual bases and ambiguities\n for(a in 1:nrow(genotypes)) {\n if(allele_info[a,2] == \".\") { # if non-polymorphic\n genotypes[a,] <- gsub(\"0/0\", allele_info[a,1], genotypes[a,])\n genotypes[a,] <- gsub(\"\\\\./\\\\.\", \"?\", genotypes[a,])\n } else { # if polymorphic\n both_genotypes <- sort(as.character(allele_info[a,]))\n if(both_genotypes[1] == \"A\" & both_genotypes[2] == \"C\") { het = \"M\" }\n if(both_genotypes[1] == \"A\" & both_genotypes[2] == \"G\") { het = \"R\" }\n if(both_genotypes[1] == \"A\" & both_genotypes[2] == \"T\") { het = \"W\" }\n if(both_genotypes[1] == \"C\" & both_genotypes[2] == \"G\") { het = \"S\" }\n if(both_genotypes[1] == \"C\" & both_genotypes[2] == \"T\") { het = \"Y\" }\n if(both_genotypes[1] == \"G\" & both_genotypes[2] == \"T\") { het = \"K\" }\n genotypes[a,] <- gsub(\"0/0\", allele_info[a,1], genotypes[a,])\n genotypes[a,] <- gsub(\"\\\\./\\\\.\", \"?\", genotypes[a,])\n genotypes[a,] <- gsub(\"1/1\", allele_info[a,2], genotypes[a,])\n genotypes[a,] <- gsub(\"0/1\", het, genotypes[a,])\n }\n }\n \n # write output\n for(a in 1:ncol(genotypes)) {\n if(a == 1) {\n write(output_names_fasta[a], file=outname, ncolumns=1)\n write(paste(genotypes[,a], collapse=\"\"), file=outname, ncolumns=1, append=T)\n } else {\n write(output_names_fasta[a], file=outname, ncolumns=1, append=T)\n write(paste(genotypes[,a], collapse=\"\"), file=outname, ncolumns=1, append=T)\n }\n }\n }\n}\n", "meta": {"hexsha": "297de600e9475a51ffc220f7a947a72653c8107d", "size": 6572, "ext": "r", "lang": "R", "max_stars_repo_path": "03_reseq_camp/window_stat_calculations.r", "max_stars_repo_name": "jdmanthey/camponotus_genomes1", "max_stars_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "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": "03_reseq_camp/window_stat_calculations.r", "max_issues_repo_name": "jdmanthey/camponotus_genomes1", "max_issues_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "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": "03_reseq_camp/window_stat_calculations.r", "max_forks_repo_name": "jdmanthey/camponotus_genomes1", "max_forks_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-29T16:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T16:29:49.000Z", "avg_line_length": 49.4135338346, "max_line_length": 159, "alphanum_fraction": 0.5091296409, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295497638851, "lm_q2_score": 0.027585283425931213, "lm_q1q2_score": 0.012290058904864294}} {"text": "\r\ncalc_fct <- function(res, ncores = NULL, SourceSplit = NULL, \r\n dxy = 1, # in m\r\n tolerance = 1e-5, # digits for rounding\r\n checkArea = TRUE\r\n ){\r\n \r\n if(!is.null(ncores)) setDTthreads(ncores)\r\n\r\n # convert old versions \r\n sres <- as.character(substitute(res))\r\n res <- copy(res)\r\n if(is.null(attr(res, \"Version\"))){\r\n warning(paste0(\"Object '\", sres[min(length(sres), 2)], \"' has not yet been converted to version 4.2+\"))\r\n convert(res)\r\n }\r\n\r\n for(g in 1:20) gc()\r\n\r\n # get relevant sources\r\n uSous <- res[, unique(Source)]\r\n Sources <- attr(res, \"ModelInput\")$Sources\r\n SourcesList <- lapply(uSous, function(x){\r\n out <- Sources[Sources[,1] %in% x,]\r\n attr(out, \"area\") <- getArea(out)\r\n out\r\n })\r\n names(SourcesList) <- uSous\r\n\r\n # get relevant sensors\r\n uSens <- res[, unique(Sensor)]\r\n Sensors <- attr(res, \"ModelInput\")$Sensors\r\n C_sens_all <- procSensors(Sensors)$Calc.Sensors\r\n C_sens <- C_sens_all[C_sens_all[, \"Sensor Name\"] %in% uSens, ]\r\n\r\n # get relevant catalogs\r\n uRn <- res[, unique(rn)]\r\n All_cats <- Catalogs(res)[Sensor %in% uSens & rn %in% uRn]\r\n # prepare catalogs\r\n Cat_Path <- CatPath(res)\r\n All_cats[, CatNum := as.integer(as.factor(Cat.Name))]\r\n C_cats <- All_cats[,{\r\n .(\r\n CatNameList = list(setNames(Cat.Name, PointSensor)),\r\n CatNums = paste(sort(unique(CatNum)), collapse = \",\"),\r\n Subset_seed = seed[1]\r\n )\r\n }, by = .(rn, Sensor)]\r\n\r\n # split sources into sub areas\r\n if(is.null(SourceSplit)) {\r\n # split\r\n SourceSplit <- splitSource(Sources[Sources[, 1] %in% uSous, ],\r\n dxy = dxy, tolerance = tolerance, checkArea = checkArea)\r\n } else {\r\n for(i in seq_along(SourceSplit)){\r\n for(j in seq_along(SourceSplit[[i]])){\r\n # allocate memory\r\n SourceSplit[[i]][[j]]$polygons <- alloc.col(SourceSplit[[i]][[j]]$polygons)\r\n }\r\n }\r\n }\r\n \r\n # copy original data.table & add columns\r\n Calc <- merge(res[,.(\r\n rn,\r\n Sensor,\r\n Source,\r\n # Subset_seed,\r\n WD,\r\n SensorHeight,\r\n Ustar,\r\n L,\r\n Zo,\r\n sUu,\r\n sVu,\r\n bw,\r\n C0,\r\n kv,\r\n A,\r\n alpha,\r\n MaxFetch,\r\n N0,\r\n fct = NA_real_\r\n )], C_cats, by = c(\"rn\", \"Sensor\"))\r\n\r\n if(!is.null(ncores) && ncores > 1){\r\n # showConnections(T)\r\n # getConnection(3)\r\n cl <- parallel::makePSOCKcluster(ncores)\r\n on.exit(parallel::stopCluster(cl))\r\n parallel::clusterEvalQ(cl, {\r\n # library(data.table)\r\n # library(bLSmodelR)\r\n data.table::setDTthreads(1)\r\n })\r\n # call parallel\r\n InList <- lapply(seq_len(nrow(Calc)), function(x, y) y[x, ], y = as.data.frame(Calc))\r\n parallel::clusterExport(cl, c(\"SourceSplit\", \"SourcesList\", \"C_sens\"), envir = environment())\r\n fct <- unlist(parallel::clusterApplyLB(cl, InList, .fct, \r\n C_Path = Cat_Path, parallel = TRUE))\r\n # fct <- unlist(parallel::clusterApplyLB(cl, InList, .fct, \r\n # SouSp = SourceSplit, SouLi = SourcesList, c_sens = C_sens, \r\n # C_Path = Cat_Path))\r\n parallel::stopCluster(cl)\r\n on.exit()\r\n } else {\r\n\r\n for(g in 1:20) gc()\r\n\r\n # loop over rows\r\n fct <- .fct(Calc, SouSp = SourceSplit, SouLi = SourcesList, \r\n c_sens = C_sens, C_Path = Cat_Path)\r\n }\r\n\r\n cbind(res, fct = fct)\r\n}\r\n\r\n# loop over rows\r\n.fct <- function(DT, SouSp = SourceSplit, SouLi = SourcesList, c_sens = C_sens, \r\n C_Path = Cat_Path, parallel = FALSE){\r\n if(parallel){\r\n setDT(DT)\r\n for(i in seq_along(SouSp)){\r\n for(j in seq_along(SouSp[[i]])){\r\n # allocate memory\r\n SouSp[[i]][[j]]$polygons <- alloc.col(SouSp[[i]][[j]]$polygons)\r\n }\r\n }\r\n }\r\n\r\n DT[,{\r\n if(!parallel){\r\n cat(\"*** row\", .BY[[1]], \"\\n\")\r\n }\r\n # get source\r\n iSource <- SouSp[[Source]]\r\n # add inside tag\r\n for(j in seq_along(iSource)){\r\n iSource[[j]]$polygons[, isInside := FALSE]\r\n }\r\n \r\n # list with point sensor names\r\n Point_Sensor <- split(names(CatNameList[[1]]), CatNameList[[1]])\r\n\r\n # loop over Catalogs\r\n for(Cat_Name in unique(CatNameList[[1]])){\r\n # get Catalog\r\n Cat0 <- readCatalog(file.path(C_Path, Cat_Name))\r\n # initialize\r\n initializeCatalog(.SD, Catalog = Cat0)\r\n # get cat N0\r\n Cat_N0 <- attr(Cat0, \"N0\")\r\n # take subset\r\n if (Cat_N0 > N0) {\r\n env <- globalenv()\r\n oseed <- env$.Random.seed\r\n set.seed(Subset_seed, kind = \"L'Ecuyer-CMRG\") \r\n takeSub <- sample.int(Cat_N0, N0)\r\n if (is.null(oseed)) {\r\n rm(list = \".Random.seed\", envir = env)\r\n } else {\r\n assign(\".Random.seed\", value = oseed, envir = env)\r\n }\r\n indexNew <- 1:N0\r\n names(indexNew) <- takeSub\r\n Cat0 <- Cat0[Traj_ID %in% takeSub, ]\r\n Cat0[, Traj_ID := indexNew[as.character(Traj_ID)]]\r\n }\r\n # rotate catalog\r\n rotateCatalog(Cat0, WD)\r\n \r\n # loop over point sensors\r\n for(ps in Point_Sensor[[Cat_Name]]){\r\n cat(\"|\\t\", ps, \"\\n\")\r\n Sens_xy <- as.numeric(c_sens[c_sens[, \"Point Sensor Name\"] %in% ps, \r\n c(\"x-Coord (m)\", \"y-Coord (m)\")])\r\n # copy catalog\r\n Cat <- Cat0[, .(x, y, inside = TRUE, inside0 = FALSE)]\r\n # add Sensor x & y\r\n Cat[, \":=\"(\r\n x = x + Sens_xy[1],\r\n y = y + Sens_xy[2]\r\n )]\r\n # get IDs inside, initial inside has to be TRUE\r\n tagNear(Cat, apply(SouLi[[Source[1]]][,2:3], 2, range))\r\n Cat[, inside0 := inside]\r\n # initialize all_check\r\n all_check <- 0\r\n # loop over sources\r\n for(jSrc in seq_along(iSource)){\r\n # jSrc <- 1\r\n iSource[[jSrc]]$polygons[(!isInside), isInside := {\r\n # copy from original inside\r\n Cat[, inside := inside0]\r\n # tag near\r\n tagNear(Cat[(inside)], .(x, y))\r\n C_sub <- Cat[(inside), .(x, y)]\r\n any(as.logical(.Call(\"pip\", C_sub[, x], C_sub[, y], C_sub[, .N], x, y, length(x), PACKAGE = \"bLSmodelR\")))\r\n }, by = .(tile, polygon)]\r\n all_check <- all_check + iSource[[jSrc]]$polygons[, as.integer(all(isInside))]\r\n }\r\n # stop if all tiles covered\r\n if(all_check == length(iSource)) break\r\n }\r\n # stop if all tiles covered\r\n if(all_check == length(iSource)) break\r\n }\r\n # calculate & return fct\r\n .(\r\n fct = sum(\r\n unlist(\r\n lapply(iSource, function(X) \r\n X$polygons[(isInside), area[1], by = .(tile, polygon)][, sum(V1)]\r\n )\r\n )\r\n ) / attr(SouLi[[Source[1]]], \"area\")\r\n )\r\n }, by = .(.Row__ = seq_len(nrow(DT)))][order(.Row__), fct]\r\n}\r\n\r\n\r\nsplitSource <- function(\r\n SourceIn,\r\n dxy = 1, # in m\r\n tolerance = 1e-5, # digits for rounding\r\n checkArea = TRUE\r\n ) {\r\n digits <- -floor(log10(tolerance))\r\n tol <- 10 ^ -digits\r\n\r\n setNumericRounding(2)\r\n\r\n # get source names\r\n uSourceNames <- unique(SourceIn[, 1])\r\n\r\n out <- lapply(uSourceNames, function(SourceName){\r\n # SourceName <- Source[1,1]\r\n Source <- SourceIn[SourceIn[, 1] %in% SourceName, ]\r\n # start lapply over polyID\r\n lapply(unique(Source[,4]), function(polyID){\r\n SubSource <- Source[Source[,4] %in% polyID,]\r\n xyMeans <- colMeans(SubSource[,2:3])\r\n SubSource[,2:3] <- round(sweep(SubSource[, 2:3], 2, xyMeans), digits - 1)\r\n Poly <- setNames(SubSource[,2:3], c(\"x\", \"y\"))\r\n Poly_extr <- attr(procSources(SubSource), \"SourceList\")[[SourceName]][, 1:2]\r\n Poly_lines <- lapply(seq_len(nrow(Poly_extr) - 1), function(x) {\r\n list(\r\n p1 = as.numeric(Poly_extr[x, ]),\r\n p2 = as.numeric(Poly_extr[x + 1, ])\r\n )\r\n })\r\n # # possibly problems with values close to 0?\r\n # Poly_lines_dir <- lapply(Poly_lines, function(x){\r\n # list(x = sign(x$p2[1] - x$p1[1]), y = sign(x$p2[2] - x$p1[2]))\r\n # })\r\n\r\n ##### Ablauf:\r\n # browser()\r\n # get BB (extended)\r\n BBoxOrig <- list(\r\n x = trunc(range(Poly$x)) + c(-1, 1), \r\n y = trunc(range(Poly$y)) + c(-1, 1)\r\n # x = range(Poly$x), \r\n # y = range(Poly$y)\r\n )\r\n BBdim <- lapply(BBoxOrig, diff)\r\n BBdim_ext <- lapply(BBdim, function(x) ceiling(x / dxy) * dxy)\r\n BBadd <- mapply(\"-\", BBdim_ext, BBdim) / 2\r\n BBox <- mapply(function(x, y) x + c(-1, 1) * y, x = BBoxOrig, y = BBadd, SIMPLIFY = FALSE)\r\n\r\n # liste mit matrix mit dxy -> grid\r\n # x & y vectors\r\n x_seq <- seq(BBox$x[1], BBox$x[2], by = dxy)\r\n y_seq <- seq(BBox$y[1], BBox$y[2], by = dxy)\r\n\r\n # create matrix M\r\n dimx <- length(x_seq) - 1\r\n dimy <- length(y_seq) - 1\r\n M <- matrix(seq_len(dimx * dimy), ncol = dimy, nrow = dimx)\r\n\r\n ####### inside\r\n # create grids Gxy & G\r\n Gxy <- as.matrix(expand.grid(row = seq_along(x_seq), col = seq_along(y_seq), KEEP.OUT.ATTRS = FALSE))\r\n G <- as.matrix(expand.grid(x = x_seq, y = y_seq, KEEP.OUT.ATTRS = FALSE))\r\n\r\n # - check Eckpunkte inside\r\n corner_inside <- as.logical(.Call(\"pip\", G[, 1], G[, 2], nrow(G), Poly[, 1], \r\n Poly[, 2], nrow(Poly), PACKAGE = \"bLSmodelR\"))\r\n corner_inside_index <- which(corner_inside)\r\n Gxy_inside <- Gxy[corner_inside,, drop = FALSE]\r\n\r\n # get tiles in M\r\n M_xy <- apply(Gxy_inside, 1, function(x){\r\n c(x[1] + c(-1, 0), x[2] + c(-1, 0))\r\n })\r\n M_xy[M_xy == 0] <- NA\r\n M_tiles <- apply(M_xy, 2, function(x){\r\n c(\r\n (x[3] - 1) * dimx + x[1],\r\n (x[3] - 1) * dimx + x[2],\r\n (x[4] - 1) * dimx + x[1],\r\n (x[4] - 1) * dimx + x[2]\r\n )\r\n })\r\n # count corners inside per tile\r\n Tiles_count <- table(M_tiles)\r\n\r\n ####### intersecting\r\n # get all points with x_i | y_j intersect mit source_poly\r\n vert <- lapply(x_seq, function(px) list(p1 = c(px, BBox$y[1]), p2 = c(px, BBox$y[2])))\r\n horiz <- lapply(y_seq, function(py) list(p1 = c(BBox$x[1], py), p2 = c(BBox$x[2], py)))\r\n \r\n # check vertical grid\r\n Vcheck <- do.call(\"rbind\", \r\n lapply(seq_along(vert), function(v) do.call(\"rbind\", \r\n lapply(seq_along(Poly_lines), function(i){\r\n cbind(inters(Poly_lines[[i]]$p1, Poly_lines[[i]]$p2, vert[[v]]$p1, vert[[v]]$p2, tol), \r\n Poly_lines_entry = i, Line_row = v, Line_col = NA)\r\n }))))\r\n # check horizontal grid\r\n Hcheck <- do.call(\"rbind\", \r\n lapply(seq_along(horiz), function(v) do.call(\"rbind\",\r\n lapply(seq_along(Poly_lines), function(i){\r\n cbind(inters(Poly_lines[[i]]$p1, Poly_lines[[i]]$p2, horiz[[v]]$p1, horiz[[v]]$p2, tol), \r\n Poly_lines_entry = i, Line_row = NA, Line_col = v)\r\n }))))\r\n\r\n # bind together\r\n All_points <- rbind(\r\n Vcheck[Vcheck[,3] == 1, ], \r\n Hcheck[Hcheck[,3] == 1, ]\r\n )\r\n\r\n # inters(Poly_lines[[1]]$p1, Poly_lines[[1]]$p2, horiz[[18]]$p1, horiz[[18]]$p2, tol)\r\n\r\n # find segment lines by x & y -> row, col\r\n Line_rows <- All_points[,\"Line_row\"]\r\n isna_row <- is.na(Line_rows)\r\n Line_rows[isna_row] <- findInterval(All_points[isna_row, 1], x_seq, rightmost.closed = TRUE)\r\n Line_cols <- All_points[,\"Line_col\"]\r\n isna_col <- is.na(Line_cols)\r\n Line_cols[isna_col] <- findInterval(All_points[isna_col, 2], y_seq, rightmost.closed = TRUE)\r\n\r\n # check exact matching\r\n Outer_rows <- abs(outer(All_points[, 1], x_seq, \"-\")) < tol\r\n Exact_rows <- as.logical(rowSums(Outer_rows) > 0)\r\n Outer_cols <- abs(outer(All_points[, 2], y_seq, \"-\")) < tol\r\n Exact_cols <- as.logical(rowSums(Outer_cols) > 0)\r\n # check for exact matches in foundIntervals\r\n if(any(Exact_rows[isna_row])){\r\n Line_rows[Exact_rows & isna_row] <- apply(Outer_rows[Exact_rows & isna_row, , drop = FALSE], 1, which)\r\n }\r\n if(any(Exact_cols[isna_col])){\r\n Line_cols[Exact_cols & isna_col] <- apply(Outer_cols[Exact_cols & isna_col, , drop = FALSE], 1, which)\r\n }\r\n\r\n # check exact corner\r\n Exact_corners <- Exact_rows & Exact_cols\r\n \r\n # round with digits\r\n All_points[, \"x\"] <- round(All_points[, \"x\"], digits - 1)\r\n All_points[, \"y\"] <- round(All_points[, \"y\"], digits - 1)\r\n\r\n # find Tiles to check: lines -> 2 Tiles\r\n Border_x <- rbind(\r\n data.table(\r\n row = Line_rows[Exact_rows & !Exact_corners],\r\n col = Line_cols[Exact_rows & !Exact_corners],\r\n Px = All_points[Exact_rows & !Exact_corners, 1],\r\n Py = All_points[Exact_rows & !Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_rows & !Exact_corners, 4]\r\n ),\r\n data.table(\r\n row = Line_rows[Exact_rows & !Exact_corners] - 1,\r\n col = Line_cols[Exact_rows & !Exact_corners],\r\n Px = All_points[Exact_rows & !Exact_corners, 1],\r\n Py = All_points[Exact_rows & !Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_rows & !Exact_corners, 4]\r\n ))\r\n Border_y <- rbind(\r\n data.table(\r\n row = Line_rows[Exact_cols & !Exact_corners],\r\n col = Line_cols[Exact_cols & !Exact_corners],\r\n Px = All_points[Exact_cols & !Exact_corners, 1],\r\n Py = All_points[Exact_cols & !Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_cols & !Exact_corners, 4]\r\n ),\r\n data.table(\r\n row = Line_rows[Exact_cols & !Exact_corners],\r\n col = Line_cols[Exact_cols & !Exact_corners] - 1,\r\n Px = All_points[Exact_cols & !Exact_corners, 1],\r\n Py = All_points[Exact_cols & !Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_cols & !Exact_corners, 4]\r\n ))\r\n\r\n # find Tiles to check: corners -> 4 Tiles\r\n Border_xy <- rbind(\r\n data.table(\r\n row = Line_rows[Exact_corners],\r\n col = Line_cols[Exact_corners],\r\n Px = All_points[Exact_corners, 1],\r\n Py = All_points[Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_corners, 4]\r\n ),\r\n data.table(\r\n row = Line_rows[Exact_corners] - 1,\r\n col = Line_cols[Exact_corners],\r\n Px = All_points[Exact_corners, 1],\r\n Py = All_points[Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_corners, 4]\r\n ),\r\n data.table(\r\n row = Line_rows[Exact_corners],\r\n col = Line_cols[Exact_corners] - 1,\r\n Px = All_points[Exact_corners, 1],\r\n Py = All_points[Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_corners, 4]\r\n ),\r\n data.table(\r\n row = Line_rows[Exact_corners] - 1,\r\n col = Line_cols[Exact_corners] - 1,\r\n Px = All_points[Exact_corners, 1],\r\n Py = All_points[Exact_corners, 2],\r\n Poly_lines_entry = All_points[Exact_corners, 4]\r\n )\r\n )\r\n\r\n # gather all tiles\r\n Border_all <- rbind(Border_x,Border_y,Border_xy)\r\n\r\n # remove borders\r\n Border <- Border_all[\r\n row > 0 &\r\n col > 0 &\r\n row <= dimx &\r\n col <= dimy,]\r\n # add Tile number\r\n Border[, tile := (Border$col - 1) * dimx + Border$row]\r\n\r\n # get number of corners inside source\r\n Border[, nc := 0L]\r\n Border[as.character(tile) %chin% names(Tiles_count), nc := {\r\n t_c <- as.character(tile)\r\n Tiles_count[t_c[t_c %in% names(Tiles_count)]]\r\n }]\r\n\r\n\r\n # # -> was falls mehrere polygons? (eher unwahrsch.)\r\n # # einbauen: if(count(Poly_lines_entry) > 2) -> mehrere Polygons\r\n # if(polyID == 2)browser()\r\n\r\n # check & get polygons\r\n All <- Border[, {\r\n\r\n # borders\r\n x_le <- x_seq[row[1]]\r\n x_ri <- x_seq[row[1] + 1]\r\n y_lo <- y_seq[col[1]]\r\n y_hi <- y_seq[col[1] + 1]\r\n\r\n # any points inside?\r\n pts_inside <- suppressWarnings(do.call(rbind, lapply(seq_len(nrow(Poly)), function(i){\r\n if(Poly[i, 1] >= x_le & Poly[i, 1] <= x_ri & \r\n Poly[i, 2] >= y_lo & Poly[i, 2] <= y_hi ){\r\n data.table(Poly[i, ], label = paste0(\"L\",c((i - 2) %% nrow(Poly) + 1, i)))\r\n } else {\r\n NULL\r\n }\r\n })))\r\n\r\n # get corners inside\r\n Corner <- as.data.table(G[corner_inside_index[which(colSums(M_tiles == .BY[[1]]) > 0)], , drop = FALSE])\r\n\r\n # get labels of corners\r\n Corner[, label := {\r\n LR <- c(\"L\", \"R\")[(abs(x - x_ri) < tol) + 1]\r\n BT <- c(\"B\", \"T\")[(abs(y - y_hi) < tol) + 1]\r\n paste0(\"C\", sapply(paste0(LR,BT), switch,\r\n \"LB\" = 1,\r\n \"RB\" = 2,\r\n \"RT\" = 3,\r\n \"LT\" = 4\r\n ))\r\n }]\r\n\r\n # browser()\r\n\r\n # cat(.BY$tile,\"\\n\")\r\n # if(.BY$tile == 14) browser() # -> Corner of Source Area!\r\n # if(.BY$tile == 18) browser() # -> sprintf of 0 results in -0.00 ???!!!\r\n\r\n # check if line corner is exactly on corner (klappt das so, falls beide lines entlang dem edge gehen???)\r\n fmt <- paste0(\"%1.\", digits,\"f\")\r\n fmt_xy <- paste(fmt, fmt, sep = \"::\")\r\n crn_xy <- Corner[, sprintf(fmt_xy, abs(x) * sign(x), abs(y) * sign(y))]\r\n sd_xy <- sprintf(fmt_xy, abs(Px) * sign(Px), abs(Py) * sign(Py))\r\n if(any(sd_dup <- duplicated(sd_xy))){\r\n sd_check <- sd_xy[sd_dup]\r\n sd_remove <- sd_check[sd_check %in% crn_xy]\r\n if(length(sd_remove) > 0){\r\n # remove lines on corner\r\n SD0 <- .SD[!(sd_xy %in% sd_remove), \r\n .(x = Px, y = Py, label = paste0(\"L\", Poly_lines_entry))]\r\n sd_xy <- sd_xy[!(sd_xy %in% sd_remove)]\r\n } else {\r\n # remove corners on line\r\n SD0 <- .SD[, .(x = Px, y = Py, label = paste0(\"L\", Poly_lines_entry))]\r\n }\r\n } else if(.N > 1) {\r\n # remove corners on line\r\n SD0 <- .SD[, .(x = Px, y = Py, label = paste0(\"L\", Poly_lines_entry))]\r\n } else {\r\n # corner lies ecaxtly on line corner\r\n SD0 <- NULL\r\n sd_xy <- NULL\r\n }\r\n\r\n # check if corner falls on line or on pnts inside\r\n if(is.null(pts_inside)){\r\n if(any(crn_xy %in% sd_xy)) {\r\n Corner0 <- Corner[!(crn_xy %in% sd_xy)]\r\n } else {\r\n Corner0 <- Corner\r\n }\r\n } else {\r\n inside_xy <- pts_inside[, sprintf(fmt_xy, abs(x) * sign(x), abs(y) * sign(y))]\r\n if(any(crn_xy %in% sd_xy, crn_xy %in% inside_xy)) {\r\n Corner0 <- Corner[!(crn_xy %in% sd_xy) & !(crn_xy %in% inside_xy)]\r\n } else {\r\n Corner0 <- Corner\r\n } \r\n }\r\n\r\n # rbind (unique nicht mehr noetig?)\r\n DT <- unique(rbind(\r\n Corner0,\r\n # Corner,\r\n # if(!is.null(SD0)) SD0[.N:1, ],\r\n SD0,\r\n pts_inside\r\n ))\r\n\r\n # plot(c(x_le, x_ri), c(y_lo, y_hi), type = \"n\")\r\n # rect(x_le, y_lo, x_ri, y_hi, lwd = 2, border = \"darkgrey\")\r\n # if(!is.null(pts_inside)) pts_inside[, points(x, y, col = \"darkgreen\")]\r\n # Corner[, points(x, y, pch = 20, cex = 1.5)]\r\n # PLE <- unique(Poly_lines_entry)\r\n # for(ple in seq_along(PLE)){\r\n # points(Px[Poly_lines_entry == PLE[ple]], Py[Poly_lines_entry == PLE[ple]], type = \"b\", col = \"red\")\r\n # }\r\n\r\n # if(.BY$tile == 9721) browser()\r\n # if(polyID == 2 && .BY$tile == 187) browser()\r\n\r\n # go around corners\r\n if(DT[, .N > 0]){\r\n DT[, \":=\"(\r\n included = FALSE,\r\n rn = 1:.N,\r\n polygon = NA_character_,\r\n polygon_order = NA_integer_,\r\n edge = checkEdge(x, y, y_lo, x_ri, y_hi, x_le, tol),\r\n corners = nc[1]\r\n ) ]\r\n poly_order <- poly_number <- 1L\r\n # get first point\r\n pnt <- DT[1,]\r\n # set polygon values in DT\r\n DT[1, \":=\"(\r\n included = TRUE,\r\n polygon = letters[poly_number],\r\n polygon_order = poly_order\r\n )]\r\n while(DT[,any(!included)]){\r\n # get point label\r\n pnt_lbl <- pnt[, label]\r\n # check if corner or line\r\n if(grepl(\"C\", pnt_lbl)){\r\n # corner\r\n if(pnt_lbl %in% c(\"C4\", \"C2\")){\r\n # check matching x & best y\r\n pnt <- DT[!included & abs(x - pnt[, x]) < tol][\r\n which.min(abs(y - pnt[, y]))]\r\n } else {\r\n # check matching y & best x\r\n pnt <- DT[!included & abs(y - pnt[, y]) < tol][\r\n which.min(abs(x - pnt[, x]))]\r\n }\r\n } else {\r\n # line\r\n if(DT[!(included), pnt_lbl %chin% label]){\r\n # take next point with label\r\n pnt <- DT[!included & label %in% pnt_lbl]\r\n } else {\r\n # search for next point on corresponding edge\r\n if(pnt[, edge == 5]){\r\n # point inside -> check for point repetition\r\n pnt <- DT[!included & abs(x - pnt[,x]) < tol & abs(y - pnt[,y]) < tol]\r\n } else {\r\n # check side for next point\r\n Side <- pnt[, edge]\r\n if(Side %in% c(2, 4)){\r\n # check matching x & best y\r\n pnt <- DT[!included & abs(x - pnt[, x]) < tol][\r\n which.min(abs(y - pnt[, y]))]\r\n } else {\r\n # check matching y & best x\r\n pnt <- DT[!included & abs(y - pnt[, y]) < tol][\r\n which.min(abs(x - pnt[, x]))]\r\n }\r\n }\r\n }\r\n }\r\n if(nrow(pnt)){\r\n # update poly_order\r\n poly_order <- poly_order + 1\r\n # set polygon values in DT\r\n DT[rn == pnt[, rn], \":=\"(\r\n included = TRUE,\r\n polygon = letters[poly_number],\r\n polygon_order = poly_order\r\n )]\r\n } else {\r\n # update poly_* for next polygon\r\n poly_order <- 1\r\n poly_number <- poly_number + 1\r\n pnt <- DT[!(included)][1,] \r\n DT[rn == pnt[, rn], \":=\"(\r\n included = TRUE,\r\n polygon = letters[poly_number],\r\n polygon_order = poly_order\r\n )]\r\n }\r\n }\r\n\r\n\r\n # DT[order(polygon_order)][,{\r\n # polygon(x, y, \r\n # col = c(\"#D63636\", \"#2E64EE\", \"green\", \"orange\", \"purple\")[.BY$corners + 1])\r\n # }, by = .(corners, polygon)]\r\n\r\n # DT[order(polygon_order), plot(x, y, type = \"b\")]\r\n DT[order(polygon_order), ][, area := {\r\n ind <- c(.N, seq(.N - 1))\r\n abs(sum(x * y[ind] - x[ind] * y)) / 2 \r\n }, by = polygon]\r\n } else {\r\n NULL\r\n }\r\n }, by = tile]\r\n\r\n # correct for xyMeans\r\n x_seq <- x_seq + xyMeans[1]\r\n y_seq <- y_seq + xyMeans[2]\r\n Poly$x <- Poly$x + xyMeans[1]\r\n Poly$y <- Poly$y + xyMeans[2]\r\n\r\n # output\r\n out <- list(\r\n x_seq = x_seq,\r\n y_seq = y_seq,\r\n polygons = rbind(\r\n All[, .(tile, polygon,\r\n x = x + xyMeans[1], \r\n y = y + xyMeans[2], \r\n corners, area)],\r\n data.table(tile = as.integer(names(Tiles_count[Tiles_count == 4])) %w/o% All[,unique(tile)])[, {\r\n col <- ceiling(tile / dimx)\r\n row <- tile - (col - 1) * dimx\r\n .(\r\n polygon = \"a\",\r\n x = x_seq[row + c(0, 1, 1, 0)],\r\n y = y_seq[col + c(0, 0, 1, 1)],\r\n corners = -1L,\r\n area = dxy * dxy\r\n )}, by = tile]),\r\n dxy = dxy,\r\n tolerance = tolerance,\r\n digits = digits,\r\n tol = tol,\r\n SourcePoly = Poly\r\n )\r\n\r\n if(checkArea && abs(getArea(SubSource) - out$polygons[,area[1], by = .(tile, polygon)][,sum(V1)]) > sqrt(tol)){\r\n x11()\r\n # plotM(out)\r\n plot(Poly$x[c(1:nrow(Poly),1)], Poly$y[c(1:nrow(Poly),1)], type = \"l\", lwd = 2)\r\n # ,xlim = c(-1, 1) + 711620, ylim = c(-1, 1) + 260850)\r\n plotPolys(out)\r\n stop(\"polygons area and total area differ by more than sqrt(tol)! try to set a better dxy..\")\r\n } else {\r\n out\r\n }\r\n\r\n })\r\n # end lapply over polygon ID\r\n })\r\n # end lapply over sources\r\n setNames(out, uSourceNames)\r\n}\r\n\r\ninters <- function(l1_p1, l1_p2, l2_p1, l2_p2, tol = 1e-5){\r\n # rewrite as vectors\r\n # -> https://demonstrations.wolfram.com/IntersectionOfTwoLinesUsingVectors/\r\n # browser()\r\n VZ <- l1_p2 - l1_p1\r\n UW <- l2_p2 - l2_p1\r\n mvz <- sqrt(sum(VZ ^ 2))\r\n muw <- sqrt(sum(UW ^ 2))\r\n beta <- acos(sum(VZ * UW) / (mvz * muw))\r\n UV <- l2_p1 - l1_p1\r\n muv <- sqrt(sum(UV ^ 2))\r\n alpha <- acos(sum(UV * UW) / (muv * muw))\r\n\r\n out <- l1_p1 + muv * sin(alpha) / sin(beta) * VZ / mvz\r\n \r\n return(cbind(\r\n x = out[1],\r\n y = out[2],\r\n inside =\r\n (\r\n (\r\n (out[1] - l1_p1[1]) >= -tol &&\r\n (out[1] - l1_p2[1]) <= tol\r\n ) || (\r\n (out[1] - l1_p1[1]) <= tol &&\r\n (out[1] - l1_p2[1]) >= -tol\r\n )\r\n ) && (\r\n (\r\n (out[1] - l2_p1[1]) >= -tol &&\r\n (out[1] - l2_p2[1]) <= tol\r\n ) || (\r\n (out[1] - l2_p1[1]) <= tol &&\r\n (out[1] - l2_p2[1]) >= -tol\r\n )\r\n ) && (\r\n (\r\n (out[2] - l1_p1[2]) >= -tol &&\r\n (out[2] - l1_p2[2]) <= tol\r\n ) || (\r\n (out[2] - l1_p1[2]) <= tol &&\r\n (out[2] - l1_p2[2]) >= -tol\r\n )\r\n ) && (\r\n (\r\n (out[2] - l2_p1[2]) >= -tol &&\r\n (out[2] - l2_p2[2]) <= tol\r\n ) || (\r\n (out[2] - l2_p1[2]) <= tol &&\r\n (out[2] - l2_p2[2]) >= -tol\r\n )\r\n ) \r\n ))\r\n}\r\n\r\ncheckEdge <- function(x, y, y_lo, x_ri, y_hi, x_le, tol = 1e-5){\r\n out <- rep(1, length(x))\r\n out[abs(x - x_le) < tol] <- out[abs(x - x_le) < tol] * 11\r\n out[abs(y - y_hi) < tol] <- out[abs(y - y_hi) < tol] * 7\r\n out[abs(x - x_ri) < tol] <- out[abs(x - x_ri) < tol] * 5\r\n out[abs(y - y_lo) < tol] <- out[abs(y - y_lo) < tol] * 3\r\n sapply(as.character(out), switch,\r\n \"3\" = 1, \"33\" = 1,\r\n \"5\" = 2, \"15\" = 2,\r\n \"7\" = 3, \"35\" = 3,\r\n \"11\" = 4, \"77\" = 4, 5)\r\n}\r\n\r\n# plotM <- function(X, xlim = NULL, ylim = NULL, cex.text = 0.35){\r\n# plot(range(X$x_seq), range(X$y_seq),type = \"n\", xlim = xlim, ylim = ylim)\r\n# lines(X$SourcePoly$x[c(1:nrow(X$SourcePoly),1)],X$SourcePoly$y[c(1:nrow(X$SourcePoly),1)], lwd = 2)\r\n# abline(h = X$y_seq)\r\n# abline(h = X$y_seq[c(1, length(X$y_seq))], lwd = 2)\r\n# abline(v = X$x_seq)\r\n# abline(v = X$x_seq[c(1, length(X$x_seq))], lwd = 2)\r\n# X$polygons[,{\r\n# polygon(x, y, \r\n# col = c(\"lightgrey\", \"#D63636\", \"#2E64EE\", \"green\", \"orange\", \"purple\")[.BY$corners + 2])\r\n# }, by = .(corners, tile, polygon)]\r\n# Tgrid <- expand.grid(X$x_seq[-1] - X$dxy/2, X$y_seq[-1] - X$dxy/2)\r\n# text(Tgrid[,1], Tgrid[,2], 1:nrow(Tgrid), cex = cex.text)\r\n# }\r\n\r\nplotPolys <- function(X, xlim = NULL, ylim = NULL, cex.text = 0.35,\r\n col = c(\"lightgrey\", \"#D63636\", \"#2E64EE\", \"green\", \"orange\", \"purple\"),\r\n tileNumbers = TRUE){\r\n if(length(col) == 1) col <- rep(col , 6)\r\n X$polygons[,{\r\n polygon(x, y, \r\n col = col[.BY$corners + 2])\r\n }, by = .(corners, tile, polygon)]\r\n if(tileNumbers){\r\n Tgrid <- expand.grid(X$x_seq[-1] - X$dxy/2, X$y_seq[-1] - X$dxy/2)\r\n text(Tgrid[,1], Tgrid[,2], 1:nrow(Tgrid), cex = cex.text)\r\n }\r\n}\r\n", "meta": {"hexsha": "36f34a6740078c2f3339088c10a8d7a8d1018ca3", "size": 27801, "ext": "r", "lang": "R", "max_stars_repo_path": "R/fraction_function.r", "max_stars_repo_name": "kwheelan/bLSmodelR", "max_stars_repo_head_hexsha": "a89d710c03786a12716ef40acfaf6071230b38d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-03-04T17:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:56:20.000Z", "max_issues_repo_path": "R/fraction_function.r", "max_issues_repo_name": "kwheelan/bLSmodelR", "max_issues_repo_head_hexsha": "a89d710c03786a12716ef40acfaf6071230b38d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-09-10T07:34:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T12:41:34.000Z", "max_forks_repo_path": "R/fraction_function.r", "max_forks_repo_name": "kwheelan/bLSmodelR", "max_forks_repo_head_hexsha": "a89d710c03786a12716ef40acfaf6071230b38d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-11-12T10:56:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:22:52.000Z", "avg_line_length": 34.7947434293, "max_line_length": 119, "alphanum_fraction": 0.4932916082, "num_tokens": 8353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.02716923340648548, "lm_q1q2_score": 0.012104695526924825}} {"text": "co2_data <- read.csv(\"https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv\")\nlibrary(shiny)\nlibrary(dplyr)\nlibrary(plotly)\nui <- fluidPage(\n tabsetPanel(\n tabPanel(\"Introduction\",\n h2(\"Overview\"),\n br(),\n p(\"This is a paragraph. In this assignment I have chosen to look at the change in CO2 over time in comparison to country. I chose to use CO2 in millions of tons and CO2 per capita based on the country. \n The line graph shows a trend from when the data was first collected until 2020. The dataset consists of many features regarding the different ways CO2 is encountered in our world. The data is collected\n and maintined by Our World in Data, which is a publication that is tasked with finding the largest global problems\n (in this case CO2 emission) and how pwerful changes can reshape the world. As per the About page on their website, Our World In Data \n uses both a small team and the works and research from a community of scholars around the world.\n They do this so that they can get multiple persepctives and post the best available research and data in an understandable way.\n Further, the publication collects the data so that there is available information about CO2 emissions for the public to educate themselves with. \n They design their work in an effort to create an impact that goes beyond what they themselves as a company can fulfill directly.Because the dataset is so large and contains\n data from countries all over the world, one limitation could be that the data is skewed in countries that are not super open about their CO2 emissions. \n In addition, another problem with the data could be that it has periods of time where there is no data present, making a variable's trend seem steeper in either way.\"),\n br(),\n p(\"Some relevant values in the data are: 2005 is the largest amount of CO2 emitted by the United states in history at a staggering 6,134 million tons. This is in comparison\n to when it was at its lowest in 1800 at .253 million tons. Over the past 10 years, CO2 emissions in America has dropped by 853 million tons. Currently, the United States\n is putting out about 4,712 million tons of CO2 (in 2020). Lastly, since the start of when the data was recorded for America, the median amount is 2,356.51 million tons.\"),\n \n ),\n \n tabPanel(\"Visualization\",\n sidebarLayout(\n sidebarPanel(\n selectInput(\"Variable\", \"Select the Variable\", c(\"co2\", \"co2_per_capita\")),\n selectInput(\"Country\", \"Select Country\", sort(unique(co2_data$country)))\n \n ),\n mainPanel(\n plotlyOutput(\"Plot\")\n )\n )),\n tabPanel(\"Value Sensitive Design\",\n h2(\"Value Sensitive Design\"),\n br(),\n p(\"Envision your system in use by a single stakeholder. Now imagine 100 such individuals interacting with the system. \n Then 1,000 individuals. Then 100,00. What new interactions might emerge from widespread use? Find three synergistic benefits of widespread \n use and three potential breakdowns.\"),\n br(),\n p(\"Three benefits of widespread use can include the following: More people are educated on why a certain topic it matters.\n Another is that, as I stated before, people can act upon something that is widespread that has come across their path in ways that others\n before could not have. An example of this is that an issue like this comes to the attention of a large company and they get involved to \n improve the sitaution. Lastly, this eliminates the questions about certain phenomenons such as CO2 emissions by widespreading the data\n thereby making it a fact knwon by all.\"),\n br(),\n p(\"Three potential breakdowns of widespread use are as follows: Creation of tensions between those who collect data such as researchers and companies due \n to different findings. In addition, widespread use of real-world data can also get into the hands of those who intend to intentionally misuse it to \n push an agenda. This was seen a lot during the COVID-19 pandemic. Lastly, when data is released widespread it is the raw form of the data, so it\n is hard for an everyday person to interpret the data unles they know how to.\"),\n \n ))\n \n )\n \nserver <- function(input, output) {\n output$Plot <- renderPlotly({\n ylab <- setNames(c(\"CO2 in Millions of Tons\", \"CO2 in Tons Per Capita\"),\n c(\"co2\", \"co2_per_capita\"))\n df <- co2_data %>%\n filter(country == input$Country)\n plot_ly() %>%\n add_trace(\n type = \"scatter\", mode = \"markers+lines+text\", \n x = df$year, y = df[,input$Variable]\n \n ) %>%\n layout(title = \"CO2 Change Over Time\", xaxis = list(title = \"Year\"), yaxis = list(title = ylab[input$Variable]))\n })\n \n}\nshinyApp(ui, server)\n", "meta": {"hexsha": "fda4c7c9d0e001ec550968bbd297ae092a590053", "size": 5256, "ext": "r", "lang": "R", "max_stars_repo_path": "app_server.r", "max_stars_repo_name": "info-201b-wi22/a4-climate-change-wsdmdsw1-1764374", "max_stars_repo_head_hexsha": "6695be91863c0772386aa86b0a4039bfbedb5ad8", "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_server.r", "max_issues_repo_name": "info-201b-wi22/a4-climate-change-wsdmdsw1-1764374", "max_issues_repo_head_hexsha": "6695be91863c0772386aa86b0a4039bfbedb5ad8", "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_server.r", "max_forks_repo_name": "info-201b-wi22/a4-climate-change-wsdmdsw1-1764374", "max_forks_repo_head_hexsha": "6695be91863c0772386aa86b0a4039bfbedb5ad8", "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": 68.2597402597, "max_line_length": 216, "alphanum_fraction": 0.6586757991, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.044680867569444296, "lm_q1q2_score": 0.012016536555785266}} {"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\n# Performs ordered logistic regression test and saves results in ordered logistic results file\ntestCategoricalOrdered <- function(varName, currentVar, varType, thisdata, orderStr=\"\") {\n\n\n\tpheno = thisdata[,phenoStartIdx:ncol(thisdata)]\n\tgeno = thisdata[,\"geno\"]\n\n\tcat(\"CAT-ORD || \");\n\tincrementCounter(\"ordCat\")\n\n\tdoCatOrdAssertions(pheno)\n\n\tuniqVar = unique(na.omit(pheno));\n\n\t# log the ordering of categories used\n\torderStr = setOrderString(orderStr, uniqVar);\n\tcat(\"order: \", orderStr, \" || \", sep=\"\");\n\n\t# check sample size\n\tnumNotNA = length(which(!is.na(pheno)))\n\tif (numNotNA<500) {\n\t\tcat(\"CATORD-SKIP-500 (\", numNotNA, \") || \",sep=\"\");\n\t\tincrementCounter(\"ordCat.500\")\n\t}\n\telse {\n\t\t# test this cat ordered variable with ordered logistic regression\t\n\n\t\tphenoFactor = factor(pheno)\n\n\t\tcat(\"num categories: \", length(unique(na.omit(phenoFactor))), \" || \", sep=\"\");\n\n\t\tif (opt$save == TRUE) {\n\t\t\t# add pheno to dataframe\n\t\t\t#storeNewVar(thisdata[,\"userID\"], phenoFactor, varName, 'catOrd')\n\t\t\tstoreNewVar(thisdata[,\"userID\"], phenoFactor, currentVar, 'catOrd')\n\t\t\tcat(\"SUCCESS results-ordered-logistic\");\n\t\t\tincrementCounter(\"success.ordCat\")\n\t\t}\n\n\t\t# ordinal logistic regression\n\t\tsink()\n\t\tsink(modelFitLogFile, append=TRUE)\n\t\tprint(\"--------------\")\n\t\tprint(varName)\n\n\t\trequire(MASS)\n\t\trequire(lmtest)\n\n\t\t### BEGIN TRYCATCH\n\t\ttryCatch({\n\t\t\tconfounders=thisdata[,3:numPreceedingCols, drop = FALSE]\n\n\t\t\tif (opt$standardise==TRUE) {\n\t\t\t\tgeno = scale(geno)\n\t\t\t}\n\n\t\t\tfit <- polr(phenoFactor ~ geno + ., data=confounders, Hess=TRUE)\n\n\t\t\tctable <- coef(summary(fit))\n\t\t\tsink()\n\t\t\tsink(resLogFile, append=TRUE)\n\n\t\t\tct = coeftest(fit)\n\t\t\tpvalue = ct[\"geno\",\"Pr(>|t|)\"]\n\t\t\tbeta = ctable[\"geno\", \"Value\"];\n\n\t\t\tif (opt$confidenceintervals == TRUE) {\n\t\t\t\tse = ctable[\"geno\", \"Std. Error\"]\n\t\t\t\tlower = beta - 1.96*se;\n\t\t\t\tupper = beta + 1.96*se;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlower = NA\n\t\t\t\tupper = NA\n\t\t\t}\n\n\t\t\twrite(paste(paste0(\"\\\"\", varName, \"\\\"\"), paste0(\"\\\"\", currentVar, \"\\\"\"), varType, numNotNA, beta, lower, upper, pvalue, sep=\",\"), file=paste(opt$resDir,\"results-ordered-logistic-\",opt$varTypeArg,\".txt\",sep=\"\"), append=\"TRUE\");\n\t\t\tcat(\"SUCCESS results-ordered-logistic\");\n\t\t\tincrementCounter(\"success.ordCat\")\n\n\t\t\tisExposure = getIsExposure(varName)\n\t\t\tif (isExposure == TRUE) {\n\t\t\t\tincrementCounter(\"success.exposure.ordCat\")\n\t\t\t}\n\n\t\t\t### END TRYCATCH\n\t\t}, error = function(e) {\n\t\t\tsink()\n\t\t\tsink(resLogFile, append=TRUE)\n\t\t\tcat(paste(\"ERROR:\", varName,gsub(\"[\\r\\n]\", \"\", e), sep=\" \"))\n\t\t\tincrementCounter(\"ordCat.error\")\n\t\t})\n\t}\n}\n\n# check that the phenotype is valid - that there are more than two categories\n# and that these all have at least 10 cases\n# something has gone wrong if this is the case\ndoCatOrdAssertions <- function(pheno) {\n\n\t# assert variable has only one column \n\tif (!is.null(dim(pheno))) stop(\"More than one column for categorical ordered\")\n\n\tuniqVar = unique(na.omit(pheno));\n\n\t# assert more than 2 categories\n\tif (length(uniqVar)<=1) stop(\"1 or zero values\")\n\tif (length(uniqVar)==2) stop(\"this variable is binary\")\n\n\t# assert each value has >= 10 examples\n\tfor (u in uniqVar) {\n\t\twithValIdx = which(pheno==u)\n\t\tnumWithVal = length(withValIdx);\n\n\t\tif (numWithVal=0) # ignore missing values\n\t\t\t\torderStr = paste(orderStr, i, sep=\"\");\n\t\t\tfirst=0;\n\t\t\tend\n\t\t}\n\t}\n\treturn(orderStr);\n}\n", "meta": {"hexsha": "7e78c40faf404a560246251448bc3efc680befc4", "size": 5038, "ext": "r", "lang": "R", "max_stars_repo_path": "WAS/testCategoricalOrdered.r", "max_stars_repo_name": "kevmanderson/PHESANT", "max_stars_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "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": "WAS/testCategoricalOrdered.r", "max_issues_repo_name": "kevmanderson/PHESANT", "max_issues_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "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": "WAS/testCategoricalOrdered.r", "max_forks_repo_name": "kevmanderson/PHESANT", "max_forks_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "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.2919254658, "max_line_length": 229, "alphanum_fraction": 0.6899563319, "num_tokens": 1404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.02800752334416486, "lm_q1q2_score": 0.011726663056599368}} {"text": "whack <- function(s) {\n paste( rev( unlist(strsplit(s, \" \"))), collapse=' ' ) }\n\npoem <- unlist( strsplit(\n'------------ Eldorado ----------\n\n... here omitted lines ...\n\nMountains the \"Over\nMoon, the Of\nShadow, the of Valley the Down\nride,\" boldly Ride,\nreplied,--- shade The\nEldorado!\" for seek you \"If\n\nPoe Edgar -----------------------', \"\\n\"))\n\nfor (line in poem) cat( whack(line), \"\\n\" )\n", "meta": {"hexsha": "a3d23e91897d2c71a8a3ddc1c4d7ce26313b15e4", "size": 394, "ext": "r", "lang": "R", "max_stars_repo_path": "Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r", "max_stars_repo_name": "LaudateCorpus1/RosettaCodeData", "max_stars_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-05T13:42:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:42:20.000Z", "max_issues_repo_path": "Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r", "max_issues_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_issues_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r", "max_forks_repo_name": "seanwallawalla-forks/RosettaCodeData", "max_forks_repo_head_hexsha": "9ad63ea473a958506c041077f1d810c0c7c8c18d", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7368421053, "max_line_length": 57, "alphanum_fraction": 0.5583756345, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.03904829174772427, "lm_q1q2_score": 0.011615693105010818}} {"text": "# Climate Indecies Calculation software\n# R language with TCL/TK package\n# Programmed by Yujun Ouyang,Mar,2004\n# rewritten by Yang Feng, July 2004\n# modified by Viacheslav Shalisko 2015\n\n# version 1.0, 2004-10-14\n# modified, 2006-01-24, \n# change .Internal(cbind) to cbind\n# change .Internal(rbind) to rbind\n# modified 2007-03-23\n# change .Internal(rep(0,n)) to rep(0,n)\n# modified, 2007-11-26,\n# get rid of .Internal on some functions: min(...), sort(...), round(...)\n# max(...), also get rid of dig=.. part from sort(...) function\n# change decrease=... part to decreasing=... at sort(...)\n# modified, 2008-05-05,\n# output TMAX mean value and TMIN mean value in nastat() function\n# modified, 2008-05-06,\n# add a random series on TMAX and TMIN in exceedance rate function\n# modified thresholds in TN10p calculation, add an 1e-5 item to avoid \n# computational error like 3.60000 > 3.6000, two functions involved:\n# nordaytem1() and exceedance()\n# modified, 2008-06-16\n# change all sort() to mysort(), deal with different version, also combined\n# different levels threshold()\n\n\n# Part I\n# General functions & TCL/TK functions\n\nlibrary(cluster)\nrequire(tcltk)\nmysort<- if(getRversion()<='2.4.1') function(x,decreasing){.Internal(sort(x,decreasing=decreasing))} else function(x,decreasing){sort.int(x,decreasing=decreasing)}\n\nfontHeading <- tkfont.create(family=\"times\",size=20,weight=\"bold\",slant=\"italic\")\nfontHeading1<-tkfont.create(family=\"times\",size=16,weight=\"bold\")\nfontHeading2<-tkfont.create(family=\"times\",size=14,weight=\"bold\")\nfontTextLabel <- tkfont.create(family=\"times\",size=12)\nfontFixedWidth <- tkfont.create(family=\"courier\",size=12)\n# initial value for check box\ncbvalue1<-tclVar(\"1\");cbvalue2<-tclVar(\"1\");cbvalue3<-tclVar(\"1\")\ncbvalue4<-tclVar(\"1\");cbvalue5<-tclVar(\"1\");cbvalue6<-tclVar(\"1\")\ncbvalue7<-tclVar(\"1\");cbvalue8<-tclVar(\"1\");cbvalue9<-tclVar(\"1\")\ncbvalue10<-tclVar(\"1\");cbvalue11<-tclVar(\"1\");cbvalue12<-tclVar(\"1\")\ncbvalue13<-tclVar(\"1\");cbvalue14<-tclVar(\"1\");cbvalue15<-tclVar(\"1\")\ncbvalue16<-tclVar(\"0\");cbvalue17<-tclVar(\"0\");cbvalue18<-tclVar(\"0\")\ncbvalue19<-tclVar(\"0\");cbvalue21<-tclVar(\"1\")\n# initial value for parameters\nstations<-tclVar(paste(\"\"));stdt<-tclVar(paste(\"3\"))\nEntry1<-tclVar(paste(\"1961\"));Entry2<-tclVar(paste(\"1990\"))\n#Entry3<-tclVar(paste(\"5\"))\nEntry4<-tclVar(paste(\"0\"))\nEntry5<-tclVar(paste(\"0\"))\nEntry6<-tclVar(paste(\"25\"));Entry7<-tclVar(paste(\"0\"))\nEntry8<-tclVar(paste(\"20\"));Entry9<-tclVar(paste(\"0\"))\n#Entry10<-tclVar(paste(\"10\"));Entry11<-tclVar(paste(\"5\"))\nEntry12<-tclVar(paste(\"25\"))\ndayim<-as.integer(c(31,28,31,30,31,30,31,31,30,31,30,31))\ncrt<-3;flag=F\ntreshold=5;winsize=5\nuu<-25;lu<-20\nul<-0;ll<-0\n\ntitle1<-\"Grafica del Ind143\";title2<-\"Ind143\";title3<-\"Años\"\nfrc<-function(dd,year,month,item){\n\n a<-dd[dd$year==year & dd$month==month,item]\n a<-a[a>-99]\n frc<-length(a)/rdim(year,month)\n }#end\n\ndone<-function(){tkdestroy(start1)}\n\npercentile<-function(n,x,pctile){\n\t x1<-x[is.na(x)==F]\n\t n1<-length(x1)\n a<-mysort(x1,decreasing=F)\n b<-n1*pctile+0.3333*pctile+0.3333\n bb<-trunc(b)\n percentile<-a[bb]+(b-bb)*(a[bb+1]-a[bb]) }#end\n\npplotts<-function(var=\"prcp\",type=\"h\",tit=NULL){\n if(var==\"dtr\"){\n ymax<-max(dd[,\"tmax\"]-dd[,\"tmin\"],na.rm=T)\n ymin<-0\n }\n else if(var==\"prcp\"){\n ymax<-max(dd[,var],na.rm=T)\n ymin<-0\n }\n else{\n ymax<-max(dd[,var],na.rm=T)+1\n ymin<-min(dd[,var],na.rm=T)-1\n }\n if(ymin>0){\n ymin<-0\n }\n if(is.na(ymax)|is.na(ymin)|(ymax==-Inf)|(ymin==-Inf)){\n ymax<-100\n ymin<-(-100)\n }\n par(mfrow=c(4,1))\n par(mar=c(3.1,2.1,2.1,2.1))\n for(i in seq(years,yeare,10)){\n at<-rep(1,10)\n# if(i>yeare)\n for(j in (i+1):min(i+9,yeare+1)){\n if(leapyear(j)) at[j-i+1]<-at[j-i]+366\n else at[j-i+1]<-at[j-i]+365\n }\n if(var==\"dtr\")\n ttmp<-dd[dd$year>=i&dd$year<=min(i+9,yeare),\"tmax\"]-dd[dd$year>=i&dd$year<=min(i+9,yeare),\"tmin\"]\n else ttmp<-dd[dd$year>=i&dd$year<=min(i+9,yeare),var]\n plot(1:length(ttmp),ttmp,type=type,col=\"blue\",xlab=\"\",ylab=\"\",xaxt=\"n\",xlim=c(1,3660),ylim=c(ymin,ymax))\n abline(h=0)\n tt<-seq(1,length(ttmp))\n tt<-tt[is.na(ttmp)==T]\n axis(side=1,at=at,labels=c(i:(i+9)))\n for(k in 1:10) abline(v=at[k],col=\"lightgreen\")\n lines(tt,rep(0,length(tt)),type=\"p\",col=\"red\")\n title(paste(\"Estación: \",tit,\", \",i,\"~\",min(i+9,yeare),\", \",var,sep=\"\"))\n }\n}\n\nind143gsl<-function(){\n if (latitude<0) south=T else south=F\n if (latitude<0) eyear=yeare-1 else eyear=yeare\n threshold<-5\n a<-eyear-years+1\n b<-rep(0,a)\n b<-cbind(b,b)\n colnames(b)<-c(\"year\",\"gsl\")\n i=1\n for (year in years:eyear) {\n b[i,\"year\"]<-year\n if(south){\n gslstart<-dd[dd$year==year&dd$month>6,]\n gslstart<-(gslstart[,\"tmax\"]+gslstart[,\"tmin\"])/2\n gslend<-dd[dd$year==(year+1)&dd$month<7,]\n gslend<-(gslend[,\"tmax\"]+gslend[,\"tmin\"])/2\n }\n else{\n gslstart<-dd[dd$year==year&dd$month<7,]\n gslstart<-(gslstart[,\"tmax\"]+gslstart[,\"tmin\"])/2\n gslend<-dd[dd$year==year&dd$month>6,]\n gslend<-(gslend[,\"tmax\"]+gslend[,\"tmin\"])/2\n }\n beginday<-0\n count=0\n for(step in 1:length(gslstart)){\n if(is.na(gslstart[step])==F){\n if(gslstart[step]>threshold) count<-count+1\n else count<-0\n }\n else count<-0\n if(count>5){\n beginday<-step-5\n break\n }\n }\n\n# if(beginday==0){\n# b[i,\"gsl\"]<-0\n# break\n# }\n\n endday<-0\n count<-0\n for(step in 1:length(gslend)){\n if(is.na(gslend[step])==F){\n if(gslend[step]5){\n endday<-step-5\n break\n }\n }\n \n if(sum(is.na(gslstart))+sum(is.na(gslend))>15) b[i,\"gsl\"]<-NA\n else{\n if(beginday==0)\n b[i,\"gsl\"]<-0\n else {\n if(endday==0) b[i,\"gsl\"]<-length(gslend)+length(gslstart)-beginday\n else b[i,\"gsl\"]<-endday+length(gslstart)-beginday\n }\n }\n \n i=i+1\n } \n b<-as.data.frame(b)\n nam1<-paste(outinddir,paste(ofilename,\"_GSL.csv\",sep=\"\"),sep=\"/\")\n write.table(b,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n \n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(b[,\"gsl\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(b[,1],b[,\"gsl\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"gsl\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n \n nam2<-paste(outjpgdir,paste(ofilename,\"_GSL.png\",sep=\"\"),sep=\"/\")\n png(file=nam2,width=1024,height=768,bg=\"white\")\n plotx(b[,1],b[,\"gsl\"],main=paste(\"GSL\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"GSL\")\n dev.off()\n nam3<-paste(outjpgdir,paste(ofilename,\"_GSL.pdf\",sep=\"\"),sep=\"/\")\n pdf(file=nam3)\n plotx(b[,1],b[,\"gsl\"],main=paste(\"GSL\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"GSL\")\n dev.off()\n}\n\ndataext<-function(dd,year,month,day,item){\ndataext<-dd[dd$year==year & dd$month==month & dd$day==day,item]\n}\n\nleapyear<-function(year){\n remainder400 <-trunc(year-400*trunc(year/400))\n remainder100 <-trunc(year-100*trunc(year/100))\n remainder4 <-trunc(year-4*trunc(year/4))\n if (remainder400 == 0) leapyear = T\n else{\n if(remainder100 == 0) leapyear = F\n else{\n if(remainder4 == 0) leapyear = T\n\t else leapyear = F\n\t }\n }\n}\n\nrdim<-function(year,month) {\n a<-leapyear(year) \n if (month==1) rdim<-31\n else if (month==3) rdim<-31\n else if (month==4) rdim<-30\n else if (month==5) rdim<-31\n else if (month==6) rdim<-30\n else if (month==7) rdim<-31\n else if (month==8) rdim<-31\n else if (month==9) rdim<-30\n else if (month==10) rdim<-31\n else if (month==11) rdim<-30\n else if (month==12) rdim<-31\n else if (a==T & month==2) rdim<-29\n else rdim<-28 \n }\n\n\nqcontrol<-function(){\n tkmessageBox(message=paste(\"Data QC(\",ofilename,\") may take a few minutes, click OK to continue.\",sep=\"\"))\n# output records of problematic like prcp <0 and NA\nddu<-duplicated(dd[,c(\"year\",\"month\",\"day\")])\nif(sum(ddu)>0){\n nam1<-paste(outlogdir,paste(ofilename,\"dupliQC.csv\",sep=\"\"),sep=\"/\")\n msg=paste(\"Date duplicated found in original data file, please check:\",nam1,sep=\" \")\n tkmessageBox(message=msg)\n ddu2<-dd[duplicated(dd[,c(\"year\",\"month\",\"day\")])==T,c(\"year\", \"month\", \"day\")]\n nam1<-paste(outlogdir,paste(ofilename,\"dupliQC.csv\",sep=\"\"),sep=\"/\")\n write.table(ddu2,file=nam1,append=F,quote=F,sep=\", \",row.names=F)\n tkdestroy(start1)\n stop(paste(\"QC stopped due to duplicated date, please check \",nam1,sep=\"\"))\n}\n \nmid<-dd[is.na(dd$prcp)==F,]\nmid<-mid[mid$prcp<0,]\n#dd[is.na(dd$prcp)==F & dd$prcp<0,\"prcp\"]<-NA\nnam1<-paste(outlogdir,paste(ofilename,\"_prcpQC.csv\",sep=\"\"),sep=\"/\")\nwrite.table(mid,file=nam1,append=F,quote=F,sep=\", \",row.names=F)\nif (dim(mid)[1]>0) tkmessageBox(message=paste(\"Errors in prcp, please check the log file\",nam1,sep=\" \"))\n# output plots for PRCP\nnam1<-paste(outlogdir,paste(ofilename,\"_prcpPLOT.pdf\",sep=\"\"),sep=\"/\")\npdf(file=nam1)\nttmp<-dd[dd$prcp>=1,\"prcp\"]\nttmp<-ttmp[is.na(ttmp)==F]\nif(length(ttmp)>30){\n hist(ttmp,main=paste(\"Histograma para estación: \",ofilename,\", PRCP >= 1mm\",sep=\"\"),breaks=c(0,5,10,15,20,25,30,35,40,45,50,60,70,80,90,100,125,150,175,max(200,ttmp)),xlab=\"\",ylab=\"Densidad\",col=\"gray\",freq=F)\n lines(density(ttmp,bw=0.2,from=1),col=\"red\")\n}\npplotts(var=\"prcp\",tit=ofilename)\ndev.off()\nnam1<-paste(outlogdir,paste(ofilename,\"_tmaxPLOT.pdf\",sep=\"\"),sep=\"/\")\npdf(file=nam1)\npplotts(var=\"tmax\",type=\"l\",tit=ofilename)\ndev.off()\nnam1<-paste(outlogdir,paste(ofilename,\"_tminPLOT.pdf\",sep=\"\"),sep=\"/\")\npdf(file=nam1)\npplotts(var=\"tmin\",type=\"l\",tit=ofilename)\ndev.off()\nnam1<-paste(outlogdir,paste(ofilename,\"_dtrPLOT.pdf\",sep=\"\"),sep=\"/\")\npdf(file=nam1)\npplotts(var=\"dtr\",type=\"l\",tit=ofilename)\ndev.off()\n\n#par(mfrow=c(1,1))\n# output problematic temperature like tmax < tmin\nmm<-dd[,\"tmax\"]-dd[,\"tmin\"]\ndd<-cbind(dd,mm)\ndimnames(dd)[[2]][7]<-\"dtr\"\n #output \"log\" file review\n temiss<-dd\n temiss<-temiss[is.na(temiss[,\"tmax\"])==F&is.na(temiss[,\"tmin\"])==F,]\n# temiss<-temiss[is.na(temiss[,6])==F,]\n temiss<-temiss[temiss[,7]<=0|temiss[,5]<=(-70)|temiss[,5]>=70|temiss[,6]<=(-70)|temiss[,6]>=70,]\n dimnames(temiss)[[2]][7]<-\"tmax-tmin\"\n nam1<-paste(outlogdir,paste(ofilename,\"_tempQC.csv\",sep=\"\"),sep=\"/\")\n write.table(temiss,file=nam1,append=F,quote=F,sep=\", \",row.names=F)\nif (dim(temiss)[1]>0) {\n tkmessageBox(message=paste(\"Errors in temperature, please check the log file\",nam1,sep=\" \"))\n # records with abs(tmax)>=70, abs(tmin)>=70 set to NA\n dd[is.na(dd[,5])==F & abs(dd[,5])>=70,5]<-NA\n dd[is.na(dd[,6])==F & abs(dd[,6])>=70,6]<-NA\n # records with tmax < tmin are set to NA\n dd[is.na(dd[,5])==F & is.na(dd[,6])==F & dd[,\"dtr\"]<0,c(\"tmax\",\"tmin\")]<-NA\n# dd[is.na(dd[,5])==F & dd[,\"mm\"]<0,\"tmin\"]<-NA\n}\n# dd<-dd[,-7]\n\n# output problematic temperature which is out of 3 standard diviation (temp only)\nys<-yeare-years+1\n\ntmaxm<-matrix(0,ys,365)\ntminm<-matrix(0,ys,365)\ntdtrm<-matrix(0,ys,365)\n\ntmaxstd<-rep(0,365)\ntminstd<-rep(0,365)\ntdtrstd<-rep(0,365)\n\ntmaxmean<-rep(0,365)\ntminmean<-rep(0,365)\ntdtrmean<-rep(0,365)\n\nfor(i in 1:ys)\n tmaxm[i,]<-dd[dd[,\"year\"]==(i+years-1)&(dd[,\"month\"]*100+dd[,\"day\"]!=229),\"tmax\"]\nfor(i in 1:365){\n tmaxstd[i]<-sqrt(var(tmaxm[,i],na.rm=T))\n tmaxmean[i]<-mean(tmaxm[,i],na.rm=T)\n}\n\nfor(i in 1:ys)\n tminm[i,]<-dd[dd[,\"year\"]==(i+years-1)&(dd[,\"month\"]*100+dd[,\"day\"]!=229),\"tmin\"]\nfor(i in 1:365){\n tminstd[i]<-sqrt(var(tminm[,i],na.rm=T))\n tminmean[i]<-mean(tminm[,i],na.rm=T)\n}\n\nfor(i in 1:ys)\n tdtrm[i,]<-dd[dd[,\"year\"]==(i+years-1)&(dd[,\"month\"]*100+dd[,\"day\"]!=229),\"dtr\"]\nfor(i in 1:365){\n tdtrstd[i]<-sqrt(var(tdtrm[,i],na.rm=T))\n tdtrmean[i]<-mean(tdtrm[,i],na.rm=T)\n}\n\ntmaxstdleap<-rep(0,366)\ntmaxstdleap[1:59]<-tmaxstd[1:59]\ntmaxstdleap[60]<-tmaxstd[59]\ntmaxstdleap[61:366]<-tmaxstd[60:365]\n\ntmaxmeanleap<-rep(0,366)\ntmaxmeanleap[1:59]<-tmaxmean[1:59]\ntmaxmeanleap[60]<-tmaxmean[59]\ntmaxmeanleap[61:366]<-tmaxmean[60:365]\n\ntminstdleap<-rep(0,366)\ntminstdleap[1:59]<-tminstd[1:59]\ntminstdleap[60]<-tminstd[59]\ntminstdleap[61:366]<-tminstd[60:365]\n\ntminmeanleap<-rep(0,366)\ntminmeanleap[1:59]<-tminmean[1:59]\ntminmeanleap[60]<-tminmean[59]\ntminmeanleap[61:366]<-tminmean[60:365]\n\ntdtrstdleap<-rep(0,366)\ntdtrstdleap[1:59]<-tdtrstd[1:59]\ntdtrstdleap[60]<-tdtrstd[59]\ntdtrstdleap[61:366]<-tdtrstd[60:365]\n\ntdtrmeanleap<-rep(0,366)\ntdtrmeanleap[1:59]<-tdtrmean[1:59]\ntdtrmeanleap[60]<-tdtrmean[59]\ntdtrmeanleap[61:366]<-tdtrmean[60:365]\n\ntmp<-matrix(0,dim(dd)[1],6)\ndimnames(tmp)<-list(NULL,c(\"tmaxlow\",\"tmaxup\",\"tminlow\",\"tminup\",\"dtrlow\",\"dtrup\"))\n\nidx<-0\nfor(i in years:yeare){\n if(leapyear(i)==T){\n tmp[(idx+1):(idx+366),1]<-tmaxmeanleap-crt*tmaxstdleap\n tmp[(idx+1):(idx+366),2]<-tmaxmeanleap+crt*tmaxstdleap\n tmp[(idx+1):(idx+366),3]<-tminmeanleap-crt*tminstdleap\n tmp[(idx+1):(idx+366),4]<-tminmeanleap+crt*tminstdleap\n tmp[(idx+1):(idx+366),5]<-tdtrmeanleap-crt*tdtrstdleap\n tmp[(idx+1):(idx+366),6]<-tdtrmeanleap+crt*tdtrstdleap\n idx<-idx+366\n }\n else{\n tmp[(idx+1):(idx+365),1]<-tmaxmean-crt*tmaxstd\n tmp[(idx+1):(idx+365),2]<-tmaxmean+crt*tmaxstd\n tmp[(idx+1):(idx+365),3]<-tminmean-crt*tminstd\n tmp[(idx+1):(idx+365),4]<-tminmean+crt*tminstd\n tmp[(idx+1):(idx+365),5]<-tdtrmean-crt*tdtrstd\n tmp[(idx+1):(idx+365),6]<-tdtrmean+crt*tdtrstd\n idx<-idx+365\n }\n}\n\nodata<-cbind(dd,tmp)\n\nodata<-odata[is.na(odata[,\"tmax\"])==F,]\nodata<-odata[is.na(odata[,\"tmin\"])==F,]\nodata<-odata[is.na(odata[,\"dtr\"])==F,]\no1data<-odata[odata[,5]odata[,9]|odata[,6]odata[,11]|odata[,7]odata[,13],]\n#o2data<-odata[odata[,5]>odata[,8],]\n#o3data<-odata[odata[,6]odata[,10],]\n\n#write.table(errstdo,file=nam1,append=F,quote=F,sep=\",\",row.names=F)\nif (dim(o1data)[1] > 0){\n nam1<-paste(outlogdir,paste(ofilename,\"_tepstdQC.csv\",sep=\"\"),sep=\"/\")\n tkmessageBox(message=paste(\"Outliers found, please check the log file: \",nam1,sep=\"\"))\n ofile<-cbind(o1data[,c(1,2,3,8,5,9,10,6,11,12,7,13)])\n write.table(round(ofile,digit=2),file=nam1,append=F,quote=F,sep=\",\",row.names=F)\n}\n\ndd<-dd[,c(\"year\",\"month\",\"day\",\"prcp\",\"tmax\",\"tmin\")];assign(\"dd\",dd,envir=.GlobalEnv)\n\nnamcal<-paste(nama,\"indcal.csv\",sep=\"\")\nassign(\"namcal\",namcal,envir=.GlobalEnv)\nwrite.table(dd,file=namcal,append=F,quote=F,sep=\",\",row.names=F,na=\"-99.9\")\n\ntkmessageBox(message=paste(\"If you have checked data(\", namcal,\"), click OK to continue.\",sep=\"\"))\n}# end of qcontrol()\n\nnastat<-function(){\n dd <- read.table(namcal,header=T,sep=\",\",na.strings=\"-99.9\",colClasses=rep(\"real\",6))\n assign(\"dd\",dd,envir=.GlobalEnv)\n# NA statistics\nnast<-rep(0,12)\nnast<-array(nast,c(1,12,12,(yeare-years+1)))\ndimnames(nast)<-list(NULL,c(\"ynapr\",\"ynatma\",\"ynatmi\",\"napr\",\"natma\",\"natmi\",\"mnapr>3\",\"mnatma>3\",\"mnatmi>3\",\"ynapr>15\",\"ynatma>15\",\"ynatmi>15\"),NULL,NULL)\nys<-yeare-years+1 \nyear=years\naa1<-matrix(NA,12*ys,4)\ndimnames(aa1)<-list(NULL,c(\"year\",\"month\",\"tmaxm\",\"tminm\"))\naa1[,\"year\"]<-years:yeare\naa1[,\"year\"]<-mysort(aa1[,\"year\"],decreasing=F)\naa1[,\"month\"]<-1:12\naa2<-matrix(NA,ys,3)\ndimnames(aa2)<-list(NULL,c(\"year\",\"tmaxm\",\"tminm\"))\naa2[,\"year\"]<-years:yeare\nfor (i in 1:(yeare-years+1)){\n month<-1;midvalue1<-dd[dd$year==year,]\n aa2[i,\"tmaxm\"]<-mean(midvalue1[,\"tmax\"],na.rm=T)\n aa2[i,\"tminm\"]<-mean(midvalue1[,\"tmin\"],na.rm=T)\n for (j in 1:12){\n midvalue2<-midvalue1[midvalue1$month==month,]\n aa1[(i-1)*12+j,\"tmaxm\"]<-mean(midvalue2[,\"tmax\"],na.rm=T)\n aa1[(i-1)*12+j,\"tminm\"]<-mean(midvalue2[,\"tmin\"],na.rm=T)\n nast[1,\"ynapr\",j,i]<-dim(midvalue1[is.na(midvalue1$prcp),])[1]\n if (nast[1,\"ynapr\",j,i]>15) nast[1,\"ynapr>15\",j,i]<-NA\n nast[1,\"ynatma\",j,i]<-dim(midvalue1[is.na(midvalue1$tmax),])[1]\n if (nast[1,\"ynatma\",j,i]>15) nast[1,\"ynatma>15\",j,i]<-NA\n nast[1,\"ynatmi\",j,i]<-dim(midvalue1[is.na(midvalue1$tmin),])[1]\n if (nast[1,\"ynatmi\",j,i]>15) nast[1,\"ynatmi>15\",j,i]<-NA\n nast[1,\"napr\",j,i]<-dim(midvalue2[is.na(midvalue2$prcp),])[1]\n if (nast[1,\"napr\",j,i]>3) nast[1,\"mnapr>3\",j,i]<-NA\n nast[1,\"natma\",j,i]<-dim(midvalue2[is.na(midvalue2$tmax),])[1]\n if (nast[1,\"natma\",j,i]>3) nast[1,\"mnatma>3\",j,i]<-NA\n nast[1,\"natmi\",j,i]<-dim(midvalue2[is.na(midvalue2$tmin),])[1]\n if (nast[1,\"natmi\",j,i]>3) nast[1,\"mnatmi>3\",j,i]<-NA\n month=month+1 }\n year=year+1 }\n nasto<-t(nast[,,,1])\n for ( i in 2:(yeare-years+1)){\n nasto<-rbind(nasto,t(nast[,,,i])) }\n nastout<-matrix(0,(yeare-years+1)*12,2)\n dimnames(nastout)<-list(NULL,c(\"year\",\"month\")) \n nastout<-as.data.frame(nastout)\n nastout[,\"year\"]<-years:yeare\n nastout[,\"year\"]<-mysort(nastout[,\"year\"],decreasing=F)\n nastout[,\"month\"]<-1:12\n \n nastout<-cbind(nastout,nasto);assign(\"nastout\",nastout,envir=.GlobalEnv)\n nastatistic<-nastout[,1:8]\n \n nacor<-nastout[,-(3:8)]\n ynacor<-matrix(0,ys,4)\n dimnames(ynacor)<-list(NULL,c(\"year\",\"ynapr>15\",\"ynatma>15\",\"ynatmi>15\"))\n ynacor[,\"year\"]<-years:yeare\n ynacor<-as.data.frame(ynacor)\n for (year in years:yeare){\n ynacor[ynacor$year==year,\"ynapr>15\"]<-nacor[nacor$year==year & nacor$month==1,\"ynapr>15\"]\n ynacor[ynacor$year==year,\"ynatma>15\"]<-nacor[nacor$year==year & nacor$month==1,\"ynatma>15\"]\n ynacor[ynacor$year==year,\"ynatmi>15\"]<-nacor[nacor$year==year & nacor$month==1,\"ynatmi>15\"]}\n nacor<-nacor[,1:5]\n assign(\"nacor\",nacor,envir=.GlobalEnv)\n assign(\"ynacor\",ynacor,envir=.GlobalEnv)\n if(sum(is.na(ynacor[,\"ynapr>15\"])==F)==0) prallna<-1\n else prallna<-0\n if(sum(is.na(ynacor[,\"ynatma>15\"])==F)==0) txallna<-1\n else txallna<-0\n if(sum(is.na(ynacor[,\"ynatmi>15\"])==F)==0) tnallna<-1\n else tnallna<-0\n assign(\"prallna\",prallna,envir=.GlobalEnv)\n assign(\"txallna\",txallna,envir=.GlobalEnv)\n assign(\"tnallna\",tnallna,envir=.GlobalEnv)\n assign(\"nastatistic\",nastatistic,envir=.GlobalEnv)\n nam1<-paste(outlogdir,paste(ofilename,\"_nastatistic.csv\",sep=\"\"),sep=\"/\")\n cat(file=nam1,\"TITLE,YEAR,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,ANN\\n\")\n for(year in years:yeare)\n for(i in 1:3) {\n if(i==1) tit<-\"PRCP\"\n\tif(i==2) tit<-\"TMAX\"\n\tif(i==3) tit<-\"TMIN\"\n\tline<-paste(tit,year,sep=\",\")\n\tfor(mon in 1:12)\n\tline<-paste(line,nastatistic[nastatistic$year==year&nastatistic$month==mon,i+5],sep=\",\")\n\tline<-paste(line,nastatistic[nastatistic$year==year&nastatistic$month==1,i+2],sep=\",\")\n\tcat(file=nam1,line,fill=100,append=T)\n }\n# write.table(nastatistic,file=nam1,append=F,quote=F,sep=\", \",row.names=F)\n aa1[,\"tmaxm\"]<-aa1[,\"tmaxm\"]+nacor[,\"mnatma>3\"]\n aa1[,\"tminm\"]<-aa1[,\"tminm\"]+nacor[,\"mnatmi>3\"]\n aa2[,\"tmaxm\"]<-aa2[,\"tmaxm\"]+ynacor[,\"ynatma>15\"]\n aa2[,\"tminm\"]<-aa2[,\"tminm\"]+ynacor[,\"ynatmi>15\"]\n ofile1<-paste(outinddir,paste(ofilename,\"_TMAXmean.csv\",sep=\"\"),sep=\"/\")\n odata<-matrix(0,ys,14)\n dimnames(odata)<-list(NULL,c(\"year\",\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\",\"annual\"))\n odata[,1]<-years:yeare\n odata[,14]<-aa2[,\"tmaxm\"]\n for(i in 1:ys) odata[i,2:13]<-aa1[((i-1)*12+1):(i*12),\"tmaxm\"]\n write.table(round(odata,2),file=ofile1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n odata[,14]<-aa2[,\"tminm\"]\n for(i in 1:ys) odata[i,2:13]<-aa1[((i-1)*12+1):(i*12),\"tminm\"]\n ofile1<-paste(outinddir,paste(ofilename,\"_TMINmean.csv\",sep=\"\"),sep=\"/\")\n write.table(round(odata,2),file=ofile1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n parameter()\n }#end of nastat()\n\n\ngetfile<-function() {\n name <- tclvalue(tkgetOpenFile(filetypes=\"{{TEXT Files} {.txt}} {{All files} *}\"))\n if (name==\"\") return();\n dd <- read.table(name,header=F,col.names=c(\"year\",\"month\",\"day\",\"prcp\",\"tmax\",\"tmin\"),colClasses=rep(\"real\",6))\n nama<-substr(name,start=1,stop=(nchar(name)-4))\n outdirtmp<-strsplit(name,\"/\")[[1]]\n if(length(outdirtmp)<=2){\n outinddir<-paste(strsplit(name,\":\")[[1]][1],\"indices\",sep=\":/\")\n outlogdir<-paste(strsplit(name,\":\")[[1]][1],\"log\",sep=\":/\")\n outjpgdir<-paste(strsplit(name,\":\")[[1]][1],\"plots\",sep=\":/\")\n outtrddir<-paste(strsplit(name,\":\")[[1]][1],\"trend\",sep=\":/\")\n }\n else{\n outdir<-outdirtmp[1]\n for(i in 2:(length(outdirtmp)-1))\n outdir<-paste(outdir,outdirtmp[i],sep=\"/\")\n outinddir<-paste(outdir,\"indices\",sep=\"/\")\n outlogdir<-paste(outdir,\"log\",sep=\"/\")\n outjpgdir<-paste(outdir,\"plots\",sep=\"/\")\n outtrddir<-paste(outdir,\"trend\",sep=\"/\")\n }\n ofilename<-substr(outdirtmp[length(outdirtmp)],start=1,stop=(nchar(outdirtmp[length(outdirtmp)])-4))\n if(!file.exists(outinddir)) dir.create(outinddir)\n if(!file.exists(outlogdir)) dir.create(outlogdir)\n if(!file.exists(outjpgdir)) dir.create(outjpgdir)\n if(!file.exists(outtrddir)) dir.create(outtrddir)\n \n# dimnames(dd)<-list(NULL,c(\"year\",\"month\",\"day\",\"prcp\",\"tmax\",\"tmin\"))\n assign(\"nama\",nama,envir=.GlobalEnv)\n assign(\"outinddir\",outinddir,envir=.GlobalEnv)\n assign(\"outlogdir\",outlogdir,envir=.GlobalEnv)\n assign(\"outjpgdir\",outjpgdir,envir=.GlobalEnv)\n assign(\"outtrddir\",outtrddir,envir=.GlobalEnv)\n assign(\"ofilename\",ofilename,envir=.GlobalEnv)\n # dd<-dd[dd$tmax!=-99.9,]\n # dd$year<-dd$year+40 # just for the test data\n # replace missing value with NA\n dd[dd$prcp<=(-99.),\"prcp\"]<-NA\n dd[dd$tmax<=(-99.),\"tmax\"]<-NA\n dd[dd$tmin<=(-99.),\"tmin\"]<-NA\n # replace missing records\n ddd<-matrix(NA,365,6)\n dddl<-matrix(NA,366,6)\n dimnames(ddd)<-list(NULL,c(\"year\",\"month\",\"day\",\"prcp\",\"tmax\",\"tmin\"))\n dimnames(dddl)<-list(NULL,c(\"year\",\"month\",\"day\",\"prcp\",\"tmax\",\"tmin\"))\n ddd[1:31,\"month\"]<-1;ddd[1:31,\"day\"]<-c(1:31);ddd[32:59,\"month\"]<-2;ddd[32:59,\"day\"]<-c(1:28)\n ddd[60:90,\"month\"]<-3;ddd[60:90,\"day\"]<-c(1:31);ddd[91:120,\"month\"]<-4;ddd[91:120,\"day\"]<-c(1:30)\n ddd[121:151,\"month\"]<-5;ddd[121:151,\"day\"]<-c(1:31);ddd[152:181,\"month\"]<-6;ddd[152:181,\"day\"]<-c(1:30)\n ddd[182:212,\"month\"]<-7;ddd[182:212,\"day\"]<-c(1:31);ddd[213:243,\"month\"]<-8;ddd[213:243,\"day\"]<-c(1:31)\n ddd[244:273,\"month\"]<-9;ddd[244:273,\"day\"]<-c(1:30);ddd[274:304,\"month\"]<-10;ddd[274:304,\"day\"]<-c(1:31)\n ddd[305:334,\"month\"]<-11;ddd[305:334,\"day\"]<-c(1:30);ddd[335:365,\"month\"]<-12;ddd[335:365,\"day\"]<-c(1:31)\n\n dddl[1:31,\"month\"]<-1;dddl[1:31,\"day\"]<-c(1:31);dddl[32:60,\"month\"]<-2;dddl[32:60,\"day\"]<-c(1:29)\n dddl[61:91,\"month\"]<-3;dddl[61:91,\"day\"]<-c(1:31);dddl[92:121,\"month\"]<-4;dddl[92:121,\"day\"]<-c(1:30)\n dddl[122:152,\"month\"]<-5;dddl[122:152,\"day\"]<-c(1:31);dddl[153:182,\"month\"]<-6;dddl[153:182,\"day\"]<-c(1:30)\n dddl[183:213,\"month\"]<-7;dddl[183:213,\"day\"]<-c(1:31);dddl[214:244,\"month\"]<-8;dddl[214:244,\"day\"]<-c(1:31)\n dddl[245:274,\"month\"]<-9;dddl[245:274,\"day\"]<-c(1:30);dddl[275:305,\"month\"]<-10;dddl[275:305,\"day\"]<-c(1:31)\n dddl[306:335,\"month\"]<-11;dddl[306:335,\"day\"]<-c(1:30);dddl[336:366,\"month\"]<-12;dddl[336:366,\"day\"]<-c(1:31)\n\n years<-dd[1,1];yeare<-dd[dim(dd)[1],1]\n if (leapyear(years)) dddd<-dddl else dddd<-ddd\n dddd[,\"year\"]<-years\n for (year in years:yeare){ # year loop start\n if (leapyear(year)) dddd1<-dddl else dddd1<-ddd\n dddd1[,\"year\"]<-year\n if (year!=years) dddd<-rbind(dddd,dddd1) }# year loop end\n\n dddd<-as.data.frame(dddd)\n dddd2<-merge(dddd,dd,by=c(\"year\",\"month\",\"day\"),all.x=T)\n dddd2<-dddd2[,-(4:6)]\n dimnames(dddd2)[[2]]<-c(\"year\",\"month\",\"day\",\"prcp\",\"tmax\",\"tmin\")\n tmporder<-dddd2[,\"year\"]*10000+dddd2[,\"month\"]*100+dddd2[,\"day\"]\n dd<-dddd2[order(tmporder),]\n \n assign(\"years\",years,envir=.GlobalEnv)\n assign(\"yeare\",yeare,envir=.GlobalEnv)\n assign(\"dd\",dd,envir=.GlobalEnv)\n\n tkmessageBox(message=paste(\"Data(\",ofilename,\") loaded, click OK to continue.\",sep=\"\"))\n \n# enter station name and the times of stadard deviation\n infor1<-tktoplevel()\n tkfocus(infor1)\n tkgrab.set(infor1)\n tkwm.title(infor1,\"Set Parameters for Data QC\")\n\n textEntry1<-stations;textEntry2<-stdt\n \n textEntryWidget1<-tkentry(infor1,width=30,textvariable=textEntry1)\n textEntryWidget2<-tkentry(infor1,width=30,textvariable=textEntry2)\n \n# tkgrid(tklabel(infor1,text=\"!!Enter parameters please\",font=fontHeading1))\n tkgrid(tklabel(infor1,text=\" Station name or code:\"),textEntryWidget1)\n tkgrid(tklabel(infor1,text=\"Criteria(number of Standard Deviation):\"),textEntryWidget2)\n \n ok1<-function(){\n station<-as.character(tclvalue(textEntry1));assign(\"station\",station,envir=.GlobalEnv)\n crt<-as.numeric(tclvalue(textEntry2));assign(\"crt\",crt,envir=.GlobalEnv)\n tkgrab.release(infor1)\n tkdestroy(infor1)\n stations<-textEntry1;assign(\"stations\",stations,envir=.GlobalEnv)\n stdt<-textEntry2;assign(\"stdt\",stdt,envir=.GlobalEnv)\n qcontrol();tkfocus(start1)\n }# end of ok\n\n cancel1<-function(){\n tkmessageBox(message=\"You have to enter these parameters before you can move on.\")\n tkfocus(infor1)}# end of cancel1\n \n ok1.but<- tkbutton(infor1,text=\" OK \",command=ok1)\n cancel1.but<-tkbutton(infor1,text=\" CANCEL \",command=cancel1)\n tkgrid(ok1.but,cancel1.but)\n }# end of getfile\n\nparameter<-function(){\n infor<-tktoplevel()\n tkfocus(infor)\n tkgrab.set(infor)\n tkwm.title(infor,\"Set Parameter Values\")\n\n textEntry1<-Entry1\n textEntry2<-Entry2\n# textEntry3<-Entry3\n textEntry4<-Entry4\n textEntry5<-Entry5\n textEntry6<-Entry6;textEntry7<-Entry7\n textEntry8<-Entry8;textEntry9<-Entry9\n# textEntry10<-Entry10;textEntry11<-Entry11\n textEntry12<-Entry12\n \n textEntryWidget1<-tkentry(infor,width=20,textvariable=textEntry1)\n textEntryWidget2<-tkentry(infor,width=20,textvariable=textEntry2)\n# textEntryWidget3<-tkentry(infor,width=20,textvariable=textEntry3)\n textEntryWidget4<-tkentry(infor,width=20,textvariable=textEntry4)\n textEntryWidget5<-tkentry(infor,width=20,textvariable=textEntry5)\n textEntryWidget6<-tkentry(infor,width=20,textvariable=textEntry6)\n textEntryWidget7<-tkentry(infor,width=20,textvariable=textEntry7)\n textEntryWidget8<-tkentry(infor,width=20,textvariable=textEntry8)\n textEntryWidget9<-tkentry(infor,width=20,textvariable=textEntry9)\n# textEntryWidget10<-tkentry(infor,width=20,textvariable=textEntry10)\n# textEntryWidget11<-tkentry(infor,width=20,textvariable=textEntry11)\n textEntryWidget12<-tkentry(infor,width=20,textvariable=textEntry12)\n \n tkgrid(tklabel(infor,text=\"User defined parameters for Indices Calculation\",font=fontHeading1))\n tkgrid(tklabel(infor,text=\"First year of base period\"),textEntryWidget1)\n tkgrid(tklabel(infor,text=\"Last year of base period\"),textEntryWidget2)\n tkgrid(tklabel(infor,text=\"Latitude of this station location\"),textEntryWidget4)\n tkgrid(tklabel(infor,text=\"Longitude of this station location\"),textEntryWidget5)\n tkgrid(tklabel(infor,text=\"User defined upper threshold of daily maximum temperature\"),textEntryWidget6)\n tkgrid(tklabel(infor,text=\"User defined lower threshold of daily maximum temperature\"),textEntryWidget7)\n tkgrid(tklabel(infor,text=\"User defined upper threshold of daily minimum temperature\"),textEntryWidget8)\n tkgrid(tklabel(infor,text=\"User defined lower threshold of daily minimum temperature\"),textEntryWidget9)\n tkgrid(tklabel(infor,text=\"User defined daily precipitation threshold\"),textEntryWidget12)\n \n ok1<-function(){\n# tkmessageBox(message=\"This process may take 2 mins to initialize the data. Please wait until the window disapear!\")\n startyear<-as.numeric(tclvalue(textEntry1));assign(\"startyear\",startyear,envir=.GlobalEnv)\n endyear<-as.numeric(tclvalue(textEntry2));assign(\"endyear\",endyear,envir=.GlobalEnv)\n if(startyearyeare){\n if(startyear0)\n icnt<-icnt+1\n else{\n if(icnt>=6) ycnt<-ycnt+icnt\n\ticnt<-0\n\t}\n if(i==ylen&icnt>=6) ycnt<-ycnt+icnt\n }\n hwfi[year-years+1,2]<-ycnt\n }\n hwfi<-as.data.frame(hwfi)\n hwfi[,\"wsdi\"]<-hwfi[,\"wsdi\"]+ynacor[,\"ynatma>15\"] \n nam1<-paste(outinddir,paste(ofilename,\"_WSDI.csv\",sep=\"\"),sep=\"/\")\n write.table(hwfi,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n \n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(hwfi[,\"wsdi\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(hwfi[,\"year\"],hwfi[,\"wsdi\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"wsdi\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_WSDI.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(hwfi[,1],hwfi[,2], main=paste(\"WSDI\",ofilename,sep=\" \"),ylab=\"WSDI\",xlab=\"Año\")\n dev.off()\n nam3<-paste(outjpgdir,paste(ofilename,\"_WSDI.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam3)\n plotx(hwfi[,1],hwfi[,2], main=paste(\"WSDI\",ofilename,sep=\" \"),ylab=\"WSDI\",xlab=\"Año\")\n dev.off()\n} # end of hwfi function\n\ncwdi<-function(){\n if (flag==T) return()\n cwdi<-matrix(0,(yeare-years+1),2)\n dimnames(cwdi)[[2]]<-c(\"year\",\"csdi\")\n cwdi[,\"year\"]<-years:yeare\n for (year in years:yeare) {\n if(leapyear(year)){\n aa<-rep(0,366)\n aa[1:59]<-aas[,\"pcmin10\"][1:59]\n aa[60]<-aa[59]\n aa[61:366]<-aas[,\"pcmin10\"][60:365]\n }\n else aa<-aas[,\"pcmin10\"]\n bb<-dd[dd$year==year,\"tmin\"]\n if(length(aa)!=length(bb)) stop(\"ERROR in CWDI, check data!\")\n midval<-aa-bb\n ylen<-length(aa)\n ycnt<-0\n icnt<-0\n for(i in 1:ylen){\n if(is.na(midval[i])==F&midval[i]>0)\n icnt<-icnt+1\n else{\n if(icnt>=6) ycnt<-ycnt+icnt\n\ticnt<-0\n }\n if(i==ylen&icnt>=6) ycnt<-ycnt+icnt\n }\n cwdi[year-years+1,2]<-ycnt\n}\n cwdi<-as.data.frame(cwdi)\n cwdi[,\"csdi\"]<-cwdi[,\"csdi\"]+ynacor[,\"ynatmi>15\"] \n nam1<-paste(outinddir,paste(ofilename,\"_CSDI.csv\",sep=\"\"),sep=\"/\")\n write.table(cwdi,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(cwdi[,\"csdi\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(cwdi[,\"year\"],cwdi[,\"csdi\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"csdi\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_CSDI.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(cwdi[,1],cwdi[,2],main=paste(\"CSDI\",ofilename,sep=\" \"),ylab=\"CSDI\",xlab=\"Año\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_CSDI.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(cwdi[,1],cwdi[,2],main=paste(\"CSDI\",ofilename,sep=\" \"),ylab=\"CSDI\",xlab=\"Año\")\n dev.off()\n} # end of cwdi function\n\nr95ptot<-function(){\n prcptmp<-dd[dd$year>=startyear&dd$year<=endyear&dd$prcp>=1,\"prcp\"]\n prcptmp<-prcptmp[is.na(prcptmp)==F]\n len<-length(prcptmp)\n prcp95<-percentile(len,prcptmp,0.95)\n prcp99<-percentile(len,prcptmp,0.99)\n\n ys<-yeare-years+1\n \n dp<-matrix(0,ys,4)\n dimnames(dp)<-list(NULL,c(\"year\",\"r95p\",\"r99p\",\"prcptot\"))\n dp[,\"year\"]<-years:yeare\n for(i in years:yeare){\n dp[(i-years+1),\"r95p\"]<-sum(dd[dd$year==i&dd$prcp>prcp95,\"prcp\"],na.rm=T)\n dp[(i-years+1),\"r99p\"]<-sum(dd[dd$year==i&dd$prcp>prcp99,\"prcp\"],na.rm=T)\n dp[(i-years+1),\"prcptot\"]<-sum(dd[dd$year==i&dd$prcp>=1,\"prcp\"],na.rm=T)\n }\n dp[,\"r95p\"]<-round(dp[,\"r95p\"],1)+ynacor[,\"ynapr>15\"]\n dp[,\"r99p\"]<-round(dp[,\"r99p\"],1)+ynacor[,\"ynapr>15\"]\n dp[,\"prcptot\"]<-round(dp[,\"prcptot\"],1)+ynacor[,\"ynapr>15\"]\n dp<-as.data.frame(dp)\n nam1<-paste(outinddir,paste(ofilename,\"_R95p.csv\",sep=\"\"),sep=\"/\")\n nam2<-paste(outinddir,paste(ofilename,\"_R99p.csv\",sep=\"\"),sep=\"/\")\n nam3<-paste(outinddir,paste(ofilename,\"_PRCPTOT.csv\",sep=\"\"),sep=\"/\")\n write.table(dp[,c(\"year\",\"r95p\")],file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n write.table(dp[,c(\"year\",\"r99p\")],file=nam2,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n write.table(dp[,c(\"year\",\"prcptot\")],file=nam3,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n for(i in c(\"r95p\",\"r99p\",\"prcptot\")){\n if(sum(is.na(dp[,i]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(dp[,\"year\"],dp[,i])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,i,years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n}\n\n nam4<-paste(outjpgdir,paste(ofilename,\"_R95p.png\",sep=\"\"),sep=\"/\")\n png(nam4,width=1024,height=768,bg=\"white\")\n plotx(dp[,1],dp[,\"r95p\"],main=paste(\"R95p\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R95p\")\n dev.off()\n nam4a<-paste(outjpgdir,paste(ofilename,\"_R95p.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam4a)\n plotx(dp[,1],dp[,\"r95p\"],main=paste(\"R95p\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R95p\")\n dev.off()\n nam5<-paste(outjpgdir,paste(ofilename,\"_R99p.png\",sep=\"\"),sep=\"/\")\n png(nam5,width=1024,height=768,bg=\"white\")\n plotx(dp[,1],dp[,\"r99p\"],main=paste(\"R99p\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R99p\")\n dev.off()\n nam5a<-paste(outjpgdir,paste(ofilename,\"_R99p.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam5a)\n plotx(dp[,1],dp[,\"r99p\"],main=paste(\"R99p\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R99p\")\n dev.off()\n nam6<-paste(outjpgdir,paste(ofilename,\"_PRCPTOT.png\",sep=\"\"),sep=\"/\")\n png(nam6,width=1024,height=768,bg=\"white\")\n plotx(dp[,1],dp[,\"prcptot\"],main=paste(\"PRCPTOT\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"PRCPTOT\")\n dev.off()\n nam6a<-paste(outjpgdir,paste(ofilename,\"_PRCPTOT.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam6a)\n plotx(dp[,1],dp[,\"prcptot\"],main=paste(\"PRCPTOT\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"PRCPTOT\")\n dev.off()\n} # end of function r95ptot\n\ndaysprcp20<-function(){\n ys<-yeare-years+1\nR20<-rep(0,ys)\nyearss<-c(years:yeare)\ntarget<-as.data.frame(cbind(yearss,R20))\nfor (year in years:yeare){\n mid<-dd[dd$year==year,\"prcp\"]\n mid<-mid[is.na(mid)==F]\ntarget[target$yearss==year,\"R20\"]<-length(mid[mid>=20])}# end for\ndimnames(target)[[2]][1]<-\"year\"\n target[,\"R20\"]<-target[,\"R20\"]+ynacor[,\"ynapr>15\"]\nnam1<-paste(outinddir,paste(ofilename,\"_R20mm.csv\",sep=\"\"),sep=\"/\")\nwrite.table(target,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(target[,\"R20\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(target[,\"year\"],target[,\"R20\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"r20mm\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\nnam2<-paste(outjpgdir,paste(ofilename,\"_R20mm.png\",sep=\"\"),sep=\"/\")\npng(nam2,width=1024,height=768,bg=\"white\")\nplotx(target[,1],target[,2],main=paste(\"R20mm\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R20mm\")\ndev.off()\nnam2a<-paste(outjpgdir,paste(ofilename,\"_R20mm.pdf\",sep=\"\"),sep=\"/\")\npdf(nam2a)\nplotx(target[,1],target[,2],main=paste(\"R20mm\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R20mm\")\ndev.off()\n}\n\ndaysprcpn<-function(){\n ys<-yeare-years+1\nRnn<-rep(0,ys)\nyearss<-c(years:yeare)\ntarget<-as.data.frame(cbind(yearss,Rnn))\nfor (year in years:yeare){\n mid<-dd[dd$year==year,\"prcp\"]\n mid<-mid[is.na(mid)==F]\n target[target$yearss==year,\"Rnn\"]<-length(mid[mid>=nn])\n}\n dimnames(target)[[2]][1]<-\"year\"\n target[,\"Rnn\"]<-target[,\"Rnn\"]+ynacor[,\"ynapr>15\"]\n\n nam1<-paste(outinddir,paste(ofilename,\"_R\",as.character(nn),\"mm.csv\",sep=\"\"),sep=\"/\")\n write.table(target,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(target[,\"Rnn\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(target[,1],target[,\"Rnn\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,paste(\"R\",as.character(nn),\"mm\",sep=\"\"),years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_R\",as.character(nn),\"mm.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(target[,1],target[,2],main=paste(\"R\",as.character(nn),\"mm\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"Rnnmm\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_R\",as.character(nn),\"mm.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(target[,1],target[,2],main=paste(\"R\",as.character(nn),\"mm\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"Rnnmm\")\n dev.off()\n }\n\nnordaytem1<-function(){ # initialize data\n# normal temp\n\ndaynorm<-dd[dd$year>=startyear,]\ndaynorm<-daynorm[daynorm$year<=endyear,] # initialize daynorm matrix\ndaynor<-daynorm # create target matrix\nnn<-dd[dd$year==startpoint,]\nnn<-nn[nn$month==12,]\nnn<-nn[nn$day>(31-round(winsize/2)),]\ndaynorm<-rbind(nn,daynorm)\nnn<-dd[dd$year==endpoint,]\nnn<-nn[nn$month==1,]\nnn<-nn[nn$day<=round(winsize/2),]\ndaynorm<-rbind(daynorm,nn)\n\ndaynorm1<-daynorm[,-4]\ndaynorm1[daynorm1$month==2 & daynorm1$day==29,]<--99\ndaynorm1<-daynorm1[daynorm1$year!=-99,]\ndayt<-daynorm1[,c(\"tmax\",\"tmin\")]\n\nddtem<-dd[,-4]\nddtem[ddtem$month==2 & ddtem$day==29,]<--99\nddtem<-ddtem[ddtem$year!=-99,]\nassign(\"ddtem\",ddtem,envir=.GlobalEnv)\n\na<-matrix(-99,5,5)\ndimnames(a)[[2]]<-c(\"year\",\"month\",\"day\",\"tmax\",\"tmin\")\nddtemt<-rbind(a,ddtem);assign(\"ddtemt\",ddtemt,envir=.GlobalEnv)\n\nys<-endyear-startyear+1\nwindow<-matrix(0,winsize,2)\nwindows<-array(window,c(winsize,2,366,ys))\ndimnames(windows)<-list(NULL,c(\"tmax\",\"tmin\"),NULL,NULL)\n\ni=winsize-round(winsize/2,digits=0)\ni1=round(winsize/2,digits=0)\ndaynormm<-daynorm[,c(\"tmax\",\"tmin\")]\ndaynormm<-as.matrix(daynormm)\nyear<-startyear\n\nfor (k in 1:ys){\n if (leapyear(year)==T) jj<-366 else {jj<-365; windows[,,366,k]<--99 }\n year<-year+1\nfor (j in 1:jj){\n windows[,,j,k]<-daynormm[(i-i1):(i+i1),]\n i=i+1 }}\n\nmwindows<-colMeans(windows,na.rm=T)\ntmax<-mwindows[\"tmax\",,];tmax<-tmax[tmax!=-99]\ntmin<-mwindows[\"tmin\",,];tmin<-tmin[tmin!=-99]\ndaynor[,\"tmax\"]<-tmax;daynor[,\"tmin\"]<-tmin\n\na<-rep(0,nrow(daynor))\na<-(daynor[,\"tmax\"]+daynor[,\"tmin\"])/2\ndaytemave<-a \ndaynor<-cbind(daynor,daytemave)\n\n# output the result to globe enviroment\nassign(\"daynor\",daynor,envir=.GlobalEnv)\nassign(\"daynorm\",daynorm,envir=.GlobalEnv)\nassign(\"daynorm1\",daynorm1,envir=.GlobalEnv)\nassign(\"dayt\",dayt,envir=.GlobalEnv)\n\n# prcp percentile 95% and 99%\n prcpnorm<-dd[dd$year>=startyear,]\n prcpnorm<-prcpnorm[prcpnorm$year<=endyear,] # initialize prcpnorm matrix\n nnp<-dd[dd$year==startpoint,]\n nnp<-nnp[nnp$month==12,]\n nnp<-nnp[nnp$day>29,]\n prcpnorm<-rbind(nnp,prcpnorm)\n nnp<-dd[dd$year==endpoint,]\n nnp<-nnp[nnp$month==1,]\n nnp<-nnp[nnp$day<=2,]\n prcpnorm<-rbind(prcpnorm,nnp)\n prcpnorm<-prcpnorm[,1:4]\n# remove Feb 29\n prcpnorm[prcpnorm$month==2 & prcpnorm$day==29,]<--99\n prcpnorm<-prcpnorm[prcpnorm$year!=-99,]\n assign(\"prcpnorm\",prcpnorm,envir=.GlobalEnv)\n\n ys<-endyear-startyear+1 \n \n aasp<-matrix(NA,365,3)\n dimnames(aasp)<-list(NULL,c(\"day\",\"prcp95\",\"prcp99\"))\n aasp[,\"day\"]<-1:365\n\n msp<-5*ys\n prcpnorm<-as.matrix(prcpnorm)\n pwindow<-matrix(0,5,1)\n pwindows<-array(pwindow,c(5,1,365,ys)) #array used to store all windows\n ip=3\n ip1=2\n for (k in 1:ys){\n for (j in 1:365){\n \n pwindows[,,j,k]<-prcpnorm[(ip-ip1):(ip+ip1),\"prcp\"]\n ip=ip+1}}\n\n prcpwin<-matrix(0,msp,2)\n prcpwin[,2]<-1:ys\n prcpwin[,2]<-mysort(prcpwin[,2],decreasing=F)\n\n prcpwins<-array(prcpwin,c(msp,2,365)) \n\nfor (j in 1:365){\nfor (i in 1:ys){\n prcpwins[prcpwins[,2,j]==i,1,j]<-pwindows[,,j,i]}}\n#assign(\"exwins\",exwins,envir=.GlobalEnv)\n\n for (i in 1:365){\n assp<-prcpwins[,,i]\n if(sum(is.na(assp[,1])==F)>=1)\n aasp[i,\"prcp95\"]<-percentile(msp,assp[,1],0.95)\n else aasp[i,\"prcp95\"]<-NA\n if(sum(is.na(assp[,1])==F)>=1)\n aasp[i,\"prcp99\"]<-percentile(msp,assp[,1],0.99)\n else aasp[i,\"prcp99\"]<-NA\n }\nassign(\"aasp\",aasp,envir=.GlobalEnv)\n\naas<-matrix(NA,365,5)\ndimnames(aas)<-list(NULL,c(\"day\",\"pcmax10\",\"pcmax90\",\"pcmin10\",\"pcmin90\"))\naas[,\"day\"]<-1:365\n\nms<-winsize*ys\ndayt<-as.matrix(dayt)\nwindow<-matrix(0,winsize,2)\nwindows<-array(window,c(winsize,2,365,ys)) #array used to store all windows\ni=winsize-round(winsize/2,digits=0)\ni1=round(winsize/2,digits=0)\nfor (k in 1:ys){\nfor (j in 1:365){\n \n windows[,,j,k]<-dayt[(i-i1):(i+i1),]\n i=i+1}}\n\nexwin<-matrix(0,ms,3)\nexwin[,3]<-1:ys\nexwin[,3]<-mysort(exwin[,3],decreasing=F)\nassign(\"exwin\",exwin,envir=.GlobalEnv)\n#indd<-exwin[exwin[,3]!=ys,3]\nexwins<-array(exwin,c(ms,3,365)) # array for bootstrap\n\nfor (j in 1:365){\nfor (i in 1:ys){\n exwins[exwins[,3,j]==i,1:2,j]<-windows[,,j,i]}}\nassign(\"exwins\",exwins,envir=.GlobalEnv)\n\nfor ( i in 1:365){\n ass<-exwins[,,i]\n ass1<-ass[,1]\n ass2<-ass[,2]\n kgb1<-length(ass1[is.na(ass1)])\n kgb2<-length(ass2[is.na(ass2)])\n if (kgb1>37.5 | kgb2>37.5) {flag=T;break}}#150*0.25=37.5\n\nassign(\"flag\",flag,envir=.GlobalEnv)\nif (flag==T) tkmessageBox(message=\"More than 25% data missing, Exceedance rate, HWDI,CWDI will not be calculated!!\")\nif (flag==T) return()\nfor (i in 1:365){\n ass<-exwins[,,i]\n# if(i == 363) {\n# ttmp<-ms\n# assign(\"ttmp\",ttmp,envir=.GlobalEnv)\n# }\n itmp<-percentile(ms,ass[,1],c(0.1,0.9))\n aas[i,\"pcmax10\"]<-itmp[1]-1e-5\n aas[i,\"pcmax90\"]<-itmp[2]+1e-5\n itmp<-percentile(ms,ass[,2],c(0.1,0.9))\n aas[i,\"pcmin10\"]<-itmp[1]-1e-5\n aas[i,\"pcmin90\"]<-itmp[2]+1e-5 }\n\nassign(\"aas\",aas,envir=.GlobalEnv)# matrix to store 10 and 90 percentile\n# exceedance rate before 1961 and after 2000\nbefore<-dd[dd$yearendyear,]\n\n# dataframe store the before monthly exceedance rate\nys1<-startyear-years;ys2<-yeare-endyear\nbmonex<-matrix(NA,ys1*12,6)\ndimnames(bmonex)<-list(NULL,c(\"year\",\"month\",\"tx10p\",\"tx90p\",\"tn10p\",\"tn90p\"))\nbmonex[,\"month\"]<-rep(1:12,ys1)\nbmonex[,\"year\"]<-years:(startyear-1)\nbmonex[,\"year\"]<-mysort(bmonex[,\"year\"],decreasing=F)\nbmonex<-as.data.frame(bmonex)\n\n# dataframe store the after monthly exceedance rate\namonex<-matrix(NA,ys2*12,6)\ndimnames(amonex)<-list(NULL,c(\"year\",\"month\",\"tx10p\",\"tx90p\",\"tn10p\",\"tn90p\"))\namonex[,\"month\"]<-rep(1:12,ys2)\namonex[,\"year\"]<-(endyear+1):yeare\namonex[,\"year\"]<-mysort(amonex[,\"year\"],decreasing=F)\namonex<-as.data.frame(amonex)\n\n# dataframe store yearly exceedance rate (before and after)\nyearex<-c(years:(startyear-1));txg10p<-rep(0,length(yearex))\ntxg90p<-rep(0,length(yearex));tng10p<-rep(0,length(yearex))\ntng90p<-rep(0,length(yearex))\nbd<-as.data.frame(cbind(yearex,txg10p,txg90p,tng10p,tng90p))\ncolnames(bd)[1]<-\"year\"\n\nyearex<-c((endyear+1):yeare);txg10p<-rep(0,length(yearex))\ntxg90p<-rep(0,length(yearex));tng10p<-rep(0,length(yearex))\ntng90p<-rep(0,length(yearex))\nad<-as.data.frame(cbind(yearex,txg10p,txg90p,tng10p,tng90p))\ncolnames(ad)[1]<-\"year\"\n\nyear=years;jjj6=1\nfor (i in 1:ys1){\n midvalue<-ddtem[ddtem$year==year,]\n exmax10<-midvalue[,4]-aas[,2]\n exmax10m1<-exmax10[1:31];exmax10m2<-exmax10[32:59];exmax10m3<-exmax10[60:90]\n exmax10m4<-exmax10[91:120];exmax10m5<-exmax10[121:151];exmax10m6<-exmax10[152:181]\n exmax10m7<-exmax10[182:212];exmax10m8<-exmax10[213:243];exmax10m9<-exmax10[244:273]\n exmax10m10<-exmax10[274:304];exmax10m11<-exmax10[305:334];exmax10m12<-exmax10[335:365]\n \n exmax90<-midvalue[,4]-aas[,3]\n exmax90m1<-exmax90[1:31];exmax90m2<-exmax90[32:59];exmax90m3<-exmax90[60:90]\n exmax90m4<-exmax90[91:120];exmax90m5<-exmax90[121:151];exmax90m6<-exmax90[152:181]\n exmax90m7<-exmax90[182:212];exmax90m8<-exmax90[213:243];exmax90m9<-exmax90[244:273]\n exmax90m10<-exmax90[274:304];exmax90m11<-exmax90[305:334];exmax90m12<-exmax90[335:365]\n\n exmin10<-midvalue[,5]-aas[,4]\n exmin10m1<-exmin10[1:31];exmin10m2<-exmin10[32:59];exmin10m3<-exmin10[60:90]\n exmin10m4<-exmin10[91:120];exmin10m5<-exmin10[121:151];exmin10m6<-exmin10[152:181]\n exmin10m7<-exmin10[182:212];exmin10m8<-exmin10[213:243];exmin10m9<-exmin10[244:273]\n exmin10m10<-exmin10[274:304];exmin10m11<-exmin10[305:334];exmin10m12<-exmin10[335:365]\n\n exmin90<-midvalue[,5]-aas[,5]\n exmin90m1<-exmin90[1:31];exmin90m2<-exmin90[32:59];exmin90m3<-exmin90[60:90]\n exmin90m4<-exmin90[91:120];exmin90m5<-exmin90[121:151];exmin90m6<-exmin90[152:181]\n exmin90m7<-exmin90[182:212];exmin90m8<-exmin90[213:243];exmin90m9<-exmin90[244:273]\n exmin90m10<-exmin90[274:304];exmin90m11<-exmin90[305:334];exmin90m12<-exmin90[335:365]\n\n bd[i,\"txg10p\"]<-length(exmax10[exmax10<0&is.na(exmax10)==F])\n bd[i,\"txg90p\"]<-length(exmax90[exmax90>0&is.na(exmax90)==F])\n bd[i,\"tng10p\"]<-length(exmin10[exmin10<0&is.na(exmin10)==F])\n bd[i,\"tng90p\"]<-length(exmin90[exmin90>0&is.na(exmin90)==F])\n \n bmonex[jjj6,\"tx10p\"]<-length(exmax10m1[exmax10m1<0&is.na(exmax10m1)==F])\n bmonex[jjj6,\"tx90p\"]<-length(exmax90m1[exmax90m1>0&is.na(exmax90m1)==F])\n bmonex[jjj6,\"tn10p\"]<-length(exmin10m1[exmin10m1<0&is.na(exmin10m1)==F])\n bmonex[jjj6,\"tn90p\"]<-length(exmin90m1[exmin90m1>0&is.na(exmin90m1)==F])\n\n bmonex[jjj6+1,\"tx10p\"]<-length(exmax10m2[exmax10m2<0&is.na(exmax10m2)==F])\n bmonex[jjj6+1,\"tx90p\"]<-length(exmax90m2[exmax90m2>0&is.na(exmax90m2)==F])\n bmonex[jjj6+1,\"tn10p\"]<-length(exmin10m2[exmin10m2<0&is.na(exmin10m2)==F])\n bmonex[jjj6+1,\"tn90p\"]<-length(exmin90m2[exmin90m2>0&is.na(exmin90m2)==F]) \n\n bmonex[jjj6+2,\"tx10p\"]<-length(exmax10m3[exmax10m3<0&is.na(exmax10m3)==F])\n bmonex[jjj6+2,\"tx90p\"]<-length(exmax90m3[exmax90m3>0&is.na(exmax90m3)==F])\n bmonex[jjj6+2,\"tn10p\"]<-length(exmin10m3[exmin10m3<0&is.na(exmin10m3)==F])\n bmonex[jjj6+2,\"tn90p\"]<-length(exmin90m3[exmin90m3>0&is.na(exmin90m3)==F])\n\n bmonex[jjj6+3,\"tx10p\"]<-length(exmax10m4[exmax10m4<0&is.na(exmax10m4)==F])\n bmonex[jjj6+3,\"tx90p\"]<-length(exmax90m4[exmax90m4>0&is.na(exmax90m4)==F])\n bmonex[jjj6+3,\"tn10p\"]<-length(exmin10m4[exmin10m4<0&is.na(exmin10m4)==F])\n bmonex[jjj6+3,\"tn90p\"]<-length(exmin90m4[exmin90m4>0&is.na(exmin90m4)==F])\n\n bmonex[jjj6+4,\"tx10p\"]<-length(exmax10m5[exmax10m5<0&is.na(exmax10m5)==F])\n bmonex[jjj6+4,\"tx90p\"]<-length(exmax90m5[exmax90m5>0&is.na(exmax90m5)==F])\n bmonex[jjj6+4,\"tn10p\"]<-length(exmin10m5[exmin10m5<0&is.na(exmin10m5)==F])\n bmonex[jjj6+4,\"tn90p\"]<-length(exmin90m5[exmin90m5>0&is.na(exmin90m5)==F])\n\n bmonex[jjj6+5,\"tx10p\"]<-length(exmax10m6[exmax10m6<0&is.na(exmax10m6)==F])\n bmonex[jjj6+5,\"tx90p\"]<-length(exmax90m6[exmax90m6>0&is.na(exmax90m6)==F])\n bmonex[jjj6+5,\"tn10p\"]<-length(exmin10m6[exmin10m6<0&is.na(exmin10m6)==F])\n bmonex[jjj6+5,\"tn90p\"]<-length(exmin90m6[exmin90m6>0&is.na(exmin90m6)==F])\n\n bmonex[jjj6+6,\"tx10p\"]<-length(exmax10m7[exmax10m7<0&is.na(exmax10m7)==F])\n bmonex[jjj6+6,\"tx90p\"]<-length(exmax90m7[exmax90m7>0&is.na(exmax90m7)==F])\n bmonex[jjj6+6,\"tn10p\"]<-length(exmin10m7[exmin10m7<0&is.na(exmin10m7)==F])\n bmonex[jjj6+6,\"tn90p\"]<-length(exmin90m7[exmin90m7>0&is.na(exmin90m7)==F])\n\n bmonex[jjj6+7,\"tx10p\"]<-length(exmax10m8[exmax10m8<0&is.na(exmax10m8)==F])\n bmonex[jjj6+7,\"tx90p\"]<-length(exmax90m8[exmax90m8>0&is.na(exmax90m8)==F])\n bmonex[jjj6+7,\"tn10p\"]<-length(exmin10m8[exmin10m8<0&is.na(exmin10m8)==F])\n bmonex[jjj6+7,\"tn90p\"]<-length(exmin90m8[exmin90m8>0&is.na(exmin90m8)==F])\n\n bmonex[jjj6+8,\"tx10p\"]<-length(exmax10m9[exmax10m9<0&is.na(exmax10m9)==F])\n bmonex[jjj6+8,\"tx90p\"]<-length(exmax90m9[exmax90m9>0&is.na(exmax90m9)==F])\n bmonex[jjj6+8,\"tn10p\"]<-length(exmin10m9[exmin10m9<0&is.na(exmin10m9)==F])\n bmonex[jjj6+8,\"tn90p\"]<-length(exmin90m9[exmin90m9>0&is.na(exmin90m9)==F])\n\n bmonex[jjj6+9,\"tx10p\"]<-length(exmax10m10[exmax10m10<0&is.na(exmax10m10)==F])\n bmonex[jjj6+9,\"tx90p\"]<-length(exmax90m10[exmax90m10>0&is.na(exmax90m10)==F])\n bmonex[jjj6+9,\"tn10p\"]<-length(exmin10m10[exmin10m10<0&is.na(exmin10m10)==F])\n bmonex[jjj6+9,\"tn90p\"]<-length(exmin90m10[exmin90m10>0&is.na(exmin90m10)==F])\n\n bmonex[jjj6+10,\"tx10p\"]<-length(exmax10m11[exmax10m11<0&is.na(exmax10m11)==F])\n bmonex[jjj6+10,\"tx90p\"]<-length(exmax90m11[exmax90m11>0&is.na(exmax90m11)==F])\n bmonex[jjj6+10,\"tn10p\"]<-length(exmin10m11[exmin10m11<0&is.na(exmin10m11)==F])\n bmonex[jjj6+10,\"tn90p\"]<-length(exmin90m11[exmin90m11>0&is.na(exmin90m11)==F])\n\n bmonex[jjj6+11,\"tx10p\"]<-length(exmax10m12[exmax10m12<0&is.na(exmax10m12)==F])\n bmonex[jjj6+11,\"tx90p\"]<-length(exmax90m12[exmax90m12>0&is.na(exmax90m12)==F])\n bmonex[jjj6+11,\"tn10p\"]<-length(exmin10m12[exmin10m12<0&is.na(exmin10m12)==F])\n bmonex[jjj6+11,\"tn90p\"]<-length(exmin90m12[exmin90m12>0&is.na(exmin90m12)==F])\n\n if(leapyear(year)){\n if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"]>aas[59,\"pcmax90\"]&is.na(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"])==F&is.na(aas[59,\"pcmax90\"])==F)\n bmonex[jjj6+1,\"tx90p\"]<-bmonex[jjj6+1,\"tx90p\"]+1\n if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"]aas[59,\"pcmin90\"]&is.na(dd[dd$year==year&dd$month==2&dd$day==29,\"tmin\"])==F&is.na(aas[59,\"pcmin90\"])==F)\n bmonex[jjj6+1,\"tn90p\"]<-bmonex[jjj6+1,\"tn90p\"]+1\n if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmin\"]0&is.na(exmax90)==F])\n ad[i,\"tng10p\"]<-length(exmin10[exmin10<0&is.na(exmin10)==F])\n ad[i,\"tng90p\"]<-length(exmin90[exmin90>0&is.na(exmin90)==F])\n \n amonex[jjj6,\"tx10p\"]<-length(exmax10m1[exmax10m1<0&is.na(exmax10m1)==F])\n amonex[jjj6,\"tx90p\"]<-length(exmax90m1[exmax90m1>0&is.na(exmax90m1)==F])\n amonex[jjj6,\"tn10p\"]<-length(exmin10m1[exmin10m1<0&is.na(exmin10m1)==F])\n amonex[jjj6,\"tn90p\"]<-length(exmin90m1[exmin90m1>0&is.na(exmin90m1)==F])\n\n amonex[jjj6+1,\"tx10p\"]<-length(exmax10m2[exmax10m2<0&is.na(exmax10m2)==F])\n amonex[jjj6+1,\"tx90p\"]<-length(exmax90m2[exmax90m2>0&is.na(exmax90m2)==F])\n amonex[jjj6+1,\"tn10p\"]<-length(exmin10m2[exmin10m2<0&is.na(exmin10m2)==F])\n amonex[jjj6+1,\"tn90p\"]<-length(exmin90m2[exmin90m2>0&is.na(exmin90m2)==F]) \n\n amonex[jjj6+2,\"tx10p\"]<-length(exmax10m3[exmax10m3<0&is.na(exmax10m3)==F])\n amonex[jjj6+2,\"tx90p\"]<-length(exmax90m3[exmax90m3>0&is.na(exmax90m3)==F])\n amonex[jjj6+2,\"tn10p\"]<-length(exmin10m3[exmin10m3<0&is.na(exmin10m3)==F])\n amonex[jjj6+2,\"tn90p\"]<-length(exmin90m3[exmin90m3>0&is.na(exmin90m3)==F])\n\n amonex[jjj6+3,\"tx10p\"]<-length(exmax10m4[exmax10m4<0&is.na(exmax10m4)==F])\n amonex[jjj6+3,\"tx90p\"]<-length(exmax90m4[exmax90m4>0&is.na(exmax90m4)==F])\n amonex[jjj6+3,\"tn10p\"]<-length(exmin10m4[exmin10m4<0&is.na(exmin10m4)==F])\n amonex[jjj6+3,\"tn90p\"]<-length(exmin90m4[exmin90m4>0&is.na(exmin90m4)==F])\n\n amonex[jjj6+4,\"tx10p\"]<-length(exmax10m5[exmax10m5<0&is.na(exmax10m5)==F])\n amonex[jjj6+4,\"tx90p\"]<-length(exmax90m5[exmax90m5>0&is.na(exmax90m5)==F])\n amonex[jjj6+4,\"tn10p\"]<-length(exmin10m5[exmin10m5<0&is.na(exmin10m5)==F])\n amonex[jjj6+4,\"tn90p\"]<-length(exmin90m5[exmin90m5>0&is.na(exmin90m5)==F])\n\n amonex[jjj6+5,\"tx10p\"]<-length(exmax10m6[exmax10m6<0&is.na(exmax10m6)==F])\n amonex[jjj6+5,\"tx90p\"]<-length(exmax90m6[exmax90m6>0&is.na(exmax90m6)==F])\n amonex[jjj6+5,\"tn10p\"]<-length(exmin10m6[exmin10m6<0&is.na(exmin10m6)==F])\n amonex[jjj6+5,\"tn90p\"]<-length(exmin90m6[exmin90m6>0&is.na(exmin90m6)==F])\n\n amonex[jjj6+6,\"tx10p\"]<-length(exmax10m7[exmax10m7<0&is.na(exmax10m7)==F])\n amonex[jjj6+6,\"tx90p\"]<-length(exmax90m7[exmax90m7>0&is.na(exmax90m7)==F])\n amonex[jjj6+6,\"tn10p\"]<-length(exmin10m7[exmin10m7<0&is.na(exmin10m7)==F])\n amonex[jjj6+6,\"tn90p\"]<-length(exmin90m7[exmin90m7>0&is.na(exmin90m7)==F])\n\n amonex[jjj6+7,\"tx10p\"]<-length(exmax10m8[exmax10m8<0&is.na(exmax10m8)==F])\n amonex[jjj6+7,\"tx90p\"]<-length(exmax90m8[exmax90m8>0&is.na(exmax90m8)==F])\n amonex[jjj6+7,\"tn10p\"]<-length(exmin10m8[exmin10m8<0&is.na(exmin10m8)==F])\n amonex[jjj6+7,\"tn90p\"]<-length(exmin90m8[exmin90m8>0&is.na(exmin90m8)==F])\n\n amonex[jjj6+8,\"tx10p\"]<-length(exmax10m9[exmax10m9<0&is.na(exmax10m9)==F])\n amonex[jjj6+8,\"tx90p\"]<-length(exmax90m9[exmax90m9>0&is.na(exmax90m9)==F])\n amonex[jjj6+8,\"tn10p\"]<-length(exmin10m9[exmin10m9<0&is.na(exmin10m9)==F])\n amonex[jjj6+8,\"tn90p\"]<-length(exmin90m9[exmin90m9>0&is.na(exmin90m9)==F])\n\n amonex[jjj6+9,\"tx10p\"]<-length(exmax10m10[exmax10m10<0&is.na(exmax10m10)==F])\n amonex[jjj6+9,\"tx90p\"]<-length(exmax90m10[exmax90m10>0&is.na(exmax90m10)==F])\n amonex[jjj6+9,\"tn10p\"]<-length(exmin10m10[exmin10m10<0&is.na(exmin10m10)==F])\n amonex[jjj6+9,\"tn90p\"]<-length(exmin90m10[exmin90m10>0&is.na(exmin90m10)==F])\n\n amonex[jjj6+10,\"tx10p\"]<-length(exmax10m11[exmax10m11<0&is.na(exmax10m11)==F])\n amonex[jjj6+10,\"tx90p\"]<-length(exmax90m11[exmax90m11>0&is.na(exmax90m11)==F])\n amonex[jjj6+10,\"tn10p\"]<-length(exmin10m11[exmin10m11<0&is.na(exmin10m11)==F])\n amonex[jjj6+10,\"tn90p\"]<-length(exmin90m11[exmin90m11>0&is.na(exmin90m11)==F])\n\n amonex[jjj6+11,\"tx10p\"]<-length(exmax10m12[exmax10m12<0&is.na(exmax10m12)==F])\n amonex[jjj6+11,\"tx90p\"]<-length(exmax90m12[exmax90m12>0&is.na(exmax90m12)==F])\n amonex[jjj6+11,\"tn10p\"]<-length(exmin10m12[exmin10m12<0&is.na(exmin10m12)==F])\n amonex[jjj6+11,\"tn90p\"]<-length(exmin90m12[exmin90m12>0&is.na(exmin90m12)==F])\n\n if(leapyear(year)){\n if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"]>aas[59,\"pcmax90\"]&is.na(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"])==F&is.na(aas[59,\"pcmax90\"])==F)\n amonex[jjj6+1,\"tx90p\"]<-amonex[jjj6+1,\"tx90p\"]+1\n if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"]aas[59,\"pcmin90\"]&is.na(dd[dd$year==year&dd$month==2&dd$day==29,\"tmin\"])==F&is.na(aas[59,\"pcmin90\"])==F)\n amonex[jjj6+1,\"tn90p\"]<-amonex[jjj6+1,\"tn90p\"]+1\n if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmin\"]3\"]+nacor[,\"mnatmi>3\"]\n ofile<-matrix(0,len,14)\n dimnames(ofile)<-list(NULL,c(\"year\",\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\",\"annual\"))\n ofile<-as.data.frame(ofile)\n for(j in years:yeare){\n k<-j-years+1\n ofile[k,1]<-j\n ofile[k,2:13]<-round(aa1[aa1[,\"year\"]==j,\"dtr\"],digit=2)\n ofile[k,14]<-round(mean(t(ofile[k,2:13]),na.rm=T),digit=2)\n }\n ofile[,14]<-ofile[,14]+ynacor[,\"ynatma>15\"]+ynacor[,\"ynatmi>15\"]\n nam1<-paste(outinddir,paste(ofilename,\"_DTR.csv\",sep=\"\"),sep=\"/\")\n write.table(ofile,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(ofile[,14]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(ofile[,1],ofile[,14])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"dtr\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_DTR.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(ofile[,1],ofile[,14],main=paste(\"DTR\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"DTR\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_DTR.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(ofile[,1],ofile[,14],main=paste(\"DTR\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"DTR\")\n dev.off()\n } # end of dtr\n\ndaysprcp10<-function(){\n ys<-yeare-years+1\nR10<-rep(0,ys)\nyearss<-c(years:yeare)\ntarget<-as.data.frame(cbind(yearss,R10))\nfor (year in years:yeare){\n mid<-dd[dd$year==year,\"prcp\"]\n mid<-mid[is.na(mid)==F]\ntarget[target$yearss==year,\"R10\"]<-length(mid[mid>=10])}\ndimnames(target)[[2]][1]<-\"year\"\n target[,\"R10\"]<-target[,\"R10\"]+ynacor[,\"ynapr>15\"]\nnam1<-paste(outinddir,paste(ofilename,\"_R10mm.csv\",sep=\"\"),sep=\"/\")\nwrite.table(target,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(target[,\"R10\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(target[,1],target[,\"R10\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"r10mm\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\nnam2<-paste(outjpgdir,paste(ofilename,\"_R10mm.png\",sep=\"\"),sep=\"/\")\npng(nam2,width=1024,height=768)\nplotx(target[,1],target[,2],main=paste(\"R10mm\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R10mm\")\ndev.off()\nnam2a<-paste(outjpgdir,paste(ofilename,\"_R10mm.pdf\",sep=\"\"),sep=\"/\")\npdf(nam2a)\nplotx(target[,1],target[,2],main=paste(\"R10mm\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"R10mm\")\ndev.off()\n}\n\nextremedays<-function(opt=0){\n if(opt==0){\n euu=uu\n eul=ul\n elu=lu\n ell=ll\n }\n else{\n euu=uuu\n eul=uul\n elu=ulu\n ell=ull\n }\n ys<-yeare-years+1\n# beginyear<-dd[1,1]\n# endyear<-dd[dim(dd)[1],1]\n tclext<-c(years:yeare)\n su<-rep(0,ys)\n id<-su\n tr<-su\n fd<-su\n tclext<-cbind(tclext,su,id,tr,fd)\n dimnames(tclext)[[2]][1]<-\"year\"\n i=1\n for (year in years:yeare) {\n mid1<-dd[dd$year==year,\"tmax\"];mid1<-mid1[is.na(mid1)==F]\n mid2<-dd[dd$year==year,\"tmin\"];mid2<-mid2[is.na(mid2)==F]\n tclext[i,\"su\"]<-length(mid1[mid1>euu])\n tclext[i,\"id\"]<-length(mid1[mid1elu])\n tclext[i,\"fd\"]<-length(mid2[mid215\"]\n tclext[,\"id\"]<-tclext[,\"id\"]+ynacor[,\"ynatma>15\"]\n tclext[,\"tr\"]<-tclext[,\"tr\"]+ynacor[,\"ynatmi>15\"]\n tclext[,\"fd\"]<-tclext[,\"fd\"]+ynacor[,\"ynatmi>15\"]\n # assign(\"extdays\",tclext,envir=.GlobalEnv)\n if(opt==0){\n nam1<-paste(outinddir,paste(ofilename,\"_SU25.csv\",sep=\"\"),sep=\"/\")\n nam2<-paste(outinddir,paste(ofilename,\"_ID0.csv\",sep=\"\"),sep=\"/\")\n nam3<-paste(outinddir,paste(ofilename,\"_TR20.csv\",sep=\"\"),sep=\"/\")\n nam4<-paste(outinddir,paste(ofilename,\"_FD0.csv\",sep=\"\"),sep=\"/\")\n }\n else{\n nam1<-paste(outinddir,paste(ofilename,\"_SU\",as.character(euu),\".csv\",sep=\"\"),sep=\"/\")\n nam2<-paste(outinddir,paste(ofilename,\"_ID\",as.character(eul),\".csv\",sep=\"\"),sep=\"/\")\n nam3<-paste(outinddir,paste(ofilename,\"_TR\",as.character(elu),\".csv\",sep=\"\"),sep=\"/\")\n nam4<-paste(outinddir,paste(ofilename,\"_FD\",as.character(ell),\".csv\",sep=\"\"),sep=\"/\")\n }\n\n write.table(tclext[,c(\"year\",\"su\")],file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n write.table(tclext[,c(\"year\",\"id\")],file=nam2,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n write.table(tclext[,c(\"year\",\"tr\")],file=nam3,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n write.table(tclext[,c(\"year\",\"fd\")],file=nam4,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n# output trend base on annual indicies data\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n for( i in c(\"su\",\"id\",\"tr\",\"fd\")){\n if(sum(is.na(tclext[,i]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(tclext[,\"year\"],tclext[,i])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n if(opt==0){\n if(i==\"su\") ii<-\"su25\"\n if(i==\"id\") ii<-\"id0\"\n if(i==\"fd\") ii<-\"fd0\"\n if(i==\"tr\") ii<-\"tr20\"\n }\n else{\n if(i==\"su\") ii<-paste(\"su\",as.character(euu),sep=\"\")\n if(i==\"id\") ii<-paste(\"id\",as.character(eul),sep=\"\")\n if(i==\"tr\") ii<-paste(\"tr\",as.character(elu),sep=\"\")\n if(i==\"fd\") ii<-paste(\"fd\",as.character(ell),sep=\"\")\n }\n cat(file=namt,paste(latitude,longitude,ii,years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n }\n \n namp<-c(\"\",\"\",\"\",\"\")\n namppdf<-c(\"\",\"\",\"\",\"\")\n if(opt==0){\n namp[1]<-paste(outjpgdir,paste(ofilename,\"_SU25.png\",sep=\"\"),sep=\"/\")\n namp[2]<-paste(outjpgdir,paste(ofilename,\"_ID0.png\",sep=\"\"),sep=\"/\")\n namp[3]<-paste(outjpgdir,paste(ofilename,\"_TR20.png\",sep=\"\"),sep=\"/\")\n namp[4]<-paste(outjpgdir,paste(ofilename,\"_FD0.png\",sep=\"\"),sep=\"/\")\n namppdf[1]<-paste(outjpgdir,paste(ofilename,\"_SU25.pdf\",sep=\"\"),sep=\"/\")\n namppdf[2]<-paste(outjpgdir,paste(ofilename,\"_ID0.pdf\",sep=\"\"),sep=\"/\")\n namppdf[3]<-paste(outjpgdir,paste(ofilename,\"_TR20.pdf\",sep=\"\"),sep=\"/\")\n namppdf[4]<-paste(outjpgdir,paste(ofilename,\"_FD0.pdf\",sep=\"\"),sep=\"/\")\n }\n else{\n namp[1]<-paste(outjpgdir,paste(ofilename,\"_SU\",as.character(euu),\".png\",sep=\"\"),sep=\"/\")\n namp[2]<-paste(outjpgdir,paste(ofilename,\"_ID\",as.character(eul),\".png\",sep=\"\"),sep=\"/\")\n namp[3]<-paste(outjpgdir,paste(ofilename,\"_TR\",as.character(elu),\".png\",sep=\"\"),sep=\"/\")\n namp[4]<-paste(outjpgdir,paste(ofilename,\"_FD\",as.character(ell),\".png\",sep=\"\"),sep=\"/\")\n namppdf[1]<-paste(outjpgdir,paste(ofilename,\"_SU\",as.character(euu),\".pdf\",sep=\"\"),sep=\"/\")\n namppdf[2]<-paste(outjpgdir,paste(ofilename,\"_ID\",as.character(eul),\".pdf\",sep=\"\"),sep=\"/\")\n namppdf[3]<-paste(outjpgdir,paste(ofilename,\"_TR\",as.character(elu),\".pdf\",sep=\"\"),sep=\"/\")\n namppdf[4]<-paste(outjpgdir,paste(ofilename,\"_FD\",as.character(ell),\".pdf\",sep=\"\"),sep=\"/\")\n \n }\n if(opt==0) ylab<-c(\"SU25\",\"ID0\",\"TR20\",\"FD0\")\n else ylab<-c(paste(\"SU\",as.character(euu),sep=\"\"), \n paste(\"ID\",as.character(eul),sep=\"\"), \n paste(\"TR\",as.character(elu),sep=\"\"), \n paste(\"FD\",as.character(ell),sep=\"\"))\n\n xlab<-rep(\"year\",4)\n for(i in 1:4){\n title1[i]<-paste(ylab[i],ofilename,sep=\" \")\n png(file=namp[i],width=1024,height=768,bg=\"white\")\n plotx(tclext[,1],tclext[,i+1],main=title1[i],ylab=ylab[i],xlab=\"Año\")\n dev.off()\n pdf(file=namppdf[i])\n plotx(tclext[,1],tclext[,i+1],main=title1[i],ylab=ylab[i],xlab=\"Año\")\n dev.off()\n }\n}\n\nexceedance<-function(){\n if (flag==T) return()\n a<-1:365\n ys<-endyear-startyear+1;yss<-ys-1\n mondays<-c(31,28,31,30,31,30,31,31,30,31,30,31)\n mone<-rep(0,12);mons<-mone\n for(i in 1:12) mone[i]<-sum(mondays[1:i])\n mons[1]<-1\n for(i in 2:12) mons[i]<-mone[i-1]+1\n\n monex<-matrix(NA,ys*12,6)\n dimnames(monex)<-list(NULL,c(\"year\",\"month\",\"tx10p\",\"tx90p\",\"tn10p\",\"tn90p\"))\n monex[,\"month\"]<-rep(1:12,ys)\n monex[,\"year\"]<-startyear:endyear\n monex[,\"year\"]<-mysort(monex[,\"year\"],decreasing=F)\n monex<-as.data.frame(monex)\n\n\n b<-matrix(0,365,4)\n a<-cbind(a,b)\n aa<-array(a,c(365,5,ys))\n dimnames(aa)<-list(NULL,c(\"day\",\"pcmax10\",\"pcmax90\",\"pcmin10\",\"pcmin90\"),NULL)\n ms<-winsize*ys\n i=winsize-round(winsize/2,digits=0)\n i1=round(winsize/2,digits=0)\n \n# daynorm2<-daynorm1[-(1:i1),] # daynorm2 is total base period normalized data\n daynorm2<-dd[dd$year>=startyear,]\n daynorm2<-daynorm2[daynorm2$year<=endyear,]\n daynorm2<-daynorm2[daynorm2$month!=2|daynorm2$day!=29,]\n daynorm2<-daynorm2[,-4]\n# i2<-dim(daynorm2)[1]\n# i3<-i2-i1+1\n# daynorm2<-daynorm2[-(i3:i2),]\n \n yearex<-c(startyear:endyear);txg10p<-rep(0,length(yearex))\n txg90p<-rep(0,length(yearex));tng10p<-rep(0,length(yearex))\n tng90p<-rep(0,length(yearex))\n d<-as.data.frame(cbind(yearex,txg10p,txg90p,tng10p,tng90p))\n colnames(d)[1]<-\"year\"\n\n monex<-matrix(0,ys*12,6)\n dimnames(monex)<-list(NULL,c(\"year\",\"month\",\"tx10p\",\"tx90p\",\"tn10p\",\"tn90p\"))\n monex[,\"month\"]<-rep(1:12,ys)\n monex[,\"year\"]<-startyear:endyear\n monex[,\"year\"]<-mysort(monex[,\"year\"],decreasing=F)\n monex<-as.data.frame(monex)\n\n ratecount<-matrix(0,365,4)\n dimnames(ratecount)<-list(NULL,c(\"pcmax10\",\"pcmax90\",\"pcmin10\",\"pcmin90\"))\n\n for (year in startyear:endyear){ # year loop start\n\n midvalue<-daynorm2[daynorm2$year==year,]\n zz=year-startpoint #index in base period, say, zzth year\n\n indd<-exwin[exwin[,3]!=ys,3]\n \n for (k in 1:(ys-1)){ # for k (boot strap) start\n\n for (i in 1:365){ # day loop start\n ppc<-exwins[,,i]\n ppc<-ppc[ppc[,3]!=zz,]\n ppc<-ppc[,-3]\n \n ppc<-cbind(ppc,indd)\n \n ppcc<-rbind(ppc[ppc[,\"indd\"]==k,],ppc)\n\titmp<-percentile(ms,ppcc[,1],c(0.1,0.9))\n aa[i,\"pcmax10\",zz]<-itmp[1]-1e-5\n aa[i,\"pcmax90\",zz]<-itmp[2]+1e-5\n\titmp<-percentile(ms,ppcc[,2],c(0.1,0.9))\n aa[i,\"pcmin10\",zz]<-itmp[1]-1e-5\n aa[i,\"pcmin90\",zz]<-itmp[2]+1e-5\n }\n ratecount[,\"pcmax10\"]<-midvalue[,\"tmax\"]-aa[,\"pcmax10\",zz]\n ratecount[,\"pcmax90\"]<-midvalue[,\"tmax\"]-aa[,\"pcmax90\",zz]\n ratecount[,\"pcmin10\"]<-midvalue[,\"tmin\"]-aa[,\"pcmin10\",zz]\n ratecount[,\"pcmin90\"]<-midvalue[,\"tmin\"]-aa[,\"pcmin90\",zz]\n for(mon in 1:12){\n tmptx10p<-ratecount[mons[mon]:mone[mon],\"pcmax10\"]\n tmptx90p<-ratecount[mons[mon]:mone[mon],\"pcmax90\"]\n tmptn10p<-ratecount[mons[mon]:mone[mon],\"pcmin10\"]\n tmptn90p<-ratecount[mons[mon]:mone[mon],\"pcmin90\"]\n monex[(zz-1)*12+mon,\"tx10p\"]<- monex[(zz-1)*12+mon,\"tx10p\"]+length(tmptx10p[tmptx10p<0&is.na(tmptx10p)==F])\n monex[(zz-1)*12+mon,\"tx90p\"]<- monex[(zz-1)*12+mon,\"tx90p\"]+length(tmptx90p[tmptx90p>0&is.na(tmptx90p)==F])\n monex[(zz-1)*12+mon,\"tn10p\"]<- monex[(zz-1)*12+mon,\"tn10p\"]+length(tmptn10p[tmptn10p<0&is.na(tmptn10p)==F])\n monex[(zz-1)*12+mon,\"tn90p\"]<- monex[(zz-1)*12+mon,\"tn90p\"]+length(tmptn90p[tmptn90p>0&is.na(tmptn90p)==F])\n\tif(leapyear(year)&mon==2){\n\t if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"]>aa[59,\"pcmax90\",zz]&is.na(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"])==F&is.na(aa[58,\"pcmax90\",zz])==F)\n\t monex[(zz-1)*12+mon,\"tx90p\"]<-monex[(zz-1)*12+mon,\"tx90p\"]+1\n\t if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmax\"]aa[59,\"pcmin90\",zz]&is.na(dd[dd$year==year&dd$month==2&dd$day==29,\"tmin\"])==F&is.na(aa[58,\"pcmin90\",zz])==F)\n\t monex[(zz-1)*12+mon,\"tn90p\"]<-monex[(zz-1)*12+mon,\"tn90p\"]+1\n\t if(dd[dd$year==year&dd$month==2&dd$day==29,\"tmin\"]10) ofile[k,(mon+1)]<-NA\n else ofile[k,(mon+1)]<-dm[(k-1)*12+mon,kk]*fulldays[mon]/(fulldays[mon]-nastatistic[(k-1)*12+mon,nastat])\n }\n ofile[k,14]<-sum(ofile[k,2:13],na.rm=T)\n }\n ofile[,14]<-ofile[,14]+ynacor[,nastat-4]\n for(j in years:yeare){\n k<-j-years+1\n if(leapyear(j)) fulldays<-c(31,29,31,30,31,30,31,31,30,31,30,31)\n else fulldays<-c(31,28,31,30,31,30,31,31,30,31,30,31)\n for(mon in 1:12) ofile[k,mon+1]<-ofile[k,mon+1]*100/fulldays[mon] # change output from counting days to %\n }\n ofile[,14]<-ofile[,14]*100/365 # change output from counting days to %\n write.table(round(ofile,2),file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n \n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(ofile[,14]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(ofile[,1],ofile[,14])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,i,years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_\",toupper(i),\".png\",sep=\"\"),sep=\"/\")\n png(file=nam2,width=1024,height=768,bg=\"white\")\n plotx(ofile[,1],ofile[,14],main=paste(toupper(i),ofilename,sep=\" \"),ylab=toupper(i),xlab=\"Año\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_\",toupper(i),\".pdf\",sep=\"\"),sep=\"/\")\n pdf(file=nam2a)\n plotx(ofile[,1],ofile[,14],main=paste(toupper(i),ofilename,sep=\" \"),ylab=toupper(i),xlab=\"Año\")\n dev.off()\n }\n}\n\nindex641cdd<-function(){\nys<-yeare-years+1\ncdd<-rep(0,ys)\nyear<-c(years:yeare)\ntarget<-as.data.frame(cbind(year,cdd))\nyear=years\nfor (i in 1:ys){\n mid<-dd[dd$year==year,\"prcp\"]\n# mid<-mid[is.na(mid)==F]\n if(i==1) kk<-0\n mm<-0\n for(j in 1:length(mid)){\n if(mid[j]<1&is.na(mid[j])==F) kk<-kk+1\n else {\n if(mm=1|is.na(dd[dd$year==year+1&dd$month==1&dd$day==1,\"prcp\"])==T) mm<-kk\n# in case whole year dry, the next year will have a CDD bigger than 365\n# then the CDD indice for current year should not be 0 but NA\n if(mm==0) mm<-NA\n }\n target[i,\"cdd\"]<-mm\n year=year+1\n}\n\n#for(i in 1:(ys-1))\n# if(target[i,\"cdd\"]==0&target[i+1,\"cdd\"]>=365) target[i,\"cdd\"]<-NA\n\ntarget[,\"cdd\"]<-target[,\"cdd\"]+ynacor[,\"ynapr>15\"]\nnam1<-paste(outinddir,paste(ofilename,\"_CDD.csv\",sep=\"\"),sep=\"/\")\nwrite.table(target,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(target[,\"cdd\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(target[,1],target[,\"cdd\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"cdd\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\nnam2<-paste(outjpgdir,paste(ofilename,\"_CDD.png\",sep=\"\"),sep=\"/\")\npng(nam2,width=1024,height=768,bg=\"white\")\nplotx(target[,1],target[,2],main=paste(\"CDD\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"CDD\")\ndev.off()\nnam2a<-paste(outjpgdir,paste(ofilename,\"_CDD.pdf\",sep=\"\"),sep=\"/\")\npdf(nam2a)\nplotx(target[,1],target[,2],main=paste(\"CDD\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"CDD\")\ndev.off()\n}\n\nindex641cwd<-function(){\nys<-yeare-years+1\ncwd<-rep(0,ys)\nyear<-years:yeare\ntarget<-as.data.frame(cbind(year,cwd))\nyear=years\nfor (i in 1:ys){\n mid<-dd[dd$year==year,\"prcp\"]\n# mid<-mid[is.na(mid)==F]\n if(i==1) kk<-0\n mm<-0\n for(j in 1:length(mid)){\n if(mid[j]>=1&is.na(mid[j])==F) kk<-kk+1\n else {\n if(mm15\"]\nnam1<-paste(outinddir,paste(ofilename,\"_CWD.csv\",sep=\"\"),sep=\"/\")\nwrite.table(target,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(target[,\"cwd\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(target[,1],target[,\"cwd\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"cwd\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\nnam2<-paste(outjpgdir,paste(ofilename,\"_CWD.png\",sep=\"\"),sep=\"/\")\npng(nam2,width=1024,height=768,bg=\"white\")\nplotx(target[,1],target[,2],main=paste(\"CWD\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"CWD\")\ndev.off()\nnam2a<-paste(outjpgdir,paste(ofilename,\"_CWD.pdf\",sep=\"\"),sep=\"/\")\npdf(nam2a)\nplotx(target[,1],target[,2],main=paste(\"CWD\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"CWD\")\ndev.off()\n}\n\nrx1d<-function(){\n len<-yeare-years+1\n aa1<-matrix(NA,12*len,3)\n dimnames(aa1)<-list(NULL,c(\"year\",\"month\",\"rx1d\"))\n aa1[,\"year\"]<-years:yeare\n aa1[,\"year\"]<-mysort(aa1[,\"year\"],decreasing=F)\n aa1[,\"month\"]<-1:12\n jjj3=1\n mid<-dd[,1:4]\n for (year in years:yeare){\n aaaa<-mid[mid$year==year,]\n aaaam1<-aaaa[aaaa$month==1,\"prcp\"];aaaam2<-aaaa[aaaa$month==2,\"prcp\"]\n aaaam3<-aaaa[aaaa$month==3,\"prcp\"];aaaam4<-aaaa[aaaa$month==4,\"prcp\"]\n aaaam5<-aaaa[aaaa$month==5,\"prcp\"];aaaam6<-aaaa[aaaa$month==6,\"prcp\"]\n aaaam7<-aaaa[aaaa$month==7,\"prcp\"];aaaam8<-aaaa[aaaa$month==8,\"prcp\"]\n aaaam9<-aaaa[aaaa$month==9,\"prcp\"];aaaam10<-aaaa[aaaa$month==10,\"prcp\"]\n aaaam11<-aaaa[aaaa$month==11,\"prcp\"];aaaam12<-aaaa[aaaa$month==12,\"prcp\"]\n aa1[jjj3,\"rx1d\"]<-max(aaaam1,na.rm=T);aa1[jjj3+1,\"rx1d\"]<-max(aaaam2,na.rm=T)\n aa1[jjj3+2,\"rx1d\"]<-max(aaaam3,na.rm=T);aa1[jjj3+3,\"rx1d\"]<-max(aaaam4,na.rm=T)\n aa1[jjj3+4,\"rx1d\"]<-max(aaaam5,na.rm=T);aa1[jjj3+5,\"rx1d\"]<-max(aaaam6,na.rm=T)\n aa1[jjj3+6,\"rx1d\"]<-max(aaaam7,na.rm=T);aa1[jjj3+7,\"rx1d\"]<-max(aaaam8,na.rm=T)\n aa1[jjj3+8,\"rx1d\"]<-max(aaaam9,na.rm=T);aa1[jjj3+9,\"rx1d\"]<-max(aaaam10,na.rm=T)\n aa1[jjj3+10,\"rx1d\"]<-max(aaaam11,na.rm=T);aa1[jjj3+11,\"rx1d\"]<-max(aaaam12,na.rm=T)\n jjj3=jjj3+12}\n aa1[,\"rx1d\"]<-aa1[,\"rx1d\"]+nacor[,\"mnapr>3\"]\n ofile<-matrix(0,len,14)\n# aa1<-as.data.frame(aa1)\n dimnames(ofile)<-list(NULL,c(\"year\",\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\",\"annual\"))\n ofile<-as.data.frame(ofile)\n for(j in years:yeare){\n k<-j-years+1\n ofile[k,1]<-j\n ofile[k,2:13]<-aa1[aa1[,1]==j,3]\n ofile[k,14]<-max(ofile[k,2:13],na.rm=F)\n }\n nam1<-paste(outinddir,paste(ofilename,\"_RX1day.csv\",sep=\"\"),sep=\"/\")\n write.table(ofile,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(ofile[,14]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(ofile[,1],ofile[,14])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"rx1day\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_RX1day.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(ofile[,1],ofile[,14],main=paste(\"RX1day\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"RX1day\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_RX1day.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(ofile[,1],ofile[,14],main=paste(\"RX1day\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"RX1day\")\n dev.off()\n}# end of rx1d()\n\nrx5d<-function(){\n a2<-c(0,0,0,0)\n a1<-dd[,\"prcp\"]\n a1<-append(a2,a1)\n n<-length(a1)\n a<-rep(0,n)\n for (i in 5:n){\n a[i]<-sum(a1[(i-4):i],na.rm=T)}\n a<-a[-(1:4)]\n a<-cbind(dd[,1:2],a)\n \n len<-yeare-years+1\n aa1<-matrix(NA,12*len,3)\n dimnames(aa1)<-list(NULL,c(\"year\",\"month\",\"rx5d\"))\n aa1[,\"year\"]<-years:yeare\n aa1[,\"year\"]<-mysort(aa1[,\"year\"],decreasing=F)\n aa1[,\"month\"]<-1:12\n jjj2=1\n for (year in years:yeare){\n aaaa<-a[a$year==year,]\n aaaam1<-aaaa[aaaa$month==1,\"a\"];aaaam2<-aaaa[aaaa$month==2,\"a\"]\n aaaam3<-aaaa[aaaa$month==3,\"a\"];aaaam4<-aaaa[aaaa$month==4,\"a\"]\n aaaam5<-aaaa[aaaa$month==5,\"a\"];aaaam6<-aaaa[aaaa$month==6,\"a\"]\n aaaam7<-aaaa[aaaa$month==7,\"a\"];aaaam8<-aaaa[aaaa$month==8,\"a\"]\n aaaam9<-aaaa[aaaa$month==9,\"a\"];aaaam10<-aaaa[aaaa$month==10,\"a\"]\n aaaam11<-aaaa[aaaa$month==11,\"a\"];aaaam12<-aaaa[aaaa$month==12,\"a\"]\n aa1[jjj2,\"rx5d\"]<-max(aaaam1,na.rm=T);aa1[jjj2+1,\"rx5d\"]<-max(aaaam2,na.rm=T)\n aa1[jjj2+2,\"rx5d\"]<-max(aaaam3,na.rm=T);aa1[jjj2+3,\"rx5d\"]<-max(aaaam4,na.rm=T)\n aa1[jjj2+4,\"rx5d\"]<-max(aaaam5,na.rm=T);aa1[jjj2+5,\"rx5d\"]<-max(aaaam6,na.rm=T)\n aa1[jjj2+6,\"rx5d\"]<-max(aaaam7,na.rm=T);aa1[jjj2+7,\"rx5d\"]<-max(aaaam8,na.rm=T)\n aa1[jjj2+8,\"rx5d\"]<-max(aaaam9,na.rm=T);aa1[jjj2+9,\"rx5d\"]<-max(aaaam10,na.rm=T)\n aa1[jjj2+10,\"rx5d\"]<-max(aaaam11,na.rm=T);aa1[jjj2+11,\"rx5d\"]<-max(aaaam12,na.rm=T)\n jjj2=jjj2+12}\n\n aa1[,\"rx5d\"]<-aa1[,\"rx5d\"]+nacor[,\"mnapr>3\"]\n \n ofile<-matrix(0,len,14)\n# aa1<-as.data.frame(aa1)\n dimnames(ofile)<-list(NULL,c(\"year\",\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\",\"annual\"))\n ofile<-as.data.frame(ofile)\n for(j in years:yeare){\n k<-j-years+1\n ofile[k,1]<-j\n ofile[k,2:13]<-aa1[aa1[,1]==j,\"rx5d\"]\n ofile[k,14]<-max(ofile[k,2:13],na.rm=F)\n }\n# print(dim(rx5d))\n nam1<-paste(outinddir,paste(ofilename,\"_RX5day.csv\",sep=\"\"),sep=\"/\")\n write.table(ofile,file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(ofile[,14]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(ofile[,1],ofile[,14])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"rx5day\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_RX5day.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(ofile[,1],ofile[,14],main=paste(\"RX5day\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"RX5day\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_RX5day.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(ofile[,1],ofile[,14],main=paste(\"RX5day\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"RX5day\")\n dev.off()\n }# end of rx5d()\n\nextremedaytem<-function(){\n len<-yeare-years+1\n aa1<-matrix(NA,12*len,6)\n dimnames(aa1)<-list(NULL,c(\"year\",\"month\",\"txx\",\"txn\",\"tnx\",\"tnn\"))\n aa1[,\"year\"]<-years:yeare\n aa1[,\"year\"]<-mysort(aa1[,\"year\"],decreasing=F)\n aa1[,\"month\"]<-1:12\n jjj4=1\n for (year in years:yeare){\n aaaa<-dd[dd$year==year,]\n aaaama1<-aaaa[aaaa$month==1,\"tmax\"];aaaama2<-aaaa[aaaa$month==2,\"tmax\"]\n aaaama3<-aaaa[aaaa$month==3,\"tmax\"];aaaama4<-aaaa[aaaa$month==4,\"tmax\"]\n aaaama5<-aaaa[aaaa$month==5,\"tmax\"];aaaama6<-aaaa[aaaa$month==6,\"tmax\"]\n aaaama7<-aaaa[aaaa$month==7,\"tmax\"];aaaama8<-aaaa[aaaa$month==8,\"tmax\"]\n aaaama9<-aaaa[aaaa$month==9,\"tmax\"];aaaama10<-aaaa[aaaa$month==10,\"tmax\"]\n aaaama11<-aaaa[aaaa$month==11,\"tmax\"];aaaama12<-aaaa[aaaa$month==12,\"tmax\"]\n \n aaaami1<-aaaa[aaaa$month==1,\"tmin\"];aaaami2<-aaaa[aaaa$month==2,\"tmin\"]\n aaaami3<-aaaa[aaaa$month==3,\"tmin\"];aaaami4<-aaaa[aaaa$month==4,\"tmin\"]\n aaaami5<-aaaa[aaaa$month==5,\"tmin\"];aaaami6<-aaaa[aaaa$month==6,\"tmin\"]\n aaaami7<-aaaa[aaaa$month==7,\"tmin\"];aaaami8<-aaaa[aaaa$month==8,\"tmin\"]\n aaaami9<-aaaa[aaaa$month==9,\"tmin\"];aaaami10<-aaaa[aaaa$month==10,\"tmin\"]\n aaaami11<-aaaa[aaaa$month==11,\"tmin\"];aaaami12<-aaaa[aaaa$month==12,\"tmin\"]\n \n aa1[jjj4,\"txx\"]<-max(aaaama1,na.rm=T);aa1[jjj4+1,\"txx\"]<-max(aaaama2,na.rm=T)\n aa1[jjj4+2,\"txx\"]<-max(aaaama3,na.rm=T);aa1[jjj4+3,\"txx\"]<-max(aaaama4,na.rm=T)\n aa1[jjj4+4,\"txx\"]<-max(aaaama5,na.rm=T);aa1[jjj4+5,\"txx\"]<-max(aaaama6,na.rm=T)\n aa1[jjj4+6,\"txx\"]<-max(aaaama7,na.rm=T);aa1[jjj4+7,\"txx\"]<-max(aaaama8,na.rm=T)\n aa1[jjj4+8,\"txx\"]<-max(aaaama9,na.rm=T);aa1[jjj4+9,\"txx\"]<-max(aaaama10,na.rm=T)\n aa1[jjj4+10,\"txx\"]<-max(aaaama11,na.rm=T);aa1[jjj4+11,\"txx\"]<-max(aaaama12,na.rm=T)\n \n aa1[jjj4,\"txn\"]<-min(aaaama1,na.rm=T);aa1[jjj4+1,\"txn\"]<-min(aaaama2,na.rm=T)\n aa1[jjj4+2,\"txn\"]<-min(aaaama3,na.rm=T);aa1[jjj4+3,\"txn\"]<-min(aaaama4,na.rm=T)\n aa1[jjj4+4,\"txn\"]<-min(aaaama5,na.rm=T);aa1[jjj4+5,\"txn\"]<-min(aaaama6,na.rm=T)\n aa1[jjj4+6,\"txn\"]<-min(aaaama7,na.rm=T);aa1[jjj4+7,\"txn\"]<-min(aaaama8,na.rm=T)\n aa1[jjj4+8,\"txn\"]<-min(aaaama9,na.rm=T);aa1[jjj4+9,\"txn\"]<-min(aaaama10,na.rm=T)\n aa1[jjj4+10,\"txn\"]<-min(aaaama11,na.rm=T);aa1[jjj4+11,\"txn\"]<-min(aaaama12,na.rm=T)\n\n aa1[jjj4,\"tnx\"]<-max(aaaami1,na.rm=T);aa1[jjj4+1,\"tnx\"]<-max(aaaami2,na.rm=T)\n aa1[jjj4+2,\"tnx\"]<-max(aaaami3,na.rm=T);aa1[jjj4+3,\"tnx\"]<-max(aaaami4,na.rm=T)\n aa1[jjj4+4,\"tnx\"]<-max(aaaami5,na.rm=T);aa1[jjj4+5,\"tnx\"]<-max(aaaami6,na.rm=T)\n aa1[jjj4+6,\"tnx\"]<-max(aaaami7,na.rm=T);aa1[jjj4+7,\"tnx\"]<-max(aaaami8,na.rm=T)\n aa1[jjj4+8,\"tnx\"]<-max(aaaami9,na.rm=T);aa1[jjj4+9,\"tnx\"]<-max(aaaami10,na.rm=T)\n aa1[jjj4+10,\"tnx\"]<-max(aaaami11,na.rm=T);aa1[jjj4+11,\"tnx\"]<-max(aaaami12,na.rm=T)\n\n aa1[jjj4,\"tnn\"]<-min(aaaami1);aa1[jjj4+1,\"tnn\"]<-min(aaaami2,na.rm=T)\n aa1[jjj4+2,\"tnn\"]<-min(aaaami3,na.rm=T);aa1[jjj4+3,\"tnn\"]<-min(aaaami4,na.rm=T)\n aa1[jjj4+4,\"tnn\"]<-min(aaaami5,na.rm=T);aa1[jjj4+5,\"tnn\"]<-min(aaaami6,na.rm=T)\n aa1[jjj4+6,\"tnn\"]<-min(aaaami7,na.rm=T);aa1[jjj4+7,\"tnn\"]<-min(aaaami8,na.rm=T)\n aa1[jjj4+8,\"tnn\"]<-min(aaaami9,na.rm=T);aa1[jjj4+9,\"tnn\"]<-min(aaaami10,na.rm=T)\n aa1[jjj4+10,\"tnn\"]<-min(aaaami11,na.rm=T);aa1[jjj4+11,\"tnn\"]<-min(aaaami12,na.rm=T)\n \n jjj4=jjj4+12}\n exdaytem<-as.data.frame(aa1)\n# midnacor<-nacor[nacor$year>=startyear,]\n# midnacor<-midnacor[midnacor$year<=endyear,]\n exdaytem[,\"txx\"]<-exdaytem[,\"txx\"]+nacor[,\"mnatma>3\"]\n exdaytem[,\"txn\"]<-exdaytem[,\"txn\"]+nacor[,\"mnatma>3\"]\n exdaytem[,\"tnx\"]<-exdaytem[,\"tnx\"]+nacor[,\"mnatmi>3\"]\n exdaytem[,\"tnn\"]<-exdaytem[,\"tnn\"]+nacor[,\"mnatmi>3\"]\n\n for(i in c(\"txx\",\"txn\",\"tnx\",\"tnn\")){\n if (i==\"txx\") {ii<-\"_TXx.csv\";ij<-\"_TXx.png\";ijpdf<-\"_TXx.pdf\";kk<-3;ik<-1;ki<-3}# ik=1, take max as yearly record\n if (i==\"txn\") {ii<-\"_TXn.csv\";ij<-\"_TXn.png\";ijpdf<-\"_TXn.pdf\";kk<-4;ik<-0;ki<-3}# ik=0, take min as yearly record\n if (i==\"tnx\") {ii<-\"_TNx.csv\";ij<-\"_TNx.png\";ijpdf<-\"_TNx.pdf\";kk<-5;ik<-1;ki<-4}# ki=3, take TMAX annual missing values\n if (i==\"tnn\") {ii<-\"_TNn.csv\";ij<-\"_TNn.png\";ijpdf<-\"_TNn.pdf\";kk<-6;ik<-0;ki<-4}# ki=4, take TMIN annual missing values\n nam<-paste(outinddir,paste(ofilename,ii,sep=\"\"),sep=\"/\")\n ofile<-matrix(0,len,14)\n# ojpg<-rep(0,len)\n dimnames(ofile)<-list(NULL,c(\"year\",\"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\",\"annual\"))\n ofile<-as.data.frame(ofile)\n for(j in years:yeare){\n k<-j-years+1\n ofile[k,1]<-j\n ofile[k,2:13]<-exdaytem[exdaytem$year==j,kk]\n if(ik==1) ofile[k,14]<-max(ofile[k,2:13],na.rm=T)\n else ofile[k,14]<-min(ofile[k,2:13],na.rm=T)\n }\n ofile[,14]<-ofile[,14]+ynacor[,ki]\n write.table(ofile,file=nam,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n \n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(ofile[,14]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(ofile[,1],ofile[,14])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,i,years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,ij,sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(ofile[,1],ofile[,14],main=paste(toupper(i),ofilename,sep=\" \"),xlab=\"Año\",ylab=(paste(toupper(substr(i,1,2)),substr(i,3,3),sep=\"\")))\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,ijpdf,sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(ofile[,1],ofile[,14],main=paste(toupper(i),ofilename,sep=\" \"),xlab=\"Año\",ylab=(paste(toupper(substr(i,1,2)),substr(i,3,3),sep=\"\")))\n dev.off()\n }\n}\n\nindex646<-function(){\n ys=yeare-years+1\n b<-matrix(0,ncol=2,nrow=ys)\n dimnames(b)<-list(NULL,c(\"year\",\"sdii\"))\n b[,\"year\"]<-c(years:yeare)\n b<-as.data.frame(b)\n year=years\n for (i in 1:ys){\n mid<-dd[dd$year==year,\"prcp\"]\n mid<-mid[mid>=1]\n b[i,\"sdii\"]<-mean(mid,na.rm=T)\n year=year+1 }\n b[,\"sdii\"]<-b[,\"sdii\"]+ynacor[,\"ynapr>15\"]\n nam1<-paste(outinddir,paste(ofilename,\"_SDII.csv\",sep=\"\"),sep=\"/\")\n write.table(round(b,digit=1),file=nam1,append=F,quote=F,sep=\", \",na=\"-99.9\",row.names=F)\n\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n if(sum(is.na(b[,\"sdii\"]))>=(yeare-years+1-10)){\n betahat<-NA\n betastd<-NA\n pvalue<-NA\n }\n else{\n fit1<-lsfit(b[,\"year\"],b[,\"sdii\"])\n out1<-ls.print(fit1,print.it=F)\n pvalue<-round(as.numeric(out1$summary[1,6]),3)\n betahat<-round(as.numeric(out1$coef.table[[1]][2,1]),3)\n betastd<-round(as.numeric(out1$coef.table[[1]][2,2]),3)\n }\n cat(file=namt,paste(latitude,longitude,\"sdii\",years,yeare,betahat,betastd,pvalue,sep=\",\"),fill=180,append=T)\n\n nam2<-paste(outjpgdir,paste(ofilename,\"_SDII.png\",sep=\"\"),sep=\"/\")\n png(nam2,width=1024,height=768,bg=\"white\")\n plotx(b[,1],b[,2],main=paste(\"SDII\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"SDII\")\n dev.off()\n nam2a<-paste(outjpgdir,paste(ofilename,\"_SDII.pdf\",sep=\"\"),sep=\"/\")\n pdf(nam2a)\n plotx(b[,1],b[,2],main=paste(\"SDII\",ofilename,sep=\" \"),xlab=\"Año\",ylab=\"SDII\")\n dev.off()\n}\n\nmain1<-function(){\n main<-tktoplevel()\n tkfocus(main)\n tkwm.title(main,\"Calculating Climate Indices\")\n tkgrid(tklabel(main,text=\"Check desired indices\",font=fontHeading1))\n\ttxt=\"It may take 5 minutes to compute all the indices, \"\n#\tif(prallna==1) tkgrid(tklabel(main, text=\"PRCP all missing, indices related to PRCP may not be calculated\",font=fontHeading2))\n#\tif(txallna==1|tnallna==1) tkgrid(tklabel(main,text=\"TMAX or TMIN all missing, indices related to TMAX and TMIN may not be calculated\",font=fontHeading2))\n\n#cb0 <- tkcheckbutton(main);cb0Val <- cbvalue0\n\ncb1 <- tkcheckbutton(main);cb1Val <- cbvalue1\ncb2 <- tkcheckbutton(main);cb2Val <- cbvalue2\ncb3 <- tkcheckbutton(main);cb3Val <- cbvalue3\ncb4 <- tkcheckbutton(main);cb4Val <- cbvalue4\ncb5 <- tkcheckbutton(main);cb5Val <- cbvalue5\ncb6 <- tkcheckbutton(main);cb6Val <- cbvalue6\ncb7 <- tkcheckbutton(main);cb7Val <- cbvalue7\ncb8 <- tkcheckbutton(main);cb8Val <- cbvalue8\ncb9 <- tkcheckbutton(main);cb9Val <- cbvalue9\ncb10 <- tkcheckbutton(main);cb10Val <- cbvalue10\ncb11 <- tkcheckbutton(main);cb11Val <- cbvalue11\ncb12 <- tkcheckbutton(main);cb12Val <- cbvalue12\ncb13 <- tkcheckbutton(main);cb13Val <- cbvalue13\ncb14 <- tkcheckbutton(main);cb14Val <- cbvalue14\ncb15 <- tkcheckbutton(main);cb15Val <- cbvalue15\ncb21 <- tkcheckbutton(main);cb21Val <- cbvalue21\n \n#tkconfigure(cb0,variable=cb0Val)#,value=cb1Val)\ntkconfigure(cb1,variable=cb1Val)#,value=cb1Val)\ntkconfigure(cb2,variable=cb2Val)#,value=cb2Val)\ntkconfigure(cb3,variable=cb3Val)#,value=cb3Val)#\"dtr\")\ntkconfigure(cb4,variable=cb4Val)#,value=cb4Val)#\"daysprcp10\")\ntkconfigure(cb5,variable=cb5Val)#,value=cb5Val)#\"nordaytem1\")\ntkconfigure(cb6,variable=cb6Val)#,value=cb6Val)#\"extremedays\")\ntkconfigure(cb7,variable=cb7Val)#,value=cb7Val)#\"exceedance\")\ntkconfigure(cb8,variable=cb8Val)#,value=cb8Val)#\"ind144hwd\")\ntkconfigure(cb9,variable=cb9Val)#,value=cb9Val)#\"ind641cdd\")\ntkconfigure(cb10,variable=cb10Val)#,value=cb10Val)#\"rx5d\")\ntkconfigure(cb11,variable=cb11Val)#,value=cb11Val)#\"ind646\")\ntkconfigure(cb12,variable=cb12Val)#,value=cb12Val)#\"ind695\")\ntkconfigure(cb13,variable=cb13Val)#,value=cb13Val)#\"rx1d\"\ntkconfigure(cb14,variable=cb14Val)#,value=cb14Val)#\"extreme day tem\"\ntkconfigure(cb15,variable=cb15Val)\ntkconfigure(cb21,variable=cb21Val)\n \n#tkgrid(tklabel(main,text=\"Select the indices you want to calculate:\"))\n\n#tkgrid(tklabel(main,text=\"ALL 26 indices!!\"),cb0)\ntkgrid(tklabel(main,text=\"SU25, FD0, TR20, ID0\"),cb1)\ntkgrid(tklabel(main,text=\"User Defined SU, FD, TR, ID\"),cb21)\n\ntkgrid(tklabel(main,text=\"GSL, growing season length\"),cb2)#143\n\ntkgrid(tklabel(main,text=\"TXx, TXn, TNx, TNn\"),cb3)\n#tkgrid(tklabel(main,text=\"TXn, TNx, TNn, following by same choice\"),cb3)#extremedaytem\n\ntkgrid(tklabel(main,text=\"TX10p, TX90p, TN10p, TN90p\"),cb4)\n#tkgrid(tklabel(main,text=\"TX90p, TN10p, TN90p, following by same choice\"),cb4)#exceedance\n\ntkgrid(tklabel(main,text=\"WSDI\"),cb5)#hwfi\ntkgrid(tklabel(main,text=\"CSDI\"),cb6)#cwdi\n \n#tkgrid(tklabel(main,text=\"Normal day temperature with user defined window size\"),cb2)\ntkgrid(tklabel(main,text=\"DTR\"),cb7)#dtr\n \ntkgrid(tklabel(main,text=\"Rx1day\"),cb8)#rx1d\ntkgrid(tklabel(main,text=\"Rx5day\"),cb9)#rx5d\n \ntkgrid(tklabel(main,text=\"SDII\"),cb10)#index646\n\ntkgrid(tklabel(main,text=\"R10mm\"),cb11)#daysprcp10()\ntkgrid(tklabel(main,text=\"R20mm\"),cb12)#daysprcp20()\ntkgrid(tklabel(main,text=\"Rnnmm\"),cb13)#daysprcpn()\n\ntkgrid(tklabel(main,text=\"CDD, CWD\"),cb14)\n#tkgrid(tklabel(main,text=\"CWD\"),cb14)#641\n\n#tkgrid(tklabel(main,text=\"daynortem \"),cb5)\n#tkgrid(tklabel(main,text=\"ind144hwd \"),cb8)#144\n \ntkgrid(tklabel(main,text=\"R95p, R99p, PRCPTOT\"),cb15)#695\n#tkgrid(tklabel(main,text=\"R99pTOT\"),cb15)\n \n#tkgrid(tklabel(main,text=\"Annual Days with PRCP>=95 percentile\"),cb17)#r95ptot\n#tkgrid(tklabel(main,text=\"Annual Days with PRCP>=99 percentile\"),cb17)\n\n OnOK <- function(){\n#filename<-tclvalue(tkgetSaveFile(filetypes=\"{{EXCEL Files} {.csv}} {{All files} *}\"))\n#if (!nchar(filename))\n#tkmessageBox(message=\"No file was selected!\")\n#else tkmessageBox(message=paste(\"The results will be saved under\",filename))\n#nam<-substr(filename,start=1,stop=(nchar(filename)-4))\n#assign(\"nam\",nam,envir=.GlobalEnv)\n\n# cbv0 <- as.character(tclvalue(cb0Val))\n cbv1 <- as.character(tclvalue(cb1Val))\n cbv21 <- as.character(tclvalue(cb21Val))\n cbv2 <- as.character(tclvalue(cb2Val))\n cbv3 <- as.character(tclvalue(cb3Val))\n cbv4 <- as.character(tclvalue(cb4Val))\n cbv5 <- as.character(tclvalue(cb5Val))\n cbv6 <- as.character(tclvalue(cb6Val))\n cbv7 <- as.character(tclvalue(cb7Val))\n cbv8 <- as.character(tclvalue(cb8Val))\n cbv9 <- as.character(tclvalue(cb9Val))\n cbv10 <- as.character(tclvalue(cb10Val))\n cbv11 <- as.character(tclvalue(cb11Val))\n cbv12 <- as.character(tclvalue(cb12Val))\n cbv13 <- as.character(tclvalue(cb13Val))\n cbv14 <- as.character(tclvalue(cb14Val))\n cbv15 <- as.character(tclvalue(cb15Val))\n tkdestroy(main)\n# if (cbv0==1) {cbv1<-1;cbv2<-1;cbv3<-1;cbv4<-1;cbv5<-1;\n namt<-paste(outtrddir,paste(ofilename,\"_trend.csv\",sep=\"\"),sep=\"/\")\n cat(file=namt,paste(\"Lon\",\"Lat\",\"Indices\",\"SYear\",\"EYear\",\"Slope\",\"STD_of_Slope\",\"P_Value\",sep=\",\"),fill=180,append=F)\n if (cbv1==1) if(txallna==0&tnallna==0) extremedays()\n if (cbv21==1) if(txallna==0&tnallna==0) extremedays(opt=1)\n if (cbv2==1) if(txallna==0&tnallna==0) ind143gsl()\n if (cbv3==1) if(txallna==0&tnallna==0) extremedaytem()\n if (cbv4==1) if(txallna==0&tnallna==0) exceedance()\n if (cbv5==1) if(txallna==0) hwfi()\n if (cbv6==1) if(tnallna==0) cwdi()\n if (cbv7==1) if(txallna==0&tnallna==0) dtr()\n if (cbv8==1) if(prallna==0) rx1d()\n if (cbv9==1) if(prallna==0) rx5d()\n if (cbv10==1) if(prallna==0) index646()\n if (cbv11==1) if(prallna==0) daysprcp10()\n if (cbv12==1) if(prallna==0) daysprcp20()\n if (cbv13==1) if(prallna==0) daysprcpn()\n if (cbv14==1) if(prallna==0) {index641cdd();index641cwd()}\n if (cbv15==1) if(prallna==0) r95ptot()\n cbvalue1<-cb1Val;assign(\"cbvalue1\",cbvalue1,envir=.GlobalEnv)\n cbvalue2<-cb2Val;assign(\"cbvalue2\",cbvalue2,envir=.GlobalEnv)\n cbvalue3<-cb3Val;assign(\"cbvalue3\",cbvalue3,envir=.GlobalEnv)\n cbvalue4<-cb4Val;assign(\"cbvalue4\",cbvalue4,envir=.GlobalEnv)\n cbvalue5<-cb5Val;assign(\"cbvalue5\",cbvalue5,envir=.GlobalEnv)\n cbvalue6<-cb6Val;assign(\"cbvalue6\",cbvalue6,envir=.GlobalEnv)\n cbvalue7<-cb7Val;assign(\"cbvalue7\",cbvalue7,envir=.GlobalEnv)\n cbvalue8<-cb8Val;assign(\"cbvalue8\",cbvalue8,envir=.GlobalEnv)\n cbvalue9<-cb9Val;assign(\"cbvalue9\",cbvalue9,envir=.GlobalEnv)\n cbvalue10<-cb10Val;assign(\"cbvalue10\",cbvalue10,envir=.GlobalEnv)\n cbvalue11<-cb11Val;assign(\"cbvalue11\",cbvalue11,envir=.GlobalEnv)\n cbvalue12<-cb12Val;assign(\"cbvalue12\",cbvalue12,envir=.GlobalEnv)\n cbvalue13<-cb13Val;assign(\"cbvalue13\",cbvalue13,envir=.GlobalEnv)\n cbvalue14<-cb14Val;assign(\"cbvalue14\",cbvalue14,envir=.GlobalEnv)\n cbvalue15<-cb15Val;assign(\"cbvalue15\",cbvalue15,envir=.GlobalEnv)\n cbvalue21<-cb21Val;assign(\"cbvalue21\",cbvalue21,envir=.GlobalEnv)\n nstation<-tktoplevel()\n tkwm.title(nstation,\"Calculation Done\")\n tkfocus(nstation)\n okk<-function(){tkdestroy(nstation);tkfocus(start1)}\n textlabel0<-tklabel(nstation,text=\" \")\n textlabel1<-tklabel(nstation,text=\"Indices calculation completed\",font=fontHeading1)\n textlabel2<-tklabel(nstation,text=paste(\"Plots are in: \",outjpgdir,sep=\" \"),font=fontHeading1)\n okk.but<-tkbutton(nstation,text=\" OK \",command=okk,width=20)\n tkgrid(textlabel0)\n tkgrid(textlabel1)\n tkgrid(textlabel2)\n tkgrid.configure(textlabel1,sticky=\"w\")\n tkgrid.configure(textlabel2,sticky=\"w\")\n tkgrid.configure(textlabel0,sticky=\"e\")\n# cancell.but<-tkbutton(nstation,text=\" NO \",command=cancell,width=15)\n# tkgrid(textlabel2,okk.but,cancell.but,textlabel0)\n tkgrid(okk.but,textlabel0)\n# tkgrid.configure(cancell.but,sticky=\"w\")\n tkgrid(textlabel0)\n }\n done2<-function(){\n tkdestroy(main)\n tkfocus(start1)\n# return()\n }\n\n ok.but <-tkbutton(main,text=\" OK \",command=OnOK,width=30)\n cancel.but<-tkbutton(main,text=\"CANCELAR\",command=done2,width=30)\n tkgrid(ok.but)\n tkgrid(cancel.but)\n tkgrid(tklabel(main,text=\"It may take more than 5 minutes to compute all the indices\",font=fontHeading2))\n tkgrid(tklabel(main,text=\"Please be patient, you will be informed once computations are done\",font=fontHeading2))\n tkgrid(tklabel(main,text=\"\",font=fontHeading))#empty line\n \n }\n\n\n\n\n# End of Part II ( Functions of Calculating climate indecies )\n\n# Part III\n# Main program\n# call getfile, read data file and store in dd.\nstart1<-tktoplevel()\n\nplotx<-\nfunction (x,y,main=\"\",xlab=\"\",ylab=\"\")\n{\n par(oma=c(3,0,0,0))\n plot(x,y,xlab=xlab,ylab=ylab,type=\"b\",col=\"gray40\")\n\n fit<-lsfit(x,y) # least squares linear fit\n out<-ls.print(fit,print.it=F)\n r2<-round(100*as.numeric(out$summary[1,2]),1)\n pval<-round(as.numeric(out$summary[1,6]),3)\n beta<-round(as.numeric(out$coef.table[[1]][2,1]),3)\n betaerr<-round(as.numeric(out$coef.table[[1]][2,2]),3)\n #abline(fit,lwd=3,col=\"blue\") \n\n # linear fit & confidence interval lines--------------\n fit2<-lm(y ~ x)\n\n newx <- seq(min(x), max(x), length.out=100)\n preds <- predict(fit2, newdata = data.frame(x=newx), \n interval = 'confidence')\n polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]),col = 'lightgray', border = NA, density = 20)\n lines(newx,preds[,2],lty = 'dashed',col=\"blue\")\n lines(newx,preds[,3],lty = 'dashed',col=\"blue\")\n abline(fit2,lwd=3,col=\"blue\")\n \n #beta_alt <- summary(fit2)$coefficients[2, 1]\n #beta_alt <- round(as.numeric(beta_alt,3))\n #beta_error_alt <- summary(fit2)$coefficients[2, 2]\n #beta_error_alt <- round(as.numeric(beta_error_alt,3))\n\n # lowess line\n xy<-cbind(x,y)\n xy<-na.omit(xy)\n lines(lowess(xy[,1],xy[,2]),lwd=3,lty=2,col=\"red\")\n\n prefiction_sequence <- data.frame(x = c(1970,1980,1990,2000,2010,2020,2030,2040,2050,2060,2070))\n prediction <- predict(fit2, prefiction_sequence, se.fit=TRUE, interval=\"confidence\",level=0.95) \n #prediction <- round(as.numeric(prediction),1)\n prediction_text <- paste(\n \" 1970:\",round(as.numeric(prediction$fit[1]),2), \n \" 1980:\",round(as.numeric(prediction$fit[2]),2),\n \" 1990:\",round(as.numeric(prediction$fit[3]),2),\n \" 2000:\",round(as.numeric(prediction$fit[4]),2),\n \" 2010:\",round(as.numeric(prediction$fit[5]),2),'\\n',\n \" 2020:\",round(as.numeric(prediction$fit[6]),2),\n \" 2030:\",round(as.numeric(prediction$fit[7]),2),\n \" 2040:\",round(as.numeric(prediction$fit[8]),2), \n \" 2050:\",round(as.numeric(prediction$fit[9]),2),\n \" 2060:\",round(as.numeric(prediction$fit[10]),2)\n )\n \n subtit=paste(\"R² = \",r2,\" Valor P = \",pval,\" Pendiente = \",beta,\" Error est. de pendiente = \",betaerr)\n #subtit=paste(\"R² = \",r2,\" Valor P = \",pval,\" Pendiente = \",beta_alt,\" Error de pendiente = \",beta_error_alt)\n title(main=main)\n title(sub=subtit,cex=0.5)\n mtext(\" Estimación:\", SOUTH<-1, line=0.4, adj=0, cex=0.8, outer=TRUE)\n mtext(prediction_text, SOUTH<-1, line=1.4, adj=0.5, cex=0.8, outer=TRUE)\n}\n\n\nts<-function(ys=x[1,1],ye=x[nrow(x),1],x=dd) \n{\n#\n# EDA function\n#\npar(mfrow=c(3,1))\nxs<-x[(x[,1]>=ys)&(x[,1]<=ye),]\nts.plot(xs[,4])\ntitle(\"Precipitación diaria\",xlab=\"dia\",ylab=\"PRECIP\")\nts.plot(xs[,5])\ntitle(\"Máximo diario de temperatura\",xlab=\"dia\",ylab=\"Tmax\")\nts.plot(xs[,6])\ntitle(\"Minimo diario de temperatura\",xlab=\"dia\",ylab=\"Tmin\")\npar(mfrow=c(1,1))\n\ncat(paste(\"Estaciones con datos de \",x[1,1],\" a \",x[nrow(x),1],\"\\n\"))\ncat(paste(\"Estadistica sumatoria para ventana de \",ys,\" a \", ye,\"\\n\"))\n}\n\nfunction (y1=x[1,1],y2=dd[nrow(x),1],m=1,v=4,x=dd) \n{\n#\n# Little function to see how many NAs there are in month m\n# in period y1 to y2 for variable v:\n# \n# Usage: nas(1960,1990,1,4)\n#\n\nxs<-x[(x[,1]>=y1)&(x[,1]<=y2)&(x[,2]==m),]\ncat(paste(\"Años \",y1,\"-\",y2,\" Mes =\",m,\" Variable =\",v,\"\\n\"))\ncat(paste(\"Total número de dias =\",length(xs[,v]),\" Total dias sin datos =\",sum(is.na(xs[,v])),\"\\n\"))\n}\n\nstartss<-function(){\ntkwm.title(start1,\"RclimDex\")\ntkgrid(tklabel(start1,text=\" RClimDex 1.0 \",font=fontHeading))\ntkgrid(tklabel(start1,text=\"\",font=fontHeading))#empty line\ntkgrid(tklabel(start1,text=\"\",font=fontHeading))#empty line\n#tkgrid(tklabel(start1,text=\"\",font=fontHeading))#empty line\nstart.but<-tkbutton(start1,text=\"Cargar datos y realizar QC\",command=getfile,width=30)\ncal.but<-tkbutton(start1,text=\"Cálculo de indicadores\",command=nastat,width=30)\ncancel.but<-tkbutton(start1,text=\"Salir\",command=done,width=30)\ntkgrid(start.but)\ntkgrid(cal.but)\ntkgrid(cancel.but)\ntkgrid(tklabel(start1,text=\"\",font=fontHeading)) }#end of startss function\n\nstartss()\n", "meta": {"hexsha": "e40b595ea7da193da8905828789618f1b20ea377", "size": 108280, "ext": "r", "lang": "R", "max_stars_repo_path": "rclimdex.r", "max_stars_repo_name": "vshalisko/rclimdex_modifications", "max_stars_repo_head_hexsha": "892a5b48ae452e1e60c7d04eabf3b451ccd2474d", "max_stars_repo_licenses": ["AFL-3.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": "rclimdex.r", "max_issues_repo_name": "vshalisko/rclimdex_modifications", "max_issues_repo_head_hexsha": "892a5b48ae452e1e60c7d04eabf3b451ccd2474d", "max_issues_repo_licenses": ["AFL-3.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": "rclimdex.r", "max_forks_repo_name": "vshalisko/rclimdex_modifications", "max_forks_repo_head_hexsha": "892a5b48ae452e1e60c7d04eabf3b451ccd2474d", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9527314994, "max_line_length": 211, "alphanum_fraction": 0.6424178057, "num_tokens": 43635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.024423091119239376, "lm_q1q2_score": 0.011544391620059685}} {"text": "###\n### file: heatmap.R\n### author: Ali Tofigh\n###\n### Functions for displaying heatmaps. Instead of using one giant heatmap\n### function that tries to do everything, the common tasks have been divided\n### into several functions. It is assumed that the user will use 'layout()' to\n### divide the graphic output into segments and will provide space for column-\n### and rownames himself. A good example of how to use these functions is\n### provided in experiment 01 in project strepi.\n###\n### The function heatmap.simple() is also provided to support quick full\n### featured figures.\n\n\n\nlibrary(colorspace)\nlibrary(grid)\nlibrary(gridBase)\n\n\ngrid.newpage.loop <- function(...) {\n plot.new()\n require(grid)\n grid.clip(...)\n} \n\n### heatmap.color.scheme()\n###\n### Computes break points and color vector for heatmaps. Can also plot\n### the HCL space for easier customization of colors.\n###\n### Arguments:\n### col.palette either a palette name or index, or a full\n### specification of an hcl palette. See the\n### 'supported.palettes' definition in the code for\n### examples.\n### low.breaks\n### high.breaks breakpoints for the low and high colors. If\n### there is a gap between these vectors,\n### 'masked.color' will be used for the gap.\n### masked.color the color to be used for the gap between the\n### low and high colors.\n### plot if TRUE, will plot the HCL color space for the\n### chosen color palette.\n### gp graphical parameters passed to grid.points and\n### grid.lines when 'plot' is TRUE.\n###\n### Returns: a list with three fields:\n### breaks vector with break points, size is one more that 'col'\n### col vector with colors, size one less than 'breaks'\n### masked.idx idx into 'col' and 'breaks' pointing to the color and\n### the left break point of the masked region (if such a\n### region exists).\nheatmap.color.scheme <- function(low.breaks=seq(-3, 0, length.out=21),\n high.breaks=seq(0, 3, length.out=21),\n masked.color=\"black\",\n col.palette=c(\"blue.red\"),\n plot=FALSE, gp=gpar())\n{\n library(colorspace)\n\n stopifnot(length(low.breaks) > 0 || length(high.breaks) > 0)\n stopifnot(length(low.breaks) == 0 || is.numeric(low.breaks) && length(low.breaks) >= 2)\n stopifnot(length(high.breaks) == 0 || is.numeric(high.breaks) && length(high.breaks) >= 2)\n stopifnot(length(low.breaks) == 0 || all(diff(low.breaks) > 0))\n stopifnot(length(high.breaks) == 0 || all(diff(high.breaks) > 0))\n stopifnot(length(low.breaks) == 0 || length(high.breaks) == 0 || tail(low.breaks, 1) <= head(high.breaks, 1))\n\n supported.palettes <- list(\"blue.red\"=list(h=c(260, 0), c=c(0, 80), l=c(85, 30), power=1.5),\n \"blue.red.2\"=list(h=c(260, 0), c=c(0, 100), l=c(90, 50), power=1.5),\n \"blue.orange.1\"=list(h=c(240, 60), c=c(0, 77), l=c(98, 72), power=1.5))\n\n if (is.character(col.palette) || is.numeric(col.palette))\n pal <- supported.palettes[[col.palette]]\n else\n pal <- col.palette\n\n if (!c(\"h\", \"c\", \"l\", \"power\") %in% names(pal) ||\n !is.numeric(pal$h) || !is.numeric(pal$c) || !is.numeric(pal$l) || !is.numeric(pal$power) ||\n length(pal$h) != 2 || length(pal$c) != 2 || length(pal$l) != 2 || length(pal$power) != 1)\n stop(\"invalid 'col.palette' specification\")\n\n color.points <- function(b) {\n if (length(b) == 2)\n {\n ret <- 1\n }\n else if (length(b) == 3)\n {\n ret <- c(0, 1)\n }\n else\n {\n mid.b <- b[-c(1, length(b))]\n ret <- c(b[1], mid.b[-length(mid.b)] + diff(mid.b)/2, b[length(b)])\n ret <- ret - ret[1]\n ret <- ret / tail(ret, 1)\n }\n ret\n }\n\n if (length(low.breaks) > 0)\n {\n low.color.points <- color.points(low.breaks)^pal$power\n low.L <- pal$l[1] + diff(pal$l) * low.color.points\n low.C <- pal$c[1] + diff(pal$c) * low.color.points\n low.colors <- rev(hex(polarLUV(L=low.L, C=low.C, H=pal$h[1]), fixup=TRUE))\n }\n\n if (length(high.breaks) > 0)\n {\n high.color.points <- color.points(high.breaks)^pal$power\n high.L <- pal$l[1] + diff(pal$l) * high.color.points\n high.C <- pal$c[1] + diff(pal$c) * high.color.points\n high.colors <- hex(polarLUV(L=high.L, C=high.C, H=pal$h[2]), fixup=TRUE)\n }\n\n\n scheme <- list()\n if (length(low.breaks) == 0)\n {\n scheme$breaks <- high.breaks\n scheme$col <- c(high.colors)\n }\n else if (length(high.breaks) == 0)\n {\n scheme$breaks <- low.breaks\n scheme$col <- c(low.colors)\n\n }\n else if (tail(low.breaks, 1) == head(high.breaks, 1))\n {\n scheme$breaks <- c(low.breaks, high.breaks[-1])\n scheme$col <- c(low.colors, high.colors)\n }\n else\n {\n scheme$breaks <- c(low.breaks, high.breaks)\n scheme$col <- c(low.colors, masked.color, high.colors)\n scheme$masked.idx <- length(low.colors) + 1\n }\n\n if (isTRUE(plot))\n {\n plot.h <- function(h, pixels)\n {\n c <- seq(0,100,length=pixels)[-1];\n l <- seq(0,100,length=pixels)[-1];\n xy <- expand.grid(c=c, l=l);\n rect.col <- hcl(h, xy$c, xy$l, fixup=FALSE)\n grid.rect(xy$c/100, xy$l/100, width=1/length(c), height=1/length(l),\n gp=gpar(fill=rect.col, col=rect.col, linejoin=\"mitre\", lwd=0.01), just=c(\"right\", \"top\"),\n default.unit=\"native\")\n grid.text(h, 0.8, 0.1, default.units=\"native\")\n }\n\n pushViewport(viewport(layout=grid.layout(3, 2, heights=c(4, 1, 4))))\n\n pushViewport(viewport(layout.pos.row=1, layout.pos.col=1, xscale=c(1, 0), clip=\"off\"))\n plot.h(pal$h[1], 100)\n grid.lines(pal$c/100, pal$l/100, default.unit=\"native\", gp=gp)\n grid.points(low.C / 100, low.L / 100, default.units=\"native\", gp=gp)\n popViewport()\n\n pushViewport(viewport(layout.pos.row=1, layout.pos.col=2))\n plot.h(pal$h[2], 100)\n grid.lines(pal$c/100, pal$l/100, default.unit=\"native\", gp=gp)\n grid.points(high.C / 100, high.L / 100, default.units=\"native\", gp=gp)\n popViewport()\n\n pushViewport(viewport(layout.pos.row=2, layout.pos.col=1:2, xscale=range(scheme$breaks)))\n grid.rect()\n grid.rect(scheme$breaks[-1], 0, width=diff(scheme$breaks), height=1,\n gp=gpar(fill=scheme$col, col=scheme$col, linejoin=\"mitre\", lwd=0.01),\n just=c(\"right\", \"bottom\"),\n default.units=\"native\")\n popViewport()\n\n pushViewport(viewport(layout.pos.row=3, layout.pos.col=1:2, xscale=range(scheme$breaks)))\n pushViewport(viewport(layout=grid.layout(4, 9)))\n\n rc <- expand.grid(c=1:9, r=1:4)\n h <- seq(0, 359, 10)\n for (i in 1:length(h))\n {\n pushViewport(viewport(layout.pos.row=rc[i, \"r\"], layout.pos.col=rc[i, \"c\"]))\n plot.h(h[i], 80)\n popViewport()\n }\n\n popViewport()\n popViewport()\n\n popViewport()\n }\n\n return(scheme)\n}\n\n\n### heatmap.is.valid.color.scheme()\n###\n### internal function for checking color schemes.\nheatmap.is.valid.color.scheme <- function(color.scheme)\n{\n is.list(color.scheme) &&\n (c(\"breaks\", \"col\") %in% names(color.scheme)) &&\n is.numeric(color.scheme$breaks) &&\n (length(color.scheme$breaks) == length(color.scheme$col) + 1) &&\n (is.null(color.scheme$masked.idx) || color.scheme$masked.idx %in% 1:length(color.scheme$col))\n}\n\n\n### heatmap.map()\n###\n### plots a heatmap of 'x' in the current viewport. Returns the color\n### scheme used.\n###\n### Arguments:\n### x a numeric matrix with the heatmap values\n### color.scheme see the function heatmap.color.scheme() for details\n### na.color color used for NA values in 'x'\n###\n### Returns:\n###\n### The color scheme invisibly.\nheatmap.map <- function(x, color.scheme=heatmap.color.scheme(), na.color = \"grey\")\n{\n library(\"colorspace\")\n\n if (length(dim(x)) != 2 || !is.numeric(x))\n stop(\"'x' must be a numeric matrix\")\n\n bc <- color.scheme\n stopifnot(heatmap.is.valid.color.scheme(bc))\n\n ## make sure no values are outside the range ['min.val', 'max.val']\n min.val <- head(bc$breaks, 1)\n max.val <- tail(bc$breaks, 1)\n x[x < min.val] <- min.val\n x[x > max.val] <- max.val\n\n ## convert numbers to colors according to our breaks\n x.colors <- findInterval(x, bc$breaks, all.inside=TRUE)\n\n ## add na.color at the end of the color scheme\n bc$col <- c(bc$col, na.color)\n x.colors[is.na(x.colors)] <- length(bc$col)\n\n ## this viewport is set up so that origo is on the top left and the\n ## ranges of the \"native\" units are number of columns and rows of x.\n pushViewport(viewport(xscale=c(0, ncol(x)), yscale=c(nrow(x),0)))\n\n ## now draw the heatmap\n grid.rect(col(x), row(x), gp=gpar(col=bc$col[x.colors], fill=bc$col[x.colors], linejoin=\"mitre\", lwd=0.01),\n width=1, height=1, just=c(\"right\", \"top\"), default.units=\"native\")\n\n popViewport()\n\n return(invisible(color.scheme))\n}\n\n\n### heatmap.key()\n###\n### plots a heatmap key in the current viewport.\n###\n### Arguments:\n### x numeric matrix that was used to plot a heatmap\n### color.scheme the color scheme used to plot the heatmap\n### key.min should be less than the least break point of the\n### color scheme\n### key.max should be greater than the greates break point of the\n### color scheme\n### key.line.color the color used to draw the histogram\n###\n### Returns:\n### invisible(NULL)\nheatmap.key <- function(x, color.scheme=heatmap.color.scheme(),\n key.min = head(color.scheme$breaks, 1) - 1,\n key.max = tail(color.scheme$breaks, 1) + 1,\n key.line.color = \"cyan\")\n{\n if (!is.numeric(x))\n stop(\"'x' must be a numeric matrix\")\n stopifnot(heatmap.is.valid.color.scheme(color.scheme))\n\n bc <- color.scheme\n\n min.val <- head(bc$breaks, 1)\n max.val <- tail(bc$breaks, 1)\n key.min <- min(key.min, min.val)\n key.max <- max(key.max, max.val)\n\n ## add breakpoints and colors for the masked region, from min.val to\n ## key.min, and from max.val to key.max. This is so that we can get\n ## a good histogram showing in the key.\n break.width <- min(diff(bc$breaks))\n\n if (!is.null(bc$masked.idx)) # extend masked region\n {\n masked.color <- bc$col[bc$masked.idx]\n a <- bc$breaks[bc$masked.idx]\n b <- bc$breaks[bc$masked.idx + 1]\n n <- round((b - a) / break.width)\n n <- max(1, n)\n new.breaks <- seq(a, b, length.out = n + 1)[-c(1, n+1)]\n bc$breaks <- c(bc$breaks[1:bc$masked.idx],\n new.breaks,\n bc$breaks[(bc$masked.idx + 1):length(bc$breaks)])\n bc$col <- c(bc$col[1:bc$masked.idx],\n rep(masked.color, n - 1),\n bc$col[(bc$masked.idx + 1):length(bc$col)])\n }\n if (key.min < min.val) # extend region between min.val and key.min\n {\n n <- round((min.val - key.min) / break.width)\n n <- max(1, n)\n new.breaks <- seq(key.min, min.val, length.out = n + 1)[-(n+1)]\n bc$breaks <- c(new.breaks, bc$breaks)\n bc$col <- c(rep(bc$col[1], n), bc$col)\n }\n if (key.max > max.val) # extend region between max.val and key.max\n {\n n <- round((key.max - max.val) / break.width)\n n <- max(1, n)\n new.breaks <- seq(max.val, key.max, length.out = n + 1)[-1]\n bc$breaks <- c(bc$breaks, new.breaks)\n bc$col <- c(bc$col, rep(bc$col[length(bc$col)], n))\n }\n\n ## draw the key\n\n ## we will leave 30% of the area below the key histogram for drawing\n ## an axis, which needs about 2 lines of text.\n axis.text <- do.call(paste, as.list(grid.pretty(c(key.min, key.max))))\n height <- convertHeight(unit(2, \"lines\"), \"points\", valueOnly=T)/convertHeight(unit(1, \"npc\"), \"points\", valueOnly=T)\n axis.cex <- min((as.double(convertHeight(unit(height, \"native\"), \"lines\")) / 2),\n (1/as.double(convertWidth(unit(1, \"strwidth\", axis.text), \"npc\"))))*0.8\n height <- height * axis.cex\n\n pushViewport(viewport(0.5, 0.9, width=0.8, height=1-height, xscale=range(bc$breaks), yscale=c(1, 0),\n just=c(\"centre\", \"top\")))\n grid.rect(bc$breaks[-1], 0,\n width=diff(bc$breaks), height=1, gp=gpar(col=NA, fill=bc$col, lty=0),\n default.units=\"native\", just=c(\"right\", \"bottom\"))\n\n\n if (!all(is.na(x)))\n {\n h <- hist(x, plot = FALSE,\n breaks = c(min(x, na.rm=TRUE), bc$breaks, max(x, na.rm = TRUE)))\n pushViewport(viewport(xscale=c(key.min, key.max), yscale=c(0, max(h$counts)*1.05)))\n breaks <- h$breaks[-c(1, length(h$breaks))]\n counts <- h$counts[-c(1, length(h$counts))]\n grid.lines(rep(breaks, each=2), c(0, rep(counts, each=2), 0),\n gp=gpar(col=key.line.color), default.units=\"native\")\n grid.xaxis(gp=gpar(cex=axis.cex, lex=axis.cex))\n popViewport()\n }\n else\n {\n pushViewport(viewport(xscale=c(key.min, key.max)))\n grid.xaxis(gp=gpar(cex=axis.cex, lex=axis.cex))\n popViewport()\n }\n popViewport()\n\n return(invisible(NULL))\n}\n\n\n### heatmap.clinical()\n###\n### plots clinical variables as boxes in the current frame. Assumes 'x'\n### is a matrix with color information in each cell. Colors are usually\n### given using character strings such as \"white\", \"red\", etc. See\n### 'colors()' for a list of color names. NAs are plotted with color as\n### given by 'na.color'.\n###\n### Arguments:\n### x matrix with colors in each cell, or NAs. Will also\n### accept data frames (with rows representing patients)\n### na.color color to be used for missing values, i.e., NAs\n###\n### Returns:\n### NULL\nheatmap.clinical <- function(x, na.color = \"grey\")\n{\n if (length(dim(x)) != 2)\n stop(\"'x' must be a color matrix\")\n\n if (is.data.frame(x))\n x <- t(as.matrix(x))\n\n x[is.na(x)] <- na.color\n\n pushViewport(viewport(xscale=c(0, ncol(x)), yscale=c(nrow(x), 0)))\n\n grid.rect(col(x), row(x), width=1, height=1, gp=gpar(col=x, fill=x, linejoin=\"mitre\", lwd=0.01),\n just=c(\"right\", \"top\"), default.units=\"native\")\n grid.rect(ncol(x), 1:nrow(x), width=ncol(x), height=1, gp=gpar(col=\"black\", fill=NA),\n just=c(\"right\", \"top\"), default.units=\"native\")\n\n popViewport()\n\n return(invisible(NULL))\n}\n\n\n### heatmap.ddr()\n###\n### A very flexible function for clustering. It allows multiple ways of\n### specifying how the dendrogram is to be computed and it knows about\n### the cor() and hclust() functions.\n###\n### Arguments:\n###\n### exprs a matrix-like object whose columns are to be\n### clustered. May be omitted if a dendrogram can be\n### obtained using only the other arguments.\n### dist.elem specifies how to compute the distance matrix. May be\n### omitted if a dendrogram can be obtained from\n### 'clust.elem' alone. Possible specifications are: An\n### object that can be coerced to a distance matrix\n### (using as.dist()), a function that takes 'exprs' and\n### produces a distance matrix, or a character string\n### specifying how a distance matrix is to be computed\n### from 'exprs'. The acceptable character strings are\n### \"cor\" and any method specification that can be\n### passed on to the dist() function. If 'dist.elem' is\n### \"cor\", then 1-correlation (between the columns of\n### 'exprs') is used as distance.\n### clust.elem specifies how to compute the dendrogram. Possible\n### specifications are: An object that can be coerced to\n### \"dendrogram\" (using as.dendrogram()), a function\n### that takes a distance matrix and produces an object\n### that can be coerced to a dendrogram, a character\n### string specifying how to compute, from a distance\n### matrix, an object that can be coerced to a\n### dendrogram, or a character string specifying how to\n### compute a dendrogram from a distance matrix.\n### p passed to the dist() function and used only when\n### 'dist.elem' is \"minkowski\" (see help on the dist()\n### function for details).\nheatmap.ddr <- function(exprs=NULL, dist.elem=\"cor\", clust.elem=\"ward\", p=2)\n{\n if (class(clust.elem) != \"dendrogram\")\n {\n ret <- try(as.dendrogram(clust.elem), silent=TRUE)\n if (class(ret) == \"try-error\")\n {\n if (mode(dist.elem) == \"numeric\" && class(dist.elem) == \"matrix\")\n {\n dist.mat <- as.dist(dist.elem)\n }\n else if (is.null(exprs))\n {\n stop(\"heatmap.ddr: 'exprs' missing\")\n }\n else if (mode(dist.elem) == \"function\")\n {\n dist.mat <- as.dist(dist.elem(exprs))\n }\n else if (mode(dist.elem) == \"character\" && length(dist.elem) == 1 && dist.elem == \"cor\")\n {\n cors <- cor(exprs, use=\"pairwise.complete.obs\")\n cors[is.na(cors)] <- 0\n dist.mat <- as.dist(1 - cors)\n }\n else if (mode(dist.elem) == \"character\" && length(dist.elem) == 1)\n {\n dist.mat <- dist(t(exprs), method=dist.elem, p=p)\n }\n else\n {\n stop(\"heatmap.ddr: bad 'dist.elem'\")\n }\n\n if (mode(clust.elem) == \"function\")\n {\n ret <- as.dendrogram(clust.elem(dist.mat))\n }\n else if (mode(clust.elem) == \"character\" && length(clust.elem) == 1)\n {\n ret <- as.dendrogram(hclust(dist.mat, method=clust.elem))\n }\n else\n {\n stop(\"heatmap.ddr: bad 'dist.elem'\")\n }\n }\n }\n else\n {\n ret <- clust.elem\n }\n\n return(ret)\n}\n\n\n### heatmap.labels.cex()\n###\n### computes a cex value that can be used when plotting text in the\n### current viewport. The assumption is that 'labels' is a character\n### vector containing text strings that are meant to be drawn in the\n### current viewport (either horizontally or vertically). This function\n### will compute and return a cex value that can be passed to\n### grid.text() such that the strings in 'labels' will fit in the\n### current viewport when drawn on separate lines.\n###\n### Arguments:\n###\n### labels\n###\n### character vector\n###\n### type\n###\n### either \"row.labels\" or \"col.labels\" indicating whether the\n### labels are intended to be drawn horizontally or vertically.\n###\n### Returns:\n###\n### a cex value to be used when drawing the strings in 'labels' in\n### the current viewport\nheatmap.labels.cex <- function(labels, type=c(\"row.labels\", \"col.labels\"))\n{\n type <- match.arg(type)\n\n rw <- convertWidth(max(do.call(unit.c, lapply(labels, function(label) {unit(1, \"strwidth\", label)}))), \"npc\")\n rw <- convertWidth((rw + unit(2, \"strwidth\", \"X\")), \"npc\")\n rh <- convertHeight(unit(1, \"strheight\", \"X\"), \"npc\") * 1.8 * length(labels)\n if (type == \"row.labels\")\n {\n cex <- min(1/as.double(convertWidth(rh, \"npc\")), 1/as.double(rw))\n }\n else\n {\n rw <- convertUnit(rw, \"npc\", \"x\", \"dimension\", \"y\", \"dimension\")\n rh <- convertUnit(rh, \"npc\", \"y\", \"dimension\", \"x\", \"dimension\")\n cex <- min(1/as.double(convertWidth(rh, \"npc\")), 1/as.double(rw))\n }\n return(cex)\n}\n\n\n### heatmap.labels()\n###\n### plots each string in 'labels' on a separate line in the current\n### viewport. The size of the text and spacing between strings are\n### adjusted so that the text will fill the viewport as much as\n### possible.\n###\n### Arguments:\n###\n### labels\n###\n### character vector with strings to be drawn in the current\n### viewport\n###\n### type\n###\n### either \"row.labels\" or \"col.lables\", determining if the text\n### is to be drawn horizontally or vertically.\n###\n### just\n###\n### the justification of the text.\n###\n### rot\n###\n### rotation of the text in angles.\n###\n### Returns:\n###\n### invisible(NULL)\nheatmap.labels <- function(labels, type=c(\"row.labels\", \"col.labels\"), just=c(\"left\", \"right\", \"centre\"), rot=0)\n{\n type <- match.arg(type)\n just <- match.arg(just)\n\n if (type == \"row.labels\")\n {\n pushViewport(viewport(xscale=c(0, 1), yscale=c(1, 0)))\n if (just == \"left\")\n x <- unit(1, \"strwidth\", \"X\")\n else if (just == \"right\")\n x <- unit(1, \"npc\") - unit(1, \"strwidth\", \"X\")\n else\n x <- 0.5\n y <- ((1:length(labels)) - 0.5) /length(labels)\n grid.text(labels, x, y, default.units=\"native\", just=just, rot = rot,\n gp=gpar(cex=heatmap.labels.cex(labels, type=type)))\n popViewport()\n }\n else\n {\n pushViewport(viewport(xscale=c(0, 1), yscale=c(0, 1)))\n x <- ((1:length(labels)) - 0.5) /length(labels)\n if (just == \"left\")\n y <- unit(1, \"strwidth\", \"X\")\n else if (just == \"right\")\n y <- unit(1, \"npc\") - unit(1, \"strwidth\", \"X\")\n else\n y <- 0.5\n grid.text(labels, x, y, default.units=\"native\", just=just, rot=90 + rot,\n gp=gpar(cex=heatmap.labels.cex(labels, type=type)))\n popViewport()\n }\n invisible(NULL)\n}\n\n\n### heatmap.simple()\n###\n### Provides an easy way to produce full heatmap figures with the most\n### common features such as dendrograms from clustering, row and column\n### labels and a matrix of clinical variables. Many of the arguments\n### will take on sensible defaults if omitted (as described below).\n###\n### this function makes extensive use of the grid package and mixes it\n### with standard R graphics plots using gridBase. The figure is divided\n### into regions (with grid.layout which is similar to base R's layout\n### function) as directed by the layout.mat character matrix. The\n### strings in layout.mat will determine where each component of the\n### figure will be drawn. Other arguments are as described for the\n### heatmap functions above.\n###\n### Arguments:\n### x matrix of values for the main heatmap.\n### layout.mat a character matrix describing the layout of\n### the figure and its parts. The figure will be\n### divided into rows and columns corresponding\n### to the rows and columns of layout.mat. Each\n### entry should be a string describing what\n### should be plotted in that region. The list\n### of recognized entries are:\n###\n### heatmap\n### key\n### title\n### row.labels.ljust\n### row.labels.rjust\n### col.labels.ljust\n### col.labels.rjust\n### row.ddr.left\n### row.ddr.right\n### col.ddr.up\n### col.ddr.down\n### clinical\n### clinical.labels.ljust\n### clinical.labels.rjust\n###\n### If layout.mat is omitted, the function will\n### try to provide a sensible one depending on\n### what other options have been supplied.\n### widths\n### heights relative widths and heights for the\n### layout. If 'layout.mat' is omitted, care should be taken\n### when supplying these since they have to match\n### the size of the default layout.mat, which can vary\n### depending on other arguments.\n### color.scheme a list defining the color scheme to be used for the\n### heatmap. See the heatmap.color.scheme() function\n### for details on the requirements for this variable\n### scale for now only supports \"row\", \"none\", or a\n### user-supplied function that will be applied\n### to each row.\n### row.labels If omitted, will default to rownames of x.\n### col.labels If omitted, will default to colnames of x.\n### row.clust\n### row.clust.dist.fun\n### row.clust.fun\n### col.clust\n### col.clust.dist.fun\n### col.clust.fun If row.clust is TRUE, then the rows will be\n### clustered by the heatmap.ddr() function, to\n### which row.clust.dist.fun and row.clust.fun\n### are passed. See that function for details on\n### these arguments. An analogous description\n### applies to col.clust.*. Note that the expression\n### matrix will still be reordered if you pass\n### a dendrogram of your own (using order.dendrogram()).\n### So make sure the dendrogram was derived from\n### 'exprs' and that 'exprs' has not been reordered.\n### clinical a matrix of colors or a data frame to be\n### passed to heatmap.clinical.\n### clinical.labels If omitted, will default to rownames of\n### 'clinical'.\n### title text string to be printed as a title\nheatmap.simple <- function(exprs,\n layout.mat=NULL,\n widths=NULL,\n heights=NULL,\n color.scheme=heatmap.color.scheme(),\n key.min=head(color.scheme$breaks, 1) - 1,\n key.max=tail(color.scheme$breaks, 1) + 1,\n na.color=\"grey\",\n scale=\"row\",\n key.line.color=\"cyan\",\n row.labels=NULL,\n col.labels=NULL,\n row.clust=TRUE,\n row.clust.dist.fun=\"cor\",\n row.clust.fun=\"ward\",\n col.clust=TRUE,\n col.clust.dist.fun=\"cor\",\n col.clust.fun=\"ward\",\n clinical=NULL,\n clinical.labels=NULL,\n clinical.na.color=na.color,\n title=NULL)\n{\n library(grid)\n library(gridBase)\n\n ## save all standard R graphical parameters\n old.par <- par(no.readonly=TRUE)\n\n ## if clinical is a vector or data.frame, then convert it to a matrix\n if (!is.null(clinical))\n {\n if (is.vector(clinical))\n clinical <- matrix(clinical, nrow=1)\n else if (is.data.frame(clinical))\n clinical <- t(as.matrix(clinical))\n }\n\n ## get default values for arguments\n if (is.null(row.labels))\n {\n row.labels <- rownames(exprs)\n if (is.null(row.labels))\n row.labels <- rep(\"\", nrow(exprs))\n }\n if (is.null(col.labels))\n {\n col.labels <- colnames(exprs)\n if (is.null(col.labels))\n col.labels <- rep(\"\", ncol(exprs))\n }\n if (is.null(clinical.labels) && !is.null(clinical))\n clinical.labels <- rownames(clinical)\n\n ## if layout.mat is omitted, try to come up with a good default layout\n if (is.null(layout.mat))\n {\n layout.mat <- matrix(c(\"key\", \"col.ddr.up\", \"\",\n \"row.ddr.left\", \"heatmap\", \"row.labels.ljust\",\n \"\", \"col.labels.rjust\", \"\"), ncol=3, byrow=TRUE)\n if (!is.null(clinical))\n {\n layout.mat <- rbind(layout.mat, c(\"clinical.labels.rjust\", \"clinical\", \"\"))\n layout.mat <- rbind(layout.mat, c(\"\", \"\", \"\"))\n }\n if (!is.null(title))\n {\n layout.mat <- rbind(c(\"\", \"title\", \"\"), layout.mat)\n }\n if (is.null(widths))\n {\n widths <- c(0.3, 1, 0.3)\n }\n if (is.null(heights))\n {\n heights <- rep(0.3, nrow(layout.mat))\n heights[which(layout.mat == \"heatmap\", arr.ind=TRUE)[1]] <- 1\n if (!is.null(clinical))\n {\n heights[length(heights) - 1] <- 0.03*nrow(clinical)\n heights[length(heights)] <- 0.03\n }\n if (!is.null(title))\n {\n heights[1] <- 0.15\n }\n }\n if (!isTRUE(row.clust))\n {\n layout.mat[grep(\"row.ddr\", layout.mat)] <- \"\"\n }\n if (!isTRUE(col.clust))\n {\n layout.mat[grep(\"col.ddr\", layout.mat)] <- \"\"\n }\n\n stopifnot(length(widths) == ncol(layout.mat))\n stopifnot(length(heights) == nrow(layout.mat))\n }\n\n ## make sure layout is character matrix\n mode(layout.mat) <- \"character\"\n layout.mat <- as.matrix(layout.mat)\n\n ## scale the rows (if indicated by caller). When using correlation\n ## as distance, we definitely need to scale the rows *before*\n ## clustering since the mean of the columns don't really mean\n ## anything (expressions of different genes are not comparable in\n ## microarray experiments). Are there situations where we might want\n ## to cluster before scaling?\n if (is.function(scale))\n {\n exprs <- t(apply(exprs, 1, scale))\n }\n else\n {\n stopifnot(length(scale) == 1 && scale %in% c(\"row\", \"none\"))\n ## scale the matrix if given\n if (scale == \"row\")\n exprs <- t(scale(t(exprs)))\n }\n\n ## get dendrograms and reorder the data matrix\n row.ddr <- NULL\n if (isTRUE(row.clust))\n {\n row.ddr <- rev(heatmap.ddr(t(exprs), row.clust.dist.fun, row.clust.fun))\n exprs <- exprs[order.dendrogram(rev(row.ddr)), ]\n row.labels <- row.labels[order.dendrogram(rev(row.ddr))]\n }\n\n col.ddr <- NULL\n if (isTRUE(col.clust))\n {\n col.ddr <- heatmap.ddr(exprs, col.clust.dist.fun, col.clust.fun)\n exprs <- exprs[ , order.dendrogram(col.ddr)]\n col.labels <- col.labels[order.dendrogram(col.ddr)]\n if (!is.null(clinical))\n clinical <- clinical[, order.dendrogram(col.ddr), drop=FALSE]\n }\n\n ## create the top viewport\n the.layout <- grid.layout(nrow(layout.mat), ncol(layout.mat), widths=widths, heights=heights)\n top.vp <- viewport(layout=the.layout, name=\"heatmap.top.vp\")\n pushViewport(top.vp)\n\n ## get all unique strings in 'layout.mat'\n elements <- unique(as.vector(layout.mat))\n elements <- elements[elements != \"\" & !is.na(elements)]\n\n ## for the known strings in layout.mat, seek the named viewport and\n ## draw accordingly\n elem <- \"heatmap\"\n if (elem %in% elements)\n {\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n heatmap.map(exprs, color.scheme=color.scheme, na.color=na.color)\n upViewport()\n }\n elem <- \"key\"\n if (elem %in% elements)\n {\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n heatmap.key(exprs, color.scheme=color.scheme, key.min=key.min, key.max=key.max, key.line.color=key.line.color)\n upViewport()\n }\n elem <- \"row.labels.ljust\"\n if (elem %in% elements)\n {\n if (length(row.labels) != nrow(exprs))\n warning(\"the number of row labels is not equal to the number of rows of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n row.labels[is.na(row.labels)] <- \"\"\n heatmap.labels(row.labels, type=\"row.labels\", just=\"left\")\n upViewport()\n }\n elem <- \"row.labels.rjust\"\n if (elem %in% elements)\n {\n if (length(row.labels) != nrow(exprs))\n warning(\"the number of row labels is not equal to the number of rows of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n row.labels[is.na(row.labels)] <- \"\"\n heatmap.labels(row.labels, type=\"row.labels\", just=\"right\")\n upViewport()\n }\n elem <- \"col.labels.ljust\"\n if (elem %in% elements)\n {\n if (length(col.labels) != ncol(exprs))\n warning(\"the number of column labels is not equal to the number of columns of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n col.labels[is.na(col.labels)] <- \"\"\n heatmap.labels(col.labels, type=\"col.labels\", just=\"left\")\n upViewport()\n }\n elem <- \"col.labels.rjust\"\n if (elem %in% elements)\n {\n if (length(col.labels) != ncol(exprs))\n warning(\"the number of column labels is not equal to the number of columns of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n col.labels[is.na(col.labels)] <- \"\"\n heatmap.labels(col.labels, type=\"col.labels\", just=\"right\")\n upViewport()\n }\n elem <- \"row.ddr.left\"\n if (elem %in% elements && !is.null(row.ddr))\n {\n if (attr(row.ddr, \"members\") != nrow(exprs))\n warning(\"the number of row dendrogram leaves is not equal to the number of rows of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2]), clip=\"off\"))\n par(new=TRUE, fig=gridFIG(), mar=c(0,0,0,0))\n plot(row.ddr, horiz=TRUE, leaflab=\"none\", xaxt=\"n\", yaxt=\"n\", xaxs=\"r\", yaxs=\"i\")\n upViewport()\n }\n elem <- \"row.ddr.right\"\n if (elem %in% elements && !is.null(row.ddr))\n {\n if (attr(row.ddr, \"members\") != nrow(exprs))\n warning(\"the number of row dendrogram leaves is not equal to the number of rows of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n par(new=TRUE, fig=gridFIG(), mar=c(0,0,0,0))\n plot(row.ddr, horiz=TRUE, leaflab=\"none\", xaxt=\"n\", yaxt=\"n\", xaxs=\"r\", yaxs=\"i\",\n xlim=c(0, attr(row.ddr, \"height\")))\n upViewport()\n }\n elem <- \"col.ddr.up\"\n if (elem %in% elements && !is.null(col.ddr))\n {\n if (attr(col.ddr, \"members\") != ncol(exprs))\n warning(\"the number of column dendrogram leaves is not equal to the number of columns of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n par(new=TRUE, fig=gridFIG(), mar=c(0,0,0,0))\n plot(col.ddr, horiz=FALSE, leaflab=\"none\", xaxt=\"n\", yaxt=\"n\", xaxs=\"i\", yaxs=\"r\")\n upViewport()\n }\n elem <- \"col.ddr.down\"\n if (elem %in% elements && !is.null(col.ddr))\n {\n if (attr(col.ddr, \"members\") != ncol(exprs))\n warning(\"the number of column dendrogram leaves is not equal to the number of columns of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n par(new=TRUE, fig=gridFIG(), mar=c(0,0,0,0))\n plot(col.ddr, horiz=FALSE, leaflab=\"none\", xaxt=\"n\", yaxt=\"n\", xaxs=\"i\", yaxs=\"r\",\n ylim=c(attr(col.ddr, \"height\"), 0))\n upViewport()\n }\n elem <- \"clinical\"\n if (elem %in% elements && !is.null(clinical))\n {\n if (ncol(clinical) != ncol(exprs))\n warning(\"the size of clinical does not correspond to the number of columns of exprs\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n heatmap.clinical(clinical, clinical.na.color)\n upViewport()\n }\n elem <- \"clinical.labels.ljust\"\n if (elem %in% elements && !is.null(clinical.labels))\n {\n if (length(clinical.labels) != nrow(clinical))\n warning(\"the number of clinical labels is not equal to the number of variables in clinical\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n clinical.labels[is.na(clinical.labels)] <- \"\"\n heatmap.labels(labels=clinical.labels, type=\"row.labels\", just=\"left\")\n upViewport()\n }\n elem <- \"clinical.labels.rjust\"\n if (elem %in% elements && !is.null(clinical.labels))\n {\n if (length(clinical.labels) != nrow(clinical))\n warning(\"the number of clinical labels is not equal to the number of variables in clinical\")\n\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n clinical.labels[is.na(clinical.labels)] <- \"\"\n heatmap.labels(labels=clinical.labels, type=\"row.labels\", just=\"right\")\n upViewport()\n }\n elem <- \"title\"\n if (elem %in% elements && !is.null(title))\n {\n idx <- which(layout.mat == elem, arr.ind=TRUE)\n pushViewport(viewport(name=elem,\n layout.pos.row=unique(idx[,1]),\n layout.pos.col=unique(idx[,2])))\n\n grid.text(title, gp=gpar(cex=0.9 * heatmap.labels.cex(title)))\n upViewport()\n }\n\n ## restore all standard R graphical parameters\n par(old.par)\n upViewport()\n\n\n row.ind <- 1:nrow(exprs)\n col.ind <- 1:ncol(exprs)\n if (!is.null(row.ddr)) row.ind <- order.dendrogram(rev(row.ddr))\n if (!is.null(col.ddr)) col.ind <- order.dendrogram(col.ddr)\n\n return(invisible(list(layout.mat=layout.mat,\n widths=widths,\n heights=heights,\n color.scheme=color.scheme,\n key.min=key.min,\n key.max=key.max,\n na.color=na.color,\n scale=scale,\n key.line.color=key.line.color,\n row.labels=row.labels,\n col.labels=col.labels,\n row.clust=row.clust,\n row.clust.dist.fun=row.clust.dist.fun,\n row.clust.fun=row.clust.fun,\n col.clust=col.clust,\n col.clust.dist.fun=col.clust.dist.fun,\n col.clust.fun=col.clust.fun,\n clinical=clinical,\n clinical.labels=clinical.labels,\n clinical.na.color=clinical.na.color,\n title=title,\n row.ind=row.ind, col.ind=col.ind,\n row.ddr=row.ddr, col.ddr=col.ddr)))\n}\n\n\n## creates html making a heatmap image created by heatmap.simple clickable.\n## e.g.\n## png(\"heatmap.png\", width=800, height=1200)\n## heatmap.out <- heatmap.simple(...)\n## dev.off()\n## writeLines(heatmap.simple.html.map(heatmap.out, \"clickable\", 800, 1200, \"heatmap.png\")$html, con=\"heatmap.html\")\nheatmap.simple.html.map <- function(heatmap.out, heatmap.name, image.width, image.height, image.filename,\n clickable=c(\"heatmap\",\"col.labels\",\"row.labels\",\"key\",\n \"title\",\"clinical\", \"clinical.labels\")) {\n col.labels <- make.names(heatmap.out$col.labels, unique=T)\n row.labels <- make.names(heatmap.out$row.labels, unique=T)\n clinical.labels <- make.names(heatmap.out$clinical.labels, unique=T)\n\n names(col.labels) <- heatmap.out$col.labels\n names(row.labels) <- heatmap.out$row.labels\n names(clinical.labels) <- heatmap.out$clinical.labels\n\n clickable <- intersect(c(clickable, paste0(clickable, \".rjust\"), paste0(clickable, \".ljust\")), heatmap.out$layout.mat)\n\n href <- sapply(clickable, function(item) {\n switch(gsub(\".[rl]{1}just$\", \"\", item),\n heatmap=sapply(col.labels, function(col)\n sapply(row.labels, function(row)\n paste(heatmap.name, \"-row-\", row, \"-col-\", col, \".html\", sep=\"\"))),\n\n col.labels=matrix(sapply(col.labels, function(col)\n paste(heatmap.name, \"-col-\", col, \".html\", sep=\"\")), nrow=1),\n\n row.labels=matrix(sapply(row.labels, function(row)\n paste(heatmap.name, \"-row-\", row, \".html\", sep=\"\")), ncol=1),\n\n key=matrix(paste(heatmap.name, \"-key.html\", sep=\"\"), nrow=1),\n\n title=matrix(paste(heatmap.name, \"-title.html\", sep=\"\"), nrow=1),\n\n clinical=sapply(col.labels, function(col)\n sapply(clinical.labels, function(clinical)\n paste(heatmap.name, \"-clinical-\", clinical, \"-col-\", col, \".html\", sep=\"\"))),\n\n clinical.labels=matrix(sapply(clinical.labels, function(label)\n paste(heatmap.name, \"-clinical-\", label, \".html\", sep=\"\")), ncol=1))\n }, simplify=F)\n\n list(html=do.call(\"layout.mat.html.map\",\n c(list(layout.mat=heatmap.out$layout.mat,\n layout.widths=heatmap.out$widths,\n layout.heights=heatmap.out$heights,\n name=heatmap.name,\n image.width=image.width,\n image.height=image.height,\n image.filename=image.filename),\n href)),\n row.labels=row.labels,\n col.labels=col.labels,\n clinical.labels=clinical.labels,\n href=href)\n}\n\n## creates an html image map according to the items in the layout.mat\n## \"...\" argument are matrices whose names match items (regions) in layout.mat\n## each corresponding region is divided into equal-sized cells corresponding\n## to the dimensions of the matrix\n## the matrix contains the link targets\n## returns image map code\nlayout.mat.html.map <- function(layout.mat, layout.widths, layout.heights,\n name,\n image.width, image.height,\n image.filename, ...) {\n stopifnot(nrow(layout.mat) == length(layout.heights))\n stopifnot(ncol(layout.mat) == length(layout.widths))\n stopifnot(all(names(list(...)) %in% layout.mat))\n\n bounding.box <- function(name) {\n mat.col <- 1:ncol(layout.mat)\n mat.row <- 1:nrow(layout.mat)\n i <- which(name == layout.mat)\n if (length(i) == 0) return(NULL)\n if (length(i) > 1) {\n warning(paste(\"layout.mat.html:bounding.box: '\", name,\n \"' matches multiple items in layout.mat, \",\n \"making only the first one clickable.\", sep=\"\"))\n i <- i[1]\n }\n col.ind <- ceiling(i/nrow(layout.mat))\n row.ind <- i - (col.ind-1)*nrow(layout.mat)\n list(x1=sum(layout.widths[which(mat.col < col.ind)])/sum(layout.widths) * image.width,\n x2=sum(layout.widths[which(mat.col <= col.ind)])/sum(layout.widths) * image.width,\n y1=sum(layout.heights[which(mat.row < row.ind)])/sum(layout.heights) * image.height,\n y2=sum(layout.heights[which(mat.row <= row.ind)])/sum(layout.heights) * image.height)\n }\n html.rect <- function(row,col,nrow,ncol,bb,link) {\n cell.width <- (bb$x2 - bb$x1)/ncol\n cell.height <- (bb$y2 - bb$y1)/nrow\n x1 <- cell.width*(col-1) + bb$x1\n x2 <- x1 + cell.width\n y1 <- cell.height*(row-1) + bb$y1\n y2 <- y1 + cell.height\n coords <- paste(floor(x1), ceiling(y1), floor(x2), ceiling(y2), sep=\",\")\n paste(\"\", sep=\"\")\n }\n\n out <- paste(\"\",sep=\"\")\n out <- c(out,paste(\"\",sep=''))\n\n href <- list(...)\n for (region.name in names(href)) {\n cat(\"layout.mat.html.map\", region.name, \"\\n\")\n region.bb <- bounding.box(region.name)\n if (!is.null(region.bb)) {\n region.nrow <- nrow(href[[region.name]])\n region.ncol <- ncol(href[[region.name]])\n out <- c(out, unlist(lapply(1:region.nrow, function(i)\n lapply(1:region.ncol, function(j)\n html.rect(i,j,region.nrow,region.ncol,region.bb,\n href[[region.name]][i,j])))))\n }\n }\n\n c(out,\"\")\n}\n\n\n## add 1-3 marks to each cell of a simple heatmap\n## e.g.\n## heatmap.out <- heatmap.simple(exprs, ...)\n## marks <- matrix(0, ncol=ncol(exprs), nrow=nrow(exprs))\n## marks[pvals < 0.01] <- 1\n## marks[pvals < 0.001] <- 2\n## heatmap.mark(heatmap.out, marks)\nheatmap.mark <- function(heatmap.out, marks, mark=\"star\") {\n stopifnot(ncol(marks) == length(heatmap.out$col.ind))\n stopifnot(nrow(marks) == length(heatmap.out$row.ind))\n stopifnot(all(marks %in% 0:3))\n\n plot.marks <- function(...) {\n if (mark == \"star\")\n plot.stars(...)\n else\n plot.box(...)\n }\n \n plot.stars <- function(x, y, pos) {\n if (length(x) == 0)\n return()\n\n id <- rep(1:length(x), 3)\n x <- x - (pos - 1)/8\n grid.polygon(c(x, x, x-(1/8)), c(y-1, y-1+(1/4), y-1),\n gp=gpar(fill=\"black\", lty=0), id = id, default.units = \"native\")\n }\n\n plot.box <- function(x,y,pos) {\n if (length(x) == 0) return()\n\n id <- rep(1:length(x), 4)\n grid.polygon(c(x,x,x-1,x-1), c(y-1,y,y,y-1),\n gp=gpar(lty=1, col=\"black\"), id=id, \n default.units=\"native\")\n }\n\n marks <- marks[heatmap.out$row.ind,]\n marks <- marks[,heatmap.out$col.ind]\n\n n <- downViewport(\"heatmap\")\n pushViewport(viewport(xscale=c(0, ncol(marks)), yscale=c(nrow(marks), 0)))\n for (i in setdiff(unique(marks), 0)) {\n idx <- which(marks>=i, arr.ind=TRUE)\n plot.marks(idx[, \"col\"], idx[, \"row\"], i)\n }\n popViewport()\n upViewport(n)\n}\n\n\n## draw a line under the row given by row.label\n## e.g.\n## heatmap.out <- heatmap.simple(exprs, ...)\n## heatmap.underline.row(heatmap.out, row.label=\"NR3C1\")\nheatmap.underline.row <- function(heatmap.out, row.label, below=TRUE, gp=gpar(col=\"black\", lty=1)) {\n y <- 1-(which(heatmap.out$row.labels == row.label) - sign(!below))/length(heatmap.out$row.labels)\n for (element in c(\"heatmap\", \"row.labels.rjust\", \"row.labels.ljust\")) {\n if (element %in% heatmap.out$layout.mat) {\n depth <- downViewport(element)\n grid.polyline(c(0,1), c(y,y), gp=gp)\n upViewport(depth)\n }\n }\n}\n\n## draw a line next to the column given by col.label\n## e.g.\n## heatmap.out <- heatmap.simple(exprs, ...)\n## heatmap.underline.column(heatmap.out, col.label=\"curtis.323\")\nheatmap.underline.column <- function(heatmap.out, col.label, left=TRUE, gp=gpar(col=\"black\", lty=1)) {\n y <- (which(heatmap.out$col.labels == col.label) - sign(left))/length(heatmap.out$col.labels)\n depth <- downViewport(\"heatmap\")\n grid.polyline(c(y,y),c(0,1), gp=gp)\n upViewport(depth)\n}\n", "meta": {"hexsha": "af2dc951479e6578fa129316ed0e3393d83a370a", "size": 49236, "ext": "r", "lang": "R", "max_stars_repo_path": "paper/heatmap-function.r", "max_stars_repo_name": "MRCIEU/ewascatalog", "max_stars_repo_head_hexsha": "a37dfeb207537831b4c5e313e0edecbad8a7c1a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-05T09:39:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T09:39:48.000Z", "max_issues_repo_path": "paper/heatmap-function.r", "max_issues_repo_name": "MRCIEU/ewascatalog", "max_issues_repo_head_hexsha": "a37dfeb207537831b4c5e313e0edecbad8a7c1a2", "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": "paper/heatmap-function.r", "max_forks_repo_name": "MRCIEU/ewascatalog", "max_forks_repo_head_hexsha": "a37dfeb207537831b4c5e313e0edecbad8a7c1a2", "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.6467817896, "max_line_length": 121, "alphanum_fraction": 0.5433422699, "num_tokens": 12311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668680822513, "lm_q2_score": 0.028436033559453556, "lm_q1q2_score": 0.011475841004270463}} {"text": "#=================================================================================================#\n# harvard_forest_datasets.r\n# Datasets and parsing functions for Harvard Forest EMS flux tower (Little Prospect Hill)\n# Note: site class is ems (EMS tower)\n# Adam Erickson, PhD, Washington State University\n# Contact: adam.michael.erickson@gmail.com\n# March 14, 2019\n# License: Apache 2.0\n#\n# Copyright 2019 Washington State University\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\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#-------------------------------------------------------------------------------------------------#\n# Datasets specific to EMS tower:\n#-------------------------------------------------------------------------------------------------#\n# HF004: Canopy-Atmosphere Exchange of Carbon, Water and Energy at Harvard Forest EMS Tower since 1991\n# HF006: Soil Respiration, Temperature and Moisture at Harvard Forest EMS Tower since 1995\n# HF060: EMS - Automated High-Frequency Methane Data\n# HF066: Concentrations and Surface Exchange of Air Pollutants at Harvard Forest EMS Tower since 1990\n# HF067: CFCs and Radiatively Important Trace Species at Harvard Forest EMS Tower 1996-2005\n# HF068: Soil Respiration Along a Hydrological Gradient at Harvard Forest EMS Tower 2003-2006\n# HF069: Biomass Inventories at Harvard Forest EMS Tower since 1993\n# HF102: Radiation Measurements at Harvard Forest EMS Tower 1991-2007\n# HF145: Hydrocarbon Concentrations at Harvard Forest EMS Tower 1992-2001\n# HF206: Microclimate at Harvard Forest HEM, LPH and EMS Towers since 2005\n# HF209: Isotopic Composition of Net Ecosystem CO2 Exchange at Harvard Forest EMS Tower since 2011\n# HF214: Fluxes of Carbonyl Sulfide at Harvard Forest EMS Tower since 2010\n# HF288: Fluxes of Molecular Hydrogen (H2) at Harvard Forest EMS Tower 2010-2012\n# HF306: Atmospheric Oxygen and Carbon Dioxide at Harvard Forest EMS Tower since 2006\n\n#-------------------------------------------------------------------------------------------------#\n# General data:\n#-------------------------------------------------------------------------------------------------#\n# \"hf069-13-annual-summ.csv\" biomass_ag (woody), ANPP (woody), recruitment, mortality, 1993-2017\n# \"hf069-15-annual-summ.csv\" biomass_ag (woody), ANPP (woody), recruitment, mortality, 1994-2013 (old)\n# \"hf069-14-understory-summ.csv\" understory regenertion, biomass, 2004-2006\n# \"hf001-04-monthly-m.csv\" meteorology, 2001-2014\n# \"hf004-02-filled.csv\" NEE/GEE, respiration (ecosystem), 1991-2015\n# \"hf069-09-trees.csv\" species, DBH, 1993-2017\n# \"hf069-11-trees.csv\" species, DBH, 1998-2013\n# \"hf008-04-tree.csv\" species, dbh, 1998-2008\n# \"hf213-01-hf-inventory.csv\" species, dbh, coordinates, 2009-2011\n# \"hf154-03-lph-cores.csv\" ANPP, 2005\n# \"hf133-03-productivity.csv\" biomass, 1996-1997\n# \"hf137-01-tree.csv\" biomass, ANPP, species, 1996 & 2006\n# \"hf008-01-foliage.csv\" canopy chemistry, 1988-2011\n# \"hf008-02-litter.csv\" canopy chemistry, 1988-2002\n# \"hf062-01-plot.csv\" canopy chemistry, 1992\n# \"hf062-02-tree.csv\" canopy chemistry, 1992\n# \"hf069-06-canopy-chem.csv\" canopy chemistry, 1998-2008\n# \"hf008-07-decomp.csv\" litter chemistry, 1998-2008\n# \"hf069-05-litter-chem.csv\" litter chemistry, 1998-2000\n# \"hf047-01-regen.csv\" regeneration, 1990-2000\n# \"hf005-05-soil-respiration.csv\" r_soil, 1991-2002, C = control\n# \"hf006-01-soil-respiration.csv\" r_soil, 1995-2010\n# \"hf006-03-autochamber.csv\" r_soil, 2003\n# \"hf068-01-soil-resp.csv\" r_soil, 2003-2006\n# \"hf045-01-soil-resp.csv\" r_soil, 2006-2012\n# \"hf148-02-lph-soil-respiration.csv\" r_soil, 2002-2007\n# \"hf194-01-soil-resp.csv\" r_soil, 1993-2006\n# \"hf194-02-synthesis-data\" r_soil, 1991-2008\n# \"hf243-01-soil-respiration.csv\" r_soil (Finzi), 2009-2010\n# \"hf040-02-species.csv\" species abundance, 1937-1991\n# \"hf015-06-species.csv\" species codes\n# \"hf040-01-species.csv\" species codes\n# \"hf222-01-vegetation.csv\" species codes\n# \"hf039-02-tree.csv\" species DBH-height, 1937\n# \"hf005-01-trace-gas.csv\" co2, ch4, n20, 1991-2002\n# \"hf003-01-plant.csv\" tree canopy dimensions, 1991\n# \"hf069-16-allometries.txt\" allometry equations\n#-------------------------------------------------------------------------------------------------#\n\n#-------------------------------------------------------------------------------------------------#\n# Metrics and units\n#-------------------------------------------------------------------------------------------------#\n# Note: kg m-2 (10 Mg ha-1); µmol m-2 sec-1 (1e-6 * 60 * 60 * 24 * 365.24 mol m-2 year-1)\n# nee ................. kg C m-2 year-1\n# biomass_ag .......... kg m-2\n# c_ag ................ kg C m-2\n# n_ag ................ kg N m-2\n# biomass_bg .......... kg m-2\n# c_bg ................ kg C m-2\n# n_bg ................ kg N m-2\n# c_so ................ kg C m-2\n# n_so ................ kg N m-2\n# r_soil .............. kg C m-2 year-1\n# anpp ................ kg m-2 year-1\n# biomass_sp .......... kg m-2\n# abundance_sp ........ % of total n-trees\n\n#-------------------------------------------------------------------------------------------------#\n# Selected data:\n#-------------------------------------------------------------------------------------------------#\n# \"hf069-13-annual-summ.csv\" (annual woody) or...\n# \"hf069-09-trees.csv\"\n# timescale: 1993-2017\n# variables: biomass_ag and modeled c_ag, n_ag, biomass_bg, c_bg, n_bg, anpp, biomass_sp, abundance_sp\n# \"hf006-01-soil-respiration.csv\"\n# timescale: 1995-2010\n# variables: r_soil,\n# \"hf015-05-soils.csv\"\n# timescale: 1937-2013\n# variables: c_so, n_so\n# \"hf004-02-filled.csv\"\n# timescale: 1991-2015\n# variables: nee\n\n#-------------------------------------------------------------------------------------------------#\n# Time period:\n#-------------------------------------------------------------------------------------------------#\n# Intersection: 1996-2009 (14 years)\n# Union: 1937-2017 (81 years)\n# Climate: 2002-2012 (11 years)\n\n# Example: download observation data\n#url <- \"http://harvardforest.fas.harvard.edu/data/p06/hf069/hf069-09-trees.csv\"\n#dest <- file.path(base, \"observations\",\"hf_ems\",\"hf069-09-trees.csv\")\n#download_file(url=url, destination=dest)\n\n#-------------------------------------------------------------------------------------------------#\n# Base directory\n#-------------------------------------------------------------------------------------------------#\nbase_hf_data <- file.path(base, \"observations\", \"hf_ems\")\n\n#-------------------------------------------------------------------------------------------------#\n# Species look-up table\n#-------------------------------------------------------------------------------------------------#\n# http://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/data/p06/hf069/hf069-17-allometries.txt\n# http://harvardforest.fas.harvard.edu:8080/exist/apps/datasets/showData.html?id=hf003\n# Using USDA PLANTS database codes: https://plants.usda.gov\nspecies_lut <- data.frame(\n abbr = c(\"AB\",\"AC\",\"ash\",\"bb\",\n \"BB\",\"BC\",\"beech\",\"bo\",\n \"cherry\",\"chestnut\",\"EH\",\"FPC\",\n \"gb\",\"haw\",\"hbb\",\"HBB\",\n \"hem\",\"HT\",\"nwr\",\"NWR\",\n \"PB\",\"rm\",\"RM\",\"ro\",\n \"RO\",\"rp\",\"sm\",\"SM\",\n \"SPI\",\"SS\",\"wb\",\"wh\",\n \"WH\",\"wo\",\"wp\",\"WP\",\n \"ws\",\"WS\",\"yb\",\"YB\"),\n name = c(\"Fagus grandifolia\",\"Castenea dentate\",\"Fraxinus americana\",\"Betula lenta\",\n \"Betula lenta\",\"Prunus serotina\",\"Fagus grandifolia\",\"Quercus velutina\",\n \"Prunus serotina\",\"Castenea dentate\",\"Tsuga canadensis\",\"?\",\n \"Betula populifolia\",\"Crataegus\",\"Vaccinium\",\"Vaccinium\",\n \"Tsuga canadensis\",\"Crataegus\",\"Viburnum\",\"Viburnum\",\n \"Betula papyrifera\",\"Acer rubrum\",\"Acer rubrum\",\"Quercus rubra\",\n \"Quercus rubra\",\"Pinus resinosa\",\"Acer pennsylvanicum\",\"Acer pennsylvanicum\",\n \"Spiraea\",\"?\",\"Ilex verticillata\",\"Hamamelis virginiania\",\n \"Hamamelis virginiania\",\"Quercus alba\",\"Pinus strobus\",\"Pinus strobus\",\n \"Picea glauca\",\"Picea glauca\",\"Betula alleghaniensis\",\"Betula alleghaniensis\"),\n genus = c(\"Fagus\",\"Castenea\",\"Fraxinus\",\"Betula\",\"Betula\",\"Prunus\",\"Fagus\",\"Quercus\",\"Prunus\",\n \"Castenea\",\"Tsuga\",\"\",\"Betula\",\"Crataegus\",\"Vaccinium\",\"Vaccinium\",\"Tsuga\",\"Crataegus\",\n \"Viburnum\",\"Viburnum\",\"Betula\",\"Acer\",\"Acer\",\"Quercus\",\"Quercus\",\"Pinus\",\"Acer\",\n \"Acer\",\"Spiraea\",\"\",\"Ilex\",\"Hamamelis\",\"Hamamelis\",\"Quercus\",\"Pinus\",\"Pinus\",\"Picea\",\n \"Picea\",\"Betula\",\"Betula\"),\n code = c(\"FAGR\",\"CADE\",\"FRAM\",\"BELE\",\n \"BELE\",\"PRSE\",\"FAGR\",\"QUVE\",\n \"PRSE\",\"CADE\",\"TSCA\",\"\",\n \"BEPO\",\"CRSP\",\"VACO\",\"VACO\",\n \"TSCA\",\"CRSP\",\"VICA\",\"VICA\",\n \"BEPA\",\"ACRU\",\"ACRU\",\"QURU\",\n \"QURU\",\"PIRE\",\"ACPE\",\"ACPE\",\n \"\",\"\",\"ILVE\",\"HAVI\",\n \"HAVI\",\"QUAL\",\"PIST\",\"PIST\",\n \"PIGL\",\"PIGL\",\"BEAL\",\"BEAL\")\n)\n#message(paste(\"Species LUT:\", jsonlite::toJSON(species_lut, pretty=TRUE)))\n\n#-------------------------------------------------------------------------------------------------#\n# Observation file list\n#-------------------------------------------------------------------------------------------------#\nobservation_list <- list(\n climate = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf001-04-monthly-m.csv\"),\n fluxes = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf004-02-filled.csv\"),\n inventory = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf069-09-trees.csv\"),\n root_cn = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf278-04-root-carbon-nitrogen.csv\"),\n litter_cn = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf069-06-canopy-chem.csv\"),\n soils = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf015-05-soils-cn.csv\"),\n r_soil = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf006-01-soil-respiration.csv\"),\n anpp = file.path(base_hf_data, \"observations\", \"hf_ems\", \"hf069-13-annual-summ.csv\")\n)\n\n#-------------------------------------------------------------------------------------------------#\n# Functions\n#-------------------------------------------------------------------------------------------------#\n\n# Tree species aboveground biomass equations; kg; DBH cm; Chojnacky, Heath, Jenkins (2014)\nget_tree_biomass_ag <- function(code, dbh) {\n switch(code, # WSG\n ACPE = { exp(-2.0470 + 2.3852 * log(dbh)) }, # 0.44\n ACRU = { exp(-2.0470 + 2.3852 * log(dbh)) }, # 0.49\n BEAL = { exp(-1.8096 + 2.3480 * log(dbh)) }, # 0.55\n BELE = { exp(-1.8096 + 2.3480 * log(dbh)) }, # 0.60\n BEPA = { exp(-2.2271 + 2.4513 * log(dbh)) }, # 0.48\n BEPO = { exp(-2.2271 + 2.4513 * log(dbh)) }, # 0.45\n CADE = { exp(-2.0705 + 2.4410 * log(dbh)) }, # 0.40\n FAGR = { exp(-2.0705 + 2.4410 * log(dbh)) }, # 0.56\n FRAM = { exp(-1.8384 + 2.3524 * log(dbh)) }, # 0.55\n PIGL = { exp(-2.1364 + 2.3233 * log(dbh)) }, # 0.37\n PIRE = { exp(-2.6177 + 2.4638 * log(dbh)) }, # 0.41\n PIST = { exp(-2.6177 + 2.4638 * log(dbh)) }, # 0.34\n PRSE = { exp(-2.2118 + 2.4133 * log(dbh)) }, # 0.47\n QUAL = { exp(-2.0705 + 2.4410 * log(dbh)) }, # 0.60\n QURU = { exp(-2.0705 + 2.4410 * log(dbh)) }, # 0.56\n QUVE = { exp(-2.0705 + 2.4410 * log(dbh)) }, # 0.56\n TSCA = { exp(-2.3480 + 2.3876 * log(dbh)) }, # 0.38\n CRSP = { NA }, # shrub\n HAVI = { NA }, # shrub\n ILVE = { NA }, # shrub\n VACO = { NA }, # shrub\n VICA = { NA }, # shrub\n NA # else\n )\n}\n\n# Tree species belowground biomass equations; kg; DBH cm; Chojnacky, Heath, Jenkins (2014)\nget_tree_biomass_bg <- function(code, dbh) {\n biomass_ag = get_tree_biomass_ag(code, dbh)\n root_coarse_frac = exp(-1.4485 - 0.03476 * log(dbh))\n root_fine_frac = exp(-1.8629 - 0.77534 * log(dbh))\n soil_frac = 0.68\n biomass_bg = (biomass_ag * root_coarse_frac) + (biomass_ag * root_fine_frac) + (biomass_ag * soil_frac)\n return(biomass_bg)\n}\n\n# Root biomass fraction by DBH class; treated as constants per Chojnacky, Heath, Jenkins (2014)\n#plot(1:100, sapply(1:100, function(dbh) exp(-1.4485 - 0.03476 * log(dbh))), type=\"l\")\n#plot(1:100, sapply(1:100, function(dbh) exp(-1.8629 - 0.77534 * log(dbh))), type=\"l\")\n\n# Main\n\n# Parent function containing child functions\nget_observations <- function(metric=\"all\") {\n funs = list(get_nee(), get_biomass_ag(), get_c_ag(), get_n_ag(), get_biomass_bg(),\n get_c_bg(), get_n_bg(), get_c_so(), get_n_so(), get_r_soil(), get_anpp(),\n get_biomass_sp(), get_abundance_sp())\n switch(metric,\n nee = { get_nee() },\n biomass_ag = { get_biomass_ag() },\n c_ag = { get_c_ag() },\n n_ag = { get_n_ag() },\n biomass_bg = { get_biomass_bg() },\n c_bg = { get_c_bg() },\n n_bg = { get_n_bg() },\n c_so = { get_c_so() },\n n_so = { get_n_so() },\n r_soil = { get_r_soil() },\n anpp = { get_anpp() },\n biomass_sp = { get_biomass_sp() },\n abundance_sp = { get_abundance_sp() },\n biomass_total = { cbind(get_biomass_ag()[,1], get_biomass_ag()[,2] + get_biomass_bg()[,2]) },\n c_total = { cbind(get_c_ag()[,1], get_c_ag()[,2] + get_c_bg()[,2]) },\n n_total = { cbind(get_n_ag()[,1], get_n_ag()[,2] + get_n_bg()[,2]) },\n all = { setNames(lapply(funs, eval),\n c(\"nee\",\"biomass_ag\",\"c_ag\",\"n_ag\",\"biomass_bg\",\n \"c_bg\",\"n_bg\",\"c_so\",\"n_so\",\"r_soil\",\"anpp\",\n \"biomass_sp\",\"abundance_sp\")) },\n { stop(paste(\"Variable\", metric, \"not found\")) }\n )\n}\n\n# NEE; kg C m-2 year-1; Converted from µmol CO2 m-2 sec-1 (10^-6 moles)\nget_nee <- function() {\n #df = read.csv(self$files$observations$flux, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf004-02-filled.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df$c_kg = df$nee * 1e-6 * 12 / 1000 # convert µmol CO2 to mol CO2 to g C to kg C\n df$c_kg = df$c_kg * 60 * 60 * 24 * 365.24 # convert kg C m-2 second-1 to kg C m-2 year-1\n return(setNames(aggregate(df$c_kg, by=list(df$year), FUN=mean), c(\"year\",\"nee\")))\n}\n\n# Aboveground biomass; kg m-2; 34 EMS tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\nget_biomass_ag <- function() {\n #df = read.csv(self$files$observations$inventory, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf069-09-trees.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n #df = df[df$site ==\"ems\" & df$tree.type == \"live\",]\n df = df[df$site ==\"ems\" & df$tree.type == \"live\" & !is.na(df$year) & df$year > 1993,]\n df$code = species_lut$code[match(df$species, species_lut$abbr)]\n df = df[df$code %in% c(\"ACPE\",\"ACRU\",\"BEAL\",\"BELE\",\"BEPO\",\"FAGR\",\"FRAM\",\"PIGL\",\n \"PIRE\",\"PIST\",\"PRSE\",\"QURU\",\"QUVE\",\"TSCA\"),] # modeled species\n # Mean annual individual tree DBH\n df = setNames(aggregate(df$dbh, by=list(df$year, df$code, df$plot, df$tag), FUN=mean, na.rm=TRUE),\n c(\"year\",\"code\",\"plot\",\"tag\",\"dbh\"))\n df = df[,c(\"year\",\"code\",\"dbh\")]\n df$biomass_ag = apply(df, 1, function(x) get_tree_biomass_ag(x[2], as.numeric(x[3])))\n agb = setNames(aggregate(df$biomass_ag, by=list(df$year), FUN=sum, na.rm=TRUE), c(\"year\",\"biomass_ag\"))\n agb$biomass_ag = agb$biomass_ag / 10681.42 # convert kg to kg m-2\n return(agb)\n}\n\n# Aboveground carbon; kg C m-2; 34 tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\nget_c_ag <- function() {\n df = get_biomass_ag()\n df$c_ag = df$biomass_ag * 0.5\n return(df[,c(\"year\",\"c_ag\")])\n}\n\n# Aboveground carbon; kg N m-2; 34 tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\nget_n_ag <- function() {\n agc = get_c_ag()\n #df = read.csv(self$files$observations$root_cn, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf278-04-root-carbon-nitrogen.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df$cn = df$c.n / 100\n cn_stem = mean(df$cn, na.rm=TRUE)\n #df = read.csv(self$files$observations$leaf_cn, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf069-06-canopy-chem.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df$cn_leaf = df$c.percent / df$n.percent\n cn_leaf = mean(df$cn_leaf, na.rm=TRUE)\n agc$n_ag = agc$c_ag / ((cn_stem * 0.80) + (cn_leaf * 0.20)) # assumes general 80/20 stem/leaf fraction\n return(agc[,c(\"year\",\"n_ag\")])\n}\n\n# Belowground biomass; kg m-2; 34 tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\n# Uses general AGB-to-BGB model of Chojnacky, Heath, Jenkins (2014)\nget_biomass_bg <- function() {\n df = read.csv(file.path(base_hf_data, \"hf069-09-trees.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df = df[df$site ==\"ems\" & df$tree.type == \"live\",]\n df$code = species_lut$code[match(df$species, species_lut$abbr)]\n df = df[df$code %in% c(\"ACPE\",\"ACRU\",\"BEAL\",\"BELE\",\"BEPO\",\"FAGR\",\"FRAM\",\"PIGL\",\n \"PIRE\",\"PIST\",\"PRSE\",\"QURU\",\"QUVE\",\"TSCA\"),] # modeled species\n # Mean annual individual tree DBH\n df = setNames(aggregate(df$dbh, by=list(df$year, df$code, df$plot, df$tag), FUN=mean, na.rm=TRUE),\n c(\"year\",\"code\",\"plot\",\"tag\",\"dbh\"))\n df = df[,c(\"year\",\"code\",\"dbh\")]\n df$biomass_ag = apply(df, 1, function(x) get_tree_biomass_ag(x[2], as.numeric(x[3])))\n #df$root_coarse = df$biomass_ag * 0.22\n #df$root_fine = df$biomass_ag * 0.01\n df$root_coarse = df$biomass_ag * exp(-1.4485 - 0.03476 * log(df$dbh))\n df$root_fine = df$biomass_ag * exp(-1.8629 - 0.77534 * log(df$dbh))\n df$soil = df$biomass_ag * 0.68\n df$biomass_bg = df$root_coarse + df$root_fine + df$soil\n bgb = setNames(aggregate(df$biomass_bg, by=list(df$year), FUN=sum, na.rm=TRUE), c(\"year\",\"biomass_bg\"))\n bgb$biomass_bg = bgb$biomass_bg / 10681.42 # convert kg to kg m-2\n return(bgb[,c(\"year\",\"biomass_bg\")])\n}\n\n# Belowground C; kg C m-2; 34 tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\nget_c_bg <- function () {\n bgb = get_biomass_bg()\n #df = read.csv(self$files$observations$root_cn, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf278-04-root-carbon-nitrogen.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n bgb$c_bg = bgb$biomass_bg * (mean(df$c.per, na.rm=TRUE) / 100)\n return(bgb[,c(\"year\",\"c_bg\")])\n}\n\n# Belowground N; kg N m-2; 34 tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\nget_n_bg <- function () {\n bgb = get_biomass_bg()\n #df = read.csv(self$files$observations$root_cn, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf278-04-root-carbon-nitrogen.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n bgb$n_bg = bgb$biomass_bg * (mean(df$n.per, na.rm=TRUE) / 100)\n return(bgb[,c(\"year\",\"n_bg\")])\n}\n\n# Soil organic C; g C cm-3; 240 (22.5 x 22.5m) 506.25 m2 plots (121500 m2 total) of 269 original plots\nget_c_so <- function() {\n #df = read.csv(self$files$observations$soils, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf015-05-soils-cn.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n bd = df$bdgcc.corr # bulk density or g soil per cm3\n c_gg = df$gcgsoil # g C per g soil\n c_so = bd * c_gg / 1000 * 1e+6 # g C per cm3 soil converted to kg per m3\n c_so = mean(c_so, na.rm=TRUE)\n return(data.frame(year=NA, c_so=c_so))\n}\n\n# Soil organic N; g N cm-3; 240 (22.5 x 22.5m) 506.25 m2 plots (121500 m2 total) of 269 original plots\nget_n_so <- function() {\n #df = read.csv(self$files$observations$soils, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf015-05-soils-cn.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n bd = df$bdgcc.corr # bulk density or g soil per cm3\n n_gg = df$gngsoil # g N per g soil\n n_so = bd * n_gg / 1000 * 1e+6 # g C per cm3 soil converted to kg per m3\n n_so = mean(n_so, na.rm=TRUE)\n return(data.frame(year=NA, n_so=n_so))\n}\n\n# Soil respiration; mg C m-2 hour-1; kg C m-2 year-1; 6 sites near EMS tower\nget_r_soil <- function() {\n #df = read.csv(self$files$observations$r_soil, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf006-01-soil-respiration.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df$date = as.POSIXlt(df$date, format=\"%m/%d/%Y\", tz=\"EST\")\n df$year = as.numeric(format(df$date, \"%Y\"))\n df$flux = df$flux / 1e+6 * 24 * 365.24 # convert mg C m-2 hour-1 to kg C m-2 year-1\n return(setNames(aggregate(df$flux, by=list(df$year), FUN=mean, na.rm=TRUE), c(\"year\",\"r_soil\")))\n}\n\n# Annual net primary productivity (ANPP); Mg year-1; kg C m-2 year-1\nget_anpp <- function() {\n #df = read.csv(self$files$observations$anpp, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf069-13-annual-summ.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df = df[df$site ==\"ems\",]\n df = df[!is.na(df$anpp),]\n df$anpp = df$anpp * 1000 / 10681.42 * 0.5 # Mg mass year-1 to kg C m-2 year-1\n return(df[,c(\"year\",\"anpp\")])\n}\n\n# Total species aboveground biomass; kg m-2; 34 tower plots (10m radius; (pi*10^2)*34 = 10681.42 m2)\nget_biomass_sp <- function() {\n #df = read.csv(self$files$observations$inventory, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf069-09-trees.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df = df[df$site ==\"ems\" & df$tree.type == \"live\",]\n df$code = species_lut$code[match(df$species, species_lut$abbr)]\n df = df[df$code %in% c(\"ACPE\",\"ACRU\",\"BEAL\",\"BELE\",\"BEPO\",\"FAGR\",\"FRAM\",\"PIGL\",\n \"PIRE\",\"PIST\",\"PRSE\",\"QURU\",\"QUVE\",\"TSCA\"),] # modeled species\n # Mean annual individual tree DBH\n df = setNames(aggregate(df$dbh, by=list(df$year, df$code, df$plot, df$tag), FUN=mean, na.rm=TRUE),\n c(\"year\",\"code\",\"plot\",\"tag\",\"dbh\"))\n df = df[,c(\"year\",\"code\",\"dbh\")]\n df$biomass_ag = apply(df, 1, function(x) get_tree_biomass_ag(x[2], as.numeric(x[3])))\n biomass_sp = aggregate(df$biomass_ag, by=list(df$year, df$code), FUN=sum, na.rm=TRUE)\n colnames(biomass_sp) = c(\"year\",\"species\",\"biomass_ag\")\n biomass_sp$biomass_ag = biomass_sp$biomass_ag / 10681.42\n return(biomass_sp)\n}\n\n# Species relative abundance; percent of n-trees\nget_abundance_sp <- function() {\n #df = read.csv(self$files$observations$inventory, header=TRUE, stringsAsFactors=FALSE)\n df = read.csv(file.path(base_hf_data, \"hf069-09-trees.csv\"), header=TRUE, stringsAsFactors=FALSE)\n colnames(df) = tolower(colnames(df))\n df = df[df$site ==\"ems\" & df$tree.type == \"live\",]\n df$code = species_lut$code[match(df$species, species_lut$abbr)]\n df = df[df$code %in% c(\"ACPE\",\"ACRU\",\"BEAL\",\"BELE\",\"BEPO\",\"FAGR\",\"FRAM\",\"PIGL\",\n \"PIRE\",\"PIST\",\"PRSE\",\"QURU\",\"QUVE\",\"TSCA\"),] # modeled species\n ntrees_yr = setNames(aggregate(df$code, by=list(df$year), FUN=length), c(\"year\",\"ntrees\"))\n df$ntrees_yr = ntrees_yr$ntrees[match(df$year, ntrees_yr$year)]\n df$fraction_yr = 1 / df$ntrees_yr # relative abundance of each tree\n return(setNames(aggregate(df$fraction_yr, by=list(df$year, df$code), FUN=sum), c(\"year\",\"species\",\"abundance\")))\n}\n", "meta": {"hexsha": "28487dd0c50cc6c3e2882b1ed3a40e5507a093d0", "size": 24791, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/harvard_forest_datasets.r", "max_stars_repo_name": "adam-erickson/ecosystem-model-comparison", "max_stars_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-03-02T13:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T11:36:59.000Z", "max_issues_repo_path": "scripts/harvard_forest_datasets.r", "max_issues_repo_name": "adam-erickson/ecosystem-model-comparison", "max_issues_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "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": "scripts/harvard_forest_datasets.r", "max_forks_repo_name": "adam-erickson/ecosystem-model-comparison", "max_forks_repo_head_hexsha": "4eb34532a0cef99e5a556c0fc1157096d44d23e5", "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": 54.6057268722, "max_line_length": 120, "alphanum_fraction": 0.5736355936, "num_tokens": 7801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3106943959796865, "lm_q2_score": 0.03514484741138068, "lm_q1q2_score": 0.010919307138277169}} {"text": "# ************************************************** #\n# Read exposure and outcome #\n# ************************************************** #\nread_gsmr_trait = function(file_con) {\n expo_str = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n outcome_str = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n strbuf = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n return(list(expo_str=expo_str, outcome_str=outcome_str))\n}\n\n# ************************************************** #\n# Read GSMR result #\n# ************************************************** #\nread_gsmr_result = function(file_con) {\n expo_str = outcome_str = bxy = bxy_se = bxy_pval = bxy_m = c()\n while(1) {\n strbuf = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n if(strbuf[1] == \"#gsmr_end\") break;\n if(strbuf[1] == \"Exposure\") next;\n expo_str = c(expo_str, strbuf[1]);\n outcome_str = c(outcome_str, strbuf[2]);\n bxy = c(bxy, as.numeric(strbuf[3]));\n bxy_se = c(bxy_se, as.numeric(strbuf[4]));\n bxy_pval = c(bxy_pval, as.numeric(strbuf[5]));\n bxy_m = c(bxy_m, as.numeric(strbuf[6]));\n }\n return(cbind(expo_str, outcome_str, bxy, bxy_se, bxy_pval, bxy_m))\n}\n\n# ************************************************** #\n# Read SNP effects #\n# ************************************************** #\nread_snp_effect = function(file_con) {\n snp_effect = c()\n while(1) {\n strbuf = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n if(strbuf[1] == \"#effect_end\") break;\n snp_effect = rbind(snp_effect, strbuf);\n print(length(strbuf))\n if(length(strbuf)<14) print(strbuf)\n }\n return(snp_effect)\n}\n\n# ************************************************** #\n# Read SNP instruments #\n# ************************************************** #\nread_snp_instru = function(file_con, snplist, nexpo, noutcome) {\n nrow = length(snplist); ncol = nexpo+noutcome\n snp_instru = matrix(NA, nrow, ncol)\n while(1) {\n strbuf = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n if(strbuf[1] == \"#marker_end\") break;\n expo_indx = as.numeric(strbuf[1]); outcome_indx = as.numeric(strbuf[2]);\n forward_flag = TRUE;\n if(expo_indx < outcome_indx) {\n outcome_indx = outcome_indx - nexpo\n } else {\n expo_indx = expo_indx - nexpo\n forward_flag = FALSE;\n }\n snpbuf = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n snp_indx = match(snpbuf, snplist)\n posbuf = rep(0, nrow); posbuf[snp_indx] = 1;\n indxbuf = expo_indx\n if(!forward_flag) indxbuf = indxbuf + nexpo\n if(length(which(!is.na(snp_instru[,indxbuf])))==0) {\n snp_instru[,indxbuf] = posbuf;\n } else {\n snp_instru[,indxbuf] = paste(snp_instru[,indxbuf], posbuf, sep=\"\")\n }\n }\n return(snp_instru)\n}\n\n# ************************************************** #\n# Read output by GCTA-GSMR for plot #\n# ************************************************** #\nread_gsmr_data = function(gsmr_effect_file) {\n trait_flag = gsmr_flag = marker_flag = effect_flag = FALSE;\n file_con = file(gsmr_effect_file, \"r\")\n while(1) {\n strbuf = scan(file_con, nlines=1, quiet=TRUE, what=\"\");\n if(strbuf == \"#trait_begin\") {\n # Read the exposures and outcomes\n resbuf = read_gsmr_trait(file_con);\n expo_str = resbuf$expo_str; \n outcome_str = resbuf$outcome_str;\n pheno_str = c(expo_str, outcome_str);\n nexpo = length(expo_str); noutcome = length(outcome_str)\n trait_flag = TRUE;\n } else if(strbuf == \"#gsmr_begin\") {\n # Read the GSMR result\n bxy_result = read_gsmr_result(file_con);\n colnames(bxy_result) = c(\"Exposure\", \"Outcome\", \"bxy\", \"se\", \"p\", \"n_snps\")\n gsmr_flag = TRUE;\n } else if(strbuf == \"#effect_begin\") {\n # Read the summary statistics\n snp_effect = read_snp_effect(file_con);\n snplist = as.character(snp_effect[,1])\n effect_flag = TRUE;\n } else if(strbuf == \"#marker_begin\") {\n # Read the SNPs\n snp_instru = read_snp_instru(file_con, snplist, nexpo, noutcome);\n snp_effect = cbind(snp_effect[,1], snp_instru, snp_effect[,-1])\n marker_flag = TRUE;\n }\n if(trait_flag==T & gsmr_flag==T & marker_flag==T & effect_flag==T) break;\n }\n return(list(pheno=c(nexpo, noutcome, pheno_str), bxy_result=bxy_result, snp_effect = snp_effect))\n}\n\n# ************************************************** #\n# Display summary of the gsmr data #\n# ************************************************** #\ngsmr_summary = function(gsmr_data) {\n message(\"\\n## Exposure and outcome\")\n pheno_str = gsmr_data$pheno[c(-1,-2)]\n # exposure\n nexpo = as.numeric(gsmr_data$pheno[1]);\n noutcome = as.numeric(gsmr_data$pheno[2]);\n logger_m = paste(nexpo, \"exposure(s):\");\n logger_m = paste(logger_m, gsmr_data$pheno[3])\n if(nexpo > 1) {\n for(i in 2 : nexpo) \n logger_m = paste(logger_m, gsmr_data$pheno[i+2], sep=\", \")\n } \n message(logger_m)\n # outcome\n logger_m = paste(noutcome, \"outcome(s):\");\n logger_m = paste(logger_m, gsmr_data$pheno[3+nexpo])\n if(noutcome > 1) {\n for(i in 2 : noutcome) \n logger_m = paste(logger_m, gsmr_data$pheno[i+2+nexpo], sep=\", \")\n } \n message(logger_m)\n\n message(\"\\n## GSMR result\")\n m_bxy_rst = data.frame(gsmr_data$bxy_result)\n print(m_bxy_rst)\n}\n\n\n# ************************************************** #\n# Retrieve SNP effects #\n# ************************************************** #\ngsmr_snp_effect = function(gsmr_data, expo_str, outcome_str) {\n # index of SNP instruments\n pheno_str = as.character(gsmr_data$pheno[c(-1,-2)])\n nexpo = as.numeric(gsmr_data$pheno[1])\n noutcome = as.numeric(gsmr_data$pheno[2])\n expo_indx = match(expo_str, pheno_str)\n if(is.na(expo_indx)) stop(\"\\\"\", expo_str, \"\\\" is not found.\")\n outcome_indx = match(outcome_str, pheno_str)\n if(is.na(outcome_indx)) stop(\"\\\"\", outcome_str, \"\\\" is not found.\")\n forward_flag = TRUE;\n if(expo_indx > outcome_indx) forward_flag = FALSE;\n if(forward_flag) {\n outcome_indx = outcome_indx - nexpo;\n } else {\n expo_indx = expo_indx - nexpo;\n }\n indxbuf = expo_indx + 1\n if(!forward_flag) indxbuf = indxbuf + nexpo\n strbuf = as.character(substr(gsmr_data$snp_effect[,indxbuf], outcome_indx, outcome_indx))\n snpindx = which(strbuf==\"1\")\n if(length(snpindx) < 3) stop(\"Not enough SNPs retained.\")\n # bxy\n indxbuf = which(gsmr_data$bxy_result[,1]==expo_str & gsmr_data$bxy_result[,2]==outcome_str)\n bxy = as.numeric(gsmr_data$bxy_result[indxbuf, 3])\n # SNP effects\n if(forward_flag) {\n indxbuf1 = 1 + nexpo + noutcome + 3 + (expo_indx-1)*2 + 1\n indxbuf2 = 1 + nexpo + noutcome + 3 + nexpo*2 + (outcome_indx-1)*2 + 1\n } else {\n indxbuf1 = 1 + nexpo + noutcome + 3 + nexpo*2 + (expo_indx-1)*2 + 1\n indxbuf2 = 1 + nexpo + noutcome + 3 + (outcome_indx-1)*2 + 1\n }\n snpid = as.character(gsmr_data$snp_effect[snpindx,1])\n bzx = as.numeric(gsmr_data$snp_effect[snpindx,indxbuf1]); indxbuf1 = indxbuf1 + 1;\n bzx_se = as.numeric(gsmr_data$snp_effect[snpindx,indxbuf1]);\n bzx_pval = pchisq((bzx/bzx_se)^2, 1, lower.tail=F);\n bzy = as.numeric(gsmr_data$snp_effect[snpindx,indxbuf2]); indxbuf2 = indxbuf2 + 1;\n bzy_se = as.numeric(gsmr_data$snp_effect[snpindx,indxbuf2]);\n bzy_pval = pchisq((bzy/bzy_se)^2, 1, lower.tail=F);\n return(list(snp=snpid, bxy=bxy, bzx=bzx, bzx_se=bzx_se, bzx_pval=bzx_pval, bzy=bzy, bzy_se=bzy_se, bzy_pval=bzy_pval))\n}\n\n# ************************************************** #\n# Plot bzy vs bzx #\n# ************************************************** #\nplot_snp_effect = function(expo_str, outcome_str, bxy, bzx, bzx_se, bzy, bzy_se, effect_col=colors()[75]) {\n vals = c(bzx-bzx_se, bzx+bzx_se)\n xmin = min(vals); xmax = max(vals)\n vals = c(bzy-bzy_se, bzy+bzy_se)\n ymin = min(vals); ymax = max(vals)\n plot(bzx, bzy, pch=20, cex=0.8, bty=\"n\", cex.axis=1.1, cex.lab=1.2,\n col=effect_col, xlim=c(xmin, xmax), ylim=c(ymin, ymax),\n xlab=substitute(paste(trait, \" (\", italic(b[zx]), \")\", sep=\"\"), list(trait=expo_str)),\n ylab=substitute(paste(trait, \" (\", italic(b[zy]), \")\", sep=\"\"), list(trait=outcome_str)))\n if(!is.na(bxy)) abline(0, bxy, lwd=1.5, lty=2, col=\"dim grey\")\n ## Standard errors\n nsnps = length(bzx)\n for( i in 1:nsnps ) {\n # x axis\n xstart = bzx[i] - bzx_se[i]; xend = bzx[i] + bzx_se[i]\n ystart = bzy[i]; yend = bzy[i]\n segments(xstart, ystart, xend, yend, lwd=1.5, col=effect_col)\n # y axis\n xstart = bzx[i]; xend = bzx[i] \n ystart = bzy[i] - bzy_se[i]; yend = bzy[i] + bzy_se[i]\n segments(xstart, ystart, xend, yend, lwd=1.5, col=effect_col)\n }\n}\n\n# ************************************************** #\n# Plot bzy_pval vs bzx_pval #\n# ************************************************** #\nplot_snp_pval = function(expo_str, outcome_str, bzx_pval, bzy_pval, gwas_thresh, truncation, effect_col) {\n eps = 1e-300; truncation = -log10(truncation);\n if(truncation > 300) {\n warning(\"The minimal truncated p-value would be 1e-300.\")\n truncation = 300\n }\n bzx_pval = -log10(bzx_pval + eps);\n bzy_pval = -log10(bzy_pval + eps);\n pval = c(bzx_pval, bzy_pval)\n min_val = 0; max_val = max(pval);\n max_val = ifelse(max_val > truncation, truncation, max_val)\n gwas_thresh = -log10(gwas_thresh);\n plot(bzx_pval, bzy_pval, pch=20, cex=0.8, bty=\"n\", cex.axis=1.1, cex.lab=1.2,\n col=effect_col, xlim=c(min_val, max_val), ylim=c(min_val, max_val),\n xlab=substitute(paste(trait, \" (\", -log[10], italic(P)[zx], \")\", sep=\"\"), list(trait=expo_str)),\n ylab=substitute(paste(trait, \" (\", -log[10], italic(P[zy]), \")\", sep=\"\"), list(trait=outcome_str)))\n abline(h=gwas_thresh, lty=2, lwd=1.5, col=\"maroon\")\n}\n\n# ************************************************** #\n# Plot bxy vs bzx_pval #\n# ************************************************** #\nplot_snp_bxy = function(expo_str, outcome_str, bxy, bzx_pval, effect_col) {\n eps = 1e-300;\n bzx_pval = -log10(bzx_pval + eps);\n xmin = min(bxy, na.rm=T); xmax = max(bxy, na.rm=T)\n ymin = min(bzx_pval); ymax = max(bzx_pval);\n plot(bxy, bzx_pval, pch=20, cex=0.8, bty=\"n\", cex.axis=1.1, cex.lab=1.2,\n col=effect_col, xlim=c(xmin, xmax), ylim=c(ymin, ymax),\n xlab=substitute(paste(italic(hat(b)[xy]), \" (\", trait1, \" -> \", trait2, \")\", sep=\"\"), list(trait1=expo_str, trait2=outcome_str)),\n ylab=substitute(paste(trait, \" (\", -log[10], italic(P[zx]), \")\", sep=\"\"), list(trait=expo_str)))\n}\n\n# ************************************************** #\n# Effect size plot #\n# ************************************************** #\n# expo_str, exposure\n# outcome_str, outcome\n# effect_col, plotting colour\nplot_gsmr_effect = function(gsmr_data, expo_str, outcome_str, effect_col=colors()[75]) {\n resbuf = gsmr_snp_effect(gsmr_data, expo_str, outcome_str);\n bxy = resbuf$bxy\n bzx = resbuf$bzx; bzx_se = resbuf$bzx_se;\n bzy = resbuf$bzy; bzy_se = resbuf$bzy_se;\n # plot\n plot_snp_effect(expo_str, outcome_str, bxy, bzx, bzx_se, bzy, bzy_se, effect_col)\n}\n\n# ************************************************** #\n# P-value plot #\n# ************************************************** #\n# expo_str, exposure\n# outcome_str, outcome\n# effect_col, plotting colour\nplot_gsmr_pvalue = function(gsmr_data, expo_str, outcome_str, gwas_thresh=5e-8, truncation=1e-50, effect_col=colors()[75]) {\n resbuf = gsmr_snp_effect(gsmr_data, expo_str, outcome_str);\n bzx_pval = resbuf$bzx_pval; bzy_pval = resbuf$bzy_pval;\n # plot\n plot_snp_pval(expo_str, outcome_str, bzx_pval, bzy_pval, gwas_thresh, truncation, effect_col)\n}\n\n# ************************************************** #\n# bxy distribution plot #\n# ************************************************** #\n\n# expo_str, exposure\n# outcome_str, outcome\n# effect_col, plotting colour\nplot_bxy_distribution = function(gsmr_data, expo_str, outcome_str, effect_col=colors()[75]) {\n resbuf = gsmr_snp_effect(gsmr_data, expo_str, outcome_str);\n bzx = resbuf$bzx; bzx_pval = resbuf$bzx_pval;\n bzy = resbuf$bzy; \n bxy = bzy/bzx\n # plot\n plot_snp_bxy(expo_str, outcome_str, bxy, bzx_pval, effect_col)\n}\n", "meta": {"hexsha": "84ead1d499511790ac4e220473f292c461837b66", "size": 12934, "ext": "r", "lang": "R", "max_stars_repo_path": "vendor/gsmr_plot.r", "max_stars_repo_name": "AtheroExpress/gsmr-bed-pipeline", "max_stars_repo_head_hexsha": "5582eae97b2bbe59593d70ffb7572378db8ec1ed", "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": "vendor/gsmr_plot.r", "max_issues_repo_name": "AtheroExpress/gsmr-bed-pipeline", "max_issues_repo_head_hexsha": "5582eae97b2bbe59593d70ffb7572378db8ec1ed", "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": "vendor/gsmr_plot.r", "max_forks_repo_name": "AtheroExpress/gsmr-bed-pipeline", "max_forks_repo_head_hexsha": "5582eae97b2bbe59593d70ffb7572378db8ec1ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-06-08T12:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T12:59:11.000Z", "avg_line_length": 43.8440677966, "max_line_length": 138, "alphanum_fraction": 0.539662904, "num_tokens": 3795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.024423089832204682, "lm_q1q2_score": 0.010881207857171867}} {"text": "## Author: Alan Ruttenberg\n## Project: OHD\n## Date: 2015-04-24\n##\n## Survival Analysis: Do it all: resin_restoration_survival_analysis()\n\nlibrary(survival)\nlibrary(\"simPH\")\n\n# Create an rsurv \"object\", mostly so that we can control printing\n# Sigh, have to be careful if we want to call by reference - i.e. slot changes persist\n# http://www.stat.berkeley.edu/~paciorek/computingTips/Pointers_passing_reference_.html\n\nrsurv <- function()\n { object=new.env(parent=globalenv()) \n class(object)=\"rsurv\"\n lastrsurv <<- object;\n return(object)\n }\n\n# We have a lot of state - don't print it all\nprint.rsurv <- function(object) { cat(\"\\n\") }\n\n# Main entry point. Query the database twice - once to fetch all\n# restorations, once to fetch all the restorations with a known\n# failure.\n# Returns an rsurv object. Important methods: plot, summary.\n\nresin_restoration_survival_analysis <- function ()\n { s <- rsurv()\n s$all <- collect_all_restorations_and_latest_encounter_after()\n s$fail <- collect_restoration_failures()\n create_rsurv(s)\n }\n\n# Summary, for now, is the correlates table\nsummary.rsurv <- function (it)\n { summary(it$correlates);\n }\n\n# Take the set of all resin restorations and subtract out those which\n# we know failed. The rest will be censored\n# Could do this in Sparql, but hadn't learned enough\n# SPARQL 1.1 when this was first written.\nsubset_all_minus_fail <- function(all, fail)\n{\n rownames(all)=all[,\"proci1\"]\n rownames(fail)=fail[,\"proci1\"]\n keep <- setdiff(rownames(all),rownames(fail));;\n res <- as.matrix(all[keep,]);\n}\n\n# Helper functions.\n\n# Takes two date strings(yyyy-mm-yy) and uses seq.date to return the\n# time difference in months. Rounds down.\n\ndifference_in_months <- function(start,end)\n { length(seq(as.Date(start),as.Date(end),by=\"month\"))-1 }\n\n# Takes two date strings(yyyy-mm-yy) and uses seq.date to return the\n# time difference in years. Rounds down.\n\ndifference_in_years <- function(start,end)\n { length(seq(as.Date(start),as.Date(end),by=\"year\"))-1 }\n\n# create arrays of correlates aligned with survival data - first the\n# the ones we know fail, then the ones that will be censored. Takes\n# as input the rsurv object, where we have already prepared the\n# matrices \"fail\" and \"have_last_visit\", each having one row per\n# \"event\".\n# Sets the \"correlates\" attribute to\n# the created data frame.\n\nprepare_survival_correlates <- function(s)\n { s$correlates <- rbind(data.frame(location=as.factor(s$fail[,\"tooth_type\"]),\n gender=as.factor(s$fail[,\"gender\"]),\n age=s$age_at_fail,\n patient=s$fail[,\"patienti\"],\n fail=TRUE),\n data.frame(location=as.factor(s$have_last_visit[,\"tooth_type\"]),\n gender=as.factor(s$have_last_visit[,\"gender\"]),\n age=s$age_at_last_visit,\n patient=s$have_last_visit[,\"patienti\"],\n fail=FALSE))\n # divide the ages into bins, [0,18) , [18-30), [30,60), over 60\n s$correlates[,\"age_group\"] <- as.factor(cut(s$correlates[,\"age\"],breaks=c(0,18,30,60,100)));\n }\n\n\n# having the failures (s$fail) and all events (s$all), create\n# s$have_last_visit as the events where we have a restoration and a\n# subsequent visit on record. These will be treated as right censored\n\nprepare_censored_events <- function(s)\n {\n # Compute all restorations without a subsequent failure on record\n no_record_of_failure <- NULL;\n no_record_of_failure <- subset_all_minus_fail(s$all,s$fail);\n\n # Filter out ones without a subsequent visit - we can't use those at all. Call those $have_last_visit.\n s$have_last_visit <- no_record_of_failure[!is.na(no_record_of_failure[,\"latest_date2\"]),];\n\n # Calculate the time in months between the restoration and the last visit date on record\n s$no_record_of_failure_in_months <-\n mapply(difference_in_months,s$have_last_visit[,\"date1\"],s$have_last_visit[,\"latest_date2\"])\n\n # Calculate the age at last visit\n s$age_at_last_visit <- mapply(difference_in_years,s$have_last_visit[,\"birthdate\"],s$have_last_visit[,\"date1\"])\n\n s$ncensor = length(s$no_record_of_failure_in_months);\n }\n\n# Calculate time until failure and the age at failure for those events\n# where there was a failure. We consider the failure event, for the\n# purpose of survival analysis, to be the date the failure is noticed\n# or replaced. For future improvement - treat the failure as interval\n# censored.\n\nprepare_failure_events <- function(s)\n{\n s$fail_difference_in_months <-\n mapply(difference_in_months,s$fail[,\"date1\"],s$fail[,\"soonest_date2\"])\n s$age_at_fail <- mapply(difference_in_years,s$fail[,\"birthdate\"],s$fail[,\"date1\"])\n s$nfail <- length(s$fail_difference_in_months);\n}\n\n# Main analysis\ncreate_rsurv <- function (s)\n {\n prepare_censored_events(s)\n\n prepare_failure_events(s)\n\n # Now compute the main inputs to the survival analysis. \n # s$status is 1 if the event was a failure, 0 if right censored.\n # combine the fail time and last visit times to make a vector\n # of time in months, and divide by 12 to get years.\n s$status <- c(rep(1,s$nfail),rep(0,s$ncensor));\n s$months <- c(s$fail_difference_in_months,s$no_record_of_failure_in_months)\n s$years <- c(s$fail_difference_in_months,s$no_record_of_failure_in_months)/12;\n prepare_survival_correlates(s)\n\n # Do the survival analysis, two argument version.\n surv <- Surv(s$years,s$status) ;\n s$surv <- surv;\n \n # Now do the univariate fits \n s$fit <- survfit(surv~1,conf.type=\"none\",data=s$correlates);\n s$location_fit <- survfit(surv~location,conf.type=\"none\",data=s$correlates);\n s$gender_fit <- survfit(surv~gender,conf.type=\"none\",data=s$correlates);\n s$age_fit <- survfit(surv~age_group,conf.type=\"none\",data=s$correlates);\n # Make the age groups prettier\n names(s$age_fit$strata)=\n c(\"age=18 and under\", \"age=18+ to 30\", \"age=30+ to 60\", \"age=60 and over\")\n \n # Compute the proportional hazards\n s$cox<-coxph(surv~location+gender+age, method=\"breslow\",data=s$correlates)\n\n s\n }\n\n# Draw one of the Kaplan-Meier plots\n# We use ggplot, and hunt the web for recipes to show the bits we want\n# to show.\n\nplot_rsurv_fit <- function (s,fit=s$location_fit,\n title=\"All\",\n xlab=\"Time in years\",\n ylab=\"Fraction surviving\",\n ci=F,col=c(\"dark green\",\"dark blue\")\n )\n { print(\n ggsurv(fit,cens.col='gray',plot.cens=F,back.white=T,\n main=title,xlab=xlab,ylab=ylab,CI=ci,surv.col=col)\n # set up the x scale\n + scale_x_continuous(breaks=1:13,expand=c(0,0),limits=c(0,12.5))\n # set up the y scale\n + scale_y_continuous(expand=c(0,.01))\n # axes font bold (tweak position to look better too)\n + theme(axis.title.y=element_text(vjust=1.5,face=\"bold\"))\n + theme(axis.title.x=element_text(vjust=-.7,face=\"bold\"))\n # So is title\n + theme(title=element_text(vjust=2,face=\"bold\"))\n # Place the legend inside the plot \n + theme(legend.position=c(.9,.5),\n legend.text=element_text(size=12,face=\"bold\"),\n legend.title=element_text(size=14))\n #add guides\n + guides(colour = guide_legend(override.aes = list(size=3))));\n\n }\n\n# Draw all of the plots. plotWrap prepares the device. bplotf devault\n# uses svg device and sends to browser.\n\nplot.rsurv <- function (sa,plotWrap=bplotf)\n{ plotWrap(function ()\n {plot_rsurv_fit(sa,title=\"Resin restoration longevity\",\n fit=sa$fit,\n col=\"dark blue\")},\n index=\"\",filebase=\"overall-longevity\")\n plotWrap(function ()\n {plot_rsurv_fit(sa,title=\"Resin restoration longevity by age at failure\",\n fit=sa$age_fit,\n col=c(\"dark gray\",\"dark green\",\"dark blue\",\"dark red\"))},\n index=\"\",filebase=\"longevity-by-age\")\n plotWrap(function () \n {plot_rsurv_fit(sa,title=\"Resin restoration longevity by gender\",\n fit=sa$gender_fit,\n col=c(\"dark blue\",\"dark red\"))},\n index=\"\",filebase=\"longevity-by-gender\")\n plotWrap(function ()\n {plot_rsurv_fit(sa,title=\"Resin restoration longevity by location\",\n fit=sa$location_fit,\n col=c(\"dark blue\",\"dark red\"))},\n index=\"\",filebase=\"longevity-by-location\")\n}\n\n\n# if factors, number of events for each factor\nsummary_text <- function(surv,correlate)\n { levels <- levels(as.factor(lastrsurv$correlates[,correlate]))\n c <- surv$correlates;\n factor_summary <- function(value,factor=correlate)\n { patient_count <- length(unique(c[(c[,factor]==value),\"patient\"]));\n event_count <- nrow(c[(c[,factor]==value),])\n failures_count <- nrow(c[(c[,factor]==value & c[,\"fail\"]),]);\n paste0(value,\": \",patient_count, \" patients\", \", \",event_count,\" events of which \",failures_count,\" were failures\")\n }\n do.call(paste,args=c(lapply(as.list(levels),factor_summary),sep=\"\\n\"))\n }\n\n\n\n\n# levels(as.factor(lastrsurv$correlates[,\"age_group\"]))\n\n## sa$cox$coef[\"locationposterior\"]\n## sa$cox$coef[\"gendermale\"]\n\n## bplotf(function(){\n## + baseline<-basehaz(coxph(x$gender_fit))\n## + plot(baseline$time, baseline$hazard, type='l',main=\"Hazard rates\") \n## + lines(baseline$time, exp(0.8245)*baseline$hazard, col=\"blue\") })\n\n## sa$correlates[,\"AgeMed\"]<-sa$correlates[,\"age\"]-40\n## Sim1 <- coxsimLinear(M1, b = \"AgeMed\", nsim = 100,Xj = seq(-30, 30, by=1))\n## bplotf(function() {print(simGG(Sim1))})\n\n## baseline<-basehaz(reg_fit)\n\n## #http://www.unc.edu/courses/2010spring/ecol/562/001/docs/lectures/lecture24.htm#coxzph\n## #http://www.uni-kiel.de/psychologie/rexrepos/posts/survivalCoxPH.html\n## #http://www.statisticsmentor.com/category/r-survival-analysis/\n\n", "meta": {"hexsha": "ae7157a9d46b22ec3aef42d2ef64feb302f444ee", "size": 10323, "ext": "r", "lang": "R", "max_stars_repo_path": "src/analysis/survival.r", "max_stars_repo_name": "oral-health-and-disease-ontologies/OHD-ontology", "max_stars_repo_head_hexsha": "e22530f45f0bfc31ccd8e1e69aa00791328e08b7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-08T16:11:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T16:11:01.000Z", "max_issues_repo_path": "src/analysis/survival.r", "max_issues_repo_name": "oral-health-and-disease-ontologies/OHD-ontology", "max_issues_repo_head_hexsha": "e22530f45f0bfc31ccd8e1e69aa00791328e08b7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2019-05-13T19:04:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-31T18:34:56.000Z", "max_forks_repo_path": "src/analysis/survival.r", "max_forks_repo_name": "oral-health-and-disease-ontologies/OHD-ontology", "max_forks_repo_head_hexsha": "e22530f45f0bfc31ccd8e1e69aa00791328e08b7", "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": 40.1673151751, "max_line_length": 127, "alphanum_fraction": 0.6420614163, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.024053554774625185, "lm_q1q2_score": 0.01080949034841121}} {"text": "#!/usr/bin/Rscript\n\n## bootstrap.r -- runs a bootstrap process across a genotype file\n\n## Author: David Eccles (gringer), 2009 \n\n## simplegt-formatted input file\ngenotypes.inFile = \"\";\n## columns of genotype file to consider cases/controls\n## (first value is ignored, so can be used as a group identifier)\ncasecontrolColumns.inFile = \"cases_controls.txt\";\n\n## number of subsamples to use for bootstrapping\nreplicates.proportion = 0.50;\nreplicates.cases = NULL; # if NULL, will be replicates.proportion or 5 less, whichever is smaller\nreplicates.controls = replicates.cases;\nrep.case.outFile = \"\";\nrep.control.outFile = \"\";\ncreateReplicates = TRUE; # if false, use existing replicate data\n## number of bootstraps to carry out\nbootstrap.count = 100;\n\n## file to place bootstrapped results into\nbootstraps.outFile = \"bootstrap_results.csv\";\n\n## should the output values be sorted within each marker?\nsortValues <- FALSE;\n\n## controls are on the first line of this file (normally expect cases first)\ncontrolsFirst <- FALSE;\n\n## method to use for calculating results\n## current options are Adelta, GTdelta, Chisqmax\nprocessMethod <- \"Adelta\";\n\n## consider complementary alleles to be the same (allows different\n## genotyping methods for the same mutation to be combined)\ncombineComplementary <- TRUE;\n\n## keep zero counts separate when calculating chi^2 (produces invalid\n## results when zero counts are observed for any genotype)\nstrictChi <- FALSE;\n\nusage <- function(){\n cat(\"usage: ./bootstrap.r\",\n \" [options]\\n\");\n cat(\"\\nOther Options:\\n\");\n cat(\"-help : Only display this help message\\n\");\n cat(\"-input : File containing genotype data\\n\");\n cat(\"-controlfile : File containing column data for cases/controls\\n\");\n cat(\"-repfiles : Files containing replicate columns (for repeat experiments)\\n\");\n cat(\"-controlsfirst : case/control file has controls as first line\\n\");\n cat(\"-count : Number of bootstrapts to carry out\\n\");\n cat(\"-casereps : case subpopulation size for boostraps (overrides proportion)\\n\");\n cat(\"-controlreps : control subpopulation size for boostraps (overrides proportion)\\n\");\n cat(\"-proportion : proportion of individuals for boostraps (currently \", replicates.proportion,\")\\n\", sep=\"\");\n cat(\"-sort : sort bootstrap results by value\\n\");\n cat(\"-strictGT : Keep complementary alleles separate (don't combine)\\n\");\n cat(\"-strictChi : Respect zero counts in chi^2 table, creates null results\\n\");\n cat(\"-output : output file for results\\n\");\n cat(\"-method : method to use for calculating results\\n\");\n cat(\" (Adelta, GTdelta, gChisq, Chisqmax, ChisqmaxAll, ShowValues)\\n\");\n cat(\"\\n\");\n}\n\nargLoc <- 1;\n\nargLoc <- grep(\"--args\",commandArgs()) + 1; # hack to get around R v2.4\n # issue stopping\n # commandArgs(TRUE) from\n # working\nwhile(!is.na(commandArgs()[argLoc])){\n if(file.exists(commandArgs()[argLoc])){ # file existence check\n casecontrolColumns.inFile <- commandArgs()[argLoc];\n } else {\n if(commandArgs()[argLoc] == \"-help\"){\n usage();\n quit(save = \"no\", status=0);\n }\n else if(commandArgs()[argLoc] == \"-input\"){\n genotypes.inFile <- commandArgs()[argLoc+1];\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-controlfile\"){\n casecontrolColumns.inFile <- commandArgs()[argLoc+1];\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-repfiles\"){\n rep.case.outFile <- commandArgs()[argLoc+1];\n rep.control.outFile <- commandArgs()[argLoc+2];\n createReplicates <- FALSE;\n argLoc <- argLoc + 2;\n }\n else if(commandArgs()[argLoc] == \"-controlsfirst\"){\n controlsFirst <- TRUE;\n }\n else if(commandArgs()[argLoc] == \"-sort\"){\n sortValues <- TRUE;\n }\n else if(commandArgs()[argLoc] == \"-strictGT\"){\n combineComplementary <- FALSE;\n }\n else if(commandArgs()[argLoc] == \"-strictChi\"){\n strictChi <- TRUE;\n }\n else if(commandArgs()[argLoc] == \"-proportion\"){\n replicates.proportion <- as.numeric(commandArgs()[argLoc+1]);\n cat(file=stderr(), \"setting proportion to\", replicates.proportion,\n \"(\",replicates.proportion*100,\"% )\\n\");\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-casereps\"){\n replicates.cases <- as.numeric(commandArgs()[argLoc+1]);\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-count\"){\n bootstrap.count <- as.numeric(commandArgs()[argLoc+1]);\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-controlreps\"){\n replicates.controls <- as.numeric(commandArgs()[argLoc+1]);\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-output\"){\n bootstraps.outFile <- commandArgs()[argLoc+1];\n argLoc <- argLoc + 1;\n }\n else if(commandArgs()[argLoc] == \"-method\"){\n processMethod <- commandArgs()[argLoc+1];\n argLoc <- argLoc + 1;\n }\n else {\n cat(\"Error: Argument '\",commandArgs()[argLoc],\n \"' is not understood by this program\\n\\n\", sep=\"\");\n usage();\n quit(save = \"no\", status=0);\n }\n }\n argLoc <- argLoc + 1;\n}\n\nif(!file.exists(casecontrolColumns.inFile)){\n cat(\"Error: No valid case/control column file given\\n\\n\");\n usage();\n quit(save = \"no\", status=1);\n}\n\nif((bootstraps.outFile != \"\") && (file.exists(bootstraps.outFile))){\n cat(\"Error: Output file (\", bootstraps.outFile,\n \") exists, please delete it before running this program\\n\\n\",sep=\"\");\n usage();\n quit(save = \"no\", status=1);\n}\n\nif(!createReplicates && (!file.exists(rep.case.outFile) || !file.exists(rep.control.outFile))){\n cat(\"Error: Replicate files do not exist\\n\\n\");\n usage();\n quit(save = \"no\", status=1);\n}\n\n## carries out a chisquare test of a vector, assuming entries 1..n/2\n## are observed, n/2+1..n are expected counts.\nvector.chisq <- function(in.vector){\n if(!is.vector(in.vector)){\n stop(\"Can only be called on a vector\");\n }\n if(length(in.vector) %% 2 == 1){\n stop(\"observed, expected must be same length\");\n }\n obs <- in.vector[seq(1,length(in.vector)/2)];\n exp <- in.vector[seq(length(in.vector)/2+1,length(in.vector))];\n ## last section taken (and simplified) from chisq.test code\n ## rescale expected values to same totals as observed values\n E = sum(obs) * exp / sum(exp);\n chisq.values <- (obs-E)^2/E;\n ## !is.nan removes NaN values from result, so cells with zero\n ## !expected counts are ignored\n if(!strictChi){\n return(sum(chisq.values[!is.nan(chisq.values)]));\n } else {\n return(sum((obs-E)^2/E));\n }\n ## don't warn about counts < 5 -- it will flood the output with\n ## warnings for markers in a whole genome\n}\n\nGTCalc <- function(in.genotypes, columns.pop1, columns.pop2, method = \"Adelta\"){\n num.reps <- dim(columns.pop1)[2];\n ## make everything upper case (simplifies search expressions)\n in.genotypes <- toupper(in.genotypes);\n if(combineComplementary){\n ## substitute complementary alleles\n in.genotypes <- gsub(\"T\",\"A\",in.genotypes);\n in.genotypes <- gsub(\"G\",\"C\",in.genotypes);\n in.genotypes <- gsub(\"CA\",\"AC\",in.genotypes);\n }\n ## calculate major/minor alleles\n gt.counts <- table(in.genotypes);\n if(sum(gt.counts) == 0){ # no individuals\n return(rep(NA, num.reps));\n }\n allele.names <- unique(sub(\"(A|C|G|T)\",\"\",names(gt.counts)));\n homozygous.counts <- sort(gt.counts[paste(allele.names, allele.names, sep=\"\")]);\n if(sum(homozygous.counts) == 0){ # no homozygous individuals\n return(rep(NA, num.reps));\n }\n minor.allele <- substr(names(homozygous.counts[1]),1,1);\n major.allele <- substr(names(homozygous.counts[length(homozygous.counts)]),1,1);\n if(major.allele == minor.allele){ # no minor allele (from homozygous counts)\n het.potentials <- names(gt.counts[grep(major.allele,names(gt.counts))]);\n if(length(het.potentials) == 1){ # no heterozygotes found, so no minor allele\n minor.allele <- \"\";\n# return(rep(NA, num.reps));\n } else {\n het.name <- het.potentials[het.potentials !=\n paste(major.allele, major.allele, sep=\"\")];\n minor.allele <- sub(major.allele, \"\", het.name);\n }\n }\n ## recode tables as Major/minor (as plink says it *should* be doing)\n ## by substituting alleles for M/m\n ## Note: everything that isn't M/m is considered an invalid\n ## genotype, so if mutation is trimorphic or tetramorphic, then only\n ## the most frequent homozygotes and least frequent homozygotes will\n ## be counted\n if(minor.allele != \"\"){\n in.genotypes <- gsub(major.allele,\"M\",gsub(minor.allele,\"m\",in.genotypes));\n } else {\n in.genotypes <- gsub(major.allele,\"M\",in.genotypes);\n }\n in.genotypes <- sub(\"Mm\",\"mM\",in.genotypes); # make heterozygotes consistently mM\n in.genotypes <- factor(in.genotypes, levels = c(\"MM\",\"mM\",\"mm\", NA));\n ## generate table based on genotype frequencies\n table1 <- apply(columns.pop1, 2, function(x){table(in.genotypes[x], exclude = NULL)})\n table2 <- apply(columns.pop2, 2, function(x){table(in.genotypes[x], exclude = NULL)})\n ## replace row name with \"XX\"\n rownames(table1)[is.na(rownames(table1))] <- \"XX\";\n rownames(table2)[is.na(rownames(table2))] <- \"XX\";\n ## return NA if there are no [non-null] genotypes for either population\n if((sum(table1[c(\"MM\",\"mM\",\"mm\"),]) == 0) ||\n (sum(table2[c(\"MM\",\"mM\",\"mm\"),]) == 0)){\n return(rep(NA, num.reps));\n }\n ## at this point, table1/2 will look like the following:\n ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n ## MM 12 11 10 10 11 12 12 12 11 11\n ## mM 41 42 44 43 42 43 42 43 44 43\n ## mm 32 32 31 32 32 30 31 30 30 31\n ## XX 0 0 0 0 0 0 0 0 0 0\n ## table1: cases, table2: controls\n ## Rows are genotypes, columns are bootstrap number. MM,mM,mm are\n ## the raw genotype counts, XX is a null/bad genotype.\n ## Next step, calculate appropriate statistic\n if(method == \"GTdelta\") { # genotype freq based delta\n ## remove null values, scale for number of individuals\n table1a <- table1[c(\"MM\",\"mM\",\"mm\"),]/\n colSums(as.matrix(table1[c(\"MM\",\"mM\",\"mm\"),]));\n table2a <- table2[c(\"MM\",\"mM\",\"mm\"),]/\n colSums(as.matrix(table2[c(\"MM\",\"mM\",\"mm\"),]));\n retVal <-\n colSums(abs(table1a - table2a))/2;\n } else if(method == \"Adelta\") { # allele freq based delta\n ## convert to allele frequencies, scale for number of [non-null]\n ## individuals\n table1a <- (table1[\"MM\",]+table1[\"mM\",]/2) /\n colSums(as.matrix(table1[c(\"MM\",\"mM\",\"mm\"),]));\n table2a <- (table2[\"MM\",]+table2[\"mM\",]/2) /\n colSums(as.matrix(table2[c(\"MM\",\"mM\",\"mm\"),]));\n ## note: if only two alleles, then comparing one allele is the\n ## same as comparing both and dividing by two\n retVal <-\n abs(table1a - table2a);\n } else if((method == \"Chisqmax\")|| # Max chi square\n (method == \"ChisqmaxAll\")||\n (method == \"gChisq\")||\n (method == \"ShowValues\")) {\n\n ## calculations for observed, expected derived from plink code\n obs.1 <- colSums(as.matrix(table1[c(\"mm\",\"mM\",\"MM\"),]));\n obs.2 <- colSums(as.matrix(table2[c(\"mm\",\"mM\",\"MM\"),]));\n obs.all <- obs.1+obs.2;\n obs.mm <- (table1[\"mm\",] + table2[\"mm\",]);\n obs.mM <- (table1[\"mM\",] + table2[\"mM\",]);\n obs.MM <- (table1[\"MM\",] + table2[\"MM\",]);\n obs.m <- 2*obs.mm + obs.mM;\n obs.M <- 2*obs.MM + obs.mM;\n exp.1.m <- (obs.1 * obs.m) / obs.all;\n exp.1.M <- (obs.1 * obs.M) / obs.all;\n exp.2.m <- (obs.2 * obs.m) / obs.all;\n exp.2.M <- (obs.2 * obs.M) / obs.all;\n exp.1.mm <- (obs.1 * obs.mm) / obs.all;\n exp.1.mM <- (obs.1 * obs.mM) / obs.all;\n exp.1.MM <- (obs.1 * obs.MM) / obs.all;\n exp.2.mm <- (obs.2 * obs.mm) / obs.all;\n exp.2.mM <- (obs.2 * obs.mM) / obs.all;\n exp.2.MM <- (obs.2 * obs.MM) / obs.all;\n\n ## calculate genotype statistics for each homozygote vs others\n\n ## Dominant -DOM.CHISQ (testing major allele genotypes vs other)\n ## i.e. minor allele is dominant\n dom.test <- rbind(table1[\"mm\",]+table1[\"mM\",],\n table1[\"MM\",],\n table2[\"mm\",]+table2[\"mM\",],\n table2[\"MM\",],\n exp.1.mm+exp.1.mM,\n exp.1.MM,\n exp.2.mm+exp.2.mM,\n exp.2.MM);\n # cat(\"dom.chisq =\",mean(apply(dom.test,2,vector.chisq)));\n\n ## Recessive -REC.CHISQ (testing minor allele genotypes vs other)\n ## i.e. minor allele is recessive\n rec.test <- rbind(table1[\"mm\",],\n table1[\"MM\",]+table1[\"mM\",],\n table2[\"mm\",],\n table2[\"MM\",]+table2[\"mM\",],\n exp.1.mm,\n exp.1.MM+exp.1.mM,\n exp.2.mm,\n exp.2.MM+exp.2.mM);\n # cat(\", rec.chisq =\",mean(apply(rec.test,2,vector.chisq)));\n\n ## CA trend test -TREND.CHISQ\n ## Note: this assumes allele 1: minor, allele 2: Major\n CA <- ((obs.2/obs.all * table1[\"mM\",]) - (obs.1/obs.all * table2[\"mM\",])) +\n 2 * ((obs.2/obs.all * table1[\"MM\",]) - (obs.1/obs.all * table2[\"MM\",]));\n var.CA <- obs.1 * obs.2 *\n (( obs.all * ( obs.mM + 4 * obs.MM )\n - ( obs.mM + 2 * obs.MM )^2 )\n / (obs.all^3));\n CA.chisq <- (CA^2) / var.CA;\n # cat(\", CA.chisq =\",mean(CA.chisq));\n if ((method == \"ChisqmaxAll\") || (method == \"ShowValues\") || (method == \"gChisq\")) {\n geno.test <- rbind(table1[\"mm\",],\n table1[\"mM\",],\n table1[\"MM\",],\n table2[\"mm\",],\n table2[\"mM\",],\n table2[\"MM\",],\n exp.1.mm,\n exp.1.mM,\n exp.1.MM,\n exp.2.mm,\n exp.2.mM,\n exp.2.MM);\n # cat(\", geno.chisq =\",mean(apply(geno.test,2,vector.chisq)));\n\n ## Multiplicative / Allelic (actually testing allele quantities of m vs M)\n mult.test <- rbind(2*table1[\"mm\",]+table1[\"mM\",],\n 2*table1[\"MM\",]+table1[\"mM\",],\n 2*table2[\"mm\",]+table2[\"mM\",],\n 2*table2[\"MM\",]+table2[\"mM\",],\n exp.1.m,\n exp.1.M,\n exp.2.m,\n exp.2.M);\n # cat(\", mult.chisq =\",mean(apply(mult.test,2,vector.chisq)),\"\\n\");\n }\n ## -1 needed in apply to avoid warnings\n if(method == \"Chisqmax\"){\n retVal <-\n apply(rbind(\n CA.chisq,\n apply(dom.test,2,vector.chisq),\n apply(rec.test,2,vector.chisq),\n -Inf),2,max, na.rm = TRUE);\n } else if (method == \"gChisq\") {\n retVal <-\n apply(geno.test,2,vector.chisq);\n } else if (method == \"ChisqmaxAll\") {\n retVal <-\n apply(rbind(\n CA.chisq,\n apply(geno.test,2,vector.chisq),\n apply(mult.test,2,vector.chisq),\n apply(dom.test,2,vector.chisq),\n apply(rec.test,2,vector.chisq),\n -Inf),2,max, na.rm = TRUE);\n } else if (method == \"ShowValues\") {\n retVal <-\n apply(rbind(\n CA.chisq,\n apply(geno.test,2,vector.chisq),\n apply(mult.test,2,vector.chisq),\n apply(dom.test,2,vector.chisq),\n apply(rec.test,2,vector.chisq)),2,paste, collapse = \",\");\n }\n } else {\n retVal <- NULL;\n }\n ## retVal should be a vector of values, with length equal to the\n ## number of bootstraps\n return(retVal);\n}\n\n## matmap -- maps a vector onto a matrix of indexes to the vector\nmatmap <- function(vector.in, matrix.indices){\n if(max(matrix.indices) > length(vector.in)){\n cat(\"Error: maximum index greater than vector length\\n\", file = stderr());\n }\n res <- vector.in[matrix.indices];\n if(is.null(dim(matrix.indices))){\n dim(res) <- c(length(matrix.indices),1);\n } else {\n dim(res) <- dim(matrix.indices);\n }\n return(res);\n}\n\n\n## carries out allele frequency based delta on a single line of simplegt input\nprocessLine <-\n function(marker.name, genotypes, popSamples1, popSamples2, output.file = \"\",\n append = TRUE, GTmethod = \"Adelta\", sortbyValue = FALSE){\n# cat(dim(popSamples1), \"\\n\", file=stderr());\n if(length(marker.name) > 1){\n stop(\"Cannot process more than one line at a time\");\n }\n if((length(marker.name) == 0) || (marker.name == \"\")){\n stop(\"Empty input: input is not valid\");\n }\n bs.results <-\n GTCalc(genotypes,popSamples1,popSamples2,GTmethod);\n ## output 1 line per result\n if(sortValues){\n bs.order <- rev(order(bs.results));\n } else {\n bs.order <- 1:length(bs.results);\n }\n if((GTmethod == \"ShowValues\") && (append == FALSE)){\n cat(\"marker,bs.run,CA.chisq,geno.test,mult.test,dom.test,rec.test\\n\",\n file = output.file, append = FALSE);\n write.table(data.frame(marker = marker.name, bs.run = bs.order,\n bs.value = bs.results[bs.order]),\n output.file, sep = \",\", quote = FALSE, append = TRUE,\n col.names = FALSE, row.names = FALSE);\n } else {\n write.table(data.frame(marker = marker.name, bs.run = bs.order,\n bs.value = bs.results[bs.order]),\n output.file, sep = \",\", quote = FALSE, append = append,\n col.names = !append, row.names = FALSE);\n }\n}\n\ncasecontrolColumns.con <- file(casecontrolColumns.inFile);\nopen(casecontrolColumns.con);\n\nif(controlsFirst){\n controls.columns <-\n as.numeric((strsplit(readLines(casecontrolColumns.con, n = 1),\" \")[[1]])[-1]);\n cases.columns <-\n as.numeric((strsplit(readLines(casecontrolColumns.con, n = 1),\" \")[[1]])[-1]);\n} else {\n cases.columns <-\n as.numeric((strsplit(readLines(casecontrolColumns.con, n = 1),\" \")[[1]])[-1]);\n controls.columns <-\n as.numeric((strsplit(readLines(casecontrolColumns.con, n = 1),\" \")[[1]])[-1]);\n}\nclose(casecontrolColumns.con);\n\nif(is.null(replicates.cases)){\n replicates.cases <- min(length(cases.columns) - 5,\n trunc(length(cases.columns)*replicates.proportion));\n}\n\nif(is.null(replicates.controls)){\n replicates.controls <- min(length(controls.columns) - 5,\n trunc(length(controls.columns)*replicates.proportion));\n}\n\n## generate bootstrap replicates first. This improves speed and\n## maintains a consistent population subsample across multiple SNPs.\n## note: this is sampling with replacement\n## file to place subsample columns into\ncases.samples <- NULL;\ncontrols.samples <- NULL;\nif(createReplicates){\n rep.case.outFile = paste(\"caseReplicates\",bootstraps.outFile,sep=\"_\");\n rep.control.outFile = paste(\"controlReplicates\",bootstraps.outFile,sep=\"_\");\n cases.samples <- replicate(bootstrap.count,\n sample(cases.columns,replicates.cases));\n controls.samples <- replicate(bootstrap.count,\n sample(controls.columns,replicates.controls));\n ## write out replicates to a file, in case validation is needed\n write.table(t(cases.samples),rep.case.outFile, quote = FALSE,\n col.names = FALSE);\n write.table(t(controls.samples),rep.control.outFile, quote = FALSE,\n col.names = FALSE);\n} else {\n cases.samples <- t(read.table(rep.case.outFile, row.names = 1));\n controls.samples <- t(read.table(rep.control.outFile, row.names = 1));\n dcc <- c(dim(cases.samples), dim(controls.samples));\n cat(sprintf(\"Retrieved data for %d bootstraps (cases %d x %d, controls %d x %d)\\n\",\n dcc[2], dcc[1], dcc[2], dcc[3], dcc[4]), file = stderr());\n}\n\nif(genotypes.inFile != \"\"){\n genotypes.con <- gzfile(genotypes.inFile);\n open(genotypes.con)\n} else {\n genotypes.con <- file(\"stdin\");\n open(genotypes.con)\n}\n\ninput.line <- scan(genotypes.con, what = character(), nlines = 1, quiet = TRUE);\nwhile((length(input.line)>0) && (substr(input.line[1],1,1) == \"#\")){\n input.line <- scan(genotypes.con, what = character(), nlines = 1, quiet = TRUE);\n}\n\nnum.indivs <- length(input.line[-1]);\nif(num.indivs != (length(cases.columns) + length(controls.columns))){\n cat(sprintf(\"Warning: number of individuals detected on first line (%d) is not the same as number of cases (%d) + number of controls (%d)\\n\", num.indivs, length(cases.columns), length(controls.columns)), file = stderr());\n}\n\n## process line *without* append (creates header)\nprocessLine(input.line[1], input.line[-1], cases.samples, controls.samples,\n append = FALSE, output.file = bootstraps.outFile,\n GTmethod = processMethod, sortbyValue = sortValues);\ninput.line <- scan(genotypes.con, what = character(), nlines = 1, quiet = TRUE);\nwhile((length(input.line)>0) && (substr(input.line[1],1,1) == \"#\")){\n input.line <- scan(genotypes.con, what = character(), nlines = 1, quiet = TRUE);\n}\nline.number <- 1;\nwhile(length(input.line) > 0){\n ## process line *with* append (no header)\n processLine(input.line[1], input.line[-1], cases.samples, controls.samples,\n append = TRUE, output.file = bootstraps.outFile,\n GTmethod = processMethod, sortbyValue = sortValues);\n line.number <- line.number+1;\n if(line.number %% 1000 == 0){\n cat(\".\", file = stderr());\n }\n input.line <- scan(genotypes.con, what = character(), nlines = 1, quiet = TRUE);\n while((length(input.line)>0) && (substr(input.line[1],1,1) == \"#\")){\n input.line <- scan(genotypes.con, what = character(), nlines = 1, quiet = TRUE);\n }\n}\nif(genotypes.inFile != \"\"){\n close(genotypes.con);\n}\n\nif(line.number > 1){\n cat(\"(\",line.number,\" lines processed)\\n\", file = stderr(), sep = \"\");\n} else {\n cat(\"(\",line.number,\" line processed)\\n\", file = stderr(), sep = \"\");\n}\n", "meta": {"hexsha": "8212f7323658ce9d2ebb8ed2b2f0da6c9a1b259b", "size": 22421, "ext": "r", "lang": "R", "max_stars_repo_path": "bootstrap.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": "bootstrap.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": "bootstrap.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": 40.9142335766, "max_line_length": 223, "alphanum_fraction": 0.5821328219, "num_tokens": 6137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180125441397, "lm_q2_score": 0.027585281427362537, "lm_q1q2_score": 0.010720137243772397}} {"text": "##################################################################################\n# Dynamic + vectorized \n# This code runs a Bonica-like algorithm to provide a longitudinal view of IFE's\n# Council General. \n# 27 Mar 2021 \n##################################################################################\n\nlibrary(arm)\nlibrary (MCMCpack)\nlibrary (foreign)\nlibrary (car)\nlibrary (gtools)\n#library (multicore)\nlibrary (R2jags)\nlibrary (mcmcplots)\nlibrary (sm)\nlibrary(lubridate)\n#\nlibrary (runjags)\nlibrary (coda)\n\n# un cambio minimo \nrm(list = ls())\nworkdir <- c(\"/home/eric/Dropbox/data/rollcall/ife_cg/ife-update/data/\")\nsetwd(workdir)\n\n# Define colors and plotting names\n# OJO: en tenure term==10 es a, term==11 es b etc. \n\nids <- matrix(c(\n ## \"Woldenberg\", \"woldenberg\", \"PRI\", \"23\",\n ## \"Barrag?n\", \"barragan\", \"PRD\", \"23\",\n ## \"Cant?\", \"cantu\", \"PRD\", \"23\",\n ## \"C?rdenas\", \"cardenas\", \"PRD\", \"23\",\n ## \"Lujambio\", \"lujambio\", \"PAN\", \"23\",\n ## \"Merino\", \"merino\", \"PRI\", \"23\",\n ## \"Molinar\", \"molinar\", \"PAN\", \"2\" ,\n ## \"Peschard\", \"peschard\", \"PRI\", \"23\",\n ## \"Zebad?a\", \"zebadua\", \"PRD\", \"2\" ,\n ## \"Rivera\", \"rivera\", \"PRI\", \"3\",\n ## \"Luken\", \"luken\", \"PAN\", \"3\",\n #\n \"Ugalde\", \"ugalde\", \"PRI\", \"4\",\n \"Albo\", \"albo\", \"PAN\", \"456\",\n \"Andrade\", \"andrade\", \"PRI\", \"4567\", \n \"Gmz. Alc?ntar\", \"alcantar\", \"PVEM\", \"4567\",\n \"Glez. Luna\", \"glezluna\", \"PAN\", \"456\",\n \"Latap?\", \"latapi\", \"PRI\", \"45\",\n \"L?pez Flores\", \"lopezflores\", \"PRI\", \"456\",\n \"Morales\", \"morales\", \"PAN\", \"45\",\n \"S?nchez\", \"sanchez\", \"PAN\", \"4567c\",\n \"Vald?s\", \"valdes\", \"PRD\", \"6789a\",\n \"Ba?os\", \"banos\", \"PRI\", \"6789abcde\",\n \"Nacif\", \"nacif\", \"PAN\", \"6789abcde\",\n \"Elizondo\", \"elizondo\", \"PAN\", \"789a\",\n \"Figueroa\", \"figueroa\", \"PRD\", \"789a\",\n \"Guerrero\", \"guerrero\", \"PRI\", \"789a\",\n \"C?rdova\", \"cordova\", \"PRD\", \"9abcdef\",\n \"Garc?a Rmz.\", \"garcia\", \"PRI\", \"9\" ,\n \"Marv?n\", \"marvan\", \"PAN\", \"9ab\",\n \"E. Andrade\", \"andrade2\", \"\", \"cde\",\n \"Favela\", \"favela\", \"\", \"cdef\",\n \"Santiago\", \"santiago\", \"\", \"c\",\n \"Galindo\", \"galindo\", \"\", \"c\",\n \"Murayama\", \"murayama\", \"\", \"cdef\",\n \"Ruiz Salda?a\", \"ruiz\", \"\", \"cdef\",\n \"San Mart?n\", \"snmartin\", \"\", \"cde\",\n \"Santiago\", \"santiago\", \"\", \"c\",\n \"Ravel\", \"ravel\", \"\", \"def\",\n \"J. Rivera\", \"rivera2\", \"\", \"def\",\n \"Zavala\", \"zavala\", \"\", \"def\",\n \"De la Cruz\", \"magana\", \"\", \"f\",\n \"Faz\", \"faz\", \"\", \"f\",\n \"Humphrey\", \"humphrey\", \"\", \"f\",\n \"Kib Espadas\", \"kib\", \"\", \"f\"),\n ncol = 4,\n byrow = TRUE)\n#\nids <- as.data.frame(ids, stringsAsFactors = FALSE)\ncolnames(ids) <- c(\"name\", \"column\", \"pty\", \"tenure\") \n#ids$tenure <- as.numeric(ids$tenure)\nids <- within(ids, party <- ifelse (pty==\"PRI\", 1,\n ifelse (pty==\"PAN\", 2,\n ifelse (pty==\"PRD\", 3, \n ifelse(pty==\"PVEM\", 4, 5)))))\nids <- within(ids, color <- ifelse (pty==\"PRI\", \"red\",\n ifelse (pty==\"PAN\", \"blue\",\n ifelse (pty==\"PRD\", \"gold\",\n ifelse(pty==\"PVEM\", \"green\", \"orangered4\")))))\nids # inspect\n\n\n####################################################################\n## select terms for analysis, e.g. for 4-11(b) \"[456789ab]\" works ##\n####################################################################\ntees <- c(\"6\",\"7\",\"8\",\"9\",\"a\")\ntees.grep <- \"[6789a]\"\nT <- length(tees)\n#\nsel <- grep(pattern = tees.grep, ids$tenure)\nname <- ids$name[sel]\nparty <- ids$party[sel]\ncolor <- ids$color[sel]\ncolumn <- ids$column[sel]\n\n## rgb.23 <- c(length=11)\n## rgb.23[c(1,6,8,10)] <- rgb(1, 0, 0, 0.6) #red\n## rgb.23[c(2:4,9)] <- rgb(1, 215/255, 0, 0.6) #gold\n## rgb.23[c(5,7,11)] <- rgb(0, 0, 1, 0.6) #blue\n\n############################################\n## Read votes ##\n## exported to disk by code/data-prep.r ##\n############################################\n#vot23 <- read.csv(\"v23.csv\" , header=TRUE)\nvot4on <- read.csv( \"v456789ab.csv\", header=TRUE)\n# choose what votes will be analyzed\n#vot <- vot23 # Woldenberg\nvot <- vot4on # Ugalde-Vald?s-C?rdova\n#colnames(vot)\n# subset to votes in chosen periods\nsel.r <- which(vot$term %in% tees)\ndrop.c <- ids$column[grep(pattern = tees.grep, ids$tenure)] # column names not in terms selected\ndrop.c <- setdiff(ids$column, drop.c)\ndrop.c <- which(colnames(vot) %in% drop.c)\nif (length(drop.c)>0) vot <- vot[sel.r, -drop.c]\ncolnames(vot)\n# total members\nJ <- length(name); J\n\n########################\n## recode vote values ##\n########################\nvs <- vot[,1:J]\n#table(v$albo, useNA = \"always\")\nvs[vs==0] <- NA ## Version probit requiere 0s y 1s\nvs[vs>2] <- NA\nvs[vs==2] <- 0\n\n# format dates\nvot$date <- ymd(vot$date)\n# summarize then drop uncontested votes\ntable(factor(vot$dunan, labels = c(\"contested\",\"not\")), vot$term, useNA = \"ifany\")\ntable(factor(vot$dunan, labels = c(\"contested\",\"not\")), useNA = \"ifany\")\nsel <- which(vot$dunan==1)\nif (length(sel)>0){\n vot <- vot[-sel,] # drop uncontested votes\n vs <- vs [-sel,] # drop uncontested votes\n}\n\n\n\n## ###########\n## ## MODEL ##\n## ###########\n## model1Dj.irt <- function() {\n## for (j in 1:J){ ## loop over respondents\n## for (i in 1:I){## loop over items\n## v[j,i] ~ dbern(p[j,i]); ## voting rule\n## probit(p[j,i]) <- mu[j,i]; ## sets 0I] <- I\nitem.date <- vot$date #ymd(vot$yr*10000+vot$mo*100+vot$dy)\nS <- length(inicio)\n\n\n# We need a matrix showing whether each councilor is actually in IFE the moment the vote takes place --- will be subset to J below\nIsCouncilor <- matrix (1, ncol=18, nrow=S)\nIsCouncilor[ vot$term < 4 | vot$term > 4,1 ] <- NA # ugalde 1\nIsCouncilor[ vot$term < 4 | vot$term > 6,2 ] <- NA # albo 2\nIsCouncilor[ vot$term < 4 | vot$term > 7,3 ] <- NA # andrade 3\nIsCouncilor[ vot$term < 4 | vot$term > 7,4 ] <- NA # alcantar 4\nIsCouncilor[ vot$term < 4 | vot$term > 6,5 ] <- NA # glezluna 5\nIsCouncilor[ vot$term < 4 | vot$term > 5,6 ] <- NA # latapi 6\nIsCouncilor[ vot$term < 4 | vot$term > 6,7 ] <- NA # lopezflores 7\nIsCouncilor[ vot$term < 4 | vot$term > 5,8 ] <- NA # morales 8\nIsCouncilor[ vot$term < 4 |(vot$term > 7 & vot$term!=12),9 ] <- NA # sanchez 9\nIsCouncilor[ vot$term < 6 | vot$term > 10,10] <- NA # valdes 10\nIsCouncilor[ vot$term < 6 | vot$term > 14,11] <- NA # banos 11\nIsCouncilor[ vot$term < 6 | vot$term > 14,12] <- NA # nacif 12\nIsCouncilor[ vot$term < 7 | vot$term > 10,13] <- NA # elizondo 13\nIsCouncilor[ vot$term < 7 | vot$term > 10,14] <- NA # figueroa 14\nIsCouncilor[ vot$term < 7 | vot$term > 10,15] <- NA # guerrero 15\nIsCouncilor[ vot$term < 9 | vot$term > 15,16] <- NA # cordova 16\nIsCouncilor[ vot$term < 9 | vot$term > 9,17] <- NA # garcia rmz 17\nIsCouncilor[ vot$term < 9 | vot$term > 11,18] <- NA # marvan 18\n####################################################\n## vector to select members present in estimation ##\n####################################################\nsel.members <- which(ids$name %in% name)\nIsCouncilor <- IsCouncilor[, sel.members]\n\n\n# Round 1 ideal points to anchor ideological space\n# (later entrants at party mean)\n# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25\n# u a a a g l l m s v b n e f g c g m a f g m r s s \n# g l n l l a p o a a a a l i u o a a n a a u u n a\n# a b d c z t z r n l ? c i g e r r r d v l r i m n\n# l o r a l a f a c d o i z u r d c v r e i a z a t\nx.location <- c(0, 0, 0, 2, 0, 0, 0, 0,-2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)[sel.members] # sel = members in estimation\nx.precision <- c(1, 1, 1, 4, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)[sel.members]\n#x.location <- c(1, 0, 0, 2,-2, 0, 0, 2,-2, 0, 2,-1,-2, 0, 2,-2, 2,-2, 0, 0, 0, 2, 0, 0, 0)[sel.members] # sel = members in estimation\n#x.precision <- c(4, 1, 1, 4, 4, 4, 1, 4, 4, 1, 4, 4, 4, 1, 4, 4, 4, 4, 1, 1, 1, 4, 1, 1, 1)[sel.members]\n# x.location and x.precision are manipulated by loop, keep a version to use as prior for new entrants instead of party mean\nx.prior.location <- x.location\nx.prior.precision <- x.precision\n#\nwindow.results <- list () ## WILL ADD SESSION'S RESULTS TO OBJECT HOLDING ALL RESULTS\npartyPlacement <- rep (NA,J)\nx.mean <- numeric ()\nx.tau <- numeric ()\n\n\nfor (s in 1:S){ # <= loop over S windows\n #\n #s <- 1 # debug\n councilor.in <- apply (IsCouncilor[inicio[s]:final[s],], 2, invalid)\n councilors <- name [councilor.in==FALSE] # window's info\n abbrev <- column [councilor.in==FALSE] # window's info\n sponsors <- party[councilor.in==FALSE] # window's info\n #\n for (c in 1:J){ # does it for all councilors whther or not present in window (hence J)\n# 5mar21: this uses partyPlacement for new entrants\n# x.mean[c] <- ifelse (!is.na(x.location[c]), x.location[c], partyPlacement[sponsors[c]])\n# x.tau[c] <- ifelse (!is.na(x.precision[c]), x.precision[c], 4)\n# 5mar21: this uses fixed x0 prior for new entrants\n x.mean[c] <- ifelse (!is.na(x.location [c]), x.location [c], x.prior.location [c])\n x.tau[c] <- ifelse (!is.na(x.precision[c]), x.precision[c], x.prior.precision[c])\n }\n #\n v <- vs[inicio[s]:final[s], 1:J][, councilor.in==FALSE]; ## EXTRACT 30 VOTES EACH TIME\n v <- as.data.frame(t(v)) ## ROLL CALLS NEED ITEMS IN COLUMNS, LEGISLATORS IN ROWS\n #\n ###################\n ## Vectorization ##\n ###################\n #J <- nrow(v); I <- ncol(v) ## SESSION TOTALS\n member.index <- 1:nrow(v)\n vote.index <- 1:ncol(v)\n \n ## Melt RC\n rc <- as.data.frame (v)\n colnames (rc) <- vote.index\n rc$member <- member.index\n #\n # determine north/south indexes in vote window\n north <- which(rownames(rc)==\"alcantar\")\n north <- ifelse (length(north)==0, NA, north) # NA if member absent, else her index \n south <- which(rownames(rc)==\"sanchez\")\n south <- ifelse (length(south)==0, NA, south) # NA if member absent, else her index \n #\n molten.rc <- reshape2::melt(rc, id.vars=\"member\", variable.name=\"vote\", value.name=\"rc\")\n #molten.rc$rc <- car::recode (molten.rc$rc, \"0=NA\")\n molten.rc <- na.omit (molten.rc)\n #molten.rc$rc <- car::recode (molten.rc$rc, \"2=0; c(3,4,5)=NA\")\n #\n ife.data.vector <- dump.format(list(\n y = molten.rc$rc\n , n.members = max(member.index)\n , n.item = max(vote.index)\n , n.obs = nrow(molten.rc)\n , vote = molten.rc$vote\n , member = molten.rc$member\n , north = north\n , south = south\n , x.mean = x.mean\n , x.tau = x.tau\n , sponsors = sponsors\n ))\n #\n ife.parameters = c(\"theta\", \"alpha\", \"beta\", \"partyPos\", \"deviance\")\n #\n ife.inits <- function() {\n dump.format(\n list(\n theta = rnorm(max(member.index))\n #theta = c(rnorm(3), NA, rnorm(4), NA, rnorm(max(member.index)-9)) # NAs s?lo en caso de spike priors, correcto?\n , alpha = rnorm(max(vote.index))\n , beta = rnorm(max(vote.index))\n , '.RNG.name'=\"base::Wichmann-Hill\"\n , '.RNG.seed'= 1971) #randomNumbers(n = 1, min = 1, max = 1e+04,col=1))\n )\n }\n #\n ife.model.v <- run.jags(\n model = ife.vector,\n monitor = ife.parameters,\n method = \"parallel\",\n data = ife.data.vector,\n inits = list (ife.inits(), ife.inits()),\n n.chains=2, thin=50, burnin=10000, sample=200,\n #n.chains=1, thin=5, burnin=200, sample=3,\n check.conv=FALSE, plots=FALSE\n )\n #\n chainsIFE.v <- mcmc.list(list (ife.model.v$mcmc[[1]], ife.model.v$mcmc[[2]])) \n gelman.diag (chainsIFE.v, multivariate=F)\n #\n Alpha.v <- rbind ( chainsIFE.v[[1]][,grep(\"alpha\", colnames(chainsIFE.v[[1]]))]\n , chainsIFE.v[[2]][,grep(\"alpha\", colnames(chainsIFE.v[[2]]))])\n Beta.v <- rbind ( chainsIFE.v[[1]][,grep(\"beta\", colnames(chainsIFE.v[[1]]))]\n , chainsIFE.v[[2]][,grep(\"beta\", colnames(chainsIFE.v[[2]]))])\n Theta.v <- rbind ( chainsIFE.v[[1]][,grep(\"theta\", colnames(chainsIFE.v[[1]]))]\n , chainsIFE.v[[2]][,grep(\"theta\", colnames(chainsIFE.v[[2]]))])\n #\n plot (colMeans (Alpha.v)) # difficulties\n plot (colMeans (Beta.v)) # signal\n #\n par (las=2, mar=c(7,3,2,2))\n plot (1:length(vot$date), colMeans (Beta.v)\n , type=\"n\"\n , axes=F, ylim=c(-1,1)\n , xlab=\"\", ylab=\"Ideal point\")\n axis (1, at=seq(1,length(vot$date),8)\n , labels=vot$date[seq(1,length(vot$date),8)], cex=0.8)\n par (las=0)\n mtext (side=1, line=6, text=\"Dates\")\n axis (2)\n for (i in 1:ncol(Theta.v)){\n segments (x0=min (c(1:length(vot$date))[vot[,i] != 0])\n , x1=max (c(1:length(vot$date))[vot[,i] != 0])\n , y0=colMeans (Theta.v)[i]\n , y1=colMeans (Theta.v)[i]\n , col=ids$color[i], lwd=3)\n }\n\t# ADD COUNCILOR NAMES AND VOTE INFO TO RESULTS OBJECT\n results <- c(results, councilors=list(councilors), abbrev=list(abbrev));\n results <- c(results, folio.date=list(vot[s,c(\"folio\",\"dy\",\"mo\",\"yr\")])); # add vote on which window is centered\n window.results <- c(window.results, list(results)); ## ADD SESSION'S RESULTS TO OBJECT HOLDING ALL RESULTS\n# results[[4]] <- GHconv; rm (GHconv)\n#\n\t# Update location of ideal point at time s, to be used as location prior at time s+1\n\tx.location <- rep (NA, J)\n\tx.precision <- rep (100, J)\n#\tlocs <- apply( rbind (results[[1]]$BUGSoutput$sims.list$x, results[[2]]$BUGSoutput$sims.list$x), 2, median)\n#\tpartyPlacement <- apply( rbind (results[[1]]$BUGSoutput$sims.list$partyPos, results[[2]]$BUGSoutput$sims.list$partyPos), 2, median)\n\tlocs <- apply( results$BUGSoutput$sims.list$x, 2, median)\n\tpartyPlacement <- apply( results$BUGSoutput$sims.list$partyPos, 2, median)\n\tfor (n in 1:J){\n\t\tif (length( which(councilors==name[n]) )==0) { # if councilor not member current round\n\t\t\tx.location[n] <- NA # then prior for next round set to NA\n\t\t\tx.precision[n] <- NA # (and line above sets it to party placement)\n\t\t}\n\t\telse { x.location[n] <- locs[which (councilors==name[n])] } # councilor's prior for next round is current x \n\t}\n\t# Precision prior is always constant at 100, implying standard deviation = sqrt (1/100) = 0.1\n} # <--- END OF LOOP OVER WINDOWS\n\n\n# plot results\ntit <- \"Terms 67 (Vald?s 2007-2010), Bonica method\"\nsource(\"../code/plot-posteriors.r\")\nx\n\n# rename object with posterior sims\nsummary(window.results[[190]])\nwindow.results.67 <- window.results\nrm(window.results)\n\n# clean\nls()\nrm(c, s, n, v, sel, ife.inits, ife.parameters, ife.data)\nrm(councilors, sponsors, inicio, final, councilor.in)\nrm(x.location, x.mean, x.precision, x.tau, item, results, item.date)\nrm(color, column, locs, name, party, partyPlacement)\n\n# save\nsummary(window.results.67)\n#summary(window.results[[232]]) # 11 members, overlap\nsave.image(file = \"posterior-samples/vald67-window-results-compress.RData\", compress = \"xz\")\n#save(window.results.23, file = \"posterior-samples/wold23-window-results-compress.RData\")\nx\n\n\n\n# Save window.results, containing all chains from all runs\n# save (window.results, file=\"DynUgaldeBonicaMarch21.RData\") # With more anchors\n# save (window.results, file=\"DynUgaldeBonicaMarch19.RData\")\n# save (window.results, file=\"DynUgaldeBonica.RData\")\n\nsource(\"http://rtm.wustl.edu/code/sendEmail.R\")\n#sendEmail (subject=\"Ugalde et al esta listo\", text=\"\", address=\"rosas.guillermo@gmail.com\")\nsendEmail (subject=\"Ugalde et al esta listo\", text=\"\", address=\"emagar@gmail.com\")\n\n# RData file with runs carried out in Mexico, early March\n# load (\"DynUgaldeBonica.RData\")\n\n# RData file with runs carried out in Wash U, March 19\n# These runs omit non-sitting Councilors and party precisions for new Councilors\nload (\"DynUgaldeBonicaMarch21.RData\")\n\n\n\n\nS <- length (semester.results)\nmultiGelman.hat <- numeric ()\nfor (i in 1:S){\n\tchainsConv <- mcmc.list(list (as.mcmc (semester.results[[i]][[2]]$BUGSoutput$sims.list$x), as.mcmc (semester.results[[i]][[1]]$BUGSoutput$sims.list$x)))\n\ttmp <- gelman.diag (chainsConv)[[2]]\n\tmultiGelman.hat <- c(multiGelman.hat, tmp)\n}\nrm (tmp, chainsConv)\n\nnonConverged <- ifelse (multiGelman.hat > 2, 1, 0) # Should be 0\n\n\nCouncilorIn <- matrix (1, nrow=J, ncol=S)\nCouncilorIn[1, all45678901$date > 20071217] <- NA\nCouncilorIn[2, all45678901$date > 20080814] <- NA\nCouncilorIn[3, all45678901$date > 20101027] <- NA\nCouncilorIn[4, all45678901$date > 20101027] <- NA\nCouncilorIn[5, all45678901$date > 20080814] <- NA\nCouncilorIn[6, all45678901$date > 20071217] <- NA\nCouncilorIn[7, all45678901$date > 20080814] <- NA\nCouncilorIn[8, all45678901$date > 20071217] <- NA\nCouncilorIn[9, all45678901$date > 20101027] <- NA\nCouncilorIn[10, all45678901$date < 20080215] <- NA\nCouncilorIn[11, all45678901$date < 20080215] <- NA\nCouncilorIn[12, all45678901$date < 20080215] <- NA\nCouncilorIn[13, all45678901$date < 20080829] <- NA\nCouncilorIn[14, all45678901$date < 20080829] <- NA\nCouncilorIn[15, all45678901$date < 20080829] <- NA\n#CouncilorIn[16, all45678901$date < 20111215] <- NA\n#CouncilorIn[17, all45678901$date < 20111215] <- NA\n#CouncilorIn[18, all45678901$date < 20111215] <- NA\n\n\n\n# If using DynUgaldeBonica.RData, use the following code to extract ideal points\nideal.points <- matrix (NA, nrow=S, ncol=J)\nfor (i in 1:S){\n\tideal.points[i,] <- apply (rbind (semester.results[[i]][[1]]$BUGSoutput$sims.list$x, semester.results[[i]][[2]]$BUGSoutput$sims.list$x), 2, median)\n}\n\n# If using DynUgaldeBonicaMarch19.RData or DynUgaldeBonicaMarch21.RData, use the following code to extract ideal points\nideal.points <- matrix (NA, nrow=S, ncol=J)\nideal.points.var <- matrix (NA, nrow=S, ncol=J)\nfor (i in 1:S){\n\tfor (j in 1:J){\n\t\tcouncilor <- names45678901[j]\n\t\tnum <- which (semester.results[[i]][[3]]==councilor)\n\t\tif ( length (num)==0 ) {\n\t\t\tideal.points[i,j] <- 1\n\t\t\tideal.points.var[i,j] <- 0\n\t\t} else {\n\t\t\t\tideal.points[i,j] <- median (c (semester.results[[i]][[1]]$BUGSoutput$sims.list$x[,num], semester.results[[i]][[2]]$BUGSoutput$sims.list$x[,num]))\n\t\t\t\tideal.points.var[i,j] <- var (c (semester.results[[i]][[1]]$BUGSoutput$sims.list$x[,num], semester.results[[i]][[2]]$BUGSoutput$sims.list$x[,num]))\n\t\t}\n\t}\n}\n\n\n# Plot different individual councilor paths:\n# There is definitely a problem at different spots of the estimation:\n# Between i=200 and i=500 and after i=600\n# The problem really obtains when we get new guys in\n# Valdes, Banos, Nacif, Elizondo, Figueroa, Guerrero come in in quick succession and destroy everything\n# Maybe the best solution is to break down estimation of this very long period in two or three chunks\n# Or maybe we need to combine priors on ideal points with priors on item parameters\nk <- 12\nplot (ideal.points[ideal.points.var[,k] != 0, k], type=\"l\")\n\n\n# Get SDs of estimates, the width should be useful to plot thickness of data points\nideal.points.var <- sqrt (ideal.points.var)\n\n# Non-smoothed ideal point time-paths\nsetwd (\"/Users/grosas/Dropbox/ifesharedge/graphs\")\npdf (\"UgaldeEtAlNonSmooth.pdf\", h=7, w=9)\nplot(c(1:S), ideal.points[1:S,1], main=\"\", ylim=c(-3,3), type=\"n\", xlab=\"\", ylab=\"Ideal points\")\nfor (j in 1:J){\n# \tlines(ideal.points[1:S,j], lwd=3, col=color45678901[j])\n\tlines(CouncilorIn[j,1:S] * ideal.points[1:S,j], lwd=3, col=rgb.45678901[j])\n}\ndev.off()\n\n\n\n# Smoothed ideal point time-paths\n# pdf (\"UgaldeEtAlSmooth.pdf\", h=7, w=9)\npdf (\"UgaldeEtAlSmoothMarch21.pdf\", h=7, w=9)\nplot(c(1:S), ideal.points[1:S,1], main=\"\", ylim=c(-3,3), type=\"n\", xlab=\"\", ylab=\"Ideal points\")\nfor (j in 1:J){\n\tlines(smooth.spline(c(1:S)[!is.na(CouncilorIn[j,1:S])], ideal.points[!is.na(CouncilorIn[j,1:S]),j], df=10), lwd=3, col=rgb.45678901[j])\n# \tlines(smooth.spline(c(1:S), ideal.points[,j], df=10), lwd=3, col=color45678901[j])\n}\ndev.off()\n\n\n\nsetwd (\"/Users/grosas/Dropbox/ifesharedge/graphs/animBits/ugalde/\")\n\n# Smoothed ideal point time-paths, daily change movie\nSmooth <- list ()\nfor (j in 1:J){\n\tSmooth[[j]] <- smooth.spline(c(1:S), ideal.points[,j], df=10)\n}\n\nfor (j in 1:J){\n\tSmooth[[j]]$y[is.na(CouncilorIn[j,1:S])] <- NA\n}\n\nsnapshot <- seq (1, 1091, by=10)\nfor (s in snapshot){\n\twhich.s <- which (snapshot==s)\n\tif (which.s < 10) {name = paste('Ugalde00', which.s,'plot.png',sep='')}\n\tif (which.s >= 10 && which.s < 100) {name = paste('Ugalde0', which.s,'plot.png', sep='')}\n\tif (which.s >= 100) {name = paste('Ugalde', which.s,'plot.png', sep='')}\n\n\tjpeg (name, quality=100, height=500, width=500)\n\n\tplot(c(1:S), ideal.points[1:S,1], main=\"\", ylim=c(-3,3), type=\"n\", xlab=\"\", ylab=\"Ideal points\")\n\tfor (j in 1:J){\n\t\tlines ( Smooth[[j]]$x[1:s], Smooth[[j]]$y[1:s], lwd=6, col=rgb.45678901[j])\n\t}\n\t# Eric: Creo que t? tienes m?s informaci?n para hacer los cambios en las siguientes tres l?neas\n\tlegend (\"topright\", bty=\"n\", legend=paste (\"vote\", s, sep=\" \")) #Change the legend for the date of the vote\n\t# Add vertical lines for elections here, but only for some realizations of S\n\t# Add names of councilors here as well, but only for some realizations of S\n\tdev.off()\n}\n\n# Make a short film\n# system(\"convert -loop 1 -delay 40 *.png IFEwolden.gif\")\nsystem(\"convert -loop 1 -delay 20 *.png IFEugaldeSofis.gif\")\n# The number after loop controls the number of automatic replays (0 stands for infinite loop)\n# The number after delay determines length of transition between slides)\n\n\n\n\n\n\n", "meta": {"hexsha": "85056a3af091379533dfa6ac5ec2d4566d5b079a", "size": 24344, "ext": "r", "lang": "R", "max_stars_repo_path": "code/ifeJagsDynBonica-vectorized-em.r", "max_stars_repo_name": "grosasballina/ife-update", "max_stars_repo_head_hexsha": "174e3bfdffa6e84bff9fe70defe1e8afff05c7d6", "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/ifeJagsDynBonica-vectorized-em.r", "max_issues_repo_name": "grosasballina/ife-update", "max_issues_repo_head_hexsha": "174e3bfdffa6e84bff9fe70defe1e8afff05c7d6", "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/ifeJagsDynBonica-vectorized-em.r", "max_forks_repo_name": "grosasballina/ife-update", "max_forks_repo_head_hexsha": "174e3bfdffa6e84bff9fe70defe1e8afff05c7d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-03-02T19:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T13:31:15.000Z", "avg_line_length": 41.756432247, "max_line_length": 153, "alphanum_fraction": 0.5594396977, "num_tokens": 8227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961687, "lm_q2_score": 0.02931223255328453, "lm_q1q2_score": 0.010639437761871937}} {"text": "#' svaPrep\n#'\n#' prepare data for sva and/or isva analysis\n#' \n#' @param variable Independent variable vector.\n#' @param covariates Covariates data frame to include in regression model,\n#' one row per sample, one column per covariate (Default: NULL).\n#' @param beta.sva Methylation levels matrix, one row per CpG site, one column per sample.\n#' @param featureset Name from \\code{\\link{meffil.list.featuresets}()} (Default: NA).\n#' one row per sample, one column per covariate (Default: NULL).\n#' @param most.variable Apply (Independent) Surrogate Variable Analysis to the \n#' given most variable CpG sites (Default: 50000).\nsvaPrep <- function(variable,covariates,beta.sva,featureset,most.variable){\n\tautosomal.sites <- meffil.get.autosomal.sites(featureset)\n\tautosomal.sites <- intersect(autosomal.sites, rownames(beta.sva))\n\tif (length(autosomal.sites) < most.variable) {\n\t\twarning(\"Probes from the sex chromosomes will be used to calculate surrogate variables.\")\n\t} else {\n\t\tbeta.sva <- beta.sva[autosomal.sites,]\n\t}\n\tvar.idx <- order(rowVars(beta.sva, na.rm=T), decreasing=T)[1:most.variable]\n\tbeta.sva <- impute.matrix(beta.sva[var.idx,,drop=F])\n\t\n\tif (!is.null(covariates)) {\n\t\tcov.frame <- model.frame(~., data.frame(covariates, stringsAsFactors=F), na.action=na.pass)\n\t\tmod0 <- model.matrix(~., cov.frame)\n\t}\n\telse\n\t\tmod0 <- matrix(1, ncol=1, nrow=length(variable))\n\tmod <- cbind(mod0, variable)\n\tres <- list(\"mod\" = mod, \"beta.sva\"=beta.sva)\n\treturn(res)\n}\n\n#' svaIsva \n#' \n#' Constructs function calls to surrogate variable analysis or independent surrogate variable analysis\n#' \n#' @param beta.sva Methylation levels matrix, one row per CpG site, one column per sample.\n#' @param covariates Covariates data frame to include in regression model,\n#' one row per sample, one column per covariate (Default: NULL).\n#' @param random.seed Value with which to seed the pseudo random number generator for reproducible results\n#' @param mod model matrix form \\code{\\link{svaPrep}}\n#' @param n.sv Number of surrogate variables \n#' @param mode Do sva or isva analysis, accepts values \"sv\" or \"isv\"\n#' @param verbose Set verbosity of isva function\nsvaIsva <- function(beta.sva,covariates,random.seed,mod,n.sv,mode=\"sv\",verbose){\n\tset.seed(random.seed)\n\tif(mode==\"sv\"){\n\t\tsva.ret <- sva(beta.sva, mod=mod, mod0=mod[,1,drop=F], n.sv=n.sv)\n\t}\n\telse if (mode==\"isv\"){\n\t\tsva.ret <- isva(beta.sva, mod, ncomp=n.sv, verbose=verbose)\n\t}\n\tif (!is.null(covariates))\n\t\tsvaRes <- data.frame(covariates, sva.ret[[mode]], stringsAsFactors=F)\n\telse\n\t\tsvaRes <- as.data.frame(sva.ret[[mode]])\n\treturn(svaRes)\n}\n\n#' outliers\n#' \n#' selects outliers based on the value of \"outlier.iqr.factor\"\n#' @param beta Methylation levels matrix, one row per CpG site, one column per sample.\n#' @param outlier.iqr.factor For each CpG site, prior to fitting regression models,\n#' set methylation levels less than\n#' \\code{Q1 - outlier.iqr.factor * IQR} or more than\n#' \\code{Q3 + outlier.iqr.factor * IQR} to NA. Here IQR is the inter-quartile\n#' range of the methylation levels at the CpG site, i.e. Q3-Q1.\n#' Set to NA to skip this step (Default: NA)\noutliers <- function(beta,outlier.iqr.factor) {\n\tq <- rowQuantiles(beta, probs = c(0.25, 0.75), na.rm = T)\n\tiqr <- q[,2] - q[,1]\n\ttoo.hi <- which(beta > q[,2] + outlier.iqr.factor * iqr, arr.ind=T)\n\ttoo.lo <- which(beta < q[,1] - outlier.iqr.factor * iqr, arr.ind=T)\n\tif (nrow(too.hi) > 0) beta[too.hi] <- NA\n\tif (nrow(too.lo) > 0) beta[too.lo] <- NA\n\tres <- list(\"too.lo\"=too.lo,\"too.hi\"=too.hi)\n\treturn(res)\n}\n\n\n#' Epigenome-wide association study\n#'\n#' Test association with each CpG site.\n#'\n#' @param beta Methylation levels matrix, one row per CpG site, one column per sample.\n#' @param variable Independent variable vector. - NB only handles discrete 2 catagory variables\n#' @param covariates Covariates data frame to include in regression model,\n#' one row per sample, one column per covariate (Default: NULL).\n#' @param batch Batch vector to be included as a random effect (Default: NULL).\n#' @param weights Non-negative observation weights.\n#' Can be a numeric matrix of individual weights of same dimension as \\code{beta},\n#' or a numeric vector of weights with length \\code{ncol(beta)},\n#' or a numeric vector of weights with length \\code{nrow(beta)}. \n#' @param cell.counts Proportion of cell counts for one cell type in cases\n#' where the samples are mainly composed of two cell types (e.g. saliva) (Default: NULL).\n#' @param isva Apply Independent Surrogate Variable Analysis (ISVA) to the\n#' methylation levels and include the resulting variables as covariates in a\n#' regression model (Default: TRUE). \n#' @param sva Apply Surrogate Variable Analysis (SVA) to the\n#' methylation levels and covariates and include\n#' the resulting variables as covariates in a regression model (Default: TRUE).\n#' @param n.sv Number of surrogate variables to calculate (Default: NULL).\n#' @param winsorize.pct Apply all regression models to methylation levels\n#' winsorized to the given level. Set to NA to avoid winsorizing (Default: 0.05).\n#' @param robust Test associations with the 'robust' option when \\code{\\link{limma::eBayes}}\n#' is called (Default: TRUE).\n#' @param rlm Test assocaitions with the 'robust' option when \\code{\\link{limma:lmFit}}\n#' is called (Default: FALSE).\n#' @param outlier.iqr.factor For each CpG site, prior to fitting regression models,\n#' set methylation levels less than\n#' \\code{Q1 - outlier.iqr.factor * IQR} or more than\n#' \\code{Q3 + outlier.iqr.factor * IQR} to NA. Here IQR is the inter-quartile\n#' range of the methylation levels at the CpG site, i.e. Q3-Q1.\n#' Set to NA to skip this step (Default: NA).\n#' @param most.variable Apply (Independent) Surrogate Variable Analysis to the \n#' given most variable CpG sites (Default: 50000).\n#' @param featureset Name from \\code{\\link{meffil.list.featuresets}()} (Default: NA).\n#' @param random.seed Value with which to seed the pseudo random number generator for reproducible results\n#' @param verbose Set to TRUE if status updates to be printed (Default: FALSE).\n#'\n#' @export\nmeffil.ewas <- function(beta, variable,\n\t\t\t\t\t\tcovariates=NULL, batch=NULL, weights=NULL,\n\t\t\t\t\t\tcell.counts=NULL,\n\t\t\t\t\t\tisva=T, sva=T, ## cate?\n\t\t\t\t\t\tn.sv=NULL,\n\t\t\t\t\t\tisva0=F,isva1=F, ## deprecated\n\t\t\t\t\t\twinsorize.pct=0.05,\n\t\t\t\t\t\trobust=TRUE,\n\t\t\t\t\t\trlm=FALSE,\n\t\t\t\t\t\toutlier.iqr.factor=NA, ## typical value = 3\n\t\t\t\t\t\tmost.variable=min(nrow(beta), 50000),\n\t\t\t\t\t\tfeatureset=NA,\n\t\t\t\t\t\trandom.seed=20161123,\n\t\t\t\t\t\tverbose=F) {\n\t## depreciated Args\n\tif (isva0 || isva1)\n\t\tstop(\"isva0 and isva1 are deprecated and superceded by isva and sva\")\n\t# warn and set isva, sva values rather than kill?\n\t\n\tif (is.na(featureset))\n\t\tfeatureset <- guess.featureset(rownames(beta))\n\tfeatures <- meffil.get.features(featureset)\n\t\n\t## data Validation / type checks\n\tstopifnot(length(rownames(beta)) > 0 && all(rownames(beta) %in% features$name))\n\tstopifnot(ncol(beta) == length(variable))\n\tstopifnot(is.null(covariates) || is.data.frame(covariates) && nrow(covariates) == ncol(beta))\n\tstopifnot(is.null(batch) || length(batch) == ncol(beta))\n\tstopifnot(is.null(weights)\n\t\t\t|| is.numeric(weights) && (is.matrix(weights) && nrow(weights) == nrow(beta) && ncol(weights) == ncol(beta)\n\t\t\t\t\t\t\t\t\t\t|| is.vector(weights) && length(weights) == nrow(beta)\n\t\t\t\t\t\t\t\t\t\t|| is.vector(weights) && length(weights) == ncol(beta)))\n\tstopifnot(most.variable > 1 && most.variable <= nrow(beta))\n\tstopifnot(!is.numeric(winsorize.pct) || winsorize.pct > 0 && winsorize.pct < 0.5)\n\t\n\t## cache var and covars\n\toriginal.variable <- variable\n\toriginal.covariates <- covariates\n\tif (is.character(variable))\n\t\tvariable <- as.factor(variable)\n\t\n\tstopifnot(!is.factor(variable) || is.ordered(variable) || length(levels(variable)) == 2)\n\t\n\tmsg(\"Simplifying any categorical variables.\", verbose=verbose)\n\tvariable <- simplify.variable(variable)\n\tif (!is.null(covariates))\n\t\tcovariates <- do.call(cbind, lapply(covariates, simplify.variable))\n\t\n\t## Getting samples without missing values\n\tsample.idx <- which(!is.na(variable))\n\tif (!is.null(covariates))\n\t\tsample.idx <- intersect(sample.idx, which(apply(!is.na(covariates), 1, all)))\n\t\n\tmsg(\"Removing\", ncol(beta) - length(sample.idx), \"missing case(s).\", verbose=verbose)\n\t\n\tif (is.matrix(weights))\n\t\tweights <- weights[,sample.idx]\n\tif (is.vector(weights) && length(weights) == ncol(beta))\n\t\tweights <- weights[sample.idx]\n\t\n\tbeta <- beta[,sample.idx]\n\tvariable <- variable[sample.idx]\n\t\n\tif (!is.null(covariates))\n\t\tcovariates <- covariates[sample.idx,,drop=F]\n\t\n\tif (!is.null(batch))\n\t\tbatch <- batch[sample.idx]\n\t\n\tif (!is.null(cell.counts))\n\t\tcell.counts <- cell.counts[sample.idx]\n\t\n\tif (!is.null(covariates)) {\n\t\tpos.var.idx <- which(apply(covariates, 2, var, na.rm=T) > 0)\n\t\tmsg(\"Removing\", ncol(covariates) - length(pos.var.idx), \"covariates with no variance.\",\n\t\t\tverbose=verbose)\n\t\tcovariates <- covariates[,pos.var.idx, drop=F]\n\t}\n\t\n\t## ewas setup\n\t### Declace list to hold different covariate sets ewas results\n\tcovariate.sets <- list(none=NULL) \n\tif (!is.null(covariates))\n\t\tcovariate.sets$all <- covariates\n\t\n\t### winsorisation\n\tif (is.numeric(winsorize.pct)) {\n\t\tmsg(winsorize.pct, \"- winsorizing the beta matrix.\", verbose=verbose)\n\t\tbeta <- winsorize(beta, pct=winsorize.pct)\n\t}\n\t\n\t### outliers\n\ttoo.hi <- too.lo <- NULL\n\tif (is.numeric(outlier.iqr.factor)) {\n\t\toutliersRes <- outliers(beta,outlier.iqr.factor)\n\t\ttoo.hi <- outliersRes$too.hi\n\t\ttoo.lo <- outliersRes$too.lo\n\t}\n\t\n\t## sva/isva\n\tif (isva || sva) {\n\t\tbeta.sva <- beta\n\t\tres <- svaPrep(variable,covariates,beta.sva,featureset,most.variable)\n\t\tmod <- res$mod\n\t\tbeta.sva <- res$beta.sva\n\t\t\n\t\tif (isva) {\n\t\t\tmsg(\"ISVA.\", verbose=verbose)\n\t\t\tcovariate.sets$isva <- svaIsva(beta.sva,covariates,random.seed,mod,n.sv,mode=\"isv\",verbose)\n\t\t\tcat(\"\\n\")\n\t\t}\n\t\t\n\t\tif (sva) {\n\t\t\tmsg(\"SVA.\", verbose=verbose)\n\t\t\tcovariate.sets$sva <- svaIsva(beta.sva,covariates,random.seed,mod,n.sv,mode=\"sv\",verbose)\n\t\t\tcat(\"\\n\")\n\t\t}\n\t}\n\t\n\t## run EWASs\n\tanalyses <- sapply(names(covariate.sets), function(name) {\n\t\tmsg(\"EWAS for covariate set\", name, verbose=verbose)\n\t\tcovariates <- covariate.sets[[name]]\n\t\tewas(variable,\n\t\t\t beta=beta,\n\t\t\t covariates=covariates,\n\t\t\t batch=batch,\n\t\t\t weights=weights,\n\t\t\t cell.counts=cell.counts,\n\t\t\t winsorize.pct=winsorize.pct, \n\t\t\t robust=robust, \n\t\t\t rlm=rlm)\n\t}, simplify=F)\n\t\n\t## extract results\n\tp.values <- sapply(analyses, function(analysis) analysis$table$p.value)\n\tcoefficients <- sapply(analyses, function(analysis) analysis$table$coefficient)\n\trownames(p.values) <- rownames(coefficients) <- rownames(analyses[[1]]$table)\n\t\n\tfor (name in names(analyses)) {\n\t\tidx <- match(rownames(analyses[[name]]$table), features$name)\n\t\tanalyses[[name]]$table$chromosome <- features$chromosome[idx]\n\t\tanalyses[[name]]$table$position <- features$position[idx]\n\t}\n\t\n\t## Return results\n\tlist(class=\"ewas\",\n\t\t version=packageVersion(\"meffil\"),\n\t\t samples=sample.idx,\n\t\t variable=original.variable[sample.idx],\n\t\t covariates=original.covariates[sample.idx,,drop=F],\n\t\t winsorize.pct=winsorize.pct,\n\t\t robust=robust,\n\t\t rlm=rlm,\n\t\t outlier.iqr.factor=outlier.iqr.factor,\n\t\t most.variable=most.variable,\n\t\t p.value=p.values,\n\t\t coefficient=coefficients,\n\t\t analyses=analyses,\n\t\t random.seed=random.seed,\n\t\t too.hi=too.hi,\n\t\t too.lo=too.lo)\n}\n\n#' is.ewas.object\n#' \n#' @param object a 'meffil' object (not an actual S3/4 R object)\nis.ewas.object <- function(object)\n\tis.list(object) && \"class\" %in% names(object) && object$class == \"ewas\"\n\n#' ewas\n#' \n#' Test associations between \\code{variable} and each row of \\code{beta}\n#' while adjusting for \\code{covariates} (fixed effects) and \\code{batch} (random effect).\n#' NB only handles discrete 2 catagory variables\n#' If \\code{cell.counts} is not \\code{NULL}, then it is assumed that\n#' the methylation data is derived from samples with two cell types.\n#' \\code{cell.counts} should then be a vector of numbers\n#' between 0 and 1 of length equal to \\code{variable} corresponding\n#' to the proportions of cell of a selected cell type in each sample.\n#' The regression model is then modified in order to identify\n#' associations specifically in the selected cell type (PMID: 24000956).\newas <- function(variable, beta, covariates=NULL, batch=NULL, weights=NULL, cell.counts=NULL, winsorize.pct=0.05,\n\t\t\t\t robust=TRUE, rlm=FALSE, verbose=F) {\n\tstopifnot(all(!is.na(variable)))\n\tstopifnot(length(variable) == ncol(beta))\n\tstopifnot(is.null(covariates) || nrow(covariates) == ncol(beta))\n\tstopifnot(is.null(batch) || length(batch) == ncol(beta))\n\tstopifnot(is.null(cell.counts)\n\t\t\t || length(cell.counts) == ncol(beta)\n\t\t\t && all(cell.counts >= 0 & cell.counts <= 1))\n \n\tmethod <- \"ls\"\n\tif (rlm) method <- \"robust\"\n \n\tif (is.null(covariates))\n\t\tdesign <- data.frame(intercept=1, variable=variable)\n\telse\n\t\tdesign <- data.frame(intercept=1, variable=variable, covariates)\n\trownames(design) <- colnames(beta)\n\n\tif (!is.null(cell.counts)) {\n\t\t## Irizarray method: Measuring cell-type specific differential methylation\n\t\t##\t in human brain tissue\n\t\t## Mi is methylation level for sample i\n\t\t## Xi is the value of the variable of interest for sample i\n\t\t## pi is the proportion of the target cell type for sample i\n\t\t## thus: Mi ~ target cell methylation * pi + other cell methylation * (1-pi)\n\t\t## and target cell methylation = base target methylation + effect of Xi value\n\t\t## and other cell methylation = base other methylation + effect of Xi value\n\t\t## thus:\n\t\t## Mi = (T + U Xi)pi + (O + P Xi)(1-pi) + e\n\t\t##\t= C + A Xi pi + B Xi (1-pi) + e\t\t\n\t\tdesign <- design[,-which(colnames(design) == \"intercept\")]\n\t\t\n\t\tdesign <- cbind(design * cell.counts,\n\t\t\t\t\t\ttypeB=design * (1-cell.counts))\n\t}\n\n\tmsg(\"Linear regression with limma::lmFit\", verbose=verbose)\n\tfit <- NULL\n\tbatch.cor <- NULL\n\tif (!is.null(batch)) {\n\t\tmsg(\"Adjusting for batch effect\", verbose=verbose)\n\t\tcorfit <- duplicateCorrelation(beta, design, block=batch, ndups=1)\n\t\tbatch.cor <- corfit$consensus\n\t\tmsg(\"Linear regression with batch as random effect\", verbose=verbose)\n\t\ttryCatch(fit <- lmFit(beta, design, method=method, block=batch, cor=batch.cor, weights=weights),\n\t\t\t\t error=function(e) {\n\t\t\t\t\t print(e)\n\t\t\t\t\t msg(\"lmFit failed with random effect batch variable, omitting\", verbose=verbose)\n\t\t\t\t })\n\t}\n\tif (is.null(fit)) {\n\t\tmsg(\"Linear regression with only fixed effects\", verbose=verbose)\n\t\tbatch <- NULL\n\t\tfit <- lmFit(beta, design, method=method, weights=weights)\n\t}\n\t\n\tmsg(\"Empirical Bayes\", verbose=verbose)\n\tif (is.numeric(winsorize.pct) && robust) {\n\t fit.ebayes <- eBayes(fit, robust=T, winsor.tail.p=c(winsorize.pct, winsorize.pct))\n\t} else {\n\t fit.ebayes <- eBayes(fit, robust=robust)\n\t}\n\n\talpha <- 0.975\n\tstd.error <- (sqrt(fit.ebayes$s2.post) * fit.ebayes$stdev.unscaled[,\"variable\"])\n\tmargin.error <- (std.error * qt(alpha, df=fit.ebayes$df.total))\n\tn <- rowSums(!is.na(beta))\n\n\tlist(design=design,\n\t\t batch=batch,\n\t\t batch.cor=batch.cor,\n\t\t cell.counts=cell.counts,\n\t\t table=data.frame(p.value=fit.ebayes$p.value[,\"variable\"],\n\t\t\t fdr=p.adjust(fit.ebayes$p.value[,\"variable\"], \"fdr\"),\n\t\t\t p.holm=p.adjust(fit.ebayes$p.value[,\"variable\"], \"holm\"),\n\t\t\t t.statistic=fit.ebayes$t[,\"variable\"],\n\t\t\t coefficient=fit.ebayes$coefficient[,\"variable\"],\n\t\t\t coefficient.ci.high=fit.ebayes$coefficient[,\"variable\"] + margin.error,\n\t\t\t coefficient.ci.low=fit.ebayes$coefficient[,\"variable\"] - margin.error,\n\t\t\t coefficient.se=std.error,\n\t\t\t n=n))\n}\n\n\n#' Epigenome-wide association study (lm)\n#'\n#' Test association with each CpG site.\n#'\n#' @param beta Methylation levels matrix, one row per CpG site, one column per sample.\n#' @param variable Independent variable vector.\n#' @param covariates Covariates data frame to include in regression model,\n#' one row per sample, one column per covariate (Default: NULL).\n#' @param weights numeric vector of weights to provide to the lm()/glm() function\n#' @param family to perform generalised linear modeling with r's glm() function\n#' @param isva Apply Independent Surrogate Variable Analysis (ISVA) to the\n#' methylation levels and include the resulting variables as covariates in a\n#' regression model (Default: TRUE). \n#' @param sva Apply Surrogate Variable Analysis (SVA) to the\n#' methylation levels and covariates and include\n#' the resulting variables as covariates in a regression model (Default: TRUE).\n#' @param n.sv Number of surrogate variables to calculate (Default: NULL).\n#' @param winsorize.pct Apply all regression models to methylation levels\n#' winsorized to the given level. Set to NA to avoid winsorizing (Default: 0.05).\n#' @param outlier.iqr.factor For each CpG site, prior to fitting regression models,\n#' set methylation levels less than\n#' \\code{Q1 - outlier.iqr.factor * IQR} or more than\n#' \\code{Q3 + outlier.iqr.factor * IQR} to NA. Here IQR is the inter-quartile\n#' range of the methylation levels at the CpG site, i.e. Q3-Q1.\n#' Set to NA to skip this step (Default: NA).\n#' @param most.variable Apply (Independent) Surrogate Variable Analysis to the \n#' given most variable CpG sites (Default: 50000).\n#' @param featureset Name from \\code{\\link{meffil.list.featuresets}()} (Default: NA).\n#' @param random.seed Value with which to seed the pseudo random number generator for reproducible results\n#' @param verbose Set to TRUE if status updates to be printed (Default: FALSE).\n#'\n#' @export\nmeffil.ewas.lm <- function(beta, variable,\n\t\t\t\t\t\t\tcovariates=NULL, \n\t\t\t\t\t\t\t#batch=NULL, \n\t\t\t\t\t\t\tweights=NULL,\n\t\t\t\t\t\t\tfamily=NULL,\n\t\t\t\t\t\t\t#cell.counts=NULL,\n\t\t\t\t\t\t\tisva=T, sva=T, ## cate?\n\t\t\t\t\t\t\tn.sv=NULL,\n\t\t\t\t\t\t\tisva0=F,isva1=F, ## deprecated\n\t\t\t\t\t\t\twinsorize.pct=0.05,\n\t\t\t\t\t\t\toutlier.iqr.factor=NA, ## typical value = 3\n\t\t\t\t\t\t\tmost.variable=min(nrow(beta), 50000),\n\t\t\t\t\t\t\tfeatureset=NA,\n\t\t\t\t\t\t\trandom.seed=20161123,\n\t\t\t\t\t\t\tverbose=F) {\n\t## depreciated Args\n\tif (isva0 || isva1)\n\t\tstop(\"isva0 and isva1 are deprecated and superceded by isva and sva\")\n\t# warn and set isva, sva values rather than kill?\n\t\n\tif (is.na(featureset))\n\t\tfeatureset <- guess.featureset(rownames(beta))\n\tfeatures <- meffil.get.features(featureset)\n\t\n\tphenotype.data <- cbind(variable,covariates)\n\t\n\tvarName <- colnames(variable)\n\tvariable <- unlist(variable,use.names = F)\n\t\n\t## data Validation / type checks\n\tstopifnot(length(rownames(beta)) > 0 && all(rownames(beta) %in% features$name))\n\tstopifnot(ncol(beta) == length(variable))\n\tstopifnot(is.null(covariates) || is.data.frame(covariates) && nrow(covariates) == ncol(beta))\n\t#stopifnot(is.null(batch) || length(batch) == ncol(beta))\n\tstopifnot(is.null(weights)|| is.numeric(weights))\n\tstopifnot(most.variable > 1 && most.variable <= nrow(beta))\n\tstopifnot(!is.numeric(winsorize.pct) || winsorize.pct > 0 && winsorize.pct < 0.5)\n\t\n\t## cache var and covars\n\toriginal.variable <- variable\n\toriginal.covariates <- covariates\n\n\tmsg(\"Simplifying any categorical variables.\", verbose=verbose)\n\tvariable <- simplify.variable(variable)\n\tif (!is.null(covariates))\n\t\tcovariates <- do.call(cbind, lapply(covariates, simplify.variable))\n\t\n\t## Getting samples without missing values\n\t# sample.idx = all samples without missing value?s\n\tsample.idx <- which(!is.na(variable))\n\t\n\t##!! removing missing values from NB phenotype.data !!##\n\t##!! get rid ot phenotype.data and merge var/covar to data frame and pass to ewas.lm !!##\n\tphenotype.data[sample.idx,,drop=F]\n\t\n\tif (!is.null(covariates))\n\t\tsample.idx <- intersect(sample.idx, which(apply(!is.na(covariates), 1, all)))\n\t\n\tmsg(\"Removing\", ncol(beta) - length(sample.idx), \"missing case(s).\", verbose=verbose)\n\t\n\tif (is.vector(weights) && length(weights) == ncol(beta))\n\t\tweights <- weights[sample.idx]\n\t\n\tbeta <- beta[,sample.idx]\n\tvariable <- variable[sample.idx]\n\t\n\tif (!is.null(covariates))\n\t\tcovariates <- covariates[sample.idx,,drop=F]\n\t\n\t# if (!is.null(batch))\n\t# \tbatch <- batch[sample.idx]\n\t# \n\t# if (!is.null(cell.counts))\n\t# \tcell.counts <- cell.counts[sample.idx]\n\t\n\tif (!is.null(covariates)) {\n\t\tpos.var.idx <- which(apply(covariates, 2, var, na.rm=T) > 0)\n\t\tmsg(\"Removing\", ncol(covariates) - length(pos.var.idx), \"covariates with no variance.\",\n\t\t\tverbose=verbose)\n\t\tcovariates <- covariates[,pos.var.idx, drop=F]\n\t}\n\t\n\t## ewas setup\n\t### Declace list to hold different covariate sets ewas results\n\tcovariate.sets <- list(none=NULL) \n\tif (!is.null(covariates))\n\t\tcovariate.sets$all <- covariates\n\t\n\t### winsorisation\n\tif (is.numeric(winsorize.pct)) {\n\t\tmsg(winsorize.pct, \"- winsorizing the beta matrix.\", verbose=verbose)\n\t\tbeta <- winsorize(beta, pct=winsorize.pct)\n\t}\n\t\n\t### outliers\n\ttoo.hi <- too.lo <- NULL\n\tif (is.numeric(outlier.iqr.factor)) {\n\t\toutliersRes <- outliers(beta,outlier.iqr.factor)\n\t\ttoo.hi <- outliersRes$too.hi\n\t\ttoo.lo <- outliersRes$too.lo\n\t}\n\t\n\t## sva/isva\n\tif (isva || sva) {\n\t\tbeta.sva <- beta\n\t\tres <- svaPrep(variable,covariates,beta.sva,featureset,most.variable)\n\t\tmod <- res$mod\n\t\tbeta.sva <- res$beta.sva\n\t\t\n\t\tif (isva) {\n\t\t\tmsg(\"ISVA.\", verbose=verbose)\n\t\t\tcovariate.sets$isva <- svaIsva(beta.sva,covariates,random.seed,mod,n.sv,mode=\"isv\",verbose)\n\t\t\tcat(\"\\n\")\n\t\t}\n\t\t\n\t\tif (sva) {\n\t\t\tmsg(\"SVA.\", verbose=verbose)\n\t\t\tcovariate.sets$sva <- svaIsva(beta.sva,covariates,random.seed,mod,n.sv,mode=\"sv\",verbose)\n\t\t\tcat(\"\\n\")\n\t\t}\n\t}\n\t\n\t## run EWASs\n\tanalyses <- sapply(names(covariate.sets), function(name) {\n\t\tmsg(\"EWAS for covariate set\", name, verbose=verbose)\n\t\tcovariates <- covariate.sets[[name]]\n\t\tif(!is.null(covariate.sets[[name]])){\n\t\t\tphenotype.data <- cbind(phenotype.data,covariate.sets[[name]]) ##!!\n\t\t\t#phenotype.data <- cbind(variable,covariate.sets[[name]]) ##!! ??\n\t\t\t#colnames(phenotype.data) <- c(varName,colnames(covariates))\n\t\t}\n\t\tewas.lm(variable=varName,\n\t\t\t\tbeta=beta,\n\t\t\t\tcovariates=colnames(covariates),\n\t\t\t\t#batch=batch,\n\t\t\t\tweights=weights,\n\t\t\t\t#cell.counts=cell.counts,\n\t\t\t\twinsorize.pct=winsorize.pct,\n\t\t\t\tphenotype.data = phenotype.data,\n\t\t\t\tfamily=family\n\t\t)\n\t}, simplify=F)\n\t\n\t## extract results\n\tp.values <- sapply(analyses, function(analysis) analysis$table$p.value)\n\tcoefficients <- sapply(analyses, function(analysis) analysis$table$coefficient)\n\trownames(p.values) <- rownames(coefficients) <- rownames(analyses[[1]]$table)\n\t\n\tfor (name in names(analyses)) {\n\t\tidx <- match(rownames(analyses[[name]]$table), features$name)\n\t\tanalyses[[name]]$table$chromosome <- features$chromosome[idx]\n\t\tanalyses[[name]]$table$position <- features$position[idx]\n\t}\n\t\n\tlist(class=\"ewas\",\n\t\tversion=packageVersion(\"meffil\"),\n\t\tsamples=sample.idx,\n\t\tvariable=original.variable[sample.idx],\n\t\tcovariates=original.covariates[sample.idx,,drop=F],\n\t\twinsorize.pct=winsorize.pct,\n\t\t#robust=robust,\n\t\t#rlm=rlm,\n\t\toutlier.iqr.factor=outlier.iqr.factor,\n\t\tmost.variable=most.variable,\n\t\tp.value=p.values,\n\t\tcoefficient=coefficients,\n\t\tanalyses=analyses,\n\t\trandom.seed=random.seed,\n\t\ttoo.hi=too.hi,\n\t\ttoo.lo=too.lo)\n}\n\n#' ewas.lm\n#' \n#' performs EWAS using r's lm()/glm() functions\n#' \n#' Test associations between \\code{variable} and each row of \\code{beta}\n#' while adjusting for \\code{covariates} \newas.lm <- function(variable, beta, covariates=NULL,\n\t\t\t\t\tweights=NULL, winsorize.pct=0.05,\n\t\t\t\t\tverbose=F,phenotype.data=NULL,family=NULL) {\n\t## Data Validation\n\tstopifnot(is.character(variable))\n\t#stopifnot(is.character(covariates))\n\tstopifnot(is.null(phenotype.data) || nrow(phenotype.data) == ncol(beta))\n\tn <- rowSums(!is.na(beta))\n\t\n\t## Set design\n\t#(different if no covars)\n\tdesign <- NULL\n\tdesignFx <- NULL\n\tif(is.null(covariates)) {\n\t\tdesign <- data.frame(intercept=1, variable=phenotype.data[,variable])\n\t\tdesignFx <- function(variable,covariates) {\n\t\t\tpaste0(variable,\"~meth.matrix[cpg,]\")\n\t\t}\n\t}\n\telse {\n\t\tdesign <- data.frame(intercept=1, variable=phenotype.data[,variable], covariates=phenotype.data[,covariates])\n\t\tdesignFx <- function(variable,covariates) {\n\t\tpaste0(variable,\"~meth.matrix[cpg,]+\",paste0(covariates,collapse=\"+\"))\n\t\t}\n\t}\n\trownames(design) <- colnames(beta)\n\t\n\t## Set modeling type - fit glm if family provided\n\tmodFx <- NULL\n\tif(is.null(family)) {\n\t\tmodFx <- function(FORM,data,family,weights){\n\t\t\tlm(FORM,data,weights)\n\t\t}\n\t}\n\telse {\n\t\tmodFx <- function(FORM,data,family,weights){\n\t\tglm(FORM,data,family = family,weights=weights)\n\t\t}\n\t}\n\t\n\t## Model building and parsing function\n\tmodel <- function(cpg, meth.matrix, variable, covariates, phenotype.data,family,weights) {\n\t\tFORM=formula(designFx(variable,covariates))\n\t\tmod= modFx(FORM,data=phenotype.data,family = family,weights=weights)\n\t\tres = summary(mod)$coef[2,c(\"Estimate\",\"Std. Error\",\"Pr(>|t|)\")]\n\t}\n\t\n\t## Run models (in parallel)\n\tewas_res <- mclapply(setNames(seq_len(nrow(beta)),dimnames(beta)[[1]]),\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tmeth.matrix=beta,\n\t\t\t\t\t\tvariable=variable,\n\t\t\t\t\t\tcovariates=covariates,\n\t\t\t\t\t\tphenotype.data=phenotype.data,\n\t\t\t\t\t\tfamily=family,\n\t\t\t\t\t\tweights=weights)\n\t\n\tewas_res <- data.frame(t(sapply(ewas_res,c)))\n\t\n\tcolnames(ewas_res)<-c(\"effect.size\",\"std.err\",\"P.value\")\n\t\n\t## Return results\n\tlist(design=design,\n\t\t#batch=batch,\n\t\t#batch.cor=batch.cor,\n\t\t#cell.counts=cell.counts,\n\t\ttable=data.frame(p.value=ewas_res$P.value,\n\t\t\t\t\t\tcoefficient=ewas_res$effect.size,\n\t\t\t\t\t\tcoefficient.se=ewas_res$std.err,\n\t\t\t\t\t\tn=n))\n}\n\n", "meta": {"hexsha": "a7895879da8386b11bfef2e47d5370bcc377b0d2", "size": 25090, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ewas.r", "max_stars_repo_name": "RichardJActon/meffil_duplicate", "max_stars_repo_head_hexsha": "22fd6b59caef488adcee59619e9f9471e22cb645", "max_stars_repo_licenses": ["Artistic-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": "R/ewas.r", "max_issues_repo_name": "RichardJActon/meffil_duplicate", "max_issues_repo_head_hexsha": "22fd6b59caef488adcee59619e9f9471e22cb645", "max_issues_repo_licenses": ["Artistic-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/ewas.r", "max_forks_repo_name": "RichardJActon/meffil_duplicate", "max_forks_repo_head_hexsha": "22fd6b59caef488adcee59619e9f9471e22cb645", "max_forks_repo_licenses": ["Artistic-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": 37.2255192878, "max_line_length": 113, "alphanum_fraction": 0.6971701873, "num_tokens": 7422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.02228618643212032, "lm_q1q2_score": 0.010621142953359931}} {"text": "# Copyright 2018 Dominic Davis-Foster, except where noted below\r\n#' v1.1'\r\n\r\n#' Clear Terminal Function\r\n#'\r\n#' This function clears the terminal on Unix systems.\r\n#' Does not work on Windows.\r\n#' Run makeActiveBinding(\"clear\", clear, environment()) \r\n#'\tto be able to type \"clear\"\r\n#' @keywords clear\r\n#' @export\r\n#' @examples\r\n#' clear()\r\nclear <- function() cat(c(\"\\033[2J\",\"\\033[0;0H\"));\r\n\r\n\r\n#' Newline Function\r\n#'\r\n#' This function starts a new line on the terminal.\r\n#' Can also be used to print a blank line.\r\n#' Run makeActiveBinding(\"newline\", newline, environment())\r\n#'\tto be able to type \"newline\r\n#' @keywords newline\r\n#' @export\r\n#' @examples\r\n#' newline()\r\nnewline <- function() cat(\"\\n\");\r\n\r\n#' Input Prompt Function\r\n#'\r\n#' This function creates an input prompt with customisable text.\r\n#' Multiple inputs are possible with \"lines\" option\".\r\n#'\r\n#' @keywords input\r\n#' @export\r\n#' @examples\r\n#' input(\"Press [Enter] to Continue\")\r\n#' name = input(\"Enter your name: \", lines=2)\r\ninput <- function(text='', lines=1) {\r\n\tcat(text);\r\n\ta <- readLines(\"stdin\",n=lines);\r\n\treturn(a)\r\n}\r\n\r\n#' Type Function\r\n#'\r\n#' Synonym for builtin \"mode\" function.\r\n#'\r\n#' @keywords type mode\r\n#' @export\r\n#' @examples\r\n#' type(LETTERS)\r\n#' \r\ntype <- function(variable) {\r\n\ta <- mode(variable);\r\n\treturn(a)\r\n}\r\n\r\n#' Mode Average Function\r\n#'\r\n#' Function to calculate the modal average.\r\n#'\r\n#' @keywords mode average\r\n#' @export\r\n#' @examples\r\n#' modes(sample(1:10, 10, replace=TRUE))\r\n#'\t\r\nmodes <- function(x) {\r\n ux <- unique(x)\r\n tab <- tabulate(match(x, ux))\r\n ux[tab == max(tab)]\r\n}\r\n\r\n#' Capitalise First Letter Function\r\n#'\r\n#' Function to capitalise the first letter of a character string.\r\n#' From https://stackoverflow.com/questions/18509527/first-letter-to-upper-case/18509816\r\n#'\r\n#' @keywords capitalise letter character string\r\n#' @export\r\n#' @examples\r\n#' firstup(\"rStudio\")\r\n#' \r\nfirstup <- function(x) {\r\n substr(x, 1, 1) <- toupper(substr(x, 1, 1))\r\nx\r\n}\r\n\r\n#' Shapiro-Wilk Test for Data Frames\r\n#'\r\n#' Function to perform Shapiro-Wilk test for each column of a Data Frame.\r\n#' Can provide interpretation for p-value with \"interpret=TRUE\".\r\n#' Modified from https://stackoverflow.com/questions/45226457/r-loop-performing-ks-tests-across-data-frame-stored-in-matrix\r\n#'\r\n#' @keywords Shapiro Shapiro-Wilk data.frame normality\r\n#' @export\r\n#' @examples\r\n#' colShapiro(dataframe, interpret=TRUE)\r\n#' \r\ncolShapiro <- function(x, print=FALSE, interpret=FALSE) {\t\r\n\tres <- sapply(x, function(y) {\r\n\t shapiro <- shapiro.test(y)\r\n\tif (interpret) {\r\n\t\tc(statistic=shapiro$statistic, p.value=shapiro$p.value, normal=shapiro$p.value>0.05)\r\n\t\tsetNames(c(shapiro$statistic, shapiro$p.value, normal=shapiro$p.value>0.05), c(\"statistic\", \"p.value\", \"normal\"))\r\n\t}\r\n\telse {\r\n\t\tc(statistic=shapiro$statistic, p.value=shapiro$p.value)\r\n\t\tsetNames(c(shapiro$statistic, shapiro$p.value), c(\"statistic\", \"p.value\"))\r\n\t}\r\n\t})\r\n\t\r\n\tif (print) {\r\n\t\tprint(\"Shapiro-Wilk Test\")\r\n\t}\r\n\treturn(res)\r\n}\r\n\r\n#' Kolmogorov-Smirnov Normal Distribution Test for Data Frames\r\n#'\r\n#' Function to perform Kolmogorov-Smirnov test for normal distribution \r\n#' on each column of a Data Frame.\r\n#' Can provide interpretation for p-value with \"interpret=TRUE\".\r\n#' Modified from https://stackoverflow.com/questions/45226457/r-loop-performing-ks-tests-across-data-frame-stored-in-matrix\r\n#'\r\n#' @keywords Kolmogorov-Smirnov data.frame normalty KS\r\n#' @export\r\n#' @examples\r\n#' colKS(dataframe, interpret=TRUE)\r\n#' \r\ncolKS <- function(x, print = FALSE, interpret=FALSE) {\r\n\tres <- sapply(x, function(y) {\r\n\tks <- ks.test(y, pnorm, mean(y), sd(y))\r\n\tif (interpret) {\r\n\t\tc(statistic=ks$statistic, p.value=ks$p.value, normal=ks$p.value>0.05)\r\n\t\tsetNames(c(ks$statistic, ks$p.value, normal=ks$p.value>0.05), c(\"statistic\", \"p.value\", \"normal\"))\r\n\t}\r\n\telse {\r\n\t\tc(statistic=ks$statistic, p.value=ks$p.value)\r\n\t\tsetNames(c(ks$statistic, ks$p.value), c(\"statistic\", \"p.value\"))\r\n\t}\r\n\t})\r\n\r\n\tif (print) {\r\n\t\tprint(\"Kolmogorov-Smirnov Test\")\r\n\t}\r\n\treturn(res)\r\n}\r\n\r\n#' Standard Deviation for Data Frames\r\n#'\r\n#' Function to calculate Standard Deviation for each column of a Data Frame.\r\n#' Modified from https://stackoverflow.com/questions/37806387/r-calculate-standard-deviation-in-cols-in-a-data-frame-despite-of-na-values\r\n#'\r\n#' @keywords Standard Deviation std sd stdev data.frame\r\n#' @export\r\n#' @examples\r\n#' colSD(dataframe)\r\n#' \r\n# data frame sd\r\ncolSD <- function(x, print=FALSE) {\r\n\tif (print) {\r\n\t\tprint(\"Standard Deviation\")\r\n\t}\r\n\tsapply(x, sd, na.rm = TRUE)\r\n}\r\n\r\n#' Median for Data Frames\r\n#'\r\n#' Function to calculate Median for each column of a Data Frame.\r\n#' Modified from https://stackoverflow.com/questions/37806387/r-calculate-standard-deviation-in-cols-in-a-data-frame-despite-of-na-values\r\n#'\r\n#' @keywords Median data.frame\r\n#' @export\r\n#' @examples\r\n#' colMedian(dataframe)\r\n#' \r\n# data frame sd\r\ncolMedian <- function(x, print=FALSE) {\r\n\tif (print) {\r\n\t\tprint(\"Median\")\r\n\t}\r\n\tsapply(x, median, na.rm = TRUE)\r\n}\r\n", "meta": {"hexsha": "cde54112cdd23799296c42fa1c6988fba10153ae", "size": 5009, "ext": "r", "lang": "R", "max_stars_repo_path": "R/domtools.r", "max_stars_repo_name": "domdfcoding/domtools", "max_stars_repo_head_hexsha": "f37181a7793a8be7a15aa615c6babf60dc1ddf34", "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": "R/domtools.r", "max_issues_repo_name": "domdfcoding/domtools", "max_issues_repo_head_hexsha": "f37181a7793a8be7a15aa615c6babf60dc1ddf34", "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": "R/domtools.r", "max_forks_repo_name": "domdfcoding/domtools", "max_forks_repo_head_hexsha": "f37181a7793a8be7a15aa615c6babf60dc1ddf34", "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": 27.0756756757, "max_line_length": 138, "alphanum_fraction": 0.6673986824, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.040845712261275036, "lm_q1q2_score": 0.010369133645023476}} {"text": "# Copyright © 2013-2015 Université catholique de Louvain, Belgium - UCL\n# All rights reserved.\n#\n# This file is part of the precall package.\n#\n# The precall package has been developed by Adrien Dessy [Machine Learning\n# Group (MLG) - Institute of Information and Communication Technologies,\n# Electronics and Applied Mathematics (ICTEAM)] for the Université catholique de\n# Louvain (UCL). The precall package enables to plot precision-recall curves and\n# to compute the Area Under Precision-Recall curves.\n#\n# The precall package is distributed under the terms of the MIT License (MIT).\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is furnished\n# to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\n#' @importFrom magrittr \"%>%\"\nNULL\n\n\n#' Plot precision-recall curves\n#'\n#' \\code{plot_precall} creates a ggplot object that represents precision-recall\n#' curves corresponding to several rankings.\n#'\n#' @param scores A matrix or vector of numeric values that specifies the rankings\n#' @param labels A vector of logical values that encodes the POSITIVE/NEGATIVE status of data\n#' @param print_friendly A boolean\n#' @param use_color A boolean\n#' @param use_linetype A boolean\n#' @param axis_label_size A numeric\n#' @param legend_title_size A numeric\n#' @param legend_text_size A numeric\n#' @param linewidth A numeric\n#'\n#' @details\n#'\n#' The \\code{labels} encode the POSITIVE/NEGATIVE (\\code{TRUE}/\\code{FALSE}) status of data\n#' while each column of \\code{scores} provides scores corresponding to a ranking of those data:\n#' a smaller score means a smaller rank.\n#'\n#' A precision-recall curve is plotted for each column of the \\code{scores}. The interpolation\n#' between points is done according to the principle of partial acceptance.\n#'\n#' \\code{print_friendly} enables to produce print-friendly plots.\n#' If set to \\code{TRUE}, the function yields a black and white plot (background and lines)\n#' with a different line type for each curve.\n#' \\code{use_color} and \\code{use_linetype}, if present, specifies if the curved should be colored or\n#' drawn with different line types.\n#' These parameters override the behavior specified by \\code{print_friendly}.\n#'\n#' \\code{axis_label_size}, \\code{legend_title_size}, \\code{legend_text_size} and \\code{linewidth} are\n#' self-explanatory parameters to tune a few aesthetics.\n#' Besides, the function returns a ggplot object which can be modified a posteriori using the ggplot\n#' interface.\n#'\n#' @return A \\code{ggplot} object representing precision-recall curves.\n#' @examples\n#'\n#' labels = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE) # 8 pieces of data\n#'\n#' ranking1 = c(1,1,8,3,7,6,4,5)\n#' ranking2 = c(4,6,3,3,2,5,6,6)\n#' ranking3 = c(6,-1,3,3,2,4,1,5)\n#'\n#' scores = cbind(ranking1, ranking2, ranking3)\n#' colnames(scores) = c(\"method a\", \"method b\", \"method c\")\n#'\n#' # Default plot\n#' plot_precall(labels, scores)\n#'\n#' # Black and white plot\n#' plot_precall(labels, scores, print_friendly=TRUE)\n#'\n#' # Print-friendly background with colored curves\n#' plot_precall(labels, scores, print_friendly=TRUE, use_color=TRUE, use_linetype=FALSE)\n#'\n#' @export\nplot_precall <- function(labels, scores, print_friendly = FALSE, use_color, use_linetype,\n axis_label_size=15, legend_title_size=13, legend_text_size=10,\n linewidth=0.7)\n{\n\n if(missing(scores)) scores = matrix(seq_along(labels))\n if(missing(use_color)) use_color = !print_friendly\n if(missing(use_linetype)) use_linetype = print_friendly\n\n if(scores %>% is.vector) scores = matrix(scores)\n check_arguments(labels, scores)\n\n # Each column corresponds to the ranking of a method.\n meth_names = paste(\"ranking\", seq_len(ncol(scores)))\n col_names = colnames(scores)\n if(!is.null(col_names)){\n meth_names[col_names != \"\"] = col_names[col_names != \"\"]\n }\n\n coord_matrices = plyr::alply(.data=scores, .margins=2,\n .fun=precall_interpolation,\n labels=labels)\n names(coord_matrices) = meth_names\n coord_matrices = lapply(meth_names, FUN=function(n) cbind(coord_matrices[[n]],n))\n coord_matrix = do.call(rbind, coord_matrices)\n coord_matrix = data.frame(coord_matrix)\n colnames(coord_matrix) = c(\"precision\", \"recall\", \"Method\")\n\n # Creating the PR-curve\n aesthetics = ggplot2::aes(x=recall, y=precision, color=Method, linetype=Method)\n if(!use_color) aesthetics$colour = NULL\n if(!use_linetype) aesthetics$linetype = NULL\n\n plot = ggplot2::ggplot(coord_matrix, aesthetics)\n plot = plot + ggplot2::geom_line(size=linewidth)\n\n plot = plot + ggplot2::scale_x_continuous(limits = c(0,1), name=\"Recall\")\n plot = plot + ggplot2::scale_y_continuous(limits = c(0,1), name=\"Precision\")\n if(print_friendly) plot = plot + ggplot2::theme_bw()\n plot = plot + ggplot2::theme(axis.title = ggplot2::element_text(size=axis_label_size, face=\"bold\"))\n plot = plot + ggplot2::theme(legend.title = ggplot2::element_text(size=legend_title_size, face=\"bold\"))\n plot = plot + ggplot2::theme(legend.text = ggplot2::element_text(size=legend_text_size))\n\n return(plot)\n}\n\n\n#' Computes the point coordinates of a precision-recall curve\n#'\n#' @param scores A vector of numeric values\n#' @param labels A vector of logical values\n#' @param nb_interpolation_points A numeric\nprecall_interpolation <- function(labels, scores, nb_interpolation_points=30)\n{\n unique_scores <- sort(unique(scores), decreasing = FALSE)\n\n if(length(unique_scores)==1) {\n precision = sum(labels)/length(labels)\n precisions = c(precision, precision)\n recalls = c(0,1)\n return(data.frame(precision = precisions, recall = recalls))\n }\n\n cumsum_num = sapply(unique_scores, function(s) sum(scores[ labels] <= s))\n cumsum_denom = sapply(unique_scores, function(s) sum(scores <= s))\n\n\n interp_num = sapply(seq_len(length(cumsum_num) - 1), function(i) {\n seq(cumsum_num[i], cumsum_num[i + 1], length = nb_interpolation_points)\n })\n interp_denom = sapply(seq_len(length(cumsum_num) - 1), function(i) {\n seq(cumsum_denom[i], cumsum_denom[i + 1], length = nb_interpolation_points)\n })\n\n dim(interp_num) = NULL\n dim(interp_denom) = NULL\n\n precisions = interp_num/interp_denom\n recalls = interp_num/sum(labels)\n precisions = c(precisions[1], precisions)\n recalls = c(0, recalls)\n\n drop = sapply(2:(length(recalls)-1), function(i) recalls[i-1]==recalls[i+1])\n drop = c(FALSE, drop, FALSE)\n\n recalls = recalls[!drop]\n precisions = precisions[!drop]\n\n return(data.frame(precision = precisions, recall = recalls))\n}\n\n\n#' Compute the AUPR for precision-recall curves.\n#'\n#' Compute the Area Under the Precision-Recall curve (AUPR) for one or multiple precision-recall curves.\n#'\n#' @param scores A matrix or vector of numeric values that specifies the rankings\n#' @param labels A vector of logical values that encodes the POSITIVE/NEGATIVE status of data\n#'\n#' @return The vector of AUPR's.\n#'\n#' @details\n#'\n#' The \\code{labels} encode the POSITIVE/NEGATIVE (\\code{TRUE}/\\code{FALSE}) status of data\n#' while each column of \\code{scores} provides scores corresponding to a ranking of those data:\n#' a smaller score means a smaller rank.\n#' A vector can be used as \\code{scores} instead of a 1-column matrix to compute the AUPR of\n#' only one ranking. If no \\code{scores} are provided, it is assumed that the labels are already\n#' sorted and the function computes the corresponding AUPR.\n#'\n#' If \\code{scores} is a k-column matrix, the function returns a vector of length k, otherwise it\n#' returns a scalar.\n#'\n#' The area is computed from precision-recall curves interpolated using the principle of partial\n#' acceptance (see vignette \\code{precall} for more details).\n#'\n#' @examples\n#'\n#' labels = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE) # 8 pieces of data\n#'\n#' ranking1 = c(1,1,8,3,7,6,4,5)\n#' ranking2 = c(4,6,3,3,2,5,6,6)\n#' ranking3 = c(6,-1,3,3,2,4,1,5)\n#'\n#' scores = cbind(ranking1, ranking2, ranking3)\n#' colnames(scores) = c(\"method a\", \"method b\", \"method c\")\n#'\n#' # Implicit ranking\n#' aupr(labels)\n#' aupr(labels) == aupr(labels, seq_along(labels)) # is TRUE\n#'\n#' # Explicit single ranking\n#' aupr(labels, ranking1)\n#'\n#' # Explicit multiple rankings\n#' aupr(labels, scores)\n#'\n#' @export\naupr <- function(labels, scores){\n\n if(missing(scores)) scores = matrix(seq_along(labels))\n if(scores %>% is.vector) scores = matrix(scores)\n check_arguments(labels, scores)\n\n apply(scores, 2, function(s) {compute_aupr(labels,s)})\n}\n\n\ncompute_aupr <- function(labels, scores){\n\n unique_scores <- sort(unique(scores), decreasing = FALSE)\n total_positives <- sum(labels)\n\n true_positives <- sapply(unique_scores, function(s) sum(scores[labels] <= s))\n positives <- sapply(unique_scores, function(s) sum(scores <= s))\n\n\n if(true_positives[1] != 0){\n area = true_positives[1] / total_positives\n area = area * true_positives[1] / positives[1]\n } else {\n area = 0\n }\n\n len = length(unique_scores) - 1\n for(i in seq_len(len)){\n\n tp1 = true_positives[i]\n tp2 = true_positives[i+1]\n\n if(tp1 == tp2) next\n\n p1 = positives[i]\n p2 = positives[i+1]\n\n area = area + .aupr_piece(tp1, tp2, p1, p2, total_positives)\n }\n\n return(area)\n}\n\n\n#' Computes a partial AUPR\n#'\n#' Computes a partial AUPR (area under precision-recall curve)\n#'\n#' @param p Total number of positives\n#' @param p1 Number of positives at position 1\n#' @param p2 Number of positives at position 2\n#' @param tp1 Number of true positives at position 1\n#' @param tp2 Number of true positives at position 2\n#'\n#' @return Return the aupr between position 1 and position 2.\n.aupr_piece <- function(tp1, tp2, p1, p2, p){\n area <- log(p2/p1) * (tp1 * p2 - tp2 * p1) / (p1 - p2)^2\n area <- area + (tp1 - tp2)/(p1 - p2)\n area <- area * (tp2-tp1)/p\n\n return(area)\n}\n\n\n# Check the validity of scores and labels arguments.\ncheck_arguments <- function(labels, scores) {\n assertthat::assert_that(scores %>% is.numeric, msg=\"scores must be a numeric matrix or vector\")\n assertthat::assert_that(scores %>% is.matrix, msg=\"scores must be a numeric matrix or vector\")\n assertthat::assert_that(labels %>% is.logical, msg=\"labels must be a vector of logical values\")\n assertthat::assert_that(labels %>% is.vector, msg=\"labels must be a vector of logical values\")\n\n assertthat::assert_that(length(labels) == nrow(scores),\n msg=\"the number of rows of scores must be equal to the length of labels.\")\n}\n", "meta": {"hexsha": "d91fca3d007cb63466b205a43abd67acc5043992", "size": 11448, "ext": "r", "lang": "R", "max_stars_repo_path": "R/precall.r", "max_stars_repo_name": "adessy/precall", "max_stars_repo_head_hexsha": "09f0053ab54e01032816ce5c088132264430bed6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2015-06-10T11:29:28.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-10T11:29:28.000Z", "max_issues_repo_path": "R/precall.r", "max_issues_repo_name": "adessy/precall", "max_issues_repo_head_hexsha": "09f0053ab54e01032816ce5c088132264430bed6", "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/precall.r", "max_forks_repo_name": "adessy/precall", "max_forks_repo_head_hexsha": "09f0053ab54e01032816ce5c088132264430bed6", "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.2899022801, "max_line_length": 105, "alphanum_fraction": 0.7110412299, "num_tokens": 3061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.0335895055291764, "lm_q1q2_score": 0.009882535018496046}} {"text": "\n\n\n\n\n\n\n C\bCH\bHA\bAP\bPT\bTE\bER\bR 2\b2\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs\n\n\n\n\n The following functions allow one to create and manipu-\n late the various types of lisp data structures. Refer to\n S1.2 for details of the data structures known to FRANZ LISP.\n\n\n\n 2\b2.\b.1\b1.\b. L\bLi\bis\bst\bts\bs\n\n The following functions exist for the creation\n and manipulating of lists. Lists are composed of a\n linked list of objects called either 'list cells',\n 'cons cells' or 'dtpr cells'. Lists are normally ter-\n minated with the special symbol n\bni\bil\bl. n\bni\bil\bl is both a\n symbol and a representation for the empty list ().\n\n\n\n 2\b2.\b.1\b1.\b.1\b1.\b. l\bli\bis\bst\bt c\bcr\bre\bea\bat\bti\bio\bon\bn\n\n (\b(c\bco\bon\bns\bs 'g_arg1 'g_arg2)\b)\n\n RETURNS: a new list cell whose car is g_arg1 and whose\n cdr is g_arg2.\n\n (\b(x\bxc\bco\bon\bns\bs 'g_arg1 'g_arg2)\b)\n\n EQUIVALENT TO: _\b(_\bc_\bo_\bn_\bs _\b'_\bg_\b__\ba_\br_\bg_\b2 _\b'_\bg_\b__\ba_\br_\bg_\b1_\b)\n\n (\b(n\bnc\bco\bon\bns\bs 'g_arg)\b)\n\n EQUIVALENT TO: _\b(_\bc_\bo_\bn_\bs _\b'_\bg_\b__\ba_\br_\bg _\bn_\bi_\bl_\b)\n\n (\b(l\bli\bis\bst\bt ['g_arg1 ... ])\b)\n\n RETURNS: a list whose elements are the g_arg_\bi.\n\n\n\n\n\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b1\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b2\n\n\n (\b(a\bap\bpp\bpe\ben\bnd\bd 'l_arg1 'l_arg2)\b)\n\n RETURNS: a list containing the elements of l_arg1 fol-\n lowed by l_arg2.\n\n NOTE: To generate the result, the top level list cells\n of l_arg1 are duplicated and the cdr of the last\n list cell is set to point to l_arg2. Thus this\n is an expensive operation if l_arg1 is large.\n See the descriptions of _\bn_\bc_\bo_\bn_\bc and _\bt_\bc_\bo_\bn_\bc for\n cheaper ways of doing the _\ba_\bp_\bp_\be_\bn_\bd if the list\n l_arg1 can be altered.\n\n (\b(a\bap\bpp\bpe\ben\bnd\bd1\b1 'l_arg1 'g_arg2)\b)\n\n RETURNS: a list like l_arg1 with g_arg2 as the last\n element.\n\n NOTE: this is equivalent to (append 'l_arg1 (list\n 'g_arg2)).\n\n\n ____________________________________________________\n\n ; A common mistake is using append to add one element to the end of a list\n -> _\b(_\ba_\bp_\bp_\be_\bn_\bd _\b'_\b(_\ba _\bb _\bc _\bd_\b) _\b'_\be_\b)\n (a b c d . e)\n ; The user intended to say:\n -> _\b(_\ba_\bp_\bp_\be_\bn_\bd _\b'_\b(_\ba _\bb _\bc _\bd_\b) _\b'_\b(_\be_\b)_\b)\n _\b(_\ba _\bb _\bc _\bd _\be_\b)\n _\b; _\bb_\be_\bt_\bt_\be_\br _\bi_\bs _\ba_\bp_\bp_\be_\bn_\bd_\b1\n _\b-_\b> _\b(_\ba_\bp_\bp_\be_\bn_\bd_\b1 _\b'_\b(_\ba _\bb _\bc _\bd_\b) _\b'_\be_\b)\n _\b(_\ba _\bb _\bc _\bd _\be_\b)\n _\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b_\n\n\n\n\n (\b(q\bqu\buo\bot\bte\be!\b! [g_qform_\bi] ...[! 'g_eform_\bi] ... [!! 'l_form_\bi] ...)\b)\n\n RETURNS: The list resulting from the splicing and\n insertion process described below.\n\n NOTE: _\bq_\bu_\bo_\bt_\be_\b! is the complement of the _\bl_\bi_\bs_\bt function.\n _\bl_\bi_\bs_\bt forms a list by evaluating each for in the\n argument list; evaluation is suppressed if the\n form is _\bq_\bu_\bo_\bt_\beed. In _\bq_\bu_\bo_\bt_\be_\b!_\b, each form is implic-\n itly _\bq_\bu_\bo_\bt_\beed. To be evaluated, a form must be\n preceded by one of the evaluate operations ! and\n !!. ! g_eform evaluates g_form and the value is\n inserted in the place of the call; !! l_form\n evaluates l_form and the value is spliced into\n the place of the call.\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b3\n\n\n `Splicing in' means that the parentheses sur-\n rounding the list are removed as the example\n below shows. Use of the evaluate operators can\n occur at any level in a form argument.\n\n Another way to get the effect of the _\bq_\bu_\bo_\bt_\be_\b! func-\n tion is to use the backquote character macro (see\n S 8.3.3).\n\n\n ____________________________________________________\n\n _\b(_\bq_\bu_\bo_\bt_\be_\b! _\bc_\bo_\bn_\bs _\b! _\b(_\bc_\bo_\bn_\bs _\b1 _\b2_\b) _\b3_\b) _\b= _\b(_\bc_\bo_\bn_\bs _\b(_\b1 _\b. _\b2_\b) _\b3_\b)\n _\b(_\bq_\bu_\bo_\bt_\be_\b! _\b1 _\b!_\b! _\b(_\bl_\bi_\bs_\bt _\b2 _\b3 _\b4_\b) _\b5_\b) _\b= _\b(_\b1 _\b2 _\b3 _\b4 _\b5_\b)\n _\b(_\bs_\be_\bt_\bq _\bq_\bu_\bo_\bt_\be_\bd _\b'_\be_\bv_\ba_\bl_\be_\bd_\b)_\b(_\bq_\bu_\bo_\bt_\be_\b! _\b! _\b(_\b(_\bI _\ba_\bm _\b! _\bq_\bu_\bo_\bt_\be_\bd_\b)_\b)_\b) _\b= _\b(_\b(_\bI _\ba_\bm _\be_\bv_\ba_\bl_\be_\bd_\b)_\b)\n _\b(_\bq_\bu_\bo_\bt_\be_\b! _\bt_\br_\by _\b! _\b'_\b(_\bt_\bh_\bi_\bs _\b! _\bo_\bn_\be_\b)_\b) _\b= _\b(_\bt_\br_\by _\b(_\bt_\bh_\bi_\bs _\b! _\bo_\bn_\be_\b)_\b)\n ____________________________________________________\n\n\n\n\n\n (\b(b\bbi\big\bgn\bnu\bum\bm-\b-t\bto\bo-\b-l\bli\bis\bst\bt 'b_arg)\b)\n\n RETURNS: A list of the fixnums which are used to repre-\n sent the bignum.\n\n NOTE: the inverse of this function is _\bl_\bi_\bs_\bt_\b-_\bt_\bo_\b-_\bb_\bi_\bg_\bn_\bu_\bm_\b.\n\n (\b(l\bli\bis\bst\bt-\b-t\bto\bo-\b-b\bbi\big\bgn\bnu\bum\bm 'l_ints)\b)\n\n WHERE: l_ints is a list of fixnums.\n\n RETURNS: a bignum constructed of the given fixnums.\n\n NOTE: the inverse of this function is _\bb_\bi_\bg_\bn_\bu_\bm_\b-_\bt_\bo_\b-_\bl_\bi_\bs_\bt_\b.\n\n\n\n\n 2\b2.\b.1\b1.\b.2\b2.\b. l\bli\bis\bst\bt p\bpr\bre\bed\bdi\bic\bca\bat\bte\bes\bs\n\n (\b(d\bdt\btp\bpr\br 'g_arg)\b)\n\n RETURNS: t iff g_arg is a list cell.\n\n NOTE: that (dtpr '()) is nil. The name d\bdt\btp\bpr\br is a con-\n traction for ``dotted pair''.\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-4\b4\n\n\n (\b(l\bli\bis\bst\btp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a list object or nil.\n\n (\b(t\bta\bai\bil\blp\bp 'l_x 'l_y)\b)\n\n RETURNS: l_x, if a list cell _\be_\bq to l_x is found by\n _\bc_\bd_\bring down l_y zero or more times, nil other-\n wise.\n\n\n ____________________________________________________\n\n -> _\b(_\bs_\be_\bt_\bq _\bx _\b'_\b(_\ba _\bb _\bc _\bd_\b) _\by _\b(_\bc_\bd_\bd_\br _\bx_\b)_\b)\n (c d)\n -> _\b(_\ba_\bn_\bd _\b(_\bd_\bt_\bp_\br _\bx_\b) _\b(_\bl_\bi_\bs_\bt_\bp _\bx_\b)_\b) ; x and y are dtprs and lists\n t\n -> _\b(_\bd_\bt_\bp_\br _\b'_\b(_\b)_\b) ; () is the same as nil and is not a dtpr\n nil\n -> _\b(_\bl_\bi_\bs_\bt_\bp _\b'_\b(_\b)_\b) ; however it is a list\n t\n -> _\b(_\bt_\ba_\bi_\bl_\bp _\by _\bx_\b)\n (c d)\n ____________________________________________________\n\n\n\n\n (\b(l\ble\ben\bng\bgt\bth\bh 'l_arg)\b)\n\n RETURNS: the number of elements in the top level of\n list l_arg.\n\n\n\n 2\b2.\b.1\b1.\b.3\b3.\b. l\bli\bis\bst\bt a\bac\bcc\bce\bes\bss\bsi\bin\bng\bg\n\n (\b(c\bca\bar\br 'l_arg)\b)\n (\b(c\bcd\bdr\br 'l_arg)\b)\n\n RETURNS: _\bc_\bo_\bn_\bs cell. (_\bc_\ba_\br (_\bc_\bo_\bn_\bs x y)) is always x, (_\bc_\bd_\br\n (_\bc_\bo_\bn_\bs x y)) is always y. In FRANZ LISP, the\n cdr portion is located first in memory. This\n is hardly noticeable, and we mention it pri-\n marily as a curiosity.\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-5\b5\n\n\n (\b(c\bc.\b..\b.r\br 'lh_arg)\b)\n\n WHERE: the .. represents any positive number of a\ba's\n and d\bd's.\n\n RETURNS: the result of accessing the list structure in\n the way determined by the function name. The\n a\ba's and d\bd's are read from right to left, a d\bd\n directing the access down the cdr part of the\n list cell and an a\ba down the car part.\n\n NOTE: lh_arg may also be nil, and it is guaranteed that\n the car and cdr of nil is nil. If lh_arg is a\n hunk, then _\b(_\bc_\ba_\br _\b'_\bl_\bh_\b__\ba_\br_\bg_\b) is the same as\n _\b(_\bc_\bx_\br _\b1 _\b'_\bl_\bh_\b__\ba_\br_\bg_\b) and _\b(_\bc_\bd_\br _\b'_\bl_\bh_\b__\ba_\br_\bg_\b) is the same as\n _\b(_\bc_\bx_\br _\b0 _\b'_\bl_\bh_\b__\ba_\br_\bg_\b).\n It is generally hard to read and understand the\n context of functions with large strings of a\ba's\n and d\bd's, but these functions are supported by\n rapid accessing and open-compiling (see Chapter\n 12).\n\n (\b(n\bnt\bth\bh 'x_index 'l_list)\b)\n\n RETURNS: the nth element of l_list, assuming zero-based\n index. Thus (nth 0 l_list) is the same as\n (car l_list). _\bn_\bt_\bh is both a function, and a\n compiler macro, so that more efficient code\n might be generated than for _\bn_\bt_\bh_\be_\bl_\be_\bm (described\n below).\n\n NOTE: If x_arg1 is non-positive or greater than the\n length of the list, nil is returned.\n\n (\b(n\bnt\bth\bhc\bcd\bdr\br 'x_index 'l_list)\b)\n\n RETURNS: the result of _\bc_\bd_\bring down the list l_list\n x_index times.\n\n NOTE: If x_index is less than 0, then\n _\b(_\bc_\bo_\bn_\bs _\bn_\bi_\bl _\b'_\bl_\b__\bl_\bi_\bs_\bt_\b) is returned.\n\n (\b(n\bnt\bth\bhe\bel\ble\bem\bm 'x_arg1 'l_arg2)\b)\n\n RETURNS: The x_arg1'_\bs_\bt element of the list l_arg2.\n\n NOTE: This function comes from the PDP-11 Lisp system.\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-6\b6\n\n\n (\b(l\bla\bas\bst\bt 'l_arg)\b)\n\n RETURNS: the last list cell in the list l_arg.\n\n EXAMPLE: _\bl_\ba_\bs_\bt does NOT return the last element of a\n list!\n _\b(_\bl_\ba_\bs_\bt _\b'_\b(_\ba _\bb_\b)_\b) = (b)\n\n (\b(l\bld\bdi\bif\bff\bf 'l_x 'l_y)\b)\n\n RETURNS: a list of all elements in l_x but not in l_y\n , i.e., the list difference of l_x and l_y.\n\n NOTE: l_y must be a tail of l_x, i.e., _\be_\bq to the result\n of applying some number of _\bc_\bd_\br's to l_x. Note\n that the value of _\bl_\bd_\bi_\bf_\bf is always new\n list structure unless l_y is nil, in which case\n _\b(_\bl_\bd_\bi_\bf_\bf _\bl_\b__\bx _\bn_\bi_\bl_\b) is l_x itself. If l_y is not\n a tail of l_x, _\bl_\bd_\bi_\bf_\bf generates an error.\n\n EXAMPLE: _\b(_\bl_\bd_\bi_\bf_\bf _\b'_\bl_\b__\bx _\b(_\bm_\be_\bm_\bb_\be_\br _\b'_\bg_\b__\bf_\bo_\bo _\b'_\bl_\b__\bx_\b)_\b) gives all\n elements in l_x up to the first g_foo.\n\n\n\n 2\b2.\b.1\b1.\b.4\b4.\b. l\bli\bis\bst\bt m\bma\ban\bni\bip\bpu\bul\bla\bat\bti\bio\bon\bn\n\n (\b(r\brp\bpl\bla\bac\bca\ba 'lh_arg1 'g_arg2)\b)\n\n RETURNS: the modified lh_arg1.\n\n SIDE EFFECT: the car of lh_arg1 is set to g_arg2. If\n lh_arg1 is a hunk then the second element\n of the hunk is set to g_arg2.\n\n (\b(r\brp\bpl\bla\bac\bcd\bd 'lh_arg1 'g_arg2)\b)\n\n RETURNS: the modified lh_arg1.\n\n SIDE EFFECT: the cdr of lh_arg2 is set to g_arg2. If\n lh_arg1 is a hunk then the first element\n of the hunk is set to g_arg2.\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-7\b7\n\n\n (\b(a\bat\btt\bta\bac\bch\bh 'g_x 'l_l)\b)\n\n RETURNS: l_l whose _\bc_\ba_\br is now g_x, whose _\bc_\ba_\bd_\br is the\n original _\b(_\bc_\ba_\br _\bl_\b__\bl_\b), and whose _\bc_\bd_\bd_\br is the\n original _\b(_\bc_\bd_\br _\bl_\b__\bl_\b).\n\n NOTE: what happens is that g_x is added to the begin-\n ning of list l_l yet maintaining the same list\n cell at the beginning of the list.\n\n (\b(d\bde\bel\ble\bet\bte\be 'g_val 'l_list ['x_count])\b)\n\n RETURNS: the result of splicing g_val from the top\n level of l_list no more than x_count times.\n\n NOTE: x_count defaults to a very large number, thus if\n x_count is not given, all occurrences of g_val\n are removed from the top level of l_list. g_val\n is compared with successive _\bc_\ba_\br's of l_list using\n the function _\be_\bq_\bu_\ba_\bl.\n\n SIDE EFFECT: l_list is modified using rplacd, no new\n list cells are used.\n\n (\b(d\bde\bel\blq\bq 'g_val 'l_list ['x_count])\b)\n (\b(d\bdr\bre\bem\bmo\bov\bve\be 'g_val 'l_list ['x_count])\b)\n\n RETURNS: the result of splicing g_val from the top\n level of l_list no more than x_count times.\n\n NOTE: _\bd_\be_\bl_\bq (and _\bd_\br_\be_\bm_\bo_\bv_\be) are the same as _\bd_\be_\bl_\be_\bt_\be except\n that _\be_\bq is used for comparison instead of _\be_\bq_\bu_\ba_\bl.\n\n\n ____________________________________________________\n\n ; note that you should use the value returned by _\bd_\be_\bl_\be_\bt_\be or _\bd_\be_\bl_\bq\n ; and not assume that g_val will always show the deletions.\n ; For example\n\n -> _\b(_\bs_\be_\bt_\bq _\bt_\be_\bs_\bt _\b'_\b(_\ba _\bb _\bc _\ba _\bd _\be_\b)_\b)\n (a b c a d e)\n -> _\b(_\bd_\be_\bl_\be_\bt_\be _\b'_\ba _\bt_\be_\bs_\bt_\b)\n (b c d e) ; the value returned is what we would expect\n -> _\bt_\be_\bs_\bt\n (a b c d e) ; but test still has the first a in the list!\n ____________________________________________________\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-8\b8\n\n\n (\b(r\bre\bem\bmq\bq 'g_x 'l_l ['x_count])\b)\n (\b(r\bre\bem\bmo\bov\bve\be 'g_x 'l_l)\b)\n\n RETURNS: a _\bc_\bo_\bp_\by of l_l with all top level elements\n _\be_\bq_\bu_\ba_\bl to g_x removed. _\br_\be_\bm_\bq uses _\be_\bq instead of\n _\be_\bq_\bu_\ba_\bl for comparisons.\n\n NOTE: remove does not modify its arguments like _\bd_\be_\bl_\be_\bt_\be,\n and _\bd_\be_\bl_\bq do.\n\n (\b(i\bin\bns\bse\ber\brt\bt 'g_object 'l_list 'u_comparefn 'g_nodups)\b)\n\n RETURNS: a list consisting of l_list with g_object\n destructively inserted in a place determined\n by the ordering function u_comparefn.\n\n NOTE: _\b(_\bc_\bo_\bm_\bp_\ba_\br_\be_\bf_\bn _\b'_\bg_\b__\bx _\b'_\bg_\b__\by_\b) should return something\n non-nil if g_x can precede g_y in sorted order,\n nil if g_y must precede g_x. If u_comparefn is\n nil, alphabetical order will be used. If\n g_nodups is non-nil, an element will not be\n inserted if an equal element is already in the\n list. _\bi_\bn_\bs_\be_\br_\bt does binary search to determine\n where to insert the new element.\n\n (\b(m\bme\ber\brg\bge\be 'l_data1 'l_data2 'u_comparefn)\b)\n\n RETURNS: the merged list of the two input sorted lists\n l_data1 and l_data1 using binary comparison\n function u_comparefn.\n\n NOTE: _\b(_\bc_\bo_\bm_\bp_\ba_\br_\be_\bf_\bn _\b'_\bg_\b__\bx _\b'_\bg_\b__\by_\b) should return something\n non-nil if g_x can precede g_y in sorted order,\n nil if g_y must precede g_x. If u_comparefn is\n nil, alphabetical order will be used.\n u_comparefn should be thought of as \"less than or\n equal\". _\bm_\be_\br_\bg_\be changes both of its data argu-\n ments.\n\n (\b(s\bsu\bub\bbs\bst\bt 'g_x 'g_y 'l_s)\b)\n (\b(d\bds\bsu\bub\bbs\bst\bt 'g_x 'g_y 'l_s)\b)\n\n RETURNS: the result of substituting g_x for all _\be_\bq_\bu_\ba_\bl\n occurrences of g_y at all levels in l_s.\n\n NOTE: If g_y is a symbol, _\be_\bq will be used for compar-\n isons. The function _\bs_\bu_\bb_\bs_\bt does not modify l_s\n but the function _\bd_\bs_\bu_\bb_\bs_\bt (destructive substitu-\n tion) does.\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-9\b9\n\n\n (\b(l\bls\bsu\bub\bbs\bst\bt 'l_x 'g_y 'l_s)\b)\n\n RETURNS: a copy of l_s with l_x spliced in for every\n occurrence of of g_y at all levels. Splicing\n in means that the parentheses surrounding the\n list l_x are removed as the example below\n shows.\n\n\n ____________________________________________________\n\n -> _\b(_\bs_\bu_\bb_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b) _\b'_\bx _\b'_\b(_\bx _\by _\bz _\b(_\bx _\by _\bz_\b) _\b(_\bx _\by _\bz_\b)_\b)_\b)\n ((a b c) y z ((a b c) y z) ((a b c) y z))\n -> _\b(_\bl_\bs_\bu_\bb_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b) _\b'_\bx _\b'_\b(_\bx _\by _\bz _\b(_\bx _\by _\bz_\b) _\b(_\bx _\by _\bz_\b)_\b)_\b)\n (a b c y z (a b c y z) (a b c y z))\n ____________________________________________________\n\n\n\n\n (\b(s\bsu\bub\bbp\bpa\bai\bir\br 'l_old 'l_new 'l_expr)\b)\n\n WHERE: there are the same number of elements in\n l_old as l_new.\n\n RETURNS: the list l_expr with all occurrences of a\n object in l_old replaced by the corresponding\n one in l_new. When a substitution is made, a\n copy of the value to substitute in is not\n made.\n\n EXAMPLE: _\b(_\bs_\bu_\bb_\bp_\ba_\bi_\br _\b'_\b(_\ba _\bc_\b)_\b' _\b(_\bx _\by_\b) _\b'_\b(_\ba _\bb _\bc _\bd_\b)_\b) _\b= _\b(_\bx _\bb _\by _\bd_\b)\n\n\n (\b(n\bnc\bco\bon\bnc\bc 'l_arg1 'l_arg2 ['l_arg3 ...])\b)\n\n RETURNS: A list consisting of the elements of l_arg1\n followed by the elements of l_arg2 followed by\n l_arg3 and so on.\n\n NOTE: The _\bc_\bd_\br of the last list cell of l_arg_\bi is\n changed to point to l_arg_\bi_\b+_\b1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b10\b0\n\n\n\n ____________________________________________________\n\n ; _\bn_\bc_\bo_\bn_\bc is faster than _\ba_\bp_\bp_\be_\bn_\bd because it doesn't allocate new list cells.\n -> _\b(_\bs_\be_\bt_\bq _\bl_\bi_\bs_\b1 _\b'_\b(_\ba _\bb _\bc_\b)_\b)\n (a b c)\n -> _\b(_\bs_\be_\bt_\bq _\bl_\bi_\bs_\b2 _\b'_\b(_\bd _\be _\bf_\b)_\b)\n (d e f)\n -> _\b(_\ba_\bp_\bp_\be_\bn_\bd _\bl_\bi_\bs_\b1 _\bl_\bi_\bs_\b2_\b)\n (a b c d e f)\n -> _\bl_\bi_\bs_\b1\n (a b c) ; note that lis1 has not been changed by _\ba_\bp_\bp_\be_\bn_\bd\n -> _\b(_\bn_\bc_\bo_\bn_\bc _\bl_\bi_\bs_\b1 _\bl_\bi_\bs_\b2_\b)\n (a b c d e f) ; _\bn_\bc_\bo_\bn_\bc returns the same value as _\ba_\bp_\bp_\be_\bn_\bd\n -> _\bl_\bi_\bs_\b1\n (a b c d e f) ; but in doing so alters lis1\n ____________________________________________________\n\n\n\n\n\n (\b(r\bre\bev\bve\ber\brs\bse\be 'l_arg)\b)\n (\b(n\bnr\bre\bev\bve\ber\brs\bse\be 'l_arg)\b)\n\n RETURNS: the list l_arg with the elements at the top\n level in reverse order.\n\n NOTE: The function _\bn_\br_\be_\bv_\be_\br_\bs_\be does the reversal in place,\n that is the list structure is modified.\n\n (\b(n\bnr\bre\bec\bco\bon\bnc\bc 'l_arg 'g_arg)\b)\n\n EQUIVALENT TO: _\b(_\bn_\bc_\bo_\bn_\bc _\b(_\bn_\br_\be_\bv_\be_\br_\bs_\be _\b'_\bl_\b__\ba_\br_\bg_\b) _\b'_\bg_\b__\ba_\br_\bg_\b)\n\n\n\n\n 2\b2.\b.2\b2.\b. P\bPr\bre\bed\bdi\bic\bca\bat\bte\bes\bs\n\n The following functions test for properties of\n data objects. When the result of the test is either\n 'false' or 'true', then n\bni\bil\bl will be returned for\n 'false' and something other than n\bni\bil\bl (often t\bt) will be\n returned for 'true'.\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b11\b1\n\n\n (\b(a\bar\brr\bra\bay\byp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is of type array.\n\n (\b(a\bat\bto\bom\bm 'g_arg)\b)\n\n RETURNS: t iff g_arg is not a list or hunk object.\n\n NOTE: _\b(_\ba_\bt_\bo_\bm _\b'_\b(_\b)_\b) returns t.\n\n (\b(b\bbc\bcd\bdp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a data object of type binary.\n\n NOTE: This function is a throwback to the PDP-11 Lisp\n system. The name stands for binary code predi-\n cate.\n\n (\b(b\bbi\big\bgp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a bignum.\n\n (\b(d\bdt\btp\bpr\br 'g_arg)\b)\n\n RETURNS: t iff g_arg is a list cell.\n\n NOTE: that (dtpr '()) is nil.\n\n (\b(h\bhu\bun\bnk\bkp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a hunk.\n\n (\b(l\bli\bis\bst\btp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a list object or nil.\n\n (\b(s\bst\btr\bri\bin\bng\bgp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a string.\n\n (\b(s\bsy\bym\bmb\bbo\bol\blp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a symbol.\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b12\b2\n\n\n (\b(v\bva\bal\blu\bue\bep\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is a value cell\n\n (\b(v\bve\bec\bct\bto\bor\brp\bp 'v_vector)\b)\n\n RETURNS: t\bt iff the argument is a vector.\n\n (\b(v\bve\bec\bct\bto\bor\bri\bip\bp 'v_vector)\b)\n\n RETURNS: t\bt iff the argument is an immediate-vector.\n\n (\b(t\bty\byp\bpe\be 'g_arg)\b)\n (\b(t\bty\byp\bpe\bep\bp 'g_arg)\b)\n\n RETURNS: a symbol whose pname describes the type of\n g_arg.\n\n (\b(s\bsi\big\bgn\bnp\bp s_test 'g_val)\b)\n\n RETURNS: t iff g_val is a number and the given test\n s_test on g_val returns true.\n\n NOTE: The fact that _\bs_\bi_\bg_\bn_\bp simply returns nil if g_val\n is not a number is probably the most important\n reason that _\bs_\bi_\bg_\bn_\bp is used. The permitted values\n for s_test and what they mean are given in this\n table.\n\n +--------------------+\n |s_test tested |\n | |\n +--------------------+\n |l g_val < 0 |\n |le g_val <= 0 |\n |e g_val = 0 |\n |n g_val != 0 |\n |ge g_val >= 0 |\n |g g_val > 0 |\n +--------------------+\n\n (\b(e\beq\bq 'g_arg1 'g_arg2)\b)\n\n RETURNS: t if g_arg1 and g_arg2 are the exact same lisp\n object.\n\n NOTE: _\bE_\bq simply tests if g_arg1 and g_arg2 are located\n in the exact same place in memory. Lisp objects\n which print the same are not necessarily _\be_\bq. The\n only objects guaranteed to be _\be_\bq are interned\n symbols with the same print name. [Unless a sym-\n bol is created in a special way (such as with\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b13\b3\n\n\n _\bu_\bc_\bo_\bn_\bc_\ba_\bt or _\bm_\ba_\bk_\bn_\ba_\bm) it will be interned.]\n\n (\b(n\bne\beq\bq 'g_x 'g_y)\b)\n\n RETURNS: t if g_x is not _\be_\bq to g_y, otherwise nil.\n\n (\b(e\beq\bqu\bua\bal\bl 'g_arg1 'g_arg2)\b)\n (\b(e\beq\bqs\bst\btr\br 'g_arg1 'g_arg2)\b)\n\n RETURNS: t iff g_arg1 and g_arg2 have the same struc-\n ture as described below.\n\n NOTE: g_arg and g_arg2 are _\be_\bq_\bu_\ba_\bl if\n\n (1) they are _\be_\bq.\n\n (2) they are both fixnums with the same value\n\n (3) they are both flonums with the same value\n\n (4) they are both bignums with the same value\n\n (5) they are both strings and are identical.\n\n (6) they are both lists and their cars and cdrs are\n _\be_\bq_\bu_\ba_\bl.\n\n\n ____________________________________________________\n\n ; _\be_\bq is much faster than _\be_\bq_\bu_\ba_\bl, especially in compiled code,\n ; however you cannot use _\be_\bq to test for equality of numbers outside\n ; of the range -1024 to 1023. _\be_\bq_\bu_\ba_\bl will always work.\n -> _\b(_\be_\bq _\b1_\b0_\b2_\b3 _\b1_\b0_\b2_\b3_\b)\n t\n -> _\b(_\be_\bq _\b1_\b0_\b2_\b4 _\b1_\b0_\b2_\b4_\b)\n nil\n -> _\b(_\be_\bq_\bu_\ba_\bl _\b1_\b0_\b2_\b4 _\b1_\b0_\b2_\b4_\b)\n t\n ____________________________________________________\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b14\b4\n\n\n (\b(n\bno\bot\bt 'g_arg)\b)\n (\b(n\bnu\bul\bll\bl 'g_arg)\b)\n\n RETURNS: t iff g_arg is nil.\n\n\n (\b(m\bme\bem\bmb\bbe\ber\br 'g_arg1 'l_arg2)\b)\n (\b(m\bme\bem\bmq\bq 'g_arg1 'l_arg2)\b)\n\n RETURNS: that part of the l_arg2 beginning with the\n first occurrence of g_arg1. If g_arg1 is not\n in the top level of l_arg2, nil is returned.\n\n NOTE: _\bm_\be_\bm_\bb_\be_\br tests for equality with _\be_\bq_\bu_\ba_\bl, _\bm_\be_\bm_\bq tests\n for equality with _\be_\bq.\n\n\n\n\n 2\b2.\b.3\b3.\b. S\bSy\bym\bmb\bbo\bol\bls\bs a\ban\bnd\bd S\bSt\btr\bri\bin\bng\bgs\bs\n\n In many of the following functions the distinc-\n tion between symbols and strings is somewhat blurred.\n To remind ourselves of the difference, a string is a\n null terminated sequence of characters, stored as com-\n pactly as possible. Strings are used as constants in\n FRANZ LISP. They _\be_\bv_\ba_\bl to themselves. A symbol has\n additional structure: a value, property list, function\n binding, as well as its external representation (or\n print-name). If a symbol is given to one of the\n string manipulation functions below, its print name\n will be used as the string.\n\n Another popular way to represent strings in Lisp\n is as a list of fixnums which represent characters.\n The suffix 'n' to a string manipulation function indi-\n cates that it returns a string in this form.\n\n\n\n 2\b2.\b.3\b3.\b.1\b1.\b. s\bsy\bym\bmb\bbo\bol\bl a\ban\bnd\bd s\bst\btr\bri\bin\bng\bg c\bcr\bre\bea\bat\bti\bio\bon\bn\n\n (\b(c\bco\bon\bnc\bca\bat\bt ['stn_arg1 ... ])\b)\n (\b(u\buc\bco\bon\bnc\bca\bat\bt ['stn_arg1 ... ])\b)\n\n RETURNS: a symbol whose print name is the result of\n concatenating the print names, string charac-\n ters or numerical representations of the\n sn_arg_\bi.\n\n NOTE: If no arguments are given, a symbol with a null\n pname is returned. _\bc_\bo_\bn_\bc_\ba_\bt places the symbol cre-\n ated on the oblist, the function _\bu_\bc_\bo_\bn_\bc_\ba_\bt does the\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b15\b5\n\n\n same thing but does not place the new symbol on\n the oblist.\n\n EXAMPLE: _\b(_\bc_\bo_\bn_\bc_\ba_\bt _\b'_\ba_\bb_\bc _\b(_\ba_\bd_\bd _\b3 _\b4_\b) _\b\"_\bd_\be_\bf_\b\"_\b) = abc7def\n\n (\b(c\bco\bon\bnc\bca\bat\btl\bl 'l_arg)\b)\n\n EQUIVALENT TO: _\b(_\ba_\bp_\bp_\bl_\by _\b'_\bc_\bo_\bn_\bc_\ba_\bt _\b'_\bl_\b__\ba_\br_\bg_\b)\n\n\n (\b(i\bim\bmp\bpl\blo\bod\bde\be 'l_arg)\b)\n (\b(m\bma\bak\bkn\bna\bam\bm 'l_arg)\b)\n\n WHERE: l_arg is a list of symbols, strings and small\n fixnums.\n\n RETURNS: The symbol whose print name is the result of\n concatenating the first characters of the\n print names of the symbols and strings in the\n list. Any fixnums are converted to the equiv-\n alent ascii character. In order to concate-\n nate entire strings or print names, use the\n function _\bc_\bo_\bn_\bc_\ba_\bt.\n\n NOTE: _\bi_\bm_\bp_\bl_\bo_\bd_\be interns the symbol it creates, _\bm_\ba_\bk_\bn_\ba_\bm\n does not.\n\n (\b(g\bge\ben\bns\bsy\bym\bm ['s_leader])\b)\n\n RETURNS: a new uninterned atom beginning with the first\n character of s_leader's pname, or beginning\n with g if s_leader is not given.\n\n NOTE: The symbol looks like x0nnnnn where x is\n s_leader's first character and nnnnn is the num-\n ber of times you have called gensym.\n\n (\b(c\bco\bop\bpy\bys\bsy\bym\bmb\bbo\bol\bl 's_arg 'g_pred)\b)\n\n RETURNS: an uninterned symbol with the same print name\n as s_arg. If g_pred is non nil, then the\n value, function binding and property list of\n the new symbol are made _\be_\bq to those of s_arg.\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b16\b6\n\n\n (\b(a\bas\bsc\bci\bii\bi 'x_charnum)\b)\n\n WHERE: x_charnum is between 0 and 255.\n\n RETURNS: a symbol whose print name is the single char-\n acter whose fixnum representation is\n x_charnum.\n\n\n (\b(i\bin\bnt\bte\ber\brn\bn 's_arg)\b)\n\n RETURNS: s_arg\n\n SIDE EFFECT: s_arg is put on the oblist if it is not\n already there.\n\n (\b(r\bre\bem\bmo\bob\bb 's_symbol)\b)\n\n RETURNS: s_symbol\n\n SIDE EFFECT: s_symbol is removed from the oblist.\n\n (\b(r\bre\bem\bma\bat\bto\bom\bm 's_arg)\b)\n\n RETURNS: t if s_arg is indeed an atom.\n\n SIDE EFFECT: s_arg is put on the free atoms list,\n effectively reclaiming an atom cell.\n\n NOTE: This function does _\bn_\bo_\bt check to see if s_arg is\n on the oblist or is referenced anywhere. Thus\n calling _\br_\be_\bm_\ba_\bt_\bo_\bm on an atom in the oblist may\n result in disaster when that atom cell is reused!\n\n\n\n 2\b2.\b.3\b3.\b.2\b2.\b. s\bst\btr\bri\bin\bng\bg a\ban\bnd\bd s\bsy\bym\bmb\bbo\bol\bl p\bpr\bre\bed\bdi\bic\bca\bat\bte\bes\bs\n\n (\b(b\bbo\bou\bun\bnd\bdp\bp 's_name)\b)\n\n RETURNS: nil if s_name is unbound: that is, it has\n never been given a value. If x_name has the\n value g_val, then (nil . g_val) is returned.\n See also _\bm_\ba_\bk_\bu_\bn_\bb_\bo_\bu_\bn_\bd.\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b17\b7\n\n\n (\b(a\bal\blp\bph\bha\bal\ble\bes\bss\bsp\bp 'st_arg1 'st_arg2)\b)\n\n RETURNS: t iff the `name' of st_arg1 is alphabetically\n less than the name of st_arg2. If st_arg is a\n symbol then its `name' is its print name. If\n st_arg is a string, then its `name' is the\n string itself.\n\n\n\n 2\b2.\b.3\b3.\b.3\b3.\b. s\bsy\bym\bmb\bbo\bol\bl a\ban\bnd\bd s\bst\btr\bri\bin\bng\bg a\bac\bcc\bce\bes\bss\bsi\bin\bng\bg\n\n (\b(s\bsy\bym\bme\bev\bva\bal\bl 's_arg)\b)\n\n RETURNS: the value of symbol s_arg.\n\n NOTE: It is illegal to ask for the value of an unbound\n symbol. This function has the same effect as\n _\be_\bv_\ba_\bl, but compiles into much more efficient code.\n\n (\b(g\bge\bet\bt_\b_p\bpn\bna\bam\bme\be 's_arg)\b)\n\n RETURNS: the string which is the print name of s_arg.\n\n (\b(p\bpl\bli\bis\bst\bt 's_arg)\b)\n\n RETURNS: the property list of s_arg.\n\n (\b(g\bge\bet\btd\bd 's_arg)\b)\n\n RETURNS: the function definition of s_arg or nil if\n there is no function definition.\n\n NOTE: the function definition may turn out to be an\n array header.\n\n (\b(g\bge\bet\btc\bch\bha\bar\br 's_arg 'x_index)\b)\n (\b(n\bnt\bth\bhc\bch\bha\bar\br 's_arg 'x_index)\b)\n (\b(g\bge\bet\btc\bch\bha\bar\brn\bn 's_arg 'x_index)\b)\n\n RETURNS: the x_index_\bt_\bh character of the print name of\n s_arg or nil if x_index is less than 1 or\n greater than the length of s_arg's print name.\n\n NOTE: _\bg_\be_\bt_\bc_\bh_\ba_\br and _\bn_\bt_\bh_\bc_\bh_\ba_\br return a symbol with a single\n character print name, _\bg_\be_\bt_\bc_\bh_\ba_\br_\bn returns the fixnum\n representation of the character.\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b18\b8\n\n\n (\b(s\bsu\bub\bbs\bst\btr\bri\bin\bng\bg 'st_string 'x_index ['x_length])\b)\n (\b(s\bsu\bub\bbs\bst\btr\bri\bin\bng\bgn\bn 'st_string 'x_index ['x_length])\b)\n\n RETURNS: a string of length at most x_length starting\n at x_index_\bt_\bh character in the string.\n\n NOTE: If x_length is not given, all of the characters\n for x_index to the end of the string are\n returned. If x_index is negative the string\n begins at the x_index_\bt_\bh character from the end.\n If x_index is out of bounds, nil is returned.\n\n NOTE: _\bs_\bu_\bb_\bs_\bt_\br_\bi_\bn_\bg returns a list of symbols, _\bs_\bu_\bb_\bs_\bt_\br_\bi_\bn_\bg_\bn\n returns a list of fixnums. If _\bs_\bu_\bb_\bs_\bt_\br_\bi_\bn_\bg_\bn is\n given a 0 x_length argument then a single fixnum\n which is the x_index_\bt_\bh character is returned.\n\n\n\n 2\b2.\b.3\b3.\b.4\b4.\b. s\bsy\bym\bmb\bbo\bol\bl a\ban\bnd\bd s\bst\btr\bri\bin\bng\bg m\bma\ban\bni\bip\bpu\bul\bla\bat\bti\bio\bon\bn\n\n (\b(s\bse\bet\bt 's_arg1 'g_arg2)\b)\n\n RETURNS: g_arg2.\n\n SIDE EFFECT: the value of s_arg1 is set to g_arg2.\n\n (\b(s\bse\bet\btq\bq s_atm1 'g_val1 [ s_atm2 'g_val2 ... ... ])\b)\n\n WHERE: the arguments are pairs of atom names and\n expressions.\n\n RETURNS: the last g_val_\bi.\n\n SIDE EFFECT: each s_atm_\bi is set to have the value\n g_val_\bi.\n\n NOTE: _\bs_\be_\bt evaluates all of its arguments, _\bs_\be_\bt_\bq does not\n evaluate the s_atm_\bi.\n\n (\b(d\bde\bes\bse\bet\btq\bq sl_pattern1 'g_exp1 [... ...])\b)\n\n RETURNS: g_expn\n\n SIDE EFFECT: This acts just like _\bs_\be_\bt_\bq if all the\n sl_pattern_\bi are symbols. If sl_pattern_\bi\n is a list then it is a template which\n should have the same structure as g_exp_\bi\n The symbols in sl_pattern are assigned to\n the corresponding parts of g_exp. (See\n also _\bs_\be_\bt_\bf )\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-1\b19\b9\n\n\n EXAMPLE: _\b(_\bd_\be_\bs_\be_\bt_\bq _\b(_\ba _\bb _\b(_\bc _\b. _\bd_\b)_\b) _\b'_\b(_\b1 _\b2 _\b(_\b3 _\b4 _\b5_\b)_\b)_\b)\n sets a to 1, b to 2, c to 3, and d to (4 5).\n\n\n (\b(s\bse\bet\btp\bpl\bli\bis\bst\bt 's_atm 'l_plist)\b)\n\n RETURNS: l_plist.\n\n SIDE EFFECT: the property list of s_atm is set to\n l_plist.\n\n (\b(m\bma\bak\bku\bun\bnb\bbo\bou\bun\bnd\bd 's_arg)\b)\n\n RETURNS: s_arg\n\n SIDE EFFECT: the value of s_arg is made `unbound'. If\n the interpreter attempts to evaluate s_arg\n before it is again given a value, an\n unbound variable error will occur.\n\n (\b(a\bae\bex\bxp\bpl\blo\bod\bde\be 's_arg)\b)\n (\b(e\bex\bxp\bpl\blo\bod\bde\be 'g_arg)\b)\n (\b(a\bae\bex\bxp\bpl\blo\bod\bde\bec\bc 's_arg)\b)\n (\b(e\bex\bxp\bpl\blo\bod\bde\bec\bc 'g_arg)\b)\n (\b(a\bae\bex\bxp\bpl\blo\bod\bde\ben\bn 's_arg)\b)\n (\b(e\bex\bxp\bpl\blo\bod\bde\ben\bn 'g_arg)\b)\n\n RETURNS: a list of the characters used to print out\n s_arg or g_arg.\n\n NOTE: The functions beginning with 'a' are internal\n functions which are limited to symbol arguments.\n The functions _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be and _\be_\bx_\bp_\bl_\bo_\bd_\be return a list\n of characters which _\bp_\br_\bi_\bn_\bt would use to print the\n argument. These characters include all necessary\n escape characters. Functions _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be_\bc and\n _\be_\bx_\bp_\bl_\bo_\bd_\be_\bc return a list of characters which _\bp_\ba_\bt_\bo_\bm\n would use to print the argument (i.e. no escape\n characters). Functions _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be_\bn and _\be_\bx_\bp_\bl_\bo_\bd_\be_\bn\n are similar to _\ba_\be_\bx_\bp_\bl_\bo_\bd_\be_\bc and _\be_\bx_\bp_\bl_\bo_\bd_\be_\bc except that\n a list of fixnum equivalents of characters are\n returned.\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b20\b0\n\n\n\n ____________________________________________________\n\n -> _\b(_\bs_\be_\bt_\bq _\bx _\b'_\b|_\bq_\bu_\bo_\bt_\be _\bt_\bh_\bi_\bs _\b\\_\b| _\bo_\bk_\b?_\b|_\b)\n |quote this \\| ok?|\n -> _\b(_\be_\bx_\bp_\bl_\bo_\bd_\be _\bx_\b)\n (q u o t e |\\\\| | | t h i s |\\\\| | | |\\\\| |\\|| |\\\\| | | o k ?)\n ; note that |\\\\| just means the single character: backslash.\n ; and |\\|| just means the single character: vertical bar\n ; and | | means the single character: space\n\n -> _\b(_\be_\bx_\bp_\bl_\bo_\bd_\be_\bc _\bx_\b)\n (q u o t e | | t h i s | | |\\|| | | o k ?)\n -> _\b(_\be_\bx_\bp_\bl_\bo_\bd_\be_\bn _\bx_\b)\n (113 117 111 116 101 32 116 104 105 115 32 124 32 111 107 63)\n ____________________________________________________\n\n\n\n\n\n\n 2\b2.\b.4\b4.\b. V\bVe\bec\bct\bto\bor\brs\bs\n\n See Chapter 9 for a discussion of vectors. They\n are less efficient that hunks but more efficient than\n arrays.\n\n\n\n 2\b2.\b.4\b4.\b.1\b1.\b. v\bve\bec\bct\bto\bor\br c\bcr\bre\bea\bat\bti\bio\bon\bn\n\n (\b(n\bne\bew\bw-\b-v\bve\bec\bct\bto\bor\br 'x_size ['g_fill ['g_prop]])\b)\n\n RETURNS: A v\bve\bec\bct\bto\bor\br of length x_size. Each data entry is\n initialized to g_fill, or to nil, if the argu-\n ment g_fill is not present. The vector's\n property is set to g_prop, or to nil, by\n default.\n\n (\b(n\bne\bew\bw-\b-v\bve\bec\bct\bto\bor\bri\bi-\b-b\bby\byt\bte\be 'x_size ['g_fill ['g_prop]])\b)\n (\b(n\bne\bew\bw-\b-v\bve\bec\bct\bto\bor\bri\bi-\b-w\bwo\bor\brd\bd 'x_size ['g_fill ['g_prop]])\b)\n (\b(n\bne\bew\bw-\b-v\bve\bec\bct\bto\bor\bri\bi-\b-l\blo\bon\bng\bg 'x_size ['g_fill ['g_prop]])\b)\n\n RETURNS: A v\bve\bec\bct\bto\bor\bri\bi with x_size elements in it. The\n actual memory requirement is two long words +\n x_size*(n bytes), where n is 1 for new-vector-\n byte, 2 for new-vector-word, or 4 for new-\n vectori-long. Each data entry is initialized\n to g_fill, or to zero, if the argument g_fill\n is not present. The vector's property is set\n to g_prop, or nil, by default.\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b21\b1\n\n\n Vectors may be created by specifying multiple initial\n values:\n\n (\b(v\bve\bec\bct\bto\bor\br ['g_val0 'g_val1 ...])\b)\n\n RETURNS: a v\bve\bec\bct\bto\bor\br, with as many data elements as there\n are arguments. It is quite possible to have a\n vector with no data elements. The vector's\n property will be a null list.\n\n (\b(v\bve\bec\bct\bto\bor\bri\bi-\b-b\bby\byt\bte\be ['x_val0 'x_val2 ...])\b)\n (\b(v\bve\bec\bct\bto\bor\bri\bi-\b-w\bwo\bor\brd\bd ['x_val0 'x_val2 ...])\b)\n (\b(v\bve\bec\bct\bto\bor\bri\bi-\b-l\blo\bon\bng\bg ['x_val0 'x_val2 ...])\b)\n\n RETURNS: a v\bve\bec\bct\bto\bor\bri\bi, with as many data elements as there\n are arguments. The arguments are required to\n be fixnums. Only the low order byte or word\n is used in the case of vectori-byte and vec-\n tori-word. The vector's property will be\n null.\n\n\n\n 2\b2.\b.4\b4.\b.2\b2.\b. v\bve\bec\bct\bto\bor\br r\bre\bef\bfe\ber\bre\ben\bnc\bce\be\n\n (\b(v\bvr\bre\bef\bf 'v_vect 'x_index)\b)\n (\b(v\bvr\bre\bef\bfi\bi-\b-b\bby\byt\bte\be 'V_vect 'x_bindex)\b)\n (\b(v\bvr\bre\bef\bfi\bi-\b-w\bwo\bor\brd\bd 'V_vect 'x_windex)\b)\n (\b(v\bvr\bre\bef\bfi\bi-\b-l\blo\bon\bng\bg 'V_vect 'x_lindex)\b)\n\n RETURNS: the desired data element from a vector. The\n indices must be fixnums. Indexing is zero-\n based. The vrefi functions sign extend the\n data.\n\n (\b(v\bvp\bpr\bro\bop\bp 'Vv_vect)\b)\n\n RETURNS: The Lisp property associated with a vector.\n\n (\b(v\bvg\bge\bet\bt 'Vv_vect 'g_ind)\b)\n\n RETURNS: The value stored under g_ind if the Lisp prop-\n erty associated with 'Vv_vect is a disembodied\n property list.\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b22\b2\n\n\n (\b(v\bvs\bsi\biz\bze\be 'Vv_vect)\b)\n (\b(v\bvs\bsi\biz\bze\be-\b-b\bby\byt\bte\be 'V_vect)\b)\n (\b(v\bvs\bsi\biz\bze\be-\b-w\bwo\bor\brd\bd 'V_vect)\b)\n\n RETURNS: the number of data elements in the vector.\n For immediate-vectors, the functions vsize-\n byte and vsize-word return the number of data\n elements, if one thinks of the binary data as\n being comprised of bytes or words.\n\n\n\n 2\b2.\b.4\b4.\b.3\b3.\b. v\bve\bec\bct\bto\bor\br m\bmo\bod\bdf\bfi\bic\bca\bat\bti\bio\bon\bn\n\n (\b(v\bvs\bse\bet\bt 'v_vect 'x_index 'g_val)\b)\n (\b(v\bvs\bse\bet\bti\bi-\b-b\bby\byt\bte\be 'V_vect 'x_bindex 'x_val)\b)\n (\b(v\bvs\bse\bet\bti\bi-\b-w\bwo\bor\brd\bd 'V_vect 'x_windex 'x_val)\b)\n (\b(v\bvs\bse\bet\bti\bi-\b-l\blo\bon\bng\bg 'V_vect 'x_lindex 'x_val)\b)\n\n RETURNS: the datum.\n\n SIDE EFFECT: The indexed element of the vector is set\n to the value. As noted above, for vseti-\n word and vseti-byte, the index is con-\n strued as the number of the data element\n within the vector. It is not a byte\n address. Also, for those two functions,\n the low order byte or word of x_val is\n what is stored.\n\n (\b(v\bvs\bse\bet\btp\bpr\bro\bop\bp 'Vv_vect 'g_value)\b)\n\n RETURNS: g_value. This should be either a symbol or a\n disembodied property list whose _\bc_\ba_\br is a sym-\n bol identifying the type of the vector.\n\n SIDE EFFECT: the property list of Vv_vect is set to\n g_value.\n\n (\b(v\bvp\bpu\but\btp\bpr\bro\bop\bp 'Vv_vect 'g_value 'g_ind)\b)\n\n RETURNS: g_value.\n\n SIDE EFFECT: If the vector property of Vv_vect is a\n disembodied property list, then vputprop\n adds the value g_value under the indicator\n g_ind. Otherwise, the old vector property\n is made the first element of the list.\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b23\b3\n\n\n 2\b2.\b.5\b5.\b. A\bAr\brr\bra\bay\bys\bs\n\n See Chapter 9 for a complete description of\n arrays. Some of these functions are part of a Maclisp\n array compatibility package representing only one sim-\n ple way of using the array structure of FRANZ LISP.\n\n\n\n 2\b2.\b.5\b5.\b.1\b1.\b. a\bar\brr\bra\bay\by c\bcr\bre\bea\bat\bti\bio\bon\bn\n\n (\b(m\bma\bar\brr\bra\bay\by 'g_data 's_access 'g_aux 'x_length 'x_delta)\b)\n\n RETURNS: an array type with the fields set up from the\n above arguments in the obvious way (see S\n 1.2.10).\n\n (\b(*\b*a\bar\brr\bra\bay\by 's_name 's_type 'x_dim1 ... 'x_dim_\bn)\b)\n (\b(a\bar\brr\bra\bay\by s_name s_type x_dim1 ... x_dim_\bn)\b)\n\n WHERE: s_type may be one of t, nil, fixnum, flonum,\n fixnum-block and flonum-block.\n\n RETURNS: an array of type s_type with n dimensions of\n extents given by the x_dim_\bi.\n\n SIDE EFFECT: If s_name is non nil, the function defini-\n tion of s_name is set to the array struc-\n ture returned.\n\n NOTE: These functions create a Maclisp compatible\n array. In FRANZ LISP arrays of type t, nil,\n fixnum and flonum are equivalent and the elements\n of these arrays can be any type of lisp object.\n Fixnum-block and flonum-block arrays are\n restricted to fixnums and flonums respectively\n and are used mainly to communicate with foreign\n functions (see S8.5).\n\n NOTE: _\b*_\ba_\br_\br_\ba_\by evaluates its arguments, _\ba_\br_\br_\ba_\by does not.\n\n\n\n 2\b2.\b.5\b5.\b.2\b2.\b. a\bar\brr\bra\bay\by p\bpr\bre\bed\bdi\bic\bca\bat\bte\be\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b24\b4\n\n\n (\b(a\bar\brr\bra\bay\byp\bp 'g_arg)\b)\n\n RETURNS: t iff g_arg is of type array.\n\n\n\n 2\b2.\b.5\b5.\b.3\b3.\b. a\bar\brr\bra\bay\by a\bac\bcc\bce\bes\bss\bso\bor\brs\bs\n\n\n (\b(g\bge\bet\bta\bac\bcc\bce\bes\bss\bs 'a_array)\b)\n (\b(g\bge\bet\bta\bau\bux\bx 'a_array)\b)\n (\b(g\bge\bet\btd\bde\bel\blt\bta\ba 'a_array)\b)\n (\b(g\bge\bet\btd\bda\bat\bta\ba 'a_array)\b)\n (\b(g\bge\bet\btl\ble\ben\bng\bgt\bth\bh 'a_array)\b)\n\n RETURNS: the field of the array object a_array given by\n the function name.\n\n (\b(a\bar\brr\bra\bay\byr\bre\bef\bf 'a_name 'x_ind)\b)\n\n RETURNS: the x_ind_\bt_\bh element of the array object\n a_name. x_ind of zero accesses the first ele-\n ment.\n\n NOTE: _\ba_\br_\br_\ba_\by_\br_\be_\bf uses the data, length and delta fields\n of a_name to determine which object to return.\n\n (\b(a\bar\brr\bra\bay\byc\bca\bal\bll\bl s_type 'as_array 'x_ind1 ... )\b)\n\n RETURNS: the element selected by the indices from the\n array a_array of type s_type.\n\n NOTE: If as_array is a symbol then the function binding\n of this symbol should contain an array object.\n s_type is ignored by _\ba_\br_\br_\ba_\by_\bc_\ba_\bl_\bl but is included\n for compatibility with Maclisp.\n\n (\b(a\bar\brr\bra\bay\byd\bdi\bim\bms\bs 's_name)\b)\n\n RETURNS: a list of the type and bounds of the array\n s_name.\n\n (\b(l\bli\bis\bst\bta\bar\brr\bra\bay\by 'sa_array ['x_elements])\b)\n\n RETURNS: a list of all of the elements in array\n sa_array. If x_elements is given, then only\n the first x_elements are returned.\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b25\b5\n\n\n\n ____________________________________________________\n\n ; We will create a 3 by 4 array of general lisp objects\n -> _\b(_\ba_\br_\br_\ba_\by _\be_\br_\bn_\bi_\be _\bt _\b3 _\b4_\b)\n array[12]\n\n ; the array header is stored in the function definition slot of the\n ; symbol ernie\n -> _\b(_\ba_\br_\br_\ba_\by_\bp _\b(_\bg_\be_\bt_\bd _\b'_\be_\br_\bn_\bi_\be_\b)_\b)\n t\n -> _\b(_\ba_\br_\br_\ba_\by_\bd_\bi_\bm_\bs _\b(_\bg_\be_\bt_\bd _\b'_\be_\br_\bn_\bi_\be_\b)_\b)\n (t 3 4)\n\n ; store in ernie[2][2] the list (test list)\n -> _\b(_\bs_\bt_\bo_\br_\be _\b(_\be_\br_\bn_\bi_\be _\b2 _\b2_\b) _\b'_\b(_\bt_\be_\bs_\bt _\bl_\bi_\bs_\bt_\b)_\b)\n (test list)\n\n ; check to see if it is there\n -> _\b(_\be_\br_\bn_\bi_\be _\b2 _\b2_\b)\n (test list)\n\n ; now use the low level function _\ba_\br_\br_\ba_\by_\br_\be_\bf to find the same element\n ; arrays are 0 based and row-major (the last subscript varies the fastest)\n ; thus element [2][2] is the 10th element , (starting at 0).\n -> _\b(_\ba_\br_\br_\ba_\by_\br_\be_\bf _\b(_\bg_\be_\bt_\bd _\b'_\be_\br_\bn_\bi_\be_\b) _\b1_\b0_\b)\n (ptr to)(test list) ; the result is a value cell (thus the (ptr to))\n ____________________________________________________\n\n\n\n\n\n\n 2\b2.\b.5\b5.\b.4\b4.\b. a\bar\brr\bra\bay\by m\bma\ban\bni\bip\bpu\bul\bla\bat\bti\bio\bon\bn\n\n (\b(p\bpu\but\bta\bac\bcc\bce\bes\bss\bs 'a_array 'su_func)\b)\n (\b(p\bpu\but\bta\bau\bux\bx 'a_array 'g_aux)\b)\n (\b(p\bpu\but\btd\bda\bat\bta\ba 'a_array 'g_arg)\b)\n (\b(p\bpu\but\btd\bde\bel\blt\bta\ba 'a_array 'x_delta)\b)\n (\b(p\bpu\but\btl\ble\ben\bng\bgt\bth\bh 'a_array 'x_length)\b)\n\n RETURNS: the second argument to the function.\n\n SIDE EFFECT: The field of the array object given by the\n function name is replaced by the second\n argument to the function.\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b26\b6\n\n\n (\b(s\bst\bto\bor\bre\be 'l_arexp 'g_val)\b)\n\n WHERE: l_arexp is an expression which references an\n array element.\n\n RETURNS: g_val\n\n SIDE EFFECT: the array location which contains the ele-\n ment which l_arexp references is changed\n to contain g_val.\n\n (\b(f\bfi\bil\bll\bla\bar\brr\bra\bay\by 's_array 'l_itms)\b)\n\n RETURNS: s_array\n\n SIDE EFFECT: the array s_array is filled with elements\n from l_itms. If there are not enough ele-\n ments in l_itms to fill the entire array,\n then the last element of l_itms is used to\n fill the remaining parts of the array.\n\n\n\n 2\b2.\b.6\b6.\b. H\bHu\bun\bnk\bks\bs\n\n Hunks are vector-like objects whose size can\n range from 1 to 128 elements. Internally, hunks are\n allocated in sizes which are powers of 2. In order to\n create hunks of a given size, a hunk with at least\n that many elements is allocated and a distinguished\n symbol EMPTY is placed in those elements not\n requested. Most hunk functions respect those distin-\n guished symbols, but there are two _\b(_\b*_\bm_\ba_\bk_\bh_\bu_\bn_\bk and\n _\b*_\br_\bp_\bl_\ba_\bc_\bx) which will overwrite the distinguished sym-\n bol.\n\n\n\n 2\b2.\b.6\b6.\b.1\b1.\b. h\bhu\bun\bnk\bk c\bcr\bre\bea\bat\bti\bio\bon\bn\n\n (\b(h\bhu\bun\bnk\bk 'g_val1 ['g_val2 ... 'g_val_\bn])\b)\n\n RETURNS: a hunk of length n whose elements are initial-\n ized to the g_val_\bi.\n\n NOTE: the maximum size of a hunk is 128.\n\n EXAMPLE: _\b(_\bh_\bu_\bn_\bk _\b4 _\b'_\bs_\bh_\ba_\br_\bp _\b'_\bk_\be_\by_\bs_\b) = {4 sharp keys}\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b27\b7\n\n\n (\b(m\bma\bak\bkh\bhu\bun\bnk\bk 'xl_arg)\b)\n\n RETURNS: a hunk of length xl_arg initialized to all\n nils if xl_arg is a fixnum. If xl_arg is a\n list, then we return a hunk of size\n _\b(_\bl_\be_\bn_\bg_\bt_\bh _\b'_\bx_\bl_\b__\ba_\br_\bg_\b) initialized to the elements\n in xl_arg.\n\n NOTE: _\b(_\bm_\ba_\bk_\bh_\bu_\bn_\bk _\b'_\b(_\ba _\bb _\bc_\b)_\b) is equivalent to\n _\b(_\bh_\bu_\bn_\bk _\b'_\ba _\b'_\bb _\b'_\bc_\b).\n\n EXAMPLE: _\b(_\bm_\ba_\bk_\bh_\bu_\bn_\bk _\b4_\b) = _\b{_\bn_\bi_\bl _\bn_\bi_\bl _\bn_\bi_\bl _\bn_\bi_\bl_\b}\n\n (\b(*\b*m\bma\bak\bkh\bhu\bun\bnk\bk 'x_arg)\b)\n\n RETURNS: a hunk of size 2initialized to EMPTY.\n\n NOTE: This is only to be used by such functions as _\bh_\bu_\bn_\bk\n and _\bm_\ba_\bk_\bh_\bu_\bn_\bk which create and initialize hunks for\n users.\n\n\n\n 2\b2.\b.6\b6.\b.2\b2.\b. h\bhu\bun\bnk\bk a\bac\bcc\bce\bes\bss\bso\bor\br\n\n (\b(c\bcx\bxr\br 'x_ind 'h_hunk)\b)\n\n RETURNS: element x_ind (starting at 0) of hunk h_hunk.\n\n (\b(h\bhu\bun\bnk\bk-\b-t\bto\bo-\b-l\bli\bis\bst\bt 'h_hunk)\b)\n\n RETURNS: a list consisting of the elements of h_hunk.\n\n\n\n 2\b2.\b.6\b6.\b.3\b3.\b. h\bhu\bun\bnk\bk m\bma\ban\bni\bip\bpu\bul\bla\bat\bto\bor\brs\bs\n\n (\b(r\brp\bpl\bla\bac\bcx\bx 'x_ind 'h_hunk 'g_val)\b)\n (\b(*\b*r\brp\bpl\bla\bac\bcx\bx 'x_ind 'h_hunk 'g_val)\b)\n\n RETURNS: h_hunk\n\n SIDE EFFECT: Element x_ind (starting at 0) of h_hunk is\n set to g_val.\n\n NOTE: _\br_\bp_\bl_\ba_\bc_\bx will not modify one of the distinguished\n (EMPTY) elements whereas _\b*_\br_\bp_\bl_\ba_\bc_\bx will.\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b28\b8\n\n\n (\b(h\bhu\bun\bnk\bks\bsi\biz\bze\be 'h_arg)\b)\n\n RETURNS: the size of the hunk h_arg.\n\n EXAMPLE: _\b(_\bh_\bu_\bn_\bk_\bs_\bi_\bz_\be _\b(_\bh_\bu_\bn_\bk _\b1 _\b2 _\b3_\b)_\b) = 3\n\n\n\n 2\b2.\b.7\b7.\b. B\bBc\bcd\bds\bs\n\n A bcd object contains a pointer to compiled code\n and to the type of function object the compiled code\n represents.\n\n (\b(g\bge\bet\btd\bdi\bis\bsc\bc 'y_bcd)\b)\n (\b(g\bge\bet\bte\ben\bnt\btr\bry\by 'y_bcd)\b)\n\n RETURNS: the field of the bcd object given by the func-\n tion name.\n\n (\b(p\bpu\but\btd\bdi\bis\bsc\bc 'y_func 's_discipline)\b)\n\n RETURNS: s_discipline\n\n SIDE EFFECT: Sets the discipline field of y_func to\n s_discipline.\n\n\n\n 2\b2.\b.8\b8.\b. S\bSt\btr\bru\buc\bct\btu\bur\bre\bes\bs\n\n There are three common structures constructed out\n of list cells: the assoc list, the property list and\n the tconc list. The functions below manipulate these\n structures.\n\n\n\n 2\b2.\b.8\b8.\b.1\b1.\b. a\bas\bss\bso\boc\bc l\bli\bis\bst\bt\n\n An `assoc list' (or alist) is a common lisp\n data structure. It has the form\n ((key1 . value1) (key2 . value2) (key3 . value3)\n ... (keyn . valuen))\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-2\b29\b9\n\n\n (\b(a\bas\bss\bso\boc\bc 'g_arg1 'l_arg2)\b)\n (\b(a\bas\bss\bsq\bq 'g_arg1 'l_arg2)\b)\n\n RETURNS: the first top level element of l_arg2 whose\n _\bc_\ba_\br is _\be_\bq_\bu_\ba_\bl (with _\ba_\bs_\bs_\bo_\bc) or _\be_\bq (with _\ba_\bs_\bs_\bq) to\n g_arg1.\n\n NOTE: Usually l_arg2 has an _\ba_\b-_\bl_\bi_\bs_\bt structure and g_arg1\n acts as key.\n\n (\b(s\bsa\bas\bss\bso\boc\bc 'g_arg1 'l_arg2 'sl_func)\b)\n\n RETURNS: the result of\n _\b(_\bc_\bo_\bn_\bd _\b(_\b(_\ba_\bs_\bs_\bo_\bc _\b'_\bg_\b__\ba_\br_\bg _\b'_\bl_\b__\ba_\br_\bg_\b2_\b) _\b(_\ba_\bp_\bp_\bl_\by _\b'_\bs_\bl_\b__\bf_\bu_\bn_\bc _\bn_\bi_\bl_\b)_\b)_\b)\n\n NOTE: sassoc is written as a macro.\n\n (\b(s\bsa\bas\bss\bsq\bq 'g_arg1 'l_arg2 'sl_func)\b)\n\n RETURNS: the result of\n _\b(_\bc_\bo_\bn_\bd _\b(_\b(_\ba_\bs_\bs_\bq _\b'_\bg_\b__\ba_\br_\bg _\b'_\bl_\b__\ba_\br_\bg_\b2_\b) _\b(_\ba_\bp_\bp_\bl_\by _\b'_\bs_\bl_\b__\bf_\bu_\bn_\bc _\bn_\bi_\bl_\b)_\b)_\b)\n\n NOTE: sassq is written as a macro.\n\n\n\n ____________________________________________________\n\n ; _\ba_\bs_\bs_\bo_\bc or _\ba_\bs_\bs_\bq is given a key and an assoc list and returns\n ; the key and value item if it exists, they differ only in how they test\n ; for equality of the keys.\n\n -> _\b(_\bs_\be_\bt_\bq _\ba_\bl_\bi_\bs_\bt _\b'_\b(_\b(_\ba_\bl_\bp_\bh_\ba _\b. _\ba_\b) _\b( _\b(_\bc_\bo_\bm_\bp_\bl_\be_\bx _\bk_\be_\by_\b) _\b. _\bb_\b) _\b(_\bj_\bu_\bn_\bk _\b. _\bx_\b)_\b)_\b)\n ((alpha . a) ((complex key) . b) (junk . x))\n\n ; we should use _\ba_\bs_\bs_\bq when the key is an atom\n -> _\b(_\ba_\bs_\bs_\bq _\b'_\ba_\bl_\bp_\bh_\ba _\ba_\bl_\bi_\bs_\bt_\b)\n (alpha . a)\n\n ; but it may not work when the key is a list\n -> _\b(_\ba_\bs_\bs_\bq _\b'_\b(_\bc_\bo_\bm_\bp_\bl_\be_\bx _\bk_\be_\by_\b) _\ba_\bl_\bi_\bs_\bt_\b)\n nil\n\n ; however _\ba_\bs_\bs_\bo_\bc will always work\n -> _\b(_\ba_\bs_\bs_\bo_\bc _\b'_\b(_\bc_\bo_\bm_\bp_\bl_\be_\bx _\bk_\be_\by_\b) _\ba_\bl_\bi_\bs_\bt_\b)\n ((complex key) . b)\n ____________________________________________________\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b30\b0\n\n\n (\b(s\bsu\bub\bbl\bli\bis\bs 'l_alst 'l_exp)\b)\n\n WHERE: l_alst is an _\ba_\b-_\bl_\bi_\bs_\bt.\n\n RETURNS: the list l_exp with every occurrence of key_\bi\n replaced by val_\bi.\n\n NOTE: new list structure is returned to prevent modifi-\n cation of l_exp. When a substitution is made, a\n copy of the value to substitute in is not made.\n\n\n\n 2\b2.\b.8\b8.\b.2\b2.\b. p\bpr\bro\bop\bpe\ber\brt\bty\by l\bli\bis\bst\bt\n\n A property list consists of an alternating\n sequence of keys and values. Normally a property\n list is stored on a symbol. A list is a 'disembod-\n ied' property list if it contains an odd number of\n elements, the first of which is ignored.\n\n (\b(p\bpl\bli\bis\bst\bt 's_name)\b)\n\n RETURNS: the property list of s_name.\n\n (\b(s\bse\bet\btp\bpl\bli\bis\bst\bt 's_atm 'l_plist)\b)\n\n RETURNS: l_plist.\n\n SIDE EFFECT: the property list of s_atm is set to\n l_plist.\n\n\n (\b(g\bge\bet\bt 'ls_name 'g_ind)\b)\n\n RETURNS: the value under indicator g_ind in ls_name's\n property list if ls_name is a symbol.\n\n NOTE: If there is no indicator g_ind in ls_name's prop-\n erty list nil is returned. If ls_name is a list\n of an odd number of elements then it is a disem-\n bodied property list. _\bg_\be_\bt searches a disembodied\n property list by starting at its _\bc_\bd_\br, and compar-\n ing every other element with g_ind, using _\be_\bq.\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b31\b1\n\n\n (\b(g\bge\bet\btl\bl 'ls_name 'l_indicators)\b)\n\n RETURNS: the property list ls_name beginning at the\n first indicator which is a member of the list\n l_indicators, or nil if none of the indicators\n in l_indicators are on ls_name's property\n list.\n\n NOTE: If ls_name is a list, then it is assumed to be a\n disembodied property list.\n\n\n (\b(p\bpu\but\btp\bpr\bro\bop\bp 'ls_name 'g_val 'g_ind)\b)\n (\b(d\bde\bef\bfp\bpr\bro\bop\bp ls_name g_val g_ind)\b)\n\n RETURNS: g_val.\n\n SIDE EFFECT: Adds to the property list of ls_name the\n value g_val under the indicator g_ind.\n\n NOTE: _\bp_\bu_\bt_\bp_\br_\bo_\bp evaluates it arguments, _\bd_\be_\bf_\bp_\br_\bo_\bp does not.\n ls_name may be a disembodied property list, see\n _\bg_\be_\bt.\n\n (\b(r\bre\bem\bmp\bpr\bro\bop\bp 'ls_name 'g_ind)\b)\n\n RETURNS: the portion of ls_name's property list begin-\n ning with the property under the indicator\n g_ind. If there is no g_ind indicator in\n ls_name's plist, nil is returned.\n\n SIDE EFFECT: the value under indicator g_ind and g_ind\n itself is removed from the property list\n of ls_name.\n\n NOTE: ls_name may be a disembodied property list, see\n _\bg_\be_\bt.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b32\b2\n\n\n\n ____________________________________________________\n\n -> _\b(_\bp_\bu_\bt_\bp_\br_\bo_\bp _\b'_\bx_\bl_\ba_\bt_\be _\b'_\ba _\b'_\ba_\bl_\bp_\bh_\ba_\b)\n a\n -> _\b(_\bp_\bu_\bt_\bp_\br_\bo_\bp _\b'_\bx_\bl_\ba_\bt_\be _\b'_\bb _\b'_\bb_\be_\bt_\ba_\b)\n b\n -> _\b(_\bp_\bl_\bi_\bs_\bt _\b'_\bx_\bl_\ba_\bt_\be_\b)\n (alpha a beta b)\n -> _\b(_\bg_\be_\bt _\b'_\bx_\bl_\ba_\bt_\be _\b'_\ba_\bl_\bp_\bh_\ba_\b)\n a\n ; use of a disembodied property list:\n -> _\b(_\bg_\be_\bt _\b'_\b(_\bn_\bi_\bl _\bf_\ba_\bt_\be_\bm_\ba_\bn _\br_\bj_\bf _\bs_\bk_\bl_\bo_\bw_\be_\br _\bk_\bl_\bs _\bf_\bo_\bd_\be_\br_\ba_\br_\bo _\bj_\bk_\bf_\b) _\b'_\bs_\bk_\bl_\bo_\bw_\be_\br_\b)\n kls\n ____________________________________________________\n\n\n\n\n\n\n 2\b2.\b.8\b8.\b.3\b3.\b. t\btc\bco\bon\bnc\bc s\bst\btr\bru\buc\bct\btu\bur\bre\be\n\n A tconc structure is a special type of list\n designed to make it easy to add objects to the end.\n It consists of a list cell whose _\bc_\ba_\br points to a\n list of the elements added with _\bt_\bc_\bo_\bn_\bc or _\bl_\bc_\bo_\bn_\bc and\n whose _\bc_\bd_\br points to the last list cell of the list\n pointed to by the _\bc_\ba_\br_\b.\n\n (\b(t\btc\bco\bon\bnc\bc 'l_ptr 'g_x)\b)\n\n WHERE: l_ptr is a tconc structure.\n\n RETURNS: l_ptr with g_x added to the end.\n\n (\b(l\blc\bco\bon\bnc\bc 'l_ptr 'l_x)\b)\n\n WHERE: l_ptr is a tconc structure.\n\n RETURNS: l_ptr with the list l_x spliced in at the end.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b33\b3\n\n\n\n ____________________________________________________\n\n ; A _\bt_\bc_\bo_\bn_\bc structure can be initialized in two ways.\n ; nil can be given to _\bt_\bc_\bo_\bn_\bc in which case _\bt_\bc_\bo_\bn_\bc will generate\n ; a _\bt_\bc_\bo_\bn_\bc structure.\n\n ->_\b(_\bs_\be_\bt_\bq _\bf_\bo_\bo _\b(_\bt_\bc_\bo_\bn_\bc _\bn_\bi_\bl _\b1_\b)_\b)\n ((1) 1)\n\n ; Since _\bt_\bc_\bo_\bn_\bc destructively adds to\n ; the list, you can now add to foo without using _\bs_\be_\bt_\bq again.\n\n ->_\b(_\bt_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\b2_\b)\n ((1 2) 2)\n ->_\bf_\bo_\bo\n ((1 2) 2)\n\n ; Another way to create a null _\bt_\bc_\bo_\bn_\bc structure\n ; is to use _\b(_\bn_\bc_\bo_\bn_\bs _\bn_\bi_\bl_\b).\n\n ->_\b(_\bs_\be_\bt_\bq _\bf_\bo_\bo _\b(_\bn_\bc_\bo_\bn_\bs _\bn_\bi_\bl_\b)_\b)\n (nil)\n ->_\b(_\bt_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\b1_\b)\n ((1) 1)\n\n ; now see what _\bl_\bc_\bo_\bn_\bc can do\n -> _\b(_\bl_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\bn_\bi_\bl_\b)\n ((1) 1) ; no change\n -> _\b(_\bl_\bc_\bo_\bn_\bc _\bf_\bo_\bo _\b'_\b(_\b2 _\b3 _\b4_\b)_\b)\n ((1 2 3 4) 4)\n ____________________________________________________\n\n\n\n\n\n\n 2\b2.\b.8\b8.\b.4\b4.\b. f\bfc\bcl\blo\bos\bsu\bur\bre\bes\bs\n\n An fclosure is a functional object which\n admits some data manipulations. They are discussed\n in S8.4. Internally, they are constructed from\n vectors.\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b34\b4\n\n\n (\b(f\bfc\bcl\blo\bos\bsu\bur\bre\be 'l_vars 'g_funobj)\b)\n\n WHERE: l_vars is a list of variables, g_funobj is any\n object that can be funcalled (including, fclo-\n sures).\n\n RETURNS: A vector which is the fclosure.\n\n (\b(f\bfc\bcl\blo\bos\bsu\bur\bre\be-\b-a\bal\bli\bis\bst\bt 'v_fclosure)\b)\n\n RETURNS: An association list representing the variables\n in the fclosure. This is a snapshot of the\n current state of the fclosure. If the bind-\n ings in the fclosure are changed, any previ-\n ously calculated results of _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be_\b-_\ba_\bl_\bi_\bs_\bt\n will not change.\n\n (\b(f\bfc\bcl\blo\bos\bsu\bur\bre\be-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn 'v_fclosure)\b)\n\n RETURNS: the functional object part of the fclosure.\n\n (\b(f\bfc\bcl\blo\bos\bsu\bur\bre\bep\bp 'v_fclosure)\b)\n\n RETURNS: t iff the argument is an fclosure.\n\n (\b(s\bsy\bym\bme\bev\bva\bal\bl-\b-i\bin\bn-\b-f\bfc\bcl\blo\bos\bsu\bur\bre\be 'v_fclosure 's_symbol)\b)\n\n RETURNS: the current binding of a particular symbol in\n an fclosure.\n\n (\b(s\bse\bet\bt-\b-i\bin\bn-\b-f\bfc\bcl\blo\bos\bsu\bur\bre\be 'v_fclosure 's_symbol 'g_newvalue)\b)\n\n RETURNS: g_newvalue.\n\n SIDE EFFECT: The variable s_symbol is bound in the\n fclosure to g_newvalue.\n\n\n\n 2\b2.\b.9\b9.\b. R\bRa\ban\bnd\bdo\bom\bm f\bfu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n The following functions don't fall into any of\n the classifications above.\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b35\b5\n\n\n (\b(b\bbc\bcd\bda\bad\bd 's_funcname)\b)\n\n RETURNS: a fixnum which is the address in memory where\n the function s_funcname begins. If s_funcname\n is not a machine coded function (binary) then\n _\bb_\bc_\bd_\ba_\bd returns nil.\n\n (\b(c\bco\bop\bpy\by 'g_arg)\b)\n\n RETURNS: A structure _\be_\bq_\bu_\ba_\bl to g_arg but with new list\n cells.\n\n (\b(c\bco\bop\bpy\byi\bin\bnt\bt*\b* 'x_arg)\b)\n\n RETURNS: a fixnum with the same value as x_arg but in a\n freshly allocated cell.\n\n (\b(c\bcp\bpy\by1\b1 'xvt_arg)\b)\n\n RETURNS: a new cell of the same type as xvt_arg with\n the same value as xvt_arg.\n\n (\b(g\bge\bet\bta\bad\bdd\bdr\bre\bes\bss\bs 's_entry1 's_binder1 'st_discipline1 [... ...\n ...])\b)\n\n RETURNS: the binary object which s_binder1's function\n field is set to.\n\n NOTE: This looks in the running lisp's symbol table for\n a symbol with the same name as s_entry_\bi. It then\n creates a binary object whose entry field points\n to s_entry_\bi and whose discipline is\n st_discipline_\bi. This binary object is stored in\n the function field of s_binder_\bi. If\n st_discipline_\bi is nil, then \"subroutine\" is used\n by default. This is especially useful for _\bc_\bf_\ba_\bs_\bl\n users.\n\n (\b(m\bma\bac\bcr\bro\boe\bex\bxp\bpa\ban\bnd\bd 'g_form)\b)\n\n RETURNS: g_form after all macros in it are expanded.\n\n NOTE: This function will only macroexpand expressions\n which could be evaluated and it does not know\n about the special nlambdas such as _\bc_\bo_\bn_\bd and _\bd_\bo,\n thus it misses many macro expansions.\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b36\b6\n\n\n (\b(p\bpt\btr\br 'g_arg)\b)\n\n RETURNS: a value cell initialized to point to g_arg.\n\n (\b(q\bqu\buo\bot\bte\be g_arg)\b)\n\n RETURNS: g_arg.\n\n NOTE: the reader allows you to abbreviate (quote foo)\n as 'foo.\n\n (\b(k\bkw\bwo\bot\bte\be 'g_arg)\b)\n\n RETURNS: _\b(_\bl_\bi_\bs_\bt _\b(_\bq_\bu_\bo_\bt_\be _\bq_\bu_\bo_\bt_\be_\b) _\bg_\b__\ba_\br_\bg_\b).\n\n (\b(r\bre\bep\bpl\bla\bac\bce\be 'g_arg1 'g_arg2)\b)\n\n WHERE: g_arg1 and g_arg2 must be the same type of\n lispval and not symbols or hunks.\n\n RETURNS: g_arg2.\n\n SIDE EFFECT: The effect of _\br_\be_\bp_\bl_\ba_\bc_\be is dependent on the\n type of the g_arg_\bi although one will\n notice a similarity in the effects. To\n understand what _\br_\be_\bp_\bl_\ba_\bc_\be does to fixnum and\n flonum arguments, you must first under-\n stand that such numbers are `boxed' in\n FRANZ LISP. What this means is that if\n the symbol x has a value 32412, then in\n memory the value element of x's symbol\n structure contains the address of another\n word of memory (called a box) with 32412\n in it.\n\n Thus, there are two ways of changing the\n value of x: the first is to change the\n value element of x's symbol structure to\n point to a word of memory with a different\n value. The second way is to change the\n value in the box which x points to. The\n former method is used almost all of the\n time, the latter is used very rarely and\n has the potential to cause great confu-\n sion. The function _\br_\be_\bp_\bl_\ba_\bc_\be allows you to\n do the latter, i.e., to actually change\n the value in the box.\n\n You should watch out for these situations.\n If you do _\b(_\bs_\be_\bt_\bq _\by _\bx_\b), then both x and y\n will point to the same box. If you now\n _\b(_\br_\be_\bp_\bl_\ba_\bc_\be _\bx _\b1_\b2_\b3_\b4_\b5_\b), then y will also have\n the value 12345. And, in fact, there may\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b37\b7\n\n\n be many other pointers to that box.\n\n Another problem with replacing fixnums is\n that some boxes are read-only. The\n fixnums between -1024 and 1023 are stored\n in a read-only area and attempts to\n replace them will result in an \"Illegal\n memory reference\" error (see the descrip-\n tion of _\bc_\bo_\bp_\by_\bi_\bn_\bt_\b* for a way around this\n problem).\n\n For the other valid types, the effect of\n _\br_\be_\bp_\bl_\ba_\bc_\be is easy to understand. The fields\n of g_val1's structure are made eq to the\n corresponding fields of g_val2's struc-\n ture. For example, if x and y have\n lists as values then the effect of\n _\b(_\br_\be_\bp_\bl_\ba_\bc_\be _\bx _\by_\b) is the same as\n _\b(_\br_\bp_\bl_\ba_\bc_\ba _\bx _\b(_\bc_\ba_\br _\by_\b)_\b) and _\b(_\br_\bp_\bl_\ba_\bc_\bd _\bx _\b(_\bc_\bd_\br _\by_\b)_\b).\n\n (\b(s\bsc\bco\bon\bns\bs 'x_arg 'bs_rest)\b)\n\n WHERE: bs_rest is a bignum or nil.\n\n RETURNS: a bignum whose first bigit is x_arg and whose\n higher order bigits are bs_rest.\n\n (\b(s\bse\bet\btf\bf g_refexpr 'g_value)\b)\n\n NOTE: _\bs_\be_\bt_\bf is a generalization of setq. Information\n may be stored by binding variables, replacing\n entries of arrays, and vectors, or being put on\n property lists, among others. Setf will allow\n the user to store data into some location, by\n mentioning the operation used to refer to the\n location. Thus, the first argument may be par-\n tially evaluated, but only to the extent needed\n to calculate a reference. _\bs_\be_\bt_\bf returns g_value.\n (Compare to _\bd_\be_\bs_\be_\bt_\bq )\n\n\n ____________________________________________________\n\n (setf x 3) = (setq x 3)\n (setf (car x) 3) = (rplaca x 3)\n (setf (get foo 'bar) 3) = (putprop foo 3 'bar)\n (setf (vref vector index) value) = (vset vector index value)\n ____________________________________________________\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n D\bDa\bat\bta\ba S\bSt\btr\bru\buc\bct\btu\bur\bre\be A\bAc\bcc\bce\bes\bss\bs 2\b2-\b-3\b38\b8\n\n\n (\b(s\bso\bor\brt\bt 'l_data 'u_comparefn)\b)\n\n RETURNS: a list of the elements of l_data ordered by\n the comparison function u_comparefn.\n\n SIDE EFFECT: the list l_data is modified rather than\n allocated in new storage.\n\n NOTE: _\b(_\bc_\bo_\bm_\bp_\ba_\br_\be_\bf_\bn _\b'_\bg_\b__\bx _\b'_\bg_\b__\by_\b) should return something\n non-nil if g_x can precede g_y in sorted order;\n nil if g_y must precede g_x. If u_comparefn is\n nil, alphabetical order will be used.\n\n (\b(s\bso\bor\brt\btc\bca\bar\br 'l_list 'u_comparefn)\b)\n\n RETURNS: a list of the elements of l_list with the\n _\bc_\ba_\br's ordered by the sort function\n u_comparefn.\n\n SIDE EFFECT: the list l_list is modified rather than\n copied.\n\n NOTE: Like _\bs_\bo_\br_\bt, if u_comparefn is nil, alphabetical\n order will be used.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n", "meta": {"hexsha": "0083d1537168bd3871afcc7ce82fa6eda3cda76c", "size": 82324, "ext": "r", "lang": "R", "max_stars_repo_path": "lisplib/manual/ch2.r", "max_stars_repo_name": "krytarowski/franz-lisp-christos", "max_stars_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-17T08:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T08:07:14.000Z", "max_issues_repo_path": "lisplib/manual/ch2.r", "max_issues_repo_name": "krytarowski/franz-lisp-christos", "max_issues_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lisplib/manual/ch2.r", "max_forks_repo_name": "krytarowski/franz-lisp-christos", "max_forks_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-15T16:38:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-15T16:38:53.000Z", "avg_line_length": 32.8114786768, "max_line_length": 194, "alphanum_fraction": 0.4713570769, "num_tokens": 27745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.15002882814282253, "lm_q2_score": 0.06560484202633814, "lm_q1q2_score": 0.009842617569706506}} {"text": "# HSR/NHANES/HSA7708_replication\nscript = 'HSA 7708 Replication Project\\nhttps://doi.org/10.3945/jn.109.112573'\n\n## Pull NHANES Data\nFiles = c('DEMO', 'DIQ', 'BPQ', 'BPX', 'FSQ', 'LAB13', 'LAB13AM', 'LAB10AM')\nCycles = c('1999-2000')\nDescriptions = c('Demographic Variables and Sample Weights', 'Diabetes', 'Blood Pressure & Cholesterol', 'Blood Pressure', 'Food Security', 'Cholesterol - Total & HDL', 'Cholesterol - LDL & Triglycerides', 'Plasma Fasting Glucose, Serum C-peptide & Insulin')\ndf_NH1 = pull_stack(Files, Cycles, Descriptions)\ndf_NH1$FSDAD <- df_NH1$ADFDSEC\nhead(df_NH1)\n\n## Pull NHANES Data\nFiles = c('DEMO', 'DIQ', 'BPQ', 'BPX', 'FSQ', 'L13', 'L13AM', 'L10AM')\nCycles = c('2001-2002')\nDescriptions = c('Demographic Variables and Sample Weights', 'Diabetes', 'Blood Pressure & Cholesterol', 'Blood Pressure', 'Food Security', 'Cholesterol - Total & HDL', 'Cholesterol - LDL & Triglycerides', 'Plasma Fasting Glucose, Serum C-peptide & Insulin')\ndf_NH2 = pull_stack(Files, Cycles, Descriptions)\ndf_NH2$FSDAD <- df_NH2$ADFDSEC\nhead(df_NH2)\n\n## Pull NHANES Data\nFiles = c('DEMO', 'DIQ', 'BPQ', 'BPX', 'FSQ', 'L13', 'L13AM', 'L10AM')\nCycles = c('2003-2004')\nDescriptions = c('Demographic Variables and Sample Weights', 'Diabetes', 'Blood Pressure & Cholesterol', 'Blood Pressure', 'Food Security', 'Cholesterol - Total & HDL', 'Cholesterol - LDL & Triglycerides', 'Plasma Fasting Glucose, Serum C-peptide & Insulin')\ndf_NH3 = pull_stack(Files, Cycles, Descriptions)\nhead(df_NH3)\n\n## Combine cycles\nV = colnames(df_NH1)\ndf_V1 = as.data.frame(V)\ndf_V1$Cycle <- '1999-2000'\nV = colnames(df_NH2)\ndf_V2 = as.data.frame(V)\ndf_V2$Cycle <- '2001-2002'\nV = colnames(df_NH3)\ndf_V3 = as.data.frame(V)\ndf_V3$Cycle <- '2003-2004'\ndf_V = merge(df_V1, df_V2, by = 'V', how = 'inner')\ndf_V = merge(df_V, df_V3, by = 'V', how = 'inner')\nvars = c(as.character(df_V$V))\ndf_NH = rbind(df_NH1[vars], df_NH2[vars], df_NH3[vars])\nhead(df_NH)\n\n## Select variables\nNHANES_Variables <- c('RIAGENDR',\n 'RIDAGEYR',\n 'RIDRETH1',\n 'DMDEDUC2',\n 'INDFMPIR',\n 'BPQ020',\n 'BPXSY1',\n 'BPXDI1', \n 'BPQ080',\n 'LBXTC', \n 'DIQ010',\n 'LBXGLU',\n 'FSDAD')\nNHANES_Description <- c('Gender',\n 'Age at Screening',\n 'Race/Ethnicity',\n 'Education Level - Adults 20+',\n 'Family income to Poverty Ratio',\n 'Doctor told you that you have high blood pressure',\n 'Systolic Blood Pressure',\n 'Diastolic Blood Pressure',\n 'Doctor told you that you have high cholesterol',\n 'Total Cholesterol (mg/dL)',\n 'Doctor told you that you have diabetes',\n 'Glucose, plasma (mg/dL)',\n 'Adult food security category')\ndf_NHANES = data.frame(NHANES_Variables, NHANES_Description)\n\nStudy_Variables <- c('Gender', \n 'Age', \n 'Race', \n 'Education', \n 'Income', \n 'Hypertension', \n 'Hyperlipidemia', \n 'Diabetes', \n 'Food')\nStudy_Description <- c('Female Identifying (RIAGENDR == 2)', \n 'Age in years (18 to 65) (RIAGENDR = RIAGENDR)', \n 'Non-white or Hispanic (RIDRETH1 != 3)', \n 'High School Education or less (DMDEDUC2 < 3)', \n 'Income Relative to Poverty Line (above 200%)', \n 'Hypertension Diagnosed (BPQ020 = 1), Clinical (BPXDI1 > 140, BPXSY1 > 90)', \n 'Hyperlipidemia Diagnosed (BPQ080 = 1), Clinical (LBXTC > 200, LBDLDL > 160)', \n 'Diabetes Diagnosed (DQI010 = 1), Clinical (LBXGLU > 126)', \n 'Food Security Low or Very Low, (FSDAD >= 3)')\ndf_Study = data.frame(Study_Variables, Study_Description)\n\n### Modify Variables\nNew = 'Gender'\nOld = 'RIAGENDR'\nLevel = 2\ndf_NH[New] <- 0\ndf_NH[New][df_NH[Old] == Level] <- 1\nsummary(df_NH[New])\nNew = 'Age'\nOld = 'RIDAGEYR'\ndf_NH[New] <- df_NH[Old]\nsummary(df_NH[New])\nNew = 'Race'\nOld = 'RIDRETH1'\nLevel = 1\ndf_NH[New] <- 3\ndf_NH[New][df_NH[Old] != Level] <- 1\nsummary(df_NH[New])\nNew = 'Education'\nOld = 'DMDEDUC2'\nLevel = 3\ndf_NH[New] <- 0\ndf_NH[New][df_NH[Old] < Level] <- 1\nsummary(df_NH[New]) \nNew = 'Income'\nOld = 'INDHHINC'\ndf_NH[New] <- df_NH[Old]\ndf_NH[New][df_NH[New] > 5] <- 5\nsummary(df_NH[New]) \nNew = 'Hypertension'\nOld = 'BPQ020'\nOld2 = 'BPXDI1'\nOld3 = 'BPXSY1'\nLevel = 1\nLevel2 = 140\nLevel3 = 90\ndf_NH[New] <- 0\ndf_NH[New][df_NH[Old] == Level] <- 1\ndf_NH[New][df_NH[Old2] > Level2] <- 1\ndf_NH[New][df_NH[Old3] > Level3] <- 1\nsummary(df_NH[New])\nNew = 'Hyperlipidemia'\nOld = 'BPQ080'\nOld2 = 'LBXTC'\nOld3 = 'LBDLDL'\nLevel = 1\nLevel2 = 200\nLevel3 = 160\ndf_NH[New] <- 0\ndf_NH[New][df_NH[Old] == Level] <- 1\ndf_NH[New][df_NH[Old2] > Level2] <- 1\ndf_NH[New][df_NH[Old3] > Level3] <- 1\nsummary(df_NH[New])\nNew = 'Diabetes'\nOld = 'DIQ010'\nOld2 = 'LBXGLU'\nLevel = 1\nLevel2 = 126\ndf_NH[New] <- 0\ndf_NH[New][df_NH[Old] == Level] <- 1\ndf_NH[New][df_NH[Old2] > Level2] <- 1\nsummary(df_NH[New])\nNew = 'Food'\nOld = 'FSDAD'\nLevel = 3\ndf_NH[New] <- 0\ndf_NH[New][df_NH[Old] >= Level] <- 1\nsummary(df_NH[New]) \n\n### Export to Summary File\noptions(width = 250)\nsink(file = 'summary.txt', append = TRUE, type = 'output')\ncat(script, '\\n\\n', file = 'summary.txt', append = TRUE)\ncat('NHANES Cycles: ', Cycles, '\\n')\ncat('NHANES Files: ', Files, '\\n')\ncat('NHANES Variables:', '\\n', file = 'summary.txt', append = TRUE)\nsummary(df_NH[NHANES_Variables])\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat('NHANES Descriptions:', '\\n', file = 'summary.txt', append = TRUE)\ndf_NHANES\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat('Study Variables:', '\\n', file = 'summary.txt', append = TRUE)\nsummary(df_NH[Study_Variables])\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat('Study Descriptions:', '\\n', file = 'summary.txt', append = TRUE)\ndf_Study\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat(c('####################', '\\n\\n'), file = 'summary.txt', append = TRUE)\nsink()\n\n### Survey Weighted Generalizaed Reghression Models\nD = df_NH[which(df_NH$INDFMPIR < 2 & df_NH$RIDAGEYR > 18 & df_NH$RIDAGEYR < 65), ]\nS = nhanes_survey_design(D, weights_column = 'WTINT2YR')\nX = 'Food'\nA = c('Gender', 'Age', 'Race', 'Education', 'Income')\nY1 = 'Hypertension'\nF1 = as.formula(paste(Y1, ' ~ ', paste(X, '+', paste(A, collapse = ' + ')), sep = ''))\nM1 = svyglm(F1, design = S, data = D, family = poisson()) # Log link [Y = ln(DV)] (aka: Log-Linear) with poisson error (aka: Poisson regression)\nY2 = 'Hyperlipidemia'\nF2 = as.formula(paste(Y2, ' ~ ', paste(X, '+', paste(A, collapse = ' + ')), sep = ''))\nM2 = svyglm(F2, design = S, data = D, family = poisson()) # Log link [Y = ln(DV)] (aka: Log-Linear) with poisson error (aka: Poisson regression)\nY3 = 'Diabetes'\nF3 = as.formula(paste(Y3, ' ~ ', paste(X, '+', paste(A, collapse = ' + ')), sep = ''))\nM3 = svyglm(F3, design = S, data = D, family = poisson()) # Log link [Y = ln(DV)] (aka: Log-Linear) with poisson error (aka: Poisson regression)\n\n### Export to Summary File\nsink(file = 'summary.txt', append = TRUE, type = 'output')\ncat('Generalized Regression Models using Survey Weights', '\\n\\n', file = 'summary.txt', append = TRUE)\ncat('Title:\\n', Y1, 'and', X, 'adjusted by', A, '\\n', file = 'summary.txt', append = TRUE)\nsummary(M1)\ncat('Odds Ratios: ', '\\n', 'Intercept', X, A, '\\n', exp(coef(M1)), '\\n', file = 'summary.txt', append = TRUE)\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat('Title:\\n', Y2, 'and', X, 'adjusted by', A, '\\n', file = 'summary.txt', append = TRUE)\nsummary(M2)\ncat('Odds Ratios: ', '\\n', 'Intercept', X, A, '\\n', exp(coef(M2)), '\\n', file = 'summary.txt', append = TRUE)\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat('Title:\\n', Y3, 'and', X, 'adjusted by', A, '\\n', file = 'summary.txt', append = TRUE)\nsummary(M3)\ncat('Odds Ratios: ', '\\n', 'Intercept', X, A, '\\n', exp(coef(M3)), '\\n', file = 'summary.txt', append = TRUE)\ncat('\\n', file = 'summary.txt', append = TRUE)\ncat(c('####################', '\\n\\n'), file = 'summary.txt', append = TRUE)\nsink()", "meta": {"hexsha": "e89fe2d244e9796e1b1d6df57b75e79ca57788b1", "size": 8393, "ext": "r", "lang": "R", "max_stars_repo_path": "NHANES/replication_old/HSA7708.r", "max_stars_repo_name": "andrewcistola/HSR", "max_stars_repo_head_hexsha": "dedf59e1a554a0e04105bb88b4c3a96405ef5ace", "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": "NHANES/replication_old/HSA7708.r", "max_issues_repo_name": "andrewcistola/HSR", "max_issues_repo_head_hexsha": "dedf59e1a554a0e04105bb88b4c3a96405ef5ace", "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": "NHANES/replication_old/HSA7708.r", "max_forks_repo_name": "andrewcistola/HSR", "max_forks_repo_head_hexsha": "dedf59e1a554a0e04105bb88b4c3a96405ef5ace", "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.5896226415, "max_line_length": 258, "alphanum_fraction": 0.5897771953, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.025178843620773834, "lm_q1q2_score": 0.009321847264603873}} {"text": "#' @title Rarefy ampvis2 object\n#' @description This is just a wrapper of \\code{\\link[vegan]{rrarefy}} with convenient error messages and adjusted to work with ampvis2 objects.\n#'\n#' @param data (\\emph{required}) Data list as loaded with \\code{\\link{amp_load}}.\n#' @param rarefy (\\emph{required}) Passed directly to \\code{\\link[vegan]{rrarefy}}.\n#'\n#' @return An ampvis2 object with rarefied OTU abundances.\n#' @importFrom vegan rrarefy\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\namp_rarefy <- function(data, rarefy) {\n ### Data must be in ampvis2 format\n if (class(data) != \"ampvis2\") {\n stop(\"The provided data is not in ampvis2 format. Use amp_load() to load your data before using ampvis2 functions. (Or class(data) <- \\\"ampvis2\\\", if you know what you are doing.)\", call. = FALSE)\n }\n \n set.seed(0) # for reproducibility\n \n reads <- colSums(data$abund)\n maxreads <- max(reads)\n minreads <- min(reads)\n if (is.numeric(rarefy)) {\n if (rarefy > maxreads) {\n stop(\"The chosen rarefy size is larger than the largest amount of reads in any sample (\", as.character(maxreads), \").\", call. = FALSE)\n } else if (rarefy < minreads) {\n data$abund <- suppressWarnings(vegan::rrarefy(t(data$abund), sample = rarefy)) %>%\n t() %>%\n as.data.frame()\n warning(\"The chosen rarefy size (\", as.character(rarefy), \") is smaller than the smallest amount of reads in any sample (\", as.character(minreads), \").\", call. = FALSE)\n } else {\n data$abund <- suppressWarnings(vegan::rrarefy(t(data$abund), sample = rarefy)) %>%\n t() %>%\n as.data.frame()\n if (minreads < rarefy) {\n message(\"The following sample(s) have not been rarefied (less than \", as.character(rarefy), \" reads):\\n\", paste(rownames(data$metadata[which(reads < rarefy), ]), collapse = \", \"))\n }\n }\n } else if (!is.numeric(rarefy)) {\n stop(\"Argument rarefy must be numerical.\", call. = FALSE)\n }\n return(data)\n}\n\n#' @title Tidy up taxonomy\n#' @description Used internally in other ampvis functions.\n#'\n#' @param data (\\emph{required}) Data list as loaded with \\code{\\link{amp_load}}.\n#' @param tax_empty How to show OTUs without taxonomic information. One of the following:\n#' \\itemize{\n#' \\item \\code{\"remove\"}: Remove OTUs without taxonomic information.\n#' \\item \\code{\"best\"}: (\\emph{default}) Use the best classification possible.\n#' \\item \\code{\"OTU\"}: Display the OTU name.\n#' }\n#' @param tax_class Converts a specific phylum to class level instead, e.g. \\code{\"p__Proteobacteria\"}.\n#' @param tax_level The taxonomic level to remove OTUs with no assigned taxonomy, only used when \\code{tax_empty = \"remove\"}. (\\emph{default:} \\code{\"Genus\"})\n#'\n#' @return A list with 3 dataframes (4 if reference sequences are provided).\n#' @importFrom dplyr mutate\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\n#' @author Mads Albertsen \\email{MadsAlbertsen85@@gmail.com}\namp_rename <- function(data, tax_class = NULL, tax_empty = \"best\", tax_level = \"Genus\") {\n tax <- data[[\"tax\"]]\n \n ## First make sure that all entries are strings\n tax[] <- lapply(tax, as.character)\n \n ## Change a specific phylum to class level\n if (!is.null(tax_class)) {\n for (i in 1:nrow(tax)) {\n if (!is.na(tax$Phylum[i]) & tax$Phylum[i] %in% tax_class) {\n tax$Phylum[i] <- tax$Class[i]\n }\n }\n }\n \n ## Remove QIIME taxonomy format prefixes across all levels\n tax[] <- lapply(tax, gsub, pattern = \"^[dkpcofgs]_+\", replacement = \"\")\n \n ## Check if there is a species level otherwise add it for consistency\n if (is.null(tax$Species)) {\n tax$Species <- \"\"\n }\n \n ## NA's as empty strings\n tax[is.na(tax)] <- \"\"\n \n ## How to handle empty taxonomic assignments\n if (tax_empty == \"OTU\") {\n for (i in 1:nrow(tax)) {\n if (tax[i, \"Species\"] == \"\") {\n tax[i, \"Species\"] <- rownames(tax)[i]\n }\n if (tax[i, \"Genus\"] == \"\") {\n tax[i, \"Genus\"] <- rownames(tax)[i]\n }\n if (tax[i, \"Family\"] == \"\") {\n tax[i, \"Family\"] <- rownames(tax)[i]\n }\n if (tax[i, \"Order\"] == \"\") {\n tax[i, \"Order\"] <- rownames(tax)[i]\n }\n if (tax[i, \"Class\"] == \"\") {\n tax[i, \"Class\"] <- rownames(tax)[i]\n }\n if (tax[i, \"Phylum\"] == \"\") {\n tax[i, \"Phylum\"] <- rownames(tax)[i]\n }\n }\n }\n \n ## Handle empty taxonomic strings\n rn <- rownames(tax) # damn rownames are silently dropped by mutate()\n if (tax_empty == \"best\") {\n tax <- mutate(tax, Kingdom, Kingdom = ifelse(Kingdom == \"\", \"Unclassified\", Kingdom)) %>%\n mutate(Phylum, Phylum = ifelse(Phylum == \"\", paste(\"k__\", Kingdom, \"_\", rownames(tax), sep = \"\"), Phylum)) %>%\n mutate(Class, Class = ifelse(Class == \"\", ifelse(grepl(\"__\", Phylum), Phylum, paste(\"p__\", Phylum, \"_\", rownames(tax), sep = \"\")), Class)) %>%\n mutate(Order, Order = ifelse(Order == \"\", ifelse(grepl(\"__\", Class), Class, paste(\"c__\", Class, \"_\", rownames(tax), sep = \"\")), Order)) %>%\n mutate(Family, Family = ifelse(Family == \"\", ifelse(grepl(\"__\", Order), Order, paste(\"o__\", Order, \"_\", rownames(tax), sep = \"\")), Family)) %>%\n mutate(Genus, Genus = ifelse(Genus == \"\", ifelse(grepl(\"__\", Family), Family, paste(\"f__\", Family, \"_\", rownames(tax), sep = \"\")), Genus)) %>%\n mutate(Species, Species = ifelse(Species == \"\", ifelse(grepl(\"__\", Genus), Genus, paste(\"g__\", Genus, \"_\", rownames(tax), sep = \"\")), Species))\n }\n rownames(tax) <- rn\n \n if (tax_empty == \"remove\") {\n abund <- data[[\"abund\"]]\n tax <- subset(tax, tax[, tax_level] != \"\")\n abund <- subset(abund, rownames(abund) %in% rownames(tax))\n data[[\"abund\"]] <- abund\n }\n data[[\"tax\"]] <- tax\n rownames(data[[\"tax\"]]) <- rownames(tax)\n \n return(data)\n}\n\n#' @title Get data from the MiDAS field guide API\n#' @description Gets all fields from the MiDAS field guide (\\url{https://midasfieldguide.org}) returned in a list.\n#'\n#' @return A list with all fields.\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\ngetMiDASFGData <- function() {\n checkReqPkg(\"jsonlite\")\n jsonlite::read_json(\"http://midasfieldguide.org/api/microbes/fieldguide\")\n}\n\n#' @title Extract functional information about Genera from the MiDAS field guide\n#' @description Extract field related to properties and metabolism of all Genera from a list obtained by \\code{\\link{getMiDASFGData}} and return in a data frame.\n#'\n#' @param FGList Data list obtained by \\code{\\link{getMiDASFGData}}.\n#'\n#' @importFrom data.table rbindlist\n#'\n#' @return A data frame where each row is a Genus and each column is a \"function\".\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\nextractFunctions <- function(FGList) {\n functions <- lapply(FGList, function(x) {\n outList <- lapply(c(x[[\"properties\"]], x[[\"metabolism\"]]), function(y) {\n if (y[[\"In situ\"]] == \"Positive\" |\n (any(y[[\"In situ\"]] %in% c(\"Variable\", \"Not Assessed\")) &\n y[[\"Other\"]] == \"Positive\")) {\n return(\"POS\")\n }\n if (y[[\"In situ\"]] == \"Negative\" |\n (y[[\"In situ\"]] == \"Not Assessed\" & y[[\"Other\"]] == \"Negative\")) {\n return(\"NEG\")\n }\n if (y[[\"In situ\"]] == \"Variable\" |\n (y[[\"In situ\"]] == \"Not Assessed\" & y[[\"Other\"]] == \"Variable\")) {\n return(\"VAR\")\n }\n if (all(c(y[[\"In situ\"]], y[[\"Other\"]]) %in% \"Not Assessed\")) {\n return(\"NT\")\n }\n })\n c(\n \"Genus\" = gsub(\"^Ca \", \"Ca_\", x[[\"name\"]]),\n \"MiDAS\" = \"POS\",\n outList\n )\n })\n outDF <- as.data.frame(data.table::rbindlist(functions, fill = TRUE))\n outDF[is.na(outDF)] <- \"NT\"\n return(outDF)\n}\n\n#' @title Calculate weighted or unweighted UniFrac distances. Adopted from fastUniFrac() from phyloseq\n#'\n#' @param abund Abundance table with OTU counts, in \\code{ampvis2} objects it is available with simply data$abund\n#' @param tree Phylogenetic tree (rooted and with branch lengths) as loaded with \\code{\\link[ape]{read.tree}}.\n#' @param weighted Calculate weighted or unweighted UniFrac distances.\n#' @param normalise Should the output be normalised such that values range from 0 to 1 independent of branch length values? Note that unweighted UniFrac is always normalised. (\\emph{default:} \\code{TRUE})\n#' @param num_threads The number of threads to be used for calculating UniFrac distances. If set to more than \\code{1} then this is set by using \\code{\\link[doParallel]{registerDoParallel}}. (\\emph{default:} \\code{1})\n#'\n#' @importFrom ape is.rooted node.depth node.depth.edgelength reorder.phylo\n#' @return A distance matrix of class \\code{dist}.\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\nunifrac <- function(abund,\n tree,\n weighted = FALSE,\n normalise = TRUE,\n num_threads = 1L) {\n checkReqPkg(\"doParallel\")\n # foreach is installed with doParallel, but its namespace needs to be loaded\n checkReqPkg(\"foreach\")\n \n # check tree\n if (!class(tree) == \"phylo\") {\n stop(\"The provided phylogenetic tree must be of class \\\"phylo\\\" as loaded with the ape::read.tree() function.\", call. = FALSE)\n }\n if (!ape::is.rooted(tree)) {\n stop(\"Tree is not rooted!\", call. = FALSE)\n # message(\"Tree is not rooted, performing a midpoint root\")\n # tree <- phytools::midpoint.root(tree)\n }\n if (is.null(tree$edge.length)) {\n stop(\"Tree has no branch lengths, cannot compute UniFrac\", call. = FALSE)\n }\n OTU <- as.matrix(abund)\n ntip <- length(tree$tip.label)\n if (ntip != nrow(OTU)) {\n stop(\"OTU table and phylogenetic tree do not match\", call. = FALSE)\n }\n # if(!all(rownames(OTU) == tree$tip.label))\n # OTU <- OTU[tree$tip.label, , drop = FALSE]\n node.desc <- matrix(tree$edge[order(tree$edge[, 1]), ][, 2], byrow = TRUE, ncol = 2)\n edge_array <- matrix(0,\n nrow = ntip + tree$Nnode,\n ncol = ncol(OTU),\n dimnames = list(NULL, sample_names = colnames(OTU))\n )\n edge_array[1:ntip, ] <- OTU\n ord.node <- order(ape::node.depth(tree))[(ntip + 1):(ntip + tree$Nnode)]\n for (i in ord.node) {\n edge_array[i, ] <- colSums(edge_array[node.desc[i - ntip, ], , drop = FALSE], na.rm = TRUE)\n }\n edge_array <- edge_array[tree$edge[, 2], ]\n rm(node.desc)\n if (isFALSE(weighted)) {\n edge_occ <- (edge_array > 0) - 0\n }\n if (isTRUE(weighted) & isTRUE(normalise)) {\n z <- ape::reorder.phylo(tree, order = \"postorder\")\n tipAges <- ape::node.depth.edgelength(tree)\n tipAges <- tipAges[1:length(tree$tip.label)]\n names(tipAges) <- z$tip.label\n tipAges <- tipAges[rownames(OTU)]\n }\n samplesums <- colSums(OTU)\n if (num_threads == 1L) {\n foreach::registerDoSEQ()\n } else if (num_threads > 1) {\n doParallel::registerDoParallel(num_threads)\n }\n spn <- combn(colnames(OTU), 2, simplify = FALSE)\n distlist <- foreach::foreach(i = spn) %dopar% {\n A <- i[1]\n B <- i[2]\n AT <- samplesums[A]\n BT <- samplesums[B]\n if (isTRUE(weighted)) {\n wUF_branchweight <- abs(edge_array[, A] / AT - edge_array[, B] / BT)\n numerator <- sum(\n {\n tree$edge.length * wUF_branchweight\n },\n na.rm = TRUE\n )\n if (isFALSE(normalise)) {\n return(numerator)\n } else {\n denominator <- sum(\n {\n tipAges * (OTU[, A] / AT + OTU[, B] / BT)\n },\n na.rm = TRUE\n )\n return(numerator / denominator)\n }\n } else {\n edge_occ_AB <- edge_occ[, c(A, B)]\n edge_uni_AB_sum <- sum((tree$edge.length * edge_occ_AB)[rowSums(edge_occ_AB, na.rm = TRUE) < 2, ], na.rm = TRUE)\n uwUFpairdist <- edge_uni_AB_sum / sum(tree$edge.length[rowSums(edge_occ_AB, na.rm = TRUE) > 0])\n return(uwUFpairdist)\n }\n }\n UniFracMat <- matrix(NA_real_, ncol(OTU), ncol(OTU))\n rownames(UniFracMat) <- colnames(UniFracMat) <- colnames(OTU)\n matIndices <- do.call(rbind, spn)[, 2:1]\n if (!is.matrix(matIndices)) matIndices <- matrix(matIndices, ncol = 2)\n UniFracMat[matIndices] <- unlist(distlist)\n return(as.dist(UniFracMat))\n}\n\n#' Calculate Jensen-Shannon Divergence distances\n#'\n#' @param abund Abundance table with OTU counts, in \\code{ampvis2} objects it is available with simply data$abund.\n#' @param pseudocount Pseudocount to use instead of 0-divisions. (\\emph{default:} \\code{0.000001})\n#'\n#' @return A distance matrix of class \\code{dist}.\n# This is based on http://enterotype.embl.de/enterotypes.html\n# Abundances of 0 will be set to the pseudocount value to avoid 0-value denominators\n# Unfortunately this code is SLOOOOOOOOW\ndist.JSD <- function(abund, pseudocount = 0.000001) {\n inMatrix <- t(abund)\n KLD <- function(x, y) sum(x * log(x / y))\n JSD <- function(x, y) sqrt(0.5 * KLD(x, (x + y) / 2) + 0.5 * KLD(y, (x + y) / 2))\n matrixColSize <- length(colnames(inMatrix))\n matrixRowSize <- length(rownames(inMatrix))\n colnames <- colnames(inMatrix)\n resultsMatrix <- matrix(0, matrixColSize, matrixColSize)\n \n inMatrix <- apply(inMatrix, 1:2, function(x) ifelse(x == 0, pseudocount, x))\n \n for (i in 1:matrixColSize) {\n for (j in 1:matrixColSize) {\n resultsMatrix[i, j] <- JSD(\n as.vector(inMatrix[, i]),\n as.vector(inMatrix[, j])\n )\n }\n }\n colnames -> colnames(resultsMatrix) -> rownames(resultsMatrix)\n as.dist(resultsMatrix) -> resultsMatrix\n attr(resultsMatrix, \"method\") <- \"dist\"\n return(resultsMatrix)\n}\n\n#' @title Find lowest taxonomic level\n#' @description Finds the lowest taxonomic level of two given levels in \\code{tax}. The hierarchic order of taxonomic levels is simply taken from the order of column names in \\code{tax}\n#'\n#' @param tax_aggregate A character vector of one or more taxonomic levels (exactly as in the column names of \\code{ampvis2obj$tax}), fx Genus or Species. (\\emph{default:} \\code{NULL})\n#' @param tax_add A second character vector similar to \\code{tax_aggregate}. (\\emph{default:} \\code{NULL})\n#' @param tax The taxonomy table from an ampvis2 object (\\code{ampvis2obj$tax})\n#'\n#' @return A length one character vector with the lowest taxonomic level.\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\ngetLowestTaxLvl <- function(tax, tax_aggregate = NULL, tax_add = NULL) {\n if (is.null(tax_aggregate) & is.null(tax_add)) {\n tax_aggregate <- colnames(tax)[ncol(tax)]\n }\n # find the lowest taxonomic level of tax_aggregate and tax_add\n taxlevels <- factor(\n x = colnames(tax),\n levels = colnames(tax)\n )\n lowestlevel <- as.character(taxlevels[max(as.numeric(c(\n taxlevels[which(taxlevels %in% tax_aggregate)],\n taxlevels[which(taxlevels %in% tax_add)]\n )))])\n return(lowestlevel)\n}\n\n#' @title Aggregate OTUs to a specific taxonomic level\n#' @description Calculates the sum of OTUs per taxonomic level\n#'\n#' @param abund The OTU abundance table from an ampvis2 object (\\code{ampvis2obj$abund})\n#' @param tax The OTU abundance table from an ampvis2 object (\\code{ampvis2obj$tax})\n#' @param tax_aggregate Aggregate (sum) OTU's to a specific taxonomic level. (\\emph{default:} \\code{\"OTU\"})\n#' @param tax_add Add additional (higher) taxonomic levels to the taxonomy string. The OTU's will be aggregated to whichever level of the \\code{tax_aggregate} and \\code{tax_add} vectors is the lowest. (\\emph{default:} \\code{NULL})\n#' @param calcSums Whether to include the sums of read counts for each sample and taxonomic group. (\\emph{default:} \\code{TRUE})\n#' @param format Output format, \\code{\"long\"} or \\code{\"abund\"}. \\code{\"abund\"} corresponds to that of a read counts table with samples as columns and the aggregated taxa as rows.\n#'\n#' @importFrom data.table data.table melt\n#' @return A data.table.\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\naggregate_abund <- function(abund,\n tax,\n tax_aggregate = \"OTU\",\n tax_add = NULL,\n calcSums = TRUE,\n format = \"long\") {\n if (any(colnames(abund) %in% \"Display\")) {\n stop(\"A column is named \\\"Display\\\" in the OTU abundance table, please change it to continue\", call. = FALSE)\n }\n \n # make sure all tax columns are of type character (nchar() does not allow factors)\n tax[] <- lapply(tax, as.character)\n \n # find the lowest taxonomic level of tax_aggregate and tax_add\n lowestTaxLevel <- getLowestTaxLvl(\n tax = tax,\n tax_aggregate = tax_aggregate,\n tax_add = tax_add\n )\n \n # Remove all OTUs that are not assigned at the chosen taxonomic level\n # and print a status message with the number of removed OTUs\n newtax <- tax[which(nchar(tax[[lowestTaxLevel]]) > 1 &\n !is.na(tax[[lowestTaxLevel]]) &\n !grepl(\"^\\\\b[dkpcofgs]*[_:;]*\\\\b$\", tax[[lowestTaxLevel]])), ]\n newabund <- abund[rownames(newtax), , drop = FALSE]\n if (nrow(newtax) != nrow(tax)) {\n message(paste0(\n nrow(tax) - nrow(newtax),\n \" OTUs (out of \",\n nrow(tax),\n \") with no assigned taxonomy at \",\n lowestTaxLevel,\n \" level were removed before aggregating OTUs\"\n ))\n }\n \n abundTax <- data.table::data.table(\n newabund,\n Display = apply(\n newtax[, c(tax_add, tax_aggregate), drop = FALSE],\n 1,\n paste,\n collapse = \"; \"\n )\n )\n abundAggr <- data.table::melt(\n abundTax,\n id.vars = \"Display\",\n variable.name = \"Sample\",\n value.name = \"Abundance\",\n variable.factor = FALSE\n )\n if (isTRUE(calcSums)) {\n abundAggr[,\n Sum := sum(Abundance),\n keyby = .(Display, Sample)\n ]\n }\n if (format == \"long\") {\n out <- abundAggr\n } else if (format == \"abund\") {\n out <- as.data.frame(\n data.table::dcast(abundAggr,\n Display ~ Sample,\n value.var = \"Abundance\",\n fun.aggregate = sum\n )\n )\n rownames(out) <- as.character(out[[1]])\n out <- out[, -1, drop = FALSE]\n } else {\n stop(\"format must be either \\\"long\\\" or \\\"abund\\\"\")\n }\n return(out)\n}\n\nabundAreCounts <- function(data) {\n ### Data must be in ampvis2 format\n is_ampvis2(data)\n \n # check if $abund contains read counts and not normalised counts or any decimals\n all(\n !isTRUE(attributes(data)$normalised),\n all(data$abund %% 1L == 0),\n !all(colSums(data$abund) == 100)\n )\n}\n\n#' @title Normalise read counts to 100, i.e. in percent relative abundance per sample\n#'\n#' @param data (\\emph{required}) Data list as loaded with \\code{\\link{amp_load}}.\n#'\n#' @return A modifed ampvis2 object\nnormaliseTo100 <- function(data) {\n ### Data must be in ampvis2 format\n is_ampvis2(data)\n \n if (!abundAreCounts(data)) {\n warning(\"The data has already been normalised. Setting normalise = TRUE (the default) will normalise the data again and the relative abundance information about the original data of which the provided data is a subset will be lost.\", call. = FALSE)\n }\n # normalise each sample to sample totals, skip samples with 0 sum to avoid NaN's\n tmp <- data$abund[, which(colSums(data$abund) != 0), drop = FALSE]\n if (nrow(tmp) == 1L) {\n # apply returns a vector and drops rownames if only 1 row, therefore set to 100 instead\n tmp[1L, ] <- 100L\n } else if (nrow(tmp) > 1L) {\n tmp <- as.data.frame(apply(tmp, 2, function(x) {\n x / sum(x) * 100\n }))\n }\n data$abund[, which(colSums(data$abund) != 0)] <- tmp\n attributes(data)$normalised <- TRUE\n return(data)\n}\n\n#' @title Filter species by a threshold in percent\n#'\n#' @param data (\\emph{required}) Data list as loaded with \\code{\\link{amp_load}}.\n#' @param filter_species Remove low abundant OTU's across all samples below this threshold in percent. (\\emph{default}: \\code{0})\n#'\n#' @importFrom ape drop.tip\n#' @return An ampvis2 object\nfilter_species <- function(data, filter_species = 0) {\n ### Data must be in ampvis2 format\n is_ampvis2(data)\n \n if (is.numeric(filter_species)) {\n if (filter_species > 0) {\n # First transform to percentages\n abund_pct <- data$abund\n abund_pct[, which(colSums(abund_pct) != 0)] <- as.data.frame(apply(abund_pct[, which(colSums(abund_pct) != 0), drop = FALSE], 2, function(x) x / sum(x) * 100))\n rownames(abund_pct) <- rownames(data$abund) # keep rownames\n \n # Then filter low abundant OTU's where ALL samples have below the threshold set with filter_species in percent\n abund_subset <- abund_pct[!apply(abund_pct, 1, function(row) all(row <= filter_species)), , drop = FALSE] # remove low abundant OTU's\n data$abund <- data$abund[which(rownames(data$abund) %in% rownames(abund_subset)), , drop = FALSE]\n rownames(data$tax) <- data$tax$OTU\n \n # also filter taxonomy, tree, and sequences\n data$tax <- data$tax[which(rownames(data$tax) %in% rownames(abund_subset)), , drop = FALSE]\n \n if (!is.null(data$tree)) {\n data$tree <- ape::drop.tip(\n phy = data$tree,\n tip = data$tree$tip.label[!data$tree$tip.label %in% data$tax$OTU]\n )\n }\n \n if (!is.null(data$refseq)) {\n if (!is.null(names(data$refseq))) {\n # sometimes there is taxonomy alongside the OTU ID's. Anything after a \";\" will be ignored\n names_stripped <- stringr::str_split(names(data$refseq), \";\", simplify = TRUE)[, 1]\n data$refseq <- data$refseq[names_stripped %in% rownames(data$abund)]\n } else if (is.null(names(data$refseq))) {\n warning(\"DNA sequences have not been subsetted, could not find the names of the sequences in data$refseq.\", call. = FALSE)\n }\n }\n }\n }\n return(data)\n}\n\n#' @title Check if data has class \"ampvis2\"\n#' @description Checks if the object is of class \"ampvis2\".\n#'\n#' @param data Object to check\n#'\n#' @return Returns error if \\code{!inherits(data, \"ampvis2\")}, otherwise \\code{invisible(TRUE)}.\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\nis_ampvis2 <- function(data) {\n if (!inherits(data, \"ampvis2\")) {\n stop(\"The provided data is not in ampvis2 format. Use amp_load() to load your data before using ampvis2 functions. (Or class(data) <- \\\"ampvis2\\\", if you know what you are doing.)\", call. = FALSE)\n }\n invisible(TRUE)\n}\n\n#' @title Check for installed package\n#' @description Returns error if a required package is not installed. Mostly used for checking whether packages listed under the Suggests field in the DESCRIPTION file is installed.\n#'\n#' @param pkg The package to check for, a character of length 1.\n#' @param msg Optionally additional text appended (with \\code{paste0}) to the default error message.\n#'\n#' @return Returns error and message if not installed, otherwise \\code{invisible(TRUE)}\n#' @author Kasper Skytte Andersen \\email{ksa@@bio.aau.dk}\ncheckReqPkg <- function(pkg, msg = \"\") {\n stopifnot(is.character(pkg), length(pkg) == 1L, nchar(pkg) > 0)\n if (!requireNamespace(pkg, quietly = TRUE)) {\n stopifnot(is.character(msg))\n stop(\n paste0(\"Package '\", pkg, \"' is required but not installed.\", msg),\n call. = FALSE\n )\n }\n require(pkg, quietly = TRUE, character.only = TRUE)\n}\n\n#' Replacement for \":::\" to suppress R CMD CHECK warnings\n# `%:::%` <- function(pkg, fun)\n# get(fun, envir = asNamespace(pkg), inherits = FALSE)", "meta": {"hexsha": "d5ba5fafdee813035f3d4a18f96b67c7922ef8fc", "size": 23211, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/ampvis2_internals.r", "max_stars_repo_name": "pietervanveelen/biogeography_lark_microbiota", "max_stars_repo_head_hexsha": "da619565b9e55ebca4cf89462431eac2a8f721e1", "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/ampvis2_internals.r", "max_issues_repo_name": "pietervanveelen/biogeography_lark_microbiota", "max_issues_repo_head_hexsha": "da619565b9e55ebca4cf89462431eac2a8f721e1", "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/ampvis2_internals.r", "max_forks_repo_name": "pietervanveelen/biogeography_lark_microbiota", "max_forks_repo_head_hexsha": "da619565b9e55ebca4cf89462431eac2a8f721e1", "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.1542553191, "max_line_length": 252, "alphanum_fraction": 0.6334496575, "num_tokens": 6725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3040416749665475, "lm_q2_score": 0.029760095236751886, "lm_q1q2_score": 0.009048309202946015}} {"text": "\n= La població d'Espanya i d'Europa\n\n:author\n Alfons Rovira\n:theme\n debian\n\n= Població\n\n((*Població absoluta*)): d'un territori és el nombre de persones que hi viuen.\n\n= Factors\n\n * (('wait'))Relleu\n * (('wait'))Clima\n\n= Raons\n\n * (('wait')) A on el relleu i el clima és més favorable major indústria i serveis.\n * (('wait')) Àrees de muntanya i d'interior. Clima més desfavorable. Poc poblades i activitats agràries.\n\n= Densitat\n\n * ((*Densitat de població*)): nombre d'habitants que viuen en un kilòmetre quadrat de superfície.\n * Espanya la densitat de població: 93,4 h/km (('sup:2'))\n\n= Definicions\n\n((*Demografia*)): Ciència que estudia la població, com es distribueix, com evoluciona la població en un lloc determinat.\n\n= Definicions\n\n((*Població urbana*)): Població que viu a municipis de més de ((*10.000*)) habitants.\n\n= Definicions\n\n((*Població absoluta*)): d'un territori és el nombre de persones que hi viuen.\n\n\n= Definicions\n\n((*Natalitat*)): nombre d'infants que naixen en un lloc durant un any.\n\n= Definicions\n\n((*Mortalitat*)): nombre d'persones que moren en un lloc durant un any.\n\n= Definicions\n\n((*Esperança de vida*)): mitjana d'anys que viu una població.\n\n= Definicions\n\n((*Creixement natural*)): diferència entre el total de naixements o natalitat i el total de defuncions o mortalitat.\n\n= Definicions\n\n((*Creixement real*)): creixement natural + saldo migratori\n\n= Definicions\n\n((*Saldo migratori*)): immigrants - emigrants\n\n= Definicions\n\n((*Població activa*)): població ocupada + població en atur\n\n\n= Definicions\n\n((*Població no activa*)): infants, estudinats, mestresses de casa i jubitalts.\n\n= Definicions\n\n((*Pirámide de població*)): és un gràfic que ordena els habitants d'un lloc per grups d'edat i sexe en un moment concret.\n\nParts:\n\n * Base: població jove\n * Tronc: població adulta\n * Cim: població anciana\n\n= Causes de les migracions\n\n * (('wait'))((*Socials i econòmiques*)): pobresa, cerca de millors condicions de vida\n * (('wait'))((*Polítiques*)): guerres, conflictes racials, conflictes religiosos\n * (('wait'))((*Naturals*)): huracans, tsunameis, terratremols sequeres\n * (('wait'))((*Familiars*)): reagrupament familiar\n\n\n= Definicions\n\n((*Migració exterior*)): abandonament del país d'origen.\n\n= Definicions\n\n((*Migració interior*)): moviment de la població dins d'un país.\n\n= Conseqüències de les migracions\n\n * ((*Dinàmica de població*)): aportació de població i augment de la natalitat\n * ((*Economia*)): creixement econòmic\n * ((*Diversistat cultural*)): contacte amb noves cultures i costums\n\n= Població europea\n\n * (('wait')) És irregular\n * (('wait')) Creixement dèbil\n * (('wait')) Envellida\n * (('wait')) Urbana\n * (('wait')) Amb molta immigració\n", "meta": {"hexsha": "af17244a7f58ec6229ee924631c1c3d8eccf1d32", "size": 2723, "ext": "rd", "lang": "R", "max_stars_repo_path": "01_socials/04/04_ud4.rd", "max_stars_repo_name": "inclusa/5pri", "max_stars_repo_head_hexsha": "d148abd29118857e5643efac8d4d65fbbf56b312", "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": "01_socials/04/04_ud4.rd", "max_issues_repo_name": "inclusa/5pri", "max_issues_repo_head_hexsha": "d148abd29118857e5643efac8d4d65fbbf56b312", "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": "01_socials/04/04_ud4.rd", "max_forks_repo_name": "inclusa/5pri", "max_forks_repo_head_hexsha": "d148abd29118857e5643efac8d4d65fbbf56b312", "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.0973451327, "max_line_length": 121, "alphanum_fraction": 0.7010650018, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24508500210441891, "lm_q2_score": 0.03676946383261257, "lm_q1q2_score": 0.009011644120794207}} {"text": "/*\tNeutron Scattering.r -- resources for \"Neutron Scattering\" XOP */\n\n// Igor resources\n#include \"XOPStandardHeaders.r\"\n\nresource 'vers' (1) { /* XOP version info */\n 0x01, 0x16, final, 0x00, 0, /* version bytes and country integer */\n \"1.22\",\n \"1.22, © 2000-2021 ILL/SANE, all rights reserved.\"\n};\n\nresource 'vers' (2) { /* Igor version info */\n 0x08, 0x04, release, 0x00, 0, /* version bytes and country integer */\n \"8.04\",\n \"(for Igor Pro 8.04 or later)\"\n};\n\nresource 'STR#' (1100) {\t\t\t\t\t/* custom error messages */\n\t{\n\t\t/* [1] */\n\t\t\"Neutron Scattering XOP requires Igor 8.04 or later.\",\n\t\t/* [2] */\n\t\t\"Null Counting Time.\",\n\t\t/* [3] */\n\t\t\"Null Count Rate.\",\n\t\t/* [4] */\n\t\t\"Null Monitor Value: Beam may not be opened !\",\n\t\t/* [5] */\n\t\t\"Infinite Flipping Ratio.\",\n\t\t/* [6] */\n\t\t\"Infinite Flipping Ratio Standard Deviation.\",\n\t\t/* [7] */\n\t\t\"Infinite Counting Time.\",\n\t\t/* [8] */\n\t\t\"Infinite Counting Time Standard Deviation.\",\n\t\t/* [9] */\n\t\t\"Undefined Detector Position.\",\n\t\t/* [10] */\n\t\t\"Infinite Asymmetry.\",\n\t\t/* [11] */\n\t\t\"Infinite Asymmetry Standard Deviation.\",\n\t\t/* [12] */\n\t\t\"Undefined Count Rate.\",\n\t\t/* [13] */\n\t\t\"Wrong lattice parameters - Det[G] = 0.\",\n\t}\n};\n\n/* no menu item */\n\nresource 'XOPI' (1100) {\n XOP_VERSION, // XOP protocol version.\n DEV_SYS_CODE, // Code for development system used to make XOP\n XOP_FEATURE_FLAGS, // Tells Igor about XOP features\n XOPI_RESERVED, // Reserved - must be zero.\n XOP_TOOLKIT_VERSION, // XOP Toolkit version.\n};\n\nresource 'XOPF' (1100) {\n\t{\n\t\t\"CountRate\",\t\t\t\t\t\t/* function name */\n\t\tF_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\t\t\t\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"CountRateSDev\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"CountRateDDT\",\t\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"CountRateDDTSDev\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"CountRateMonitor\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"CountRateMonitorSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"FlippingRatio\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"FlippingRatioSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"FlippingRatioOpt\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"FlippingRatioOptSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"FlippingRatioOptDDT\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"FlippingRatioOptDDTSDev\",\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTpp\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTbp\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTpm\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTbm\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTppSDev\",\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTbpSDev\",\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTpmSDev\",\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"OptCountingTimeTbmSDev\",\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"PeakCentringLin\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"PeakCentringLinSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"PeakCentringGauss\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"PeakCentringGaussSDev\",\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLcubic\",\t\t\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLhexagonal\",\t\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLrhombohedral\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLtetragonal\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLorthorhombic\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLmonoclinicB\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLmonoclinicC\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"STLtriclinic\",\t\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"Asymmetry\",\t\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"AsymmetrySDev\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"AsymmetryOpt\",\t\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"AsymmetryOptSDev\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"AsymmetryOptDDT\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"AsymmetryOptDDTSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3Efficiency\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3EfficiencySDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3Efficiency2\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3Efficiency2SDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3Transmission\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3TransmissionSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n NT_FP64,\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3Polarisation\",\t\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n \n\t\t\"He3PolarisationSDev\",\t\t\t\t/* function name */\n F_UTIL | F_EXTERNAL, /* function category */\n\t\tNT_FP64,\t\t\t\t\t\t\t/* return value type */\t\t\t\n\t\t{\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\t\t\t\t\t\t/* parameter types */\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n NT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t\tNT_FP64,\n\t\t},\n\t}\n};\n", "meta": {"hexsha": "4685ad1111412bd3abffff16aa79adc815b6a1e7", "size": 14945, "ext": "r", "lang": "R", "max_stars_repo_path": "Xcode project/Neutron Scattering.r", "max_stars_repo_name": "EddyLB/XOP-Neutron-Scattering", "max_stars_repo_head_hexsha": "2dc220bb4d233df5a92d0f05ab4b07837a3837db", "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": "Xcode project/Neutron Scattering.r", "max_issues_repo_name": "EddyLB/XOP-Neutron-Scattering", "max_issues_repo_head_hexsha": "2dc220bb4d233df5a92d0f05ab4b07837a3837db", "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": "Xcode project/Neutron Scattering.r", "max_forks_repo_name": "EddyLB/XOP-Neutron-Scattering", "max_forks_repo_head_hexsha": "2dc220bb4d233df5a92d0f05ab4b07837a3837db", "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": 22.4399399399, "max_line_length": 91, "alphanum_fraction": 0.512278354, "num_tokens": 4926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.025178843940802508, "lm_q1q2_score": 0.008958000521835329}} {"text": "#' @exportClass Node\n#' @name Node \n#' @rdname Node\n#' @aliases Node-class \n#' @title The Node class\n#'\n#' @description \n#' This class is part of the \\pkg{HNUORTools}. It represents \n#' the base class for every locateable class in an\n#' \\dfn{Operations-Research (OR)}-context.\n#' \n#' @details Find here the defined slots for this class.\n#' @section Slots: \n#' \\describe{\n#' \\item{\\code{id}:}{\n#' Object of class \\code{\"character\"}, containing data from id.\n#' \\strong{Should be unique}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{label}:}{\n#' Object of class \\code{\"character\"}, containing the label of \n#' the \\code{\\link{Node}}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{x}:}{\n#' Object of class \\code{\"numeric\"}, containing the x-coordinate \n#' of the \\code{\\link{Node}}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{y}:}{\n#' Object of class \\code{\"numeric\"}, containing the y-coordinate \n#' of the \\code{\\link{Node}}.\n#' The default value will be caluclated randomly.\n#' }\n#' }\n#'\n#' @seealso The classes are derived from this class and the following Methods can be used with this class.:\n#' @section Creating objects of type \\code{\\link{Node}}:\n#' \\describe{\n#' \\item{Creating an \\code{S4-Object}}{ \n#' \\code{new(\"Node\", ...)}\n#' } \n#' \\item{Converting from a \\code{data.frame}}{ \n#' \\code{as.Node{}}\n#' See also below in the Methods-Section.\n#' }\n#' \\item{Converting from a \\code{list}}{ \n#' \\code{as.Node{}}\n#' See also below in the Methods-Section.\n#' }\n#' }\n#' @section Methods:\n#' \\describe{\n#' \\item{\\code{as.list(node, ...)}}{\n#' Converts a \\code{\\link{Node}} into a \\code{\\link{list}}.\n#' \\code{...} are user-defined (not used) parameters.\n#' }\n#' \\item{\\code{as.data.frame(node, ...)}}{\n#' Converts a \\code{\\link{Node}} into a \\code{\\link{data.frame}}.\n#' \\code{as.data.frame} accepts the optional parameter \\code{withrownames} of class \\code{\"logical\"} (default is \\code{TRUE}). \n#' If \\code{withrownames == TRUE} the returned \\code{\\link{data.frame}} will recieve the \\code{id} as rowname.\n#' \\code{...} are user-defined (not used) parameters.\n#'\n#' }\n#' \\item{\\code{as.Node(obj)}}{\n#' Converts an object of class \\code{\\link{data.frame}} or of class \\code{\\link{list}} into a \\code{\\link{Node}}.\n#' } \n#' \\item{\\code{is.Node(obj)}}{\n#' Checks if the object \\code{obj} is of type \\code{\\link{Node}}.\n#' } \n#' \\item{\\code{\\link{getDistance}}}{\n#' Calculating the distance between two \\code{\\link{Node}s} \n#' (As the classes \\code{\\link{Customer}} and \\code{\\link{Warehouse}} \n#' depend on \\code{\\link{Node}}, distances can be calculated between any of these objects).\n#' }\n#' \\item{\\code{\\link{getpolar}}}{\n#' Calculating the polar-angle to the x-Axis of a link, \n#' connecting two \\code{\\link{Node}s} \n#' (As the classes \\code{\\link{Customer}} and \\code{\\link{Warehouse}} \n#' depend on \\code{\\link{Node}}, polar-angles can be calculated between any of these objects).\n#' }\n#' } \n#' \n#' @section Derived Classes:\n#' \\describe{\n#' \\item{\\code{\\link{Customer}}}{\n#' This class extends the \\code{\\link{Node}}-Class \n#' with attributes for according to customers for OR-Problems.\n#' }\n#' \\item{\\code{\\link{Warehouse}}}{\n#' This class extends the \\code{\\link{Node}}-Class \n#' with attributes for according to warehouses for OR-Problems.\n#' }\n#' \\item{\\code{\\link{Link}}}{\n#' This class is constructed by two entities of the \\code{\\link{Node}}-Class \n#' representing the origin and destination of \\code{\\link{Link}} for OR-Problems.\n#' }\n#' }\n#' @section To be used for:\n#' \\describe{ \n#' \\item{SPP}{\n#' Shortest-Path-Problem\n#' }\n#' \\item{TSP}{\n#' Travelling Salesman Problem\n#' }\n#' } \n#' \n#' @note \n#' for citing use: Felix Lindemann (2014). HNUORTools: Operations Research Tools. R package version 1.1-0. \\url{http://felixlindemann.github.io/HNUORTools/}.\n#' \n#' @author Dipl. Kfm. Felix Lindemann \\email{felix.lindemann@@hs-neu-ulm.de} \n#' \n#' Wissenschaftlicher Mitarbeiter\n#' Kompetenzzentrum Logistik\n#' Buro ZWEI, 17\n#'\n#' Hochschule fur angewandte Wissenschaften \n#' Fachhochschule Neu-Ulm | Neu-Ulm University \n#' Wileystr. 1 \n#' \n#' D-89231 Neu-Ulm \n#' \n#' \n#' Phone +49(0)731-9762-1437 \n#' Web \\url{www.hs-neu-ulm.de/felix-lindemann/} \n#' \\url{http://felixlindemann.blogspot.de}\n#' @examples \n#' # create a new Node with specific values\n#' x<- new(\"Node\", x= 10, y=20, id=\"myid\", label = \"mylabel\")\n#' x\n#' # create from data.frame\n#' df<- data.frame(x=10,y=20)\n#' new(\"Node\", df)\n#' as(df, \"Node\")\n#' as.Node(df)\n#' #create some nodes\n#' n1 <- new(\"Node\",x=10,y=20, id =\"n1\")\n#' n2 <- new(\"Node\",x=13,y=24, id =\"n1\")\n#' # calculate Beeline distance\n#' #getDistance(n1,n2) # should result 5\n#' #getDistance(n1,n2, costs = 2) # should result 10\nsetClass(\n\tClass = \"Node\",\n representation=representation(\n \tid = \"character\",\n label = \"character\",\n \tx = \"numeric\",\n \ty = \"numeric\"\n ), \n validity = function(object){\n \n N <- length(object@id) \n if(length(object@label) != N) \n return(\"Invalid Object of Type 'Node': the length of the attributes 'id' and 'label' differ!\")\n if(length(object@x) != N) \n return(\"Invalid Object of Type 'Node': the length of the attributes 'id' and 'x' differ!\")\n if(length(object@y) != N) \n return(\"Invalid Object of Type 'Node': the length of the attributes 'id' and 'y' differ!\") \n\n if( sum(is.null(object@x)) + sum( is.na(object@x)) > 0 ) \n return(paste(\"Invalid Object of Type 'Node': Error with value x: Value is not initialized\", class(object@x)))\n \n if( sum(is.null(object@y)) + sum( is.na(object@y)) > 0) \n return(paste(\"Invalid Object of Type 'Node': Error with value y: Value is not initialized\", class(object@y)))\n \n if( class(object@x)!=\"numeric\" ) \n return(paste(\"Invalid Object of Type 'Node': Error with value x: expected numeric datatype, but obtained\", class(object@x)))\n \n if( class(object@y)!=\"numeric\" ) \n return(paste(\"Invalid Object of Type 'Node': Error with value y: expected numeric datatype, but obtained\", class(object@y))) \n\n return(TRUE) \n } \n)\n################################### initialize - Method ###################################################\n#' @title initialize Method\n#' @name initialize\n#' @aliases initialize,Node-method \n#' @rdname initialize-methods \n#' @param data can of type \\code{\\link{data.frame}} or \\code{\\link{list}}\nsetMethod(\"initialize\", signature=\"Node\", function(.Object, data=NULL, ...) {\n \n li <- list(...)\n N<-1\n if(is.null(li$showwarnings)) li$showwarnings <- FALSE\n if(!is.null(data)){ \n \n if(class(data) ==\"list\") {\n data <- as.data.frame(data)\n }\n if(class(data) ==\"data.frame\") {\n N<-nrow(data)\n li$id <- data$id\n li$label <- data$label \n li$x <- data$x\n li$y <- data$y\n\n } else{ \n stop(\"Error: argument data should be of type 'data.frame'!\")\n }\n } \n if(is.null(li$x)) {\n li$x <- as.numeric(runif(N,0,100)) \n w <- paste(\"x-Coordinate simulated (x= \",li$x,\").\")\n if(li$showwarnings) warning(w) \n }\n if(is.null(li$y)) {\n li$y <- as.numeric(runif(N,0,100)) \n w <- paste(\"y-Coordinate simulated (y= \",li$y,\").\")\n if(li$showwarnings) warning(w) \n }\n if(is.null(li$id)) {\n tmp.id <-NULL\n for(i in 1:N){\n tmp.id <- c(tmp.id, UUIDgenerate()) \n }\n li$id <- tmp.id\n w <- paste(\"Random ID (\",li$id,\") provided. Uniqueness should be given.\")\n if(li$showwarnings) warning(w) \n }\n if(is.null(li$label)) {\n li$label <- li$id \n }\n .Object@id <- as.character(li$id)\n .Object@label <- as.character(li$label)\n\n .Object@x <- as.numeric( li$x)\n .Object@y <- as.numeric( li$y)\n \n validObject(.Object)\n \n return(.Object ) \n})\n################################### extract - Method ###################################################\n\n#' @title Extract Methods\n#' @name $\n#' @aliases $,Node-method \n#' @rdname Extract-methods-1\n#' @param name Name of Attribute.\nsetMethod(\"$\",\"Node\",function(x,name) {return(slot(x,name))})\n#' @title Extract Methods\n#' @name [\n#' @aliases [,Node-method \n#' @rdname Extract-methods-2\n#' @param i Row Index\n#' @param j Name or Column index\n#' @param drop Optional value for Drop-Levels.\nsetMethod(\"[\", \"Node\",\n function(x, i, j, drop){\n N <- length(x)\n if(min(i) <=0) stop(\"Index i out of bound. it must be positive non zero.\")\n if(max(i) >N) stop(\"Index i out of bound. it must not be larger than the total length.\")\n \n\n if(!missing(j)){\n if(class(j) == \"character\"){\n return(slot(x,j)[i])\n }\n if(class(j) == \"integer\"){\n return(slot(x,j)[i]) \n }\n }\n df <- as.data.frame(x)[i,]\n return (new(\"Node\", df)) \n } \n) \n################################### Set - Method ###################################################\n \n#' @title Set Methods\n#' @name $<- \n#' @aliases $<-,Node-method \n#' @rdname Set-methods-1\n#' @param name Name of parameter to change\n#' @param value new Value.\nsetMethod(\"$<-\",\"Node\",function(x,name,value) {\n slot(x,name,check=TRUE) <- value\n valid<-validObject(x)\n return(x)\n})\n\n#' @title Set Methods\n#' @name [<-\n#' @aliases [<-,Node-method \n#' @rdname Set-methods-2\n#' @param x The Node\n#' @param i row-Index\n#' @param j Name or Column index\nsetReplaceMethod(\"[\",signature(x=\"Node\"),\n function(x,i,j,value){\n N <- length(x)\n if(min(i) <=0) stop(\"Index i out of bound. It must be positive non zero.\")\n if(max(i) >N) stop(\"Index i out of bound. It must not be larger than the total length.\")\n if(length(value)!=length(i)) stop(\"The replacement length is not equal to the number of elements to be replaced.\") \n \n if(is(value, \"Node\")){\n \n # copy original values to tmp vectors\n tmp <- as.data.frame(x)\n \n\n #replace the item(s) regarding to i\n tmp$id[i] <- value@id \n tmp$label[i] <- value@label \n tmp$x[i] <- value@x \n tmp$y[i] <- value@y\n \n # return new item\n return (new(\"Node\", tmp)) \n } else {\n if(missing(j)) {\n # call the function recursivly\n # might throw an error if the conversion is not supported.\n x[i] <- as.Node(value)\n }else{ \n if(class(j) == \"character\"){\n slot(x,j)[i] <- value\n }else if(class(j) == \"integer\" | class(j) == \"numeric\"){ \n slot(x,slotNames(x)[j])[i] <- value \n }else{\n warning(paste(\"no changes have been made. the provided value of j (class:\",class(j), \"value:\",j,\") was not recocnized.\"))\n }\n }\n valid<-validObject(x)\n return(x) \n }\n } \n)\n\n################################### as... - Method ###################################################\n#local Methods\nas.Node.list = function(x, ...){return(new(\"Node\", data=x))}\nas.Node.data.frame = function(x, ...){return(new(\"Node\", data=x))}\n#local convert message\nas.data.frame.Node = function(x, ...){\n li<-list(...)\n if(is.null(li$withrownames)) li$withrownames <- FALSE\n df<-data.frame(id=x@id, label = x@label, x= x@x, y= x@y)\n if(li$withrownames) rownames(df)<-x@id\n return (df)\n}\nas.list.Node = function(x, ...){list(id=x@id, label = x@label, x= x@x, y= x@y)}\n\n\n#' @export\nsetGeneric(\"as.Node\", function(x, ...) standardGeneric( \"as.Node\")) \n\n#' @title Convert Objects to Nodes\n#' @name as.Node \n#' @param x an Object to convert.\n#' @param ... optional parameters\n#' @aliases as.Node,list-method \n#' @rdname as.Node-methods \nsetMethod(\"as.Node\", signature(x = \"list\"), as.Node.list) \n\n#' @title Convert Objects to Nodes\n#' @name as.Node\n#' @aliases as.Node,data.frame-method \n#' @rdname as.Node-methods \nsetMethod(\"as.Node\", signature(x = \"data.frame\"), as.Node.data.frame) \n\n#' @title Convert Objects to lists\n#' @name as.list\n#' @param x the Node \n#' @aliases as.list,Node-method \n#' @rdname as.list-methods \nsetMethod(\"as.list\", signature(x = \"Node\"), as.list.Node) \n\n#' @title Convert Objects to data.frames\n#' @name as.data.frame\n#' @param x the Node \n#' @aliases as.data.frame,Node-method \n#' @rdname as.data.frame-methods \nsetMethod(\"as.data.frame\", signature(x = \"Node\"), as.data.frame.Node) \n \nsetAs(\"data.frame\", \"Node\", def=function(from){return(as.Node.data.frame(from))})\nsetAs(\"list\", \"Node\", def=function(from){return(as.Node.list(from))})\n################################### is... - Method ###################################################\n\n#' @title Checks if an Object is as Node\n#' @export\n#' @name is.Node\n#' @param x the Node \n#' @param ... optional Parameters (not supported)\nsetGeneric(\"is.Node\", function(x, ...) standardGeneric( \"is.Node\")) \n\n#' @aliases is.Node,Node-method \n#' @rdname is.Node\nsetMethod( \"is.Node\", \"Node\", function(x, ...){ \n return(is(x ,\"Node\")) \n})\n \n \n#' @title How many Nodes are included?\n#' @name length\n#' @param x the Nodes\n#' @aliases length,Node-method \n#' @rdname length \nsetMethod(\"length\", \"Node\",\n function(x){\n N <- length(x@id)\n return(N)\n } \n)\n \n#' @aliases getDistance,Node,Node-method \n#' @rdname getDistance \n#' @examples \n#' # w1 <- new(\"Node\", x=0, y=0)\n#' # c1 <- new(\"Node\", x=3, y=4)\n#' # getDistance(w1,c1) # should result 5. \n#' # getDistance(w1,c1,costfactor=3) # should result 15. \nsetMethod( \"getDistance\", signature = c(\"Node\", \"Node\"),\n function(n0,n1, ...) {\n li<-list(...)\n \n p0<-c(n0$x,n0$y)\n p1<-c(n1$x,n1$y)\n \n value <- getDistance(p0,p1, ...)\n \n return(value)\n }\n)\n \n#' @aliases getpolar,Node,Node-method \n#' @rdname getpolar \n#' @examples\n#' # w1 <- new(\"Node\", x=0, y=0)\n#' # c1 <- new(\"Node\", x=1, y=1)\n#' # getpolar(w1,c1,deg=TRUE) # should result 45. \nsetMethod(\"getpolar\", signature=c(\"Node\", \"Node\"),\n function(n0,n1, ...) {\n li<-list(...) \n validObject(n0)\n validObject(n1)\n \n p0<-c(n0$x,n0$y)\n p1<-c(n1$x,n1$y)\n\n value <- getpolar(p0,p1, ...)\n \n return(value)\n }\n)\n ", "meta": {"hexsha": "cd8ce4595878f57c73a2bb9d1f8e89e006a92e94", "size": 15936, "ext": "r", "lang": "R", "max_stars_repo_path": "R/01Node.r", "max_stars_repo_name": "felixlindemann/HNUORTools", "max_stars_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/01Node.r", "max_issues_repo_name": "felixlindemann/HNUORTools", "max_issues_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/01Node.r", "max_forks_repo_name": "felixlindemann/HNUORTools", "max_forks_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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.6510067114, "max_line_length": 162, "alphanum_fraction": 0.5181350402, "num_tokens": 4159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353989809524, "lm_q2_score": 0.02716923291416851, "lm_q1q2_score": 0.00880922707393185}} {"text": "##\n# Copyright (c) 2015, Intel Corporation\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of Intel Corporation nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n##\n# @file\n# This file is part of SeisSol.\n#\n# @author Alex Breuer (breuer AT mytum.de, http://www5.in.tum.de/wiki/index.php/Dipl.-Math._Alexander_Breuer)\n#\n# @section LICENSE\n# Copyright (c) 2014, SeisSol Group\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# \n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# @section DESCRIPTION\n# Performance model for SeisSol setups.\n\ncomputeMeshStatistics <- function( i_meshName,\n i_pathToCsvFile,\n i_performanceParameters,\n i_outputFileTable,\n i_outputFilePlot ) {\n message( 'reading mesh', i_pathToCsvFile )\n l_meshStatistics <- read.csv( file = i_pathToCsvFile,\n header = TRUE )\n\n #\n # compute data to send and receive in MPI-communication\n #\n # mpi-information per time step in GB, regular mpi faces\n l_meshStatistics$mpi_send <- (l_meshStatistics$mpi_copy_elements*i_performanceParameters$dofs_size)/1024^3\n # mpi-information per time step in GB, dr mpi face come on top\n #TODO here need a more accurate number, DR is really complex depending on the neighour realitions: \n #TODO DR-DR coupling, DR-WP coupling, for now let's overestimate (2* for time derivatives instead of time integrated)\n l_meshStatistics$mpi_send <- l_meshStatistics$mpi_send + ((2*l_meshStatistics$mpi_dr_faces*i_performanceParameters$dofs_size)/1024^3)\n # now get time\n l_meshStatistics$mpi_send <- l_meshStatistics$mpi_send/i_performanceParameters$network_bandwidth\n\n # receiving is asymmetric to sending :-/\n l_meshStatistics$mpi_recv <- (l_meshStatistics$mpi_ghost_elements*i_performanceParameters$dofs_size)/1024^3\n l_meshStatistics$mpi_recv <- l_meshStatistics$mpi_recv + ((2*l_meshStatistics$mpi_dr_faces*i_performanceParameters$dofs_size)/1024^3)\n l_meshStatistics$mpi_recv <- l_meshStatistics$mpi_recv/i_performanceParameters$network_bandwidth\n\n # compute timings for\n # * local integration copy layer\n # * local integration interior\n # * neigh integration copy layer\n # * neigh integration interior\n # * additional flux computation for dunamic rupture faces\n # TODO: we might want to substract outflow boundary conditions\n # Please note we incease the time by 10% for the copy layers since they are very small \n # and therefore run at lower performance\n l_meshStatistics$local_integration_copy <- l_meshStatistics$mpi_copy_elements*i_performanceParameters$local_integration*1.1\n l_meshStatistics$local_integration_interior <- l_meshStatistics$interior_elements*i_performanceParameters$local_integration\n l_meshStatistics$neigh_integration_copy <- l_meshStatistics$mpi_copy_elements*i_performanceParameters$neigh_integration*1.1\n l_meshStatistics$neigh_integration_interior <- l_meshStatistics$interior_elements*i_performanceParameters$neigh_integration\n l_meshStatistics$dynamic_rupture_fluxes <- l_meshStatistics$dynamic_rupture_faces*i_performanceParameters$dynamic_rupture \n \n # compute MPI wait time (recv)\n l_meshStatistics$wait_recv <- pmax(l_meshStatistics$mpi_recv -\n l_meshStatistics$local_integration_copy -\n l_meshStatistics$local_integration_interior -\n l_meshStatistics$neigh_integration_interior , 0)\n\n # compute MPI wait time (send)\n # this assumes that waitforCopyLayerSends() is posted before receiveGhostLayer()\n # this is not true, but the error intorudced by this is very minor!\n l_meshStatistics$wait_send <- pmax(l_meshStatistics$mpi_send -\n l_meshStatistics$neigh_integration_copy -\n l_meshStatistics$local_integration_interior -\n l_meshStatistics$neigh_integration_interior -\n l_meshStatistics$dynamic_rupture_fluxes -\n l_meshStatistics$wait_recv , 0)\n\n # let's sum the waits up\n l_meshStatistics$time_communication_wait <- l_meshStatistics$wait_recv +\n l_meshStatistics$wait_send\n\n #let's sum everyting up, and we are done\n l_meshStatistics$time_total <- l_meshStatistics$local_integration_copy +\n l_meshStatistics$local_integration_interior +\n l_meshStatistics$neigh_integration_copy +\n l_meshStatistics$neigh_integration_interior +\n l_meshStatistics$dynamic_rupture_fluxes +\n l_meshStatistics$wait_recv +\n l_meshStatistics$wait_send\n \n #message( 'summary mesh statistics')\n #print( summary( l_meshStatistics ) )\n\n message( 'writing csv' )\n write.csv( x=l_meshStatistics, file=i_outputFileTable)\n \n message( 'plotting information' )\n pdf( file = i_outputFilePlot,\n paper = 'a4r',\n width=20,\n height=10)\n\n # overview boxplots\n par( mfrow=c(1,9) )\n boxplot(l_meshStatistics$local_integration_copy, main='local copy' )\n boxplot(l_meshStatistics$local_integration_interior, main='local interior' )\n boxplot(l_meshStatistics$neigh_integration_interior, main='neigh interior' )\n boxplot(l_meshStatistics$neigh_integration_copy, main='neigh copy' )\n boxplot(l_meshStatistics$dynamic_rupture_fluxes, main='dyn. rupt.' )\n boxplot(l_meshStatistics$mpi_recv, main='recv time' )\n boxplot(l_meshStatistics$mpi_recv, main='send time' )\n boxplot(l_meshStatistics$time_communication_wait, main='wait time' )\n boxplot(l_meshStatistics$time_total, main='total time' )\n \n # detailed plot of every characteristic value\n #for( l_name in names(l_meshStatistics[-1]) ) {\n # layout( matrix(c(1,2), 2, 2, byrow = TRUE), \n # widths=c(4,1) )\n # plot( x=l_meshStatistics$partition,\n # y=l_meshStatistics[,l_name],\n # xlab=\"partition\",\n # ylab=l_name )\n # boxplot(l_meshStatistics[l_name])\n #}\n dev.off()\n \n return( max(l_meshStatistics$time_total) )\n}\n\nprintWeakScaling <- function( i_machineList,\n i_nodeCounts,\n i_meshID ) {\n for( l_machine in i_machineList ) {\n l_runtime = list()\n for( l_nodes in i_nodeCounts ) {\n l_runtime = c( l_runtime, l_expectedSimulationTime[[paste(i_meshID, '_', l_nodes, '_', l_machine, sep='')]] )\n }\n l_runtime <- l_runtime[[1]] / unlist(l_runtime)\n \n print(l_machine)\n print(unlist(i_nodeCounts))\n print(l_runtime)\n \n pdf(paste('scaling_', i_meshID, '_', l_machine,'.pdf', sep=''))\n plot( x=i_nodeCounts, l_runtime, ylab='parallel efficiency (weak-scaling)', main=l_machine )\n dev.off()\n }\n}\n\nprintStrongScaling <- function( i_machineList,\n i_nodeCounts,\n i_meshID ) {\n for( l_machine in i_machineList ) {\n l_runtime = list()\n for( l_nodes in i_nodeCounts ) {\n l_runtime = c( l_runtime, l_expectedSimulationTime[[paste(i_meshID, '_', l_nodes, '_', l_machine, sep='')]] * ( l_nodes / i_nodeCounts[[1]]) )\n }\n l_runtime <- l_runtime[[1]] / unlist(l_runtime)\n \n print(l_machine)\n print(unlist(i_nodeCounts))\n print(l_runtime)\n \n pdf(paste('scaling_', i_meshID, '_', l_machine,'.pdf', sep=''))\n plot( x=i_nodeCounts, l_runtime, ylab='parallel efficiency (strong-scaling)', main=l_machine )\n dev.off()\n }\n}\n\nl_config = list ( mesh_names = list( #'statistics_cubes_1024',\n #'statistics_cubes_2048',\n #'statistics_cubes_4096',\n #'statistics_cubes_9216',\n #'statistics_Landers191M_02_05_02_512',\n #'statistics_Landers191M_02_05_02_768',\n #'statistics_Landers191M_02_05_02_1024',\n #'statistics_Landers191M_02_05_02_1536',\n #'statistics_Landers191M_02_05_02_3072',\n #'statistics_Landers191M_02_05_02_2048',\n #'statistics_Landers191M_02_05_02_4096',\n #'statistics_Landers191M_02_05_02_6144',\n #'statistics_Landers191M_02_05_02_9216',\n #'statistics_Landers191M_02_05_02_12288',\n #'statistics_Landers191M_02_05_02_24756',\n 'statistics_LOH1_small_1',\n 'statistics_LOH1_small_2',\n 'statistics_LOH1_small_4',\n 'statistics_LOH1_small_8',\n 'statistics_LOH1_small_16',\n 'statistics_LOH1_small_32',\n 'statistics_LOH1_small_64',\n 'statistics_LOH1_small_128',\n 'statistics_LOH1_small_256',\n 'statistics_LOH1_small_512',\n 'statistics_LOH1_small_1024'),\n \n statistics_directory = 'mesh_statistics',\n \n performance_parameters = list( supermuc = list( basisFunctions = 56,\n quantities = 9,\n dofs_size = 56*9*8,\n network_bandwidth = 0.4, # unidirectionl, TODO: missing reference point\n neigh_integration = 0.00000131, # 1250 elements per core, seissol proxy, random\n local_integration = 0.00000244, # 1250 elements per core, seissol proxy, random\n dynamic_rupture = 109.33 / 22798 / 1000 ) # TODO: missing reference point\n )\n )\n\nl_expectedSimulationTime = list()\n\nmessage( 'lets go' )\nfor( l_machine in list('supermuc') ) {\n for( l_meshName in l_config$mesh_names ) {\n message( 'analyzing: ', l_meshName )\n l_expectedSimulationTime[[paste(l_meshName,'_',l_machine, sep='')]] =\n computeMeshStatistics( i_meshName = l_meshName,\n i_pathToCsvFile = paste(l_config$statistics_directory,'/',l_meshName,'.csv', sep=''),\n i_performanceParameters = (l_config$performance_parameters)[[l_machine]],\n i_outputFileTable = paste(l_meshName,'_',l_machine,'.csv', sep=''),\n i_outputFilePlot = paste(l_meshName,'_',l_machine,'.pdf', sep='') )\n }\n}\n\n#message( 'generating weak-scaling plot for cubes' )\n#printWeakScaling( list('supermuc'), list( 1024, 2048, 4096, 9216 ), 'statistics_cubes' )\n\n#message( 'generating strong-scaling plot for Landers' )\n#printStrongScaling( list('supermuc'), list( 768, 1024, 1536, 2048, 3072, 4096, 6144, 9216, 12288, 24756 ), 'statistics_Landers191M_02_05_02' )\n\nmessage( 'generating strong-scaling plot for LOH1' )\nprintStrongScaling( list('supermuc'), list( 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 ), 'statistics_LOH1_small' )\n\n\n", "meta": {"hexsha": "c7886ac6965e649e4bad78a3d0dd4131eaf5cb0f", "size": 15283, "ext": "r", "lang": "R", "max_stars_repo_path": "postprocessing/performance/model/mesh_based_model.r", "max_stars_repo_name": "fabian-kutschera/SeisSol", "max_stars_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 165, "max_stars_repo_stars_event_min_datetime": "2015-01-30T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:22:14.000Z", "max_issues_repo_path": "postprocessing/performance/model/mesh_based_model.r", "max_issues_repo_name": "fabian-kutschera/SeisSol", "max_issues_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 351, "max_issues_repo_issues_event_min_datetime": "2015-10-06T15:06:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:23:13.000Z", "max_forks_repo_path": "postprocessing/performance/model/mesh_based_model.r", "max_forks_repo_name": "fabian-kutschera/SeisSol", "max_forks_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 96, "max_forks_repo_forks_event_min_datetime": "2015-07-27T15:13:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T19:19:32.000Z", "avg_line_length": 54.7777777778, "max_line_length": 159, "alphanum_fraction": 0.6091735916, "num_tokens": 3234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.025957354607609142, "lm_q1q2_score": 0.0087755877962824}} {"text": "#' @exportClass Customer\n#' @name Customer \n#' @rdname Customer\n#' @aliases Customer-class \n#' @title The Customer class\n#'\n#' @description \n#' This class is part of the \\pkg{HNUORTools}. It represents \n#' the base class for every locateable class in an\n#' \\dfn{Operations-Research (OR)}-context.\n#' \n#' @details Find here the defined slots for this class.\n#' @section Slots: \n#' \\describe{\n#' \\item{\\code{demand}:}{\n#' Object of class \\code{\"numeric\"}, containing the amount for the demand.\n#' The default value cannot be negative.\n#' }\n#' \\item{\\code{isDummy}:}{\n#' Object of class \\code{\"logical\"}, indicating if a customer was added \n#' in an algorithm (e.g. TPP-Column-Minimum-Method) in order to avoid\n#' degenerated soulutions.\n#' }\n#' }\n#' @section Slots (from \\code{\\link{Node}}): \n#' \\describe{\n#' \\item{\\code{id}:}{\n#' Object of class \\code{\"character\"}, containing data from id.\n#' \\strong{Should be unique}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{label}:}{\n#' Object of class \\code{\"character\"}, containing the label of \n#' the \\code{\\link{Customer}}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{x}:}{\n#' Object of class \\code{\"numeric\"}, containing the x-coordinate \n#' of the \\code{\\link{Customer}}.\n#' The default value will be caluclated randomly.\n#' }\n#' \\item{\\code{y}:}{\n#' Object of class \\code{\"numeric\"}, containing the y-coordinate \n#' of the \\code{\\link{Customer}}.\n#' The default value will be caluclated randomly.\n#' }\n#' }\n#'\n#' @seealso The classes are derived from this class and the following Methods can be used with this class.:\n#' @section Creating objects of type \\code{\\link{Customer}}:\n#' \\describe{\n#' \\item{Creating an \\code{S4-Object}}{ \n#' \\code{new(\"Customer\", ...)}\n#' } \n#' \\item{Converting from a \\code{data.frame}}{ \n#' \\code{as.Customer{}}\n#' See also below in the Methods-Section.\n#' }\n#' \\item{Converting from a \\code{list}}{ \n#' \\code{as.Customer{}}\n#' See also below in the Methods-Section.\n#' }\n#' }\n#' @section Methods:\n#' \\describe{\n#' \\item{\\code{as.list(Customer, ...)}}{\n#' Converts a \\code{\\link{Customer}} into a \\code{\\link{list}}.\n#' \\code{...} are user-defined (not used) parameters.\n#' }\n#' \\item{\\code{as.data.frame(Customer, ...)}}{\n#' Converts a \\code{\\link{Customer}} into a \\code{\\link{data.frame}}.\n#' \\code{as.data.frame} accepts the optional parameter \\code{withrownames} of class \\code{\"logical\"} (default is \\code{TRUE}). \n#' If \\code{withrownames == TRUE} the returned \\code{\\link{data.frame}} will recieve the \\code{id} as rowname.\n#' \\code{...} are user-defined (not used) parameters.\n#'\n#' }\n#' \\item{\\code{as.Customer(obj)}}{\n#' Converts an object of class \\code{\\link{data.frame}} or of class \\code{\\link{list}} into a \\code{\\link{Customer}}.\n#' } \n#' \\item{\\code{is.Customer(obj)}}{\n#' Checks if the object \\code{obj} is of type \\code{\\link{Customer}}.\n#' } \n#' \\item{\\code{\\link{getDistance}}}{\n#' Calculating the distance between two \\code{\\link{Node}s} \n#' (As the classes \\code{\\link{Customer}} and \\code{\\link{Warehouse}} \n#' depend on \\code{\\link{Node}}, distances can be calculated between any of these objects).\n#' }\n#' \\item{\\code{\\link{getpolar}}}{\n#' Calculating the polar-angle to the x-Axis of a link, \n#' connecting two \\code{\\link{Node}s} \n#' (As the classes \\code{\\link{Customer}} and \\code{\\link{Warehouse}} \n#' depend on \\code{\\link{Node}}, polar-angles can be calculated between any of these objects).\n#' }\n#' } \n#' \n#' @section Derived Classes:\n#' None.\n#' @section To be used for:\n#' \\describe{\n#' \\item{WLP}{\n#' Warehouse-Location-Problem\n#' }\n#' \\item{TPP}{\n#' Transportation Problem\n#' }\n#' \\item{VRP}{\n#' Vehicle Routing Problem\n#' }\n#' } \n#' \n#' @note \n#' for citing use: Felix Lindemann (2014). HNUORTools: Operations Research Tools. R package version 1.1-0. \\url{http://felixlindemann.github.io/HNUORTools/}.\n#' \n#' @author Dipl. Kfm. Felix Lindemann \\email{felix.lindemann@@hs-neu-ulm.de} \n#' \n#' Wissenschaftlicher Mitarbeiter\n#' Kompetenzzentrum Logistik\n#' Buro ZWEI, 17\n#'\n#' Hochschule fur angewandte Wissenschaften \n#' Fachhochschule Neu-Ulm | Neu-Ulm University \n#' Wileystr. 1 \n#' \n#' D-89231 Neu-Ulm \n#' \n#' \n#' Phone +49(0)731-9762-1437 \n#' Web \\url{www.hs-neu-ulm.de/felix-lindemann/} \n#' \\url{http://felixlindemann.blogspot.de}\n#' @examples \n#' # create a new Customer with specific values\n#' x<- new(\"Customer\", x= 10, y=20, id=\"myid\", label = \"mylabel\", demand = 20)\n#' x\n#' # create from data.frame\n#' df<- data.frame(x=10,y=20, demand = 30)\n#' new(\"Customer\", df)\n#' as(df, \"Customer\")\n#' as.Customer(df)\n#' #create some Customers\n#' n1 <- new(\"Customer\",x=10,y=20, demand = 30, id =\"n1\")\n#' n2 <- new(\"Customer\",x=13,y=24, demand = 40, id =\"n2\")\n#' # calculate Beeline distance\n#' #getDistance(n1,n2) # should result 5\n#' #getDistance(n1,n2, costs = 2) # should result 10\nsetClass(\n Class = \"Customer\",\n representation=representation(\n demand=\"numeric\",\n isDummy = \"logical\"\n ), \n contains = \"Node\",\n validity = function(object){\n \n \n df <- as.data.frame(object)\n node <- as.Node(df)\n if(validObject(node)){ \n N <- length(object@id) \n if(length(object@demand) != N) \n return(\"Invalid Object of Type 'Customer': the length of the attributes 'id' and 'demand' differ!\")\n if(length(object@isDummy) != N) \n return(\"Invalid Object of Type 'Customer': the length of the attributes 'id' and 'isDummy' differ!\")\n \n if( sum(is.null(object@demand)) + sum( is.na(object@demand)) > 0 ) \n return(paste(\"Invalid Object of Type 'Customer': Error with value demand: Value is not initialized\", class(object@demand)))\n \n if( sum(is.null(object@isDummy)) + sum( is.na(object@isDummy)) > 0) \n return(paste(\"Invalid Object of Type 'Customer': Error with value isDummy: Value is not initialized\", class(object@isDummy)))\n \n if( class(object@demand)!=\"numeric\" ) \n return(paste(\"Invalid Object of Type 'Customer': Error with value demand: expected numeric datatype, but obtained\", class(object@demand)))\n \n if( class(object@isDummy)!=\"logical\" ) \n return(paste(\"Invalid Object of Type 'Customer': Error with value isDummy: expected logical datatype, but obtained\", class(object@isDummy))) \n \n if(min(object@demand)<0)\n return(paste(\"Invalid Object of Type 'Customer': Error with value demand: at least one value is negative. Only positive Values are allowed.\"))\n \n return(TRUE) \n \n }else{\n return (FALSE)\n }\n } \n)\n################################### initialize - Method ###################################################\n#' @title initialize Method\n#' @name initialize\n#' @aliases initialize,Customer-method \n#' @rdname initialize-methods \nsetMethod(\"initialize\", signature=\"Customer\", function(.Object, data=NULL, ...) {\n \n li <- list(...)\n if(is.null(li$showwarnings)) li$showwarnings <- FALSE\n \n #init from parent Node-Object.\n N<-1\n \n if(!is.null(data)){ \n \n if(class(data) ==\"list\") {\n data <- as.data.frame(data)\n }\n if(class(data) ==\"data.frame\") {\n N<-nrow(data)\n li$isDummy <- data$isDummy\n li$demand <- data$demand\n \n } else{ \n stop(\"Error: argument data should be of type 'data.frame'!\")\n }\n } \n if(is.null(li$demand) | length(li$demand) ==0) {\n li$demand <- as.numeric(sample(30:100,N,replace=TRUE)) \n w <- paste(\"y-Coordinate simulated (y= \",li$demand,\").\")\n if(li$showwarnings) warning(w) \n } \n if(is.null(li$isDummy)) {\n li$isDummy <- rep(FALSE,N)\n }\n \n .Object@demand <- as.numeric( li$demand)\n .Object@isDummy <- as.logical( li$isDummy) \n \n .Object<-callNextMethod(.Object,data,...) \n validObject(.Object)\n \n return(.Object ) \n})\n################################### extract - Method ###################################################\n#' @title Extract Methods\n#' @name [\n#' @aliases [,Customer-method \n#' @rdname Extract-methods-2 \nsetMethod(\"[\", \"Customer\",\n function(x, i, j, drop){\n N <- length(x)\n if(min(i) <=0) stop(\"Index i out of bound. it must be positive non zero.\")\n if(max(i) >N) stop(\"Index i out of bound. it must not be larger than the total length.\")\n \n \n if(!missing(j)){\n if(class(j) == \"character\"){\n return(slot(x,j)[i])\n }\n if(class(j) == \"integer\"){\n return(slot(x,j)[i]) \n }\n }\n df <- as.data.frame(x)[i,]\n return (new(\"Customer\", df)) \n } \n) \n################################### Set - Method ###################################################\n\n#' @title Set Methods\n#' @name [<-\n#' @aliases [<-,Customer-method \n#' @rdname Set-methods-2\n#' @param x The Customer\n#' @param i row-Index\n#' @param j Name or Column index\nsetReplaceMethod(\"[\",signature(x=\"Customer\"),\n function(x,i,j,value){\n N <- length(x)\n if(min(i) <=0) stop(\"Index i out of bound. It must be positive non zero.\")\n if(max(i) >N) stop(\"Index i out of bound. It must not be larger than the total length.\")\n if(length(value)!=length(i)) stop(\"The replacement length is not equal to the number of elements to be replaced.\") \n \n if(is(value, \"Customer\")){\n \n \n #replace the item(s) regarding to i\n x$id[i] <- value@id \n x$label[i] <- value@label \n x$x[i] <- value@x \n x$y[i] <- value@y\n x$demand[i] <- value@demand\n x$isDummy[i] <- value@isDummy\n \n # return new item\n return (x) \n } else {\n if(missing(j)) {\n # call the function recursivly\n # might throw an error if the conversion is not supported.\n x[i] <- as.Customer(value)\n }else{ \n if(class(j) == \"character\"){\n slot(x,j)[i] <- value\n }else if(class(j) == \"integer\" | class(j) == \"numeric\"){ \n slot(x,slotNames(x)[j])[i] <- value \n }else{\n warning(paste(\"no changes have been made. the provided value of j (class:\",class(j), \"value:\",j,\") was not recocnized.\"))\n }\n }\n valid<-validObject(x)\n return(x) \n }\n } \n)\n\n################################### as... - Method ###################################################\n#local Methods\nas.Customer.list = function(x, ...){return(new(\"Customer\", data=x))}\nas.Customer.data.frame = function(x, ...){return(new(\"Customer\", data=x))}\n#local convert message\nas.data.frame.Customer = function(x, ...){\n li<-list(...)\n if(is.null(li$withrownames)) li$withrownames <- FALSE\n df<-data.frame(id=x@id, label = x@label, x= x@x, y= x@y, demand=x@demand, isDummy = x@isDummy)\n if(li$withrownames) rownames(df)<-x@id\n return (df)\n}\nas.list.Customer = function(x, ...){list(id=x@id, label = x@label, x= x@x, y= x@y, demand=x@demand, isDummy = x@isDummy)}\n\n\n#' @export\nsetGeneric(\"as.Customer\", function(x, ...) standardGeneric( \"as.Customer\")) \n\n#' @title Convert Objects to Customers\n#' @name as.Customer \n#' @param x an Object to convert.\n#' @param ... optional parameters\n#' @aliases as.Customer,list-method \n#' @rdname as.Customer-methods \nsetMethod(\"as.Customer\", signature(x = \"list\"), as.Customer.list) \n\n#' @title Convert Objects to Customers\n#' @name as.Customer\n#' @aliases as.Customer,data.frame-method \n#' @rdname as.Customer-methods \nsetMethod(\"as.Customer\", signature(x = \"data.frame\"), as.Customer.data.frame) \n\n#' @title Convert Objects to lists\n#' @name as.list \n#' @aliases as.list,Customer-method \n#' @rdname as.list-methods \nsetMethod(\"as.list\", signature(x = \"Customer\"), as.list.Customer) \n\n#' @title Convert Objects to data.frames\n#' @name as.data.frame \n#' @aliases as.data.frame,Customer-method \n#' @rdname as.data.frame-methods \nsetMethod(\"as.data.frame\", signature(x = \"Customer\"), as.data.frame.Customer) \n\nsetAs(\"data.frame\", \"Customer\", def=function(from){return(as.Customer.data.frame(from))})\nsetAs(\"list\", \"Customer\", def=function(from){return(as.Customer.list(from))})\n################################### is... - Method ###################################################\n\n#' @title Checks if an Object is as Customer\n#' @export\n#' @name is.Customer\n#' @aliases is.Customer\n#' @param x the object to be checked for class \\code{\\link{Customer}}\n#' @param ... optional Parameters (not supported)\nsetGeneric(\"is.Customer\", function(x, ...) standardGeneric( \"is.Customer\")) \n\n#' @aliases is.Customer,Customer-method \n#' @rdname is.Customer\nsetMethod( \"is.Customer\", \"Customer\", function(x, ...){return(is(x ,\"Customer\"))})\n\n#' @title How many Customers are included?\n#' @name length \n#' @aliases length,Customer-method \n#' @rdname length \nsetMethod(\"length\", \"Customer\",\n function(x){\n N <- length(x@id)\n return(N)\n } \n) \n\n\n\n", "meta": {"hexsha": "49aa93c0216bc731abea8108c92ecfc6cdd24127", "size": 14775, "ext": "r", "lang": "R", "max_stars_repo_path": "R/02Customer.r", "max_stars_repo_name": "felixlindemann/HNUORTools", "max_stars_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/02Customer.r", "max_issues_repo_name": "felixlindemann/HNUORTools", "max_issues_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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/02Customer.r", "max_forks_repo_name": "felixlindemann/HNUORTools", "max_forks_repo_head_hexsha": "0cb22cc0da14550b2fb48c996e75dfdad6138904", "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.295212766, "max_line_length": 162, "alphanum_fraction": 0.5260913706, "num_tokens": 3562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.024053550489520677, "lm_q1q2_score": 0.00855764936403395}} {"text": "REBOL [\n Title: \"Formatting functions\"\n File: %format.r\n Author: \"Eric Long\"\n Email: kgd03011@nifty.ne.jp\n Date: 20-Feb-2000\n Category: [utility math]\n Version: 1.0.3\n Purpose: {\n A few functions for formatting.\n\n FORMAT aims to be a Reboloid replacement for sprintf.\n It converts data into strings, with rounding of decimal\n values, choice of scientific or fixed-point notation,\n padding to a given length, and right and left justification.\n FORMAT also handles blocks of data, with corresponding blocks\n of formatting options to be applied to successive items.\n\n QT is useful for printing out long blocks of words or numerical\n data, and QC formats and prints out tabular data stored in\n nested blocks.\n\n FULL-FORM returns a string representation of a decimal that will\n load back to exactly the original value. All values that correspond\n to an exact integer up to 2 ** 53 are represented as an integer.\n }\n Acknowledgements: {\n Many thanks to Larry Palmiter and Gerald Goertzel, who tested\n these functions and suggested many improvements. The idea of\n FULL-FORM is originally Larry's, and the development of the\n code was a collaboration among the three of us.\n\n Thanks to Carl for suggesting the best way to pass the options\n argument.\n }\n]\n\ncomment { ================ FORMAT REFORMAT ================\n\nREFORMAT is a shortcut to reduce a block before applying FORMAT.\n\nEXAMPLES:\n\n>> format pi #.4\n== \"3.1416\"\n\n>> reformat/full [pi exp 1] #.15 ; greater precision than FORM\n== [\"3.141592653589793\" \"2.718281828459045\"]\n\n>> format 2 ** 32 #.-6.8 ; round to nearest million\n== \"4,295,000,000\" ; insert commas option\n\n>> reformat [pi exp 1 square-root 2] [#8.4 #6.2] ; width specified\n== [\" 3.1416\" \" 2.72\" \" 1.41\"]\n\n>> format 2 ** 40 #.5.1 ; scientific notation\n== \"1.09951E+012\"\n\n>> reformat [\"pi =\" pi] #7.4.2 ; auto-justification\n== [\"pi = \" \" 3.1416\"]\n\n>> reformat [\"very long string\" 2 ** 32] #6.0.4 ; truncation of string\n== [\"string\" \"4294967296\"]\n\n>> reformat [\"very long string\" 2 ** 32] #4.0.6 ; ... plus auto-justification\n== [\"very\" \"4294967296\"]\n\n>> format $20 / 3 #.4 ; money values handled\n== \"$6.6667\" ; just like number values\n\n>> format now #0 ; inserts zeroes into dates\n== \"06-Feb-2000/13:19\" ; and times for alignment\n}\n\nformat: func [\n {Converts Rebol data into formatted strings.}\n item \"value or block of values to format\"\n options [block! any-string!]\n {single option, or block of options to be applied successively to\n a block of items (with last option used repeatedly if necessary).\n Formed options are parsed to integers: A.B.C\n A width of formatted string\n (negative for left justified)\n B precision to right of decimal point\n (negative for rounding to left of decimal point)\n C and 1 scientific notation\n C and 2 auto justification (number! and money! right justified)\n C and 4 truncate string values\n C and 8 insert commas\n C and 16 prefix value with '$'} ; Added by Mike Yaunish\n\n /full \"use extra precision in forming decimal values\"\n /local n fraction exponent neg decimal\n scientific width left-j trunc commas\n ptr round-off-point format-path prefix\n][\n either data-block? :item [\n ; process block\n if object? :item [ item: next second item ]\n format-path: make path! [format]\n if full [insert tail :format-path 'full]\n if not block? options [ options: reduce [options] ]\n n: to block! :item\n while [not tail? n][\n either data-block? item: first n [\n ; recurse with all format values\n change/only n format-path :item head options\n ][\n ; use current format value\n change/only n format-path :item first options\n ]\n n: next n\n ; get next format values, or reuse the last one\n if 1 < length? options [ options: next options ]\n ]\n ][\n ; process single value\n if block? options [ options: first options ]\n set [width decimal options] parse-integers/def options [0 0 0]\n if negative? width [width: - width left-j: true]\n if not zero? 1 and options [scientific: true decimal: abs decimal]\n if not zero? 2 and options [\n left-j: not any [number? :item money? :item]\n ]\n if all [\n not zero? 4 and options\n not zero? width\n string? :item\n ][trunc: true]\n if not zero? 8 and options [commas: true]\n if not zero? 16 and options [\n prefix: \"$\"\n ]\n if money? :item [\n prefix: append item/1 \"$\"\n item: item/2\n ]\n\n either number? :item [\n ; format number value\n if negative? item [item: - item neg: true]\n n: either full [full-form item][form item]\n\n ; find the power of ten\n either ptr: find n \"E\" [\n exponent: to integer! next ptr\n clear ptr\n ][\n exponent: 0\n ]\n either ptr: find n \".\" [\n remove ptr\n ][\n ptr: tail n\n ]\n exponent: exponent - 2 + index? ptr\n\n ; round off to the desired precision\n round-off-point: either scientific [\n while [ #\"0\" = pick n 1 ] [\n exponent: exponent - 1\n remove n\n ]\n decimal + 1\n ][\n decimal + exponent + 1\n ]\n either round-off-point < length? n [\n either negative? round-off-point [n: copy \"0\"][\n fraction: copy skip n round-off-point\n either zero? round-off-point [n: copy \"0\"][\n clear skip n round-off-point\n ]\n if positive? to integer! .5 +\n to decimal! head insert fraction \".\" [\n n: to string! 1 + to integer! n\n ]\n ]\n ][\n insert/dup tail n \"0\" round-off-point - length? n\n ]\n\n either scientific [\n if positive? decimal [insert next n \".\"]\n insert tail n \"E\"\n either negative? exponent [\n insert tail n \"-\"\n exponent: - exponent\n ][\n insert tail n \"+\"\n ]\n exponent: form exponent\n insert/dup exponent \"0\" 3 - length? exponent\n insert tail n exponent\n ][\n either positive? decimal [\n insert/dup n \"0\" decimal + 1 - length? n\n insert skip tail n (- decimal) \".\"\n ][\n if all [\n negative? decimal\n n <> \"0\"\n ][\n insert/dup tail n \"0\" (- decimal)\n ]\n ]\n ]\n if commas [\n if not ptr: find n \".\" [ ptr: tail n ]\n ptr: skip ptr -3\n while [ not head? ptr ] [\n insert ptr \",\"\n ptr: skip ptr -3\n ]\n ]\n if prefix [insert n prefix]\n if neg [insert n \"-\"]\n ; number value now formatted\n ][\n either any [date? :item time? :item][\n n: form item\n ; remove time zone data if any\n if ptr: find n \"+\" [ clear ptr ]\n ; add zeroes to line up columns\n if #\"-\" = second n [ insert n \"0\" ]\n ptr: either ptr: find n #\"/\" [next ptr][n]\n if #\":\" = second ptr [ insert ptr \"0\" ]\n ; remove seconds if any\n parse n [ thru \":\" to \":\" ptr: (clear ptr)]\n ][\n either any-word? :item [\n n: mold :item\n ][\n n: form :item\n ]\n ]\n ]\n ; pad with spaces\n either left-j [\n if trunc [n: copy/part n width]\n insert/dup tail n \" \" width - length? n\n ][\n if trunc [n: copy skip tail n (- width)]\n insert/dup n \" \" width - length? n\n ]\n ]\n head n\n]\n\nreformat: func [\n {Reduces and formats the items in a block}\n b \"block to format\"\n options [block! any-string!]\n {Formatting options. Do \"help format\" for more information}\n /full \"use extra precision in forming decimal values\"\n][\n either full [\n format/full reduce b options\n ][\n format reduce b options\n ]\n]\n\n\ncomment { ================ QT ================\n\nEXAMPLES:\n\n>> arr: copy [] repeat x 25 [append arr log-e x]\n== [0 0.693147180559945 1.09861228866811 1.38629436111989 ...\n\n>> qt arr\n0.0000 0.6931 1.0986 1.3863 1.6094 1.7918 1.9459 2.0794 2.1972 2.3026 2.3979\n2.4849 2.5649 2.6391 2.7081 2.7726 2.8332 2.8904 2.9444 2.9957 3.0445 3.0910\n3.1355 3.1781 3.2189\n\n>> qt/o arr #.2\n0.00 0.69 1.10 1.39 1.61 1.79 1.95 2.08 2.20 2.30 2.40 2.48 2.56 2.64 2.71\n2.77 2.83 2.89 2.94 3.00 3.04 3.09 3.14 3.18 3.22\n\n>> qt/o arr #.2..2 ; two extra spaces\n0.00 0.69 1.10 1.39 1.61 1.79 1.95 2.08 2.20 2.30 2.40\n2.48 2.56 2.64 2.71 2.77 2.83 2.89 2.94 3.00 3.04 3.09\n3.14 3.18 3.22\n\n\n>> arr: copy [] repeat x 20 [append arr exp x]\n== [2.71828182845905 7.38905609893065 20.0855369231877 ...\n\n>> qt arr\n 2.7183 7.3891 20.0855 54.5982 148.4132\n 403.4288 1096.6332 2980.9580 8103.0839 22026.4658\n 59874.1417 162754.7914 442413.3920 1202604.2842 3269017.3725\n 8886110.5205 24154952.7536 65659969.1373 178482300.9632 485165195.4098\n\n>> qt/o arr #.0 ; /o refinement for options\n 3 7 20 55 148 403 1097\n 2981 8103 22026 59874 162755 442413 1202604\n 3269017 8886111 24154953 65659969 178482301 485165195\n\n>> qt/o arr #.2.1\n2.72E+000 7.39E+000 2.01E+001 5.46E+001 1.48E+002 4.03E+002 1.10E+003\n2.98E+003 8.10E+003 2.20E+004 5.99E+004 1.63E+005 4.42E+005 1.20E+006\n3.27E+006 8.89E+006 2.42E+007 6.57E+007 1.78E+008 4.85E+008\n\n\n>> arr: copy [] repeat x 26 [append arr x * x - 1e-5]\n== [0.99999 3.99999 8.99999 15.99999 24.99999 35.99999 48.99999 63.99999 ...\n\n>> qt arr ; automatic rounding to integer\n 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361\n400 441 484 529 576 625 676\n\n\n>> qt system\nself version build product words options user script\nconsole ports network schemes error standard\n\n>> right-margin: 50\n== 50\n>> qt system\nself version build product words\noptions user script console ports\nnetwork schemes error standard\n\n>> s: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n>> arr: copy [] repeat x 12 [append arr s]\n== [\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" ...\n\n>> qt arr ; long values truncated by default 3 to a line\nABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP\nABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP\nABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP\nABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP\n\n>> qt/o arr #0.0.0 ; no truncation\nABCDEFGHIJKLMNOPQRSTUVWXYZ\nABCDEFGHIJKLMNOPQRSTUVWXYZ\nABCDEFGHIJKLMNOPQRSTUVWXYZ\n.....\n\n>> qt/o arr #5.0.4 ; truncation to five characters\nVWXYZ VWXYZ VWXYZ VWXYZ VWXYZ VWXYZ VWXYZ VWXYZ\nVWXYZ VWXYZ VWXYZ VWXYZ\n\n>> qt/o arr #5.0.6 ; ... plus auto-justification\nABCDE ABCDE ABCDE ABCDE ABCDE ABCDE ABCDE ABCDE\nABCDE ABCDE ABCDE ABCDE\n}\n\nqt: func [\n {Quick table: prints out a simple block in aligned columns}\n b [any-block! object!]\n /o options [block! any-string!]\n /local s rm width decimal out tmp-options max-width extra-width pad\n][\n\n if object? b [\n b: first b\n ]\n rm: either value? 'right-margin [right-margin][77]\n if not options [\n either find b money! [\n options: #0.2.6\n ][\n options: #0.0.6\n if find b decimal! [\n foreach a b [\n if all [decimal? :a not zero? a] [\n if 10 < log-10 abs a [\n options: #0.4.7 break ; use scientific\n ]\n if 1e-4 < ((abs a) + 5e-5 // 1) [ ; if significantly\n options: #0.4.6 ; different from an integer\n ]\n ]\n ]\n ]\n ]\n ]\n set [width decimal tmp-options extra-width]\n parse-integers/def options [0 0 6 0]\n extra-width: extra-width + 1\n options: to issue! rejoin [ width \".\" decimal \".\" tmp-options ]\n if zero? width [\n max-width: to integer! rm + extra-width / 3 - extra-width\n foreach a b [\n if not data-block? :a [\n width: maximum width length? format :a options\n ]\n if width >= max-width [\n width: max-width\n break\n ]\n ]\n ]\n pad: head insert/dup copy \"\" \" \" extra-width\n s: 0\n options: to issue! rejoin [ width \".\" decimal \".\" tmp-options ]\n foreach a b [\n either data-block? :a [\n print \"^/(nested)\"\n qt/o a options\n s: 0\n ][\n s: s + length? out: format :a options\n if s > rm [\n print \"\"\n s: length? out\n ]\n prin out\n s: s + extra-width\n if positive? rm - s - extra-width [\n prin pad\n ]\n ]\n ]\n print \"\"\n exit\n]\n\ncomment { ================ QC ================\n\nEXAMPLES:\n\n>> arr: compose/deep [\n[ [\"pi\" (pi)]\n[ [\"pi * pi\" (pi * pi)]\n[ [\"exp pi\" (exp pi)]\n[ [\"log-e pi\" (log-e pi)]]\n== [[\"pi\" 3.14159265358979] [\"pi * pi\" 9.86960440108936] [\"exp pi\" ...\n\n>> qc arr\npi 3.14\npi * pi 9.87\nexp pi 23.14\nlog-e pi 1.14\n\n>> qc arr #.4 ; with optional options argument\npi 3.1416\npi * pi 9.8696\nexp pi 23.1407\nlog-e pi 1.1447\n\n>> qc arr #.4.2.2 ; two extra spaces\npi 3.1416\npi * pi 9.8696\nexp pi 23.1407\nlog-e pi 1.1447\n\n>> qc arr [#-10 #6.2] ; passing block of options to FORMAT\npi 3.14\npi * pi 9.87\nexp pi 23.14\nlog-e pi 1.14\n}\n\nunset!: (type?)\n\nqc: func [\n {prints out nested blocks in aligned columns}\n b [any-block!]\n options [block! any-string! unset!] \"optional options\"\n /local widths w max-width decimal tmp-options extra-width bb\n][\n\n if not value? 'options [\n options: #20.2.6\n ]\n if not any-block? first b [\n qt/o b options\n exit\n ]\n if data-block? first first b [\n foreach a b [\n either value? 'options [qc a options][qc a]\n print \"\"\n ]\n exit\n ]\n if not block? options [\n set [max-width decimal tmp-options extra-width]\n parse-integers/def options [20 2 6 0]\n if zero? max-width [max-width: 20]\n options: to issue! rejoin [ 0 \".\" decimal \".\" tmp-options ]\n widths: array/initial length? b/1 4\n foreach bb b [\n while [(length? widths) < (length? :bb)] [\n append widths 4\n ]\n while [ not tail? :bb ] [\n w: minimum\n maximum\n length? format first :bb options\n first widths\n max-width\n if w > first widths [\n change widths w\n ]\n bb: next :bb\n widths: next widths\n ]\n widths: head widths\n ]\n while [ not tail? widths ] [\n change widths to issue! rejoin [\n extra-width + first widths \".\"\n decimal \".\"\n tmp-options\n ]\n widths: next widths\n ]\n options: head widths\n ]\n foreach bb b [\n print format :bb options\n ]\n]\n\ncomment { ================ PARSE-INTEGERS ================\n\nNOTE: Used by FORMAT, QT and QC to parse the options argument.\n Any datatype formable to a sequence of periods and integers\n may be used.\n\nEXAMPLES:\n\n>> parse-integers #20.3.-4\n== [20 3 -4]\n>> parse-integers 2.18\n== [2 18]\n>> parse-integers 2.100 ; trailing zeroes disappear when\n== [2 1] ; decimal is formed\n>> parse-integers #4....6\n== [4 0 0 0 6] ; zero is default\n\n>> parse-integers/def #4....6 [11 12 13 14 15 16 17 18 19 20]\n== [4 12 13 14 6 16 17 18 19 20]\n>> parse-integers/def 4....6 [11 12 13 14 15 16 17 18 19 20]\n== [4 0 0 0 6 16 17 18 19 20] ; zeroes appear when tuple is formed\n}\n\nparse-integers: func [\n {parse integers from the form of S}\n s\n /def defaults [block!] \"block of default values\"\n /local item\n][\n defaults: copy either def [defaults][[]]\n s: parse form s \".\"\n while [ not tail? s ] [\n defaults: either integer? item: load first s [\n either tail? defaults [\n insert tail defaults item\n ][\n change defaults item\n ]\n ][\n either tail? defaults [\n insert tail defaults 0\n ][\n next defaults\n ]\n ]\n s: next s\n ]\n head defaults\n]\n\ncomment { ================ DATA-BLOCK? ================\n\nNOTE: Used by FORMAT, QT and QC\n\n}\ndata-block?: func [\n {Returns TRUE if VALUE is a block, list, hash, paren or object}\n value [any-type!]\n][\n all [\n value? 'value\n any [\n block? :value\n list? :value\n hash? :value\n paren? :value\n object? :value\n ]\n ]\n]\n\ncomment { ================ FULL-FORM ================\n\nEXAMPLES:\n\n>> form pi\n== \"3.14159265358979\"\n>> full-form pi\n== \"3.141592653589793\" ; forms to full precision\n\n>> pi - to-decimal form pi\n== 3.10862446895044E-15 ; cannot recover original value\n>> pi - to-decimal full-form pi\n== 0 ; original value restored\n\n>> full-form 2 ** 53 - 1\n== \"9007199254740991\"\n>> full-form 2 ** 53\n== \"9007199254740992\" ; greatest \"integer\"\n>> full-form 2 ** 53 + 2\n== \"9.007199254740994E+15\" ; higher values in scientific notation\n\n>> full-form 2 ** -1074 ; smallest positive decimal value\n== \"4.94065645841247E-324\" ; (excess precision here)\n}\n\nfull-form: func [\n {returns full-precision form of number}\n n [number!]\n /local\n s digit exponent sign formed\n first-n diff form-it savs f-exp too-big big-int\n][\n sign: either negative? n ; save sign as string and\n [n: (- n) \"-\"][\"\"] ; make N positive\n\n too-big: positive? n - 1.79769313486231E+308 ; highest FORM-able number\n\n big-int: all [ ; pseudo-integer, incrementable\n not negative? n - 1E+15 ; by 1, but FORM converts it to\n not positive? n - (2 ** 53) ; scientific format\n ]\n\n if all [\n not big-int ; always take control from 1E+15 to MAXINTEGER\n not too-big ; if TOO-BIG, TO DECIMAL! FORM N overflows\n zero? n - to decimal! form n ; otherwise if FORM is good enough\n ][return head insert form n sign] ; ... use it\n\n first-n: n\n s: copy \"\"\n\n exponent: either any [\n positive? exponent: log-10 n ; get rough value of exponent\n zero? exponent - (to integer! exponent)\n ][ ; get integer at or below rough value\n to integer! exponent\n ][\n -1 + to integer! exponent\n ]\n\n n: n / (10 ** exponent) ; convert N so that (N >= 1) and (N < 10)\n digit: to integer! n ; get the integer portion\n\n if zero? digit [ ; in case LOG-10 rounded up to next integer,\n exponent: exponent - 1 ; making (N < 1) ...\n digit: to integer! n: n * 10 ; adjust and recalculate\n ]\n\n loop 16 [\n insert tail s digit ; append integer portion to N\n n: n - digit * 10 ; increment N by factor of 10\n digit: to integer! n ; to get next integer portion\n ]\n\n insert next s \".\" ; add decimal point to get representation of N\n\n f-exp: either negative? exponent [head insert form exponent \"E\" ][\n either positive? exponent ; make exponent string\n [head insert form exponent \"E+\"][\"\"]\n ]\n form-it: func [][\n formed: copy f-exp ; tack on exponent string to get\n insert formed s ; decimal representation of FIRST-N\n first-n - to decimal! formed ; return the value for DIFF\n ]\n\n if not zero? diff: form-it [ ; if 16 loops didn't work ...\n savs: s\n if not too-big [\n s: string-add s \"1\" ; first try incrementing,\n diff: form-it\n ]\n if not zero? diff [ ; and if that didn't work ...\n s: savs\n insert tail s digit ; tack on 17th digit\n ]\n ]\n if zero? diff [ ; return if we had the exact form\n return head insert either big-int [\n head remove skip s 1 ; without decimal point if possible\n ][formed] sign\n ]\n\n either positive? diff: form-it [ ; now see where we are\n while [ positive? diff ] [ ; increment till it works ...\n s: string-add s \"1\"\n diff: do form-it\n ]\n ][\n while [ negative? diff ] [ ; or decrement ...\n s: string-subtract/full-length s \"1\"\n diff: form-it\n ]\n ]\n head insert formed sign\n]\n\ncomment { ================ STRING-ADD ================\n\nNOTE: Used by FULL-FORM\n\nEXAMPLES:\n\n>> string-add \"123456789999999999875\" \"125\"\n== \"123456790000000000000\"\n\n>> string-add \"2.0000000000000000\" \"-125\"\n== \"1.9999999999999875\" ; decimal point in longer arg ignored\n}\n\nstring-add: func [\n {add two string representations of integers numerically -\n NOTE: decimal points in longer argument are ignored}\n a [string!] b [string!]\n /local c d neg\n][\n a: copy a b: copy b\n either #\"-\" = first a [\n either #\"-\" = first b [neg: true remove a remove b][\n remove a return string-subtract b a\n ]\n ][\n if #\"-\" = first b [remove b return string-subtract a b]\n ]\n if (length? a) < (length? b) [set [a b] reduce [b a]]\n insert/dup b \"0\" (length? a) - (length? b)\n a: tail a b: tail b\n d: 0 while [ not head? b ] [\n a: back a b: back b\n if #\".\" = first a [a: back a]\n c: (first a) + (first b) + d - 48\n d: either c > #\"9\" [c: c - 10 1][0]\n change a c\n ]\n if d > 0 [insert a \"1\"]\n if neg [insert a \"-\"]\n a\n]\n\ncomment { ================ STRING-SUBTRACT ================\n\nNOTE: Used by FULL-FORM\n}\n\nstring-subtract: func [\n {subtract two string representations of integers numerically -\n NOTE: decimal points in longer argument are ignored}\n a [string!] b [string!]\n /full-length\n /local c d neg\n][\n a: copy a b: copy b\n either #\"-\" = first a [\n either #\"-\" = first b [neg: true remove a remove b][\n insert b \"-\" return string-add a b\n ]\n ][\n if #\"-\" = first b [remove b return string-add a b]\n ]\n if any [\n (length? a) < (length? b)\n all [(length? a) = (length? b) a < b]\n ][set [a b] reduce [b a] neg: not neg]\n insert/dup b \"0\" (length? a) - (length? b)\n a: tail a b: tail b\n d: 0 while [ not head? b ] [\n a: back a b: back b\n if #\".\" = first a [a: back a]\n c: to char! (first a) - (first b) - d + 48\n d: either c < #\"0\" [c: c + 10 1][0]\n change a c\n ]\n if not full-length [\n while [all [#\"0\" = first a 1 < length? a]][remove a]\n ]\n if neg [\n either #\"-\" = first a [remove a][insert a \"-\"]\n ]\n a\n]\n\ncomment { ================ PAREN-FORM ================\n\nNOTE: This is the fastest way to make a precise string representation\n of an arbitrary decimal\n\nEXAMPLE:\n\n>> paren-form pi\n== \"(3.14159265358979 + 3.10862446895044E-15)\"\n>> pi - do paren-form pi\n== 0\n}\n\nparen-form: func [\n {returns a string precisely representing numerical value}\n n [number!]\n /local s diff\n][\n diff: n - to decimal! s: form n\n either zero? diff [s][to string! reduce [\"(\" s \" + \" diff \")\"]]\n]\n", "meta": {"hexsha": "416714ff258e185256d99b487281f3ebf6955c0d", "size": 25564, "ext": "r", "lang": "R", "max_stars_repo_path": "community-scripts/format.r", "max_stars_repo_name": "mikeyaunish/DB-Rider", "max_stars_repo_head_hexsha": "d711bcd91bc7f384a3994b367ae484d91b51efb9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-11-09T10:45:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T06:46:19.000Z", "max_issues_repo_path": "community-scripts/format.r", "max_issues_repo_name": "mikeyaunish/DB-Rider", "max_issues_repo_head_hexsha": "d711bcd91bc7f384a3994b367ae484d91b51efb9", "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": "community-scripts/format.r", "max_forks_repo_name": "mikeyaunish/DB-Rider", "max_forks_repo_head_hexsha": "d711bcd91bc7f384a3994b367ae484d91b51efb9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-02-12T08:45:46.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T08:45:46.000Z", "avg_line_length": 31.4440344403, "max_line_length": 78, "alphanum_fraction": 0.5088796745, "num_tokens": 6948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3242353859211693, "lm_q2_score": 0.026355350838651363, "lm_q1q2_score": 0.008545337350257937}} {"text": "\n\n\n\n\n\n\n C\bCH\bHA\bAP\bPT\bTE\bER\bR 8\b8\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs\n\n\n\n\n\n\n 8\b8.\b.1\b1.\b. v\bva\bal\bli\bid\bd f\bfu\bun\bnc\bct\bti\bio\bon\bn o\bob\bbj\bje\bec\bct\bts\bs\n\n There are many different objects which can occupy\n the function field of a symbol object. Table 8.1, on\n the following page, shows all of the possibilities,\n how to recognize them, and where to look for documen-\n tation.\n\n\n\n 8\b8.\b.2\b2.\b. f\bfu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n The basic Lisp function is the lambda function.\n When a lambda function is called, the actual arguments\n are evaluated from left to right and are lambda-bound\n to the formal parameters of the lambda function.\n\n An nlambda function is usually used for functions\n which are invoked by the user at top level. Some\n built-in functions which evaluate their arguments in\n special ways are also nlambdas (e.g _\bc_\bo_\bn_\bd, _\bd_\bo, _\bo_\br).\n When an nlambda function is called, the list of\n unevaluated arguments is lambda bound to the single\n formal parameter of the nlambda function.\n\n Some programmers will use an nlambda function\n when they are not sure how many arguments will be\n passed. Then, the first thing the nlambda function\n does is map _\be_\bv_\ba_\bl over the list of unevaluated argu-\n ments it has been passed. This is usually the wrong\n thing to do, as it will not work compiled if any of\n the arguments are local variables. The solution is to\n use a lexpr. When a lexpr function is called, the\n arguments are evaluated and a fixnum whose value is\n the number of arguments is lambda-bound to the single\n formal parameter of the lexpr function. The lexpr can\n then access the arguments using the _\ba_\br_\bg function.\n\n When a function is compiled, _\bs_\bp_\be_\bc_\bi_\ba_\bl declarations\n may be needed to preserve its behavior. An argument\n is not lambda-bound to the name of the corresponding\n formal parameter unless that formal parameter has been\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b1\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-2\b2\n\n\n\n\n\n +-------------------+------------------------+----------------+\n | informal name | object type | documentation |\n +-------------------+------------------------+----------------+\n | interpreted | list with _\bc_\ba_\br | 8.2 |\n | lambda function | _\be_\bq to lambda | |\n +-------------------+------------------------+----------------+\n | interpreted | list with _\bc_\ba_\br | 8.2 |\n | nlambda function | _\be_\bq to nlambda | |\n +-------------------+------------------------+----------------+\n | interpreted | list with _\bc_\ba_\br | 8.2 |\n | lexpr function | _\be_\bq to lexpr | |\n +-------------------+------------------------+----------------+\n | interpreted | list with _\bc_\ba_\br | 8.3 |\n | macro | _\be_\bq to macro | |\n +-------------------+------------------------+----------------+\n | fclosure | vector with _\bv_\bp_\br_\bo_\bp | 8.4 |\n | | _\be_\bq to fclosure | |\n +-------------------+------------------------+----------------+\n | compiled | binary with discipline | 8.2 |\n | lambda or lexpr | _\be_\bq to lambda | |\n | function | | |\n +-------------------+------------------------+----------------+\n | compiled | binary with discipline | 8.2 |\n | nlambda function | _\be_\bq to nlambda | |\n +-------------------+------------------------+----------------+\n | compiled | binary with discipline | 8.3 |\n | macro | _\be_\bq to macro | |\n +-------------------+------------------------+----------------+\n | foreign | binary with discipline | 8.5 |\n +-----\bs-\bu-\bb-\br-\bo-\bu\bo-\bt\bf-\bi-\bn\b\"-\be\bs-\bu-\bb-\br-\bo-\bu+\bt-\bi-\bn-\be-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b2-\b4-\b0-\b>-\b?-\b1-\b2-\b4-\b0-+----------------+\n | foreign | binary with discipline | 8.5 |\n +------\bf-\bu-\bn-\bc-\bt-\bi-\bo\bo-\bn\bf--\b\"-\bf-\bu-\bn-\bc+\bt-\bi-\bo-\bn-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b3-\b2-\b0-\b>-\b?-\b1-\b3-\b2-\b0-+----------------+\n | foreign | binary with discipline | 8.5 |\n +--\bi-\bn-\bt\bo-\be\bf-\bg-\be\b\"-\br\bi-\bn-\bf\bt-\bu\be-\bn\bg-\bc\be-\bt\br-\bi\b--\bo\bf-\bn\bu-\bn-\bc+\bt-\bi-\bo-\bn-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b4-\b0-\b0-\b>-\b?-\b1-\b4-\b0-\b0-+----------------+\n | foreign | binary with discipline | 8.5 |\n +---\br-\be-\ba-\bl-\bo-\bf\bf-\bu-\bn\b\"-\bc\br-\bt\be-\bi\ba-\bo\bl-\bn\b--\bf-\bu-\bn-\bc+\bt-\bi-\bo-\bn-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b4-\b8-\b0-\b>-\b?-\b1-\b4-\b8-\b0-+----------------+\n | foreign | binary with discipline | 8.5 |\n +-----\bC--\bf-\bu-\bn-\bc\bo-\bt\bf-\bi-\bo\b\"-\bn\bc-\b--\bf-\bu-\bn-\bc+\bt-\bi-\bo-\bn-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b5-\b6-\b0-\b>-\b?-\b1-\b5-\b6-\b0-+----------------+\n | foreign | binary with discipline | 8.5 |\n +--\bd-\bo\bo-\bu\bf-\bb-\bl\b\"-\be\bd-\bo-\bf\bu-\bu\bb-\bn\bl-\bc\be-\bt\b--\bi\bc-\bo\b--\bn\bf-\bu-\bn-\bc+\bt-\bi-\bo-\bn-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b6-\b4-\b0-\b>-\b?-\b1-\b6-\b4-\b0-+----------------+\n | foreign | binary with discipline | 8.5 |\n +-\bs-\bt-\br\bo-\bu\bf-\bc-\bt\b\"-\bu\bv-\br\be-\be\bc-\bt-\bf\bo-\bu\br-\bn\b--\bc\bc-\bt\b--\bi\bf-\bo\bu-\bn\bn-\bc+\bt-\bi-\bo-\bn-\b\"-\b.-\bn-\br--\b3-\bb-\bo-\bt--\b1-\b7-\b2-\b0-\b>-\b?-\b1-\b7-\b2-\b0-+----------------+\n | array | array object | 9 |\n +-------------------+------------------------+----------------+\n Table 8.1\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-3\b3\n\n\n declared _\bs_\bp_\be_\bc_\bi_\ba_\bl (see S12.3.2.2).\n\n Lambda and lexpr functions both compile into a\n binary object with a discipline of lambda. However, a\n compiled lexpr still acts like an interpreted lexpr.\n\n\n\n 8\b8.\b.3\b3.\b. m\bma\bac\bcr\bro\bos\bs\n\n An important feature of Lisp is its ability to\n manipulate programs as data. As a result of this,\n most Lisp implementations have very powerful macro\n facilities. The Lisp language's macro facility can be\n used to incorporate popular features of the other lan-\n guages into Lisp. For example, there are macro pack-\n ages which allow one to create records (ala Pascal)\n and refer to elements of those records by the field\n names. The _\bs_\bt_\br_\bu_\bc_\bt package imported from Maclisp does\n this. Another popular use for macros is to create\n more readable control structures which expand into\n _\bc_\bo_\bn_\bd, _\bo_\br and _\ba_\bn_\bd. One such example is the If macro.\n It allows you to write\n\n _\b(_\bI_\bf _\b(_\be_\bq_\bu_\ba_\bl _\bn_\bu_\bm_\bb _\b0_\b) _\bt_\bh_\be_\bn _\b(_\bp_\br_\bi_\bn_\bt _\b'_\bz_\be_\br_\bo_\b) _\b(_\bt_\be_\br_\bp_\br_\b)\n _\be_\bl_\bs_\be_\bi_\bf _\b(_\be_\bq_\bu_\ba_\bl _\bn_\bu_\bm_\bb _\b1_\b) _\bt_\bh_\be_\bn _\b(_\bp_\br_\bi_\bn_\bt _\b'_\bo_\bn_\be_\b) _\b(_\bt_\be_\br_\bp_\br_\b)\n _\be_\bl_\bs_\be _\b(_\bp_\br_\bi_\bn_\bt _\b'_\b|_\bI _\bg_\bi_\bv_\be _\bu_\bp_\b|_\b)_\b)\n\n which expands to\n\n _\b(_\bc_\bo_\bn_\bd\n _\b(_\b(_\be_\bq_\bu_\ba_\bl _\bn_\bu_\bm_\bb _\b0_\b) _\b(_\bp_\br_\bi_\bn_\bt _\b'_\bz_\be_\br_\bo_\b) _\b(_\bt_\be_\br_\bp_\br_\b)_\b)\n _\b(_\b(_\be_\bq_\bu_\ba_\bl _\bn_\bu_\bm_\bb _\b1_\b) _\b(_\bp_\br_\bi_\bn_\bt _\b'_\bo_\bn_\be_\b) _\b(_\bt_\be_\br_\bp_\br_\b)_\b)\n _\b(_\bt _\b(_\bp_\br_\bi_\bn_\bt _\b'_\b|_\bI _\bg_\bi_\bv_\be _\bu_\bp_\b|_\b)_\b)_\b)\n\n\n\n\n 8\b8.\b.3\b3.\b.1\b1.\b. m\bma\bac\bcr\bro\bo f\bfo\bor\brm\bms\bs\n\n A macro is a function which accepts a Lisp\n expression as input and returns another Lisp\n expression. The action the macro takes is called\n macro expansion. Here is a simple example:\n\n -> _\b(_\bd_\be_\bf _\bf_\bi_\br_\bs_\bt _\b(_\bm_\ba_\bc_\br_\bo _\b(_\bx_\b) _\b(_\bc_\bo_\bn_\bs _\b'_\bc_\ba_\br _\b(_\bc_\bd_\br _\bx_\b)_\b)_\b)_\b)\n first\n -> _\b(_\bf_\bi_\br_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b)_\b)\n a\n ____________________\n t\bth\bhe\be f\bfi\bir\brs\bst\bt c\bch\bha\bar\bra\bac\bct\bte\ber\br o\bof\bf t\bth\bhe\be s\bst\btr\bri\bin\bng\bg i\bis\bs s\bsi\big\bgn\bni\bif\bfi\bic\bca\ban\bnt\bt (\b(i\bi.\b.e\be \"\b\"s\bs\"\b\"\n i\bis\bs o\bok\bk f\bfo\bor\br \"\b\"s\bsu\bub\bbr\bro\bou\but\bti\bin\bne\be\"\b\")\b)\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-4\b4\n\n\n -> _\b(_\ba_\bp_\bp_\bl_\by _\b'_\bf_\bi_\br_\bs_\bt _\b'_\b(_\bf_\bi_\br_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b)_\b)_\b)\n (car '(a b c))\n\n The first input line defines a macro called _\bf_\bi_\br_\bs_\bt.\n Notice that the macro has one formal parameter, _\bx.\n On the second input line, we ask the interpreter to\n evaluate _\b(_\bf_\bi_\br_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b)_\b). _\bE_\bv_\ba_\bl sees that _\bf_\bi_\br_\bs_\bt\n has a function definition of type macro, so it\n evaluates _\bf_\bi_\br_\bs_\bt's definition, passing to _\bf_\bi_\br_\bs_\bt, as\n an argument, the form _\be_\bv_\ba_\bl itself was trying to\n evaluate: _\b(_\bf_\bi_\br_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b)_\b). The _\bf_\bi_\br_\bs_\bt macro chops\n off the car of the argument with _\bc_\bd_\br, cons' a _\bc_\ba_\br\n at the beginning of the list and returns\n _\b(_\bc_\ba_\br _\b'_\b(_\ba _\bb _\bc_\b)_\b), which _\be_\bv_\ba_\bl evaluates. The value _\ba\n is returned as the value of _\b(_\bf_\bi_\br_\bs_\bt _\b'_\b(_\ba _\bb _\bc_\b)_\b). Thus\n whenever _\be_\bv_\ba_\bl tries to evaluate a list whose car\n has a macro definition it ends up doing (at least)\n two operations, the first of which is a call to the\n macro to let it macro expand the form, and the\n other is the evaluation of the result of the macro.\n The result of the macro may be yet another call to\n a macro, so _\be_\bv_\ba_\bl may have to do even more evalua-\n tions until it can finally determine the value of\n an expression. One way to see how a macro will\n expand is to use _\ba_\bp_\bp_\bl_\by as shown on the third input\n line above.\n\n\n\n 8\b8.\b.3\b3.\b.2\b2.\b. d\bde\bef\bfm\bma\bac\bcr\bro\bo\n\n The macro _\bd_\be_\bf_\bm_\ba_\bc_\br_\bo makes it easier to define\n macros because it allows you to name the arguments\n to the macro call. For example, suppose we find\n ourselves often writing code like\n _\b(_\bs_\be_\bt_\bq _\bs_\bt_\ba_\bc_\bk _\b(_\bc_\bo_\bn_\bs _\bn_\be_\bw_\be_\bl_\bt _\bs_\bt_\ba_\bc_\bk_\b). We could define a\n macro named _\bp_\bu_\bs_\bh to do this for us. One way to\n define it is:\n\n -> _\b(_\bd_\be_\bf _\bp_\bu_\bs_\bh\n _\b(_\bm_\ba_\bc_\br_\bo _\b(_\bx_\b) _\b(_\bl_\bi_\bs_\bt _\b'_\bs_\be_\bt_\bq _\b(_\bc_\ba_\bd_\bd_\br _\bx_\b) _\b(_\bl_\bi_\bs_\bt _\b'_\bc_\bo_\bn_\bs _\b(_\bc_\ba_\bd_\br _\bx_\b) _\b(_\bc_\ba_\bd_\bd_\br _\bx_\b)_\b)_\b)_\b)_\b)\n push\n\n then _\b(_\bp_\bu_\bs_\bh _\bn_\be_\bw_\be_\bl_\bt _\bs_\bt_\ba_\bc_\bk_\b) will expand to the form\n mentioned above. The same macro written using def-\n macro would be:\n\n -> _\b(_\bd_\be_\bf_\bm_\ba_\bc_\br_\bo _\bp_\bu_\bs_\bh _\b(_\bv_\ba_\bl_\bu_\be _\bs_\bt_\ba_\bc_\bk_\b)\n _\b(_\bl_\bi_\bs_\bt _\b'_\bs_\be_\bt_\bq _\b,_\bs_\bt_\ba_\bc_\bk _\b(_\bl_\bi_\bs_\bt _\b'_\bc_\bo_\bn_\bs _\b,_\bv_\ba_\bl_\bu_\be _\b,_\bs_\bt_\ba_\bc_\bk_\b)_\b)_\b)\n push\n\n Defmacro allows you to name the arguments of the\n macro call, and makes the macro definition look\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-5\b5\n\n\n more like a function definition.\n\n\n\n 8\b8.\b.3\b3.\b.3\b3.\b. t\bth\bhe\be b\bba\bac\bck\bkq\bqu\buo\bot\bte\be c\bch\bha\bar\bra\bac\bct\bte\ber\br m\bma\bac\bcr\bro\bo\n\n The default syntax for FRANZ LISP has four\n characters with associated character macros. One\n is semicolon for comments. Two others are the\n backquote and comma which are used by the backquote\n character macro. The fourth is the sharp sign\n macro described in the next section.\n\n The backquote macro is used to create lists\n where many of the elements are fixed (quoted).\n This makes it very useful for creating macro defi-\n nitions. In the simplest case, a backquote acts\n just like a single quote:\n\n ->_\b`_\b(_\ba _\bb _\bc _\bd _\be_\b)\n (a b c d e)\n\n If a comma precedes an element of a backquoted list\n then that element is evaluated and its value is put\n in the list.\n\n ->_\b(_\bs_\be_\bt_\bq _\bd _\b'_\b(_\bx _\by _\bz_\b)_\b)\n (x y z)\n ->_\b`_\b(_\ba _\bb _\bc _\b,_\bd _\be_\b)\n (a b c (x y z) e)\n\n If a comma followed by an at sign precedes an ele-\n ment in a backquoted list, then that element is\n evaluated and spliced into the list with _\ba_\bp_\bp_\be_\bn_\bd.\n\n ->_\b`_\b(_\ba _\bb _\bc _\b,_\b@_\bd _\be_\b)\n (a b c x y z e)\n\n Once a list begins with a backquote, the commas may\n appear anywhere in the list as this example shows:\n\n ->_\b`_\b(_\ba _\bb _\b(_\bc _\bd _\b,_\b(_\bc_\bd_\br _\bd_\b)_\b) _\b(_\be _\bf _\b(_\bg _\bh _\b,_\b@_\b(_\bc_\bd_\bd_\br _\bd_\b) _\b,_\b@_\bd_\b)_\b)_\b)\n (a b (c d (y z)) (e f (g h z x y z)))\n\n It is also possible and sometimes even useful to\n use the backquote macro within itself. As a final\n demonstration of the backquote macro, we shall\n define the first and push macros using all the\n power at our disposal: defmacro and the backquote\n macro.\n\n ->_\b(_\bd_\be_\bf_\bm_\ba_\bc_\br_\bo _\bf_\bi_\br_\bs_\bt _\b(_\bl_\bi_\bs_\bt_\b) _\b`_\b(_\bc_\ba_\br _\b,_\bl_\bi_\bs_\bt_\b)_\b)\n first\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-6\b6\n\n\n ->_\b(_\bd_\be_\bf_\bm_\ba_\bc_\br_\bo _\bp_\bu_\bs_\bh _\b(_\bv_\ba_\bl_\bu_\be _\bs_\bt_\ba_\bc_\bk_\b) _\b`_\b(_\bs_\be_\bt_\bq _\b,_\bs_\bt_\ba_\bc_\bk _\b(_\bc_\bo_\bn_\bs _\b,_\bv_\ba_\bl_\bu_\be _\b,_\bs_\bt_\ba_\bc_\bk_\b)_\b)_\b)\n stack\n\n\n\n 8\b8.\b.3\b3.\b.4\b4.\b. s\bsh\bha\bar\brp\bp s\bsi\big\bgn\bn c\bch\bha\bar\bra\bac\bct\bte\ber\br m\bma\bac\bcr\bro\bo\n\n The sharp sign macro can perform a number of\n different functions at read time. The character\n directly following the sharp sign determines which\n function will be done, and following Lisp s-\n expressions may serve as arguments.\n\n\n\n 8\b8.\b.3\b3.\b.4\b4.\b.1\b1.\b. c\bco\bon\bnd\bdi\bit\bti\bio\bon\bna\bal\bl i\bin\bnc\bcl\blu\bus\bsi\bio\bon\bn\n\n If you plan to run one source file in more than\n one environment then you may want to some pieces\n of code to be included or not included depend-\n ing on the environment. The C language uses\n \"#ifdef\" and \"#ifndef\" for this purpose, and\n Lisp uses \"#+\" and \"#-\". The environment that\n the sharp sign macro checks is the _\b(_\bs_\bt_\ba_\bt_\bu_\bs _\bf_\be_\ba_\b-\n _\bt_\bu_\br_\be_\bs_\b) list which is initialized when the Lisp\n system is built and which may be altered by\n _\b(_\bs_\bs_\bt_\ba_\bt_\bu_\bs _\bf_\be_\ba_\bt_\bu_\br_\be _\bf_\bo_\bo_\b) and\n _\b(_\bs_\bs_\bt_\ba_\bt_\bu_\bs _\bn_\bo_\bf_\be_\ba_\bt_\bu_\br_\be _\bb_\ba_\br_\b) The form of conditional\n inclusion is\n _\b#_\b+_\bw_\bh_\be_\bn _\bw_\bh_\ba_\bt\n where _\bw_\bh_\be_\bn is either a symbol or an expression\n involving symbols and the functions _\ba_\bn_\bd, _\bo_\br, and\n _\bn_\bo_\bt. The meaning is that _\bw_\bh_\ba_\bt will only be read\n in if _\bw_\bh_\be_\bn is true. A symbol in _\bw_\bh_\be_\bn is true\n only if it appears in the _\b(_\bs_\bt_\ba_\bt_\bu_\bs _\bf_\be_\ba_\bt_\bu_\br_\be_\bs_\b)\n list.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-7\b7\n\n\n\n ____________________________________________________\n\n ; suppose we want to write a program which references a file\n ; and which can run at ucb, ucsd and cmu where the file naming conventions\n ; are different.\n ;\n -> _\b(_\bd_\be_\bf_\bu_\bn _\bh_\bo_\bw_\bo_\bl_\bd _\b(_\bn_\ba_\bm_\be_\b)\n _\b(_\bt_\be_\br_\bp_\br_\b)\n _\b(_\bl_\bo_\ba_\bd _\b#_\b+_\b(_\bo_\br _\bu_\bc_\bb _\bu_\bc_\bs_\bd_\b) _\b\"_\b/_\bu_\bs_\br_\b/_\bl_\bi_\bb_\b/_\bl_\bi_\bs_\bp_\b/_\ba_\bg_\be_\bs_\b._\bl_\b\"\n _\b#_\b+_\bc_\bm_\bu _\b\"_\b/_\bu_\bs_\br_\b/_\bl_\bi_\bs_\bp_\b/_\bd_\bo_\bc_\b/_\ba_\bg_\be_\bs_\b._\bl_\b\"_\b)\n _\b(_\bp_\ba_\bt_\bo_\bm _\bn_\ba_\bm_\be_\b)\n _\b(_\bp_\ba_\bt_\bo_\bm _\b\" _\bi_\bs _\b\"_\b)\n _\b(_\bp_\br_\bi_\bn_\bt _\b(_\bc_\bd_\br _\b(_\ba_\bs_\bs_\bo_\bc _\bn_\ba_\bm_\be _\ba_\bg_\be_\bf_\bi_\bl_\be_\b)_\b)_\b)\n _\b(_\bp_\ba_\bt_\bo_\bm _\b\"_\by_\be_\ba_\br_\bs _\bo_\bl_\bd_\b\"_\b)\n _\b(_\bt_\be_\br_\bp_\br_\b)_\b)\n ____________________________________________________\n\n\n\n The form\n _\b#_\b-_\bw_\bh_\be_\bn _\bw_\bh_\ba_\bt\n is equivalent to\n _\b#_\b+_\b(_\bn_\bo_\bt _\bw_\bh_\be_\bn_\b) _\bw_\bh_\ba_\bt\n\n\n\n 8\b8.\b.3\b3.\b.4\b4.\b.2\b2.\b. f\bfi\bix\bxn\bnu\bum\bm c\bch\bha\bar\bra\bac\bct\bte\ber\br e\beq\bqu\bui\biv\bva\bal\ble\ben\bnt\bts\bs\n\n When working with fixnum equivalents of charac-\n ters, it is often hard to remember the number\n corresponding to a character. The form\n _\b#_\b/_\bc\n is equivalent to the fixnum representation of\n character c.\n\n\n ____________________________________________________\n\n ; a function which returns t if the user types y else it returns nil.\n ;\n -> _\b(_\bd_\be_\bf_\bu_\bn _\by_\be_\bs_\bo_\br_\bn_\bo _\bn_\bi_\bl\n _\b(_\bp_\br_\bo_\bg_\bn _\b(_\ba_\bn_\bs_\b)\n _\b(_\bs_\be_\bt_\bq _\ba_\bn_\bs _\b(_\bt_\by_\bi_\b)_\b)\n _\b(_\bc_\bo_\bn_\bd _\b(_\b(_\be_\bq_\bu_\ba_\bl _\ba_\bn_\bs _\b#_\b/_\by_\b) _\bt_\b)\n _\b(_\bt _\bn_\bi_\bl_\b)_\b)_\b)_\b)\n ____________________________________________________\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-8\b8\n\n\n 8\b8.\b.3\b3.\b.4\b4.\b.3\b3.\b. r\bre\bea\bad\bd t\bti\bim\bme\be e\bev\bva\bal\blu\bua\bat\bti\bio\bon\bn\n\n Occasionally you want to express a constant as a\n Lisp expression, yet you don't want to pay the\n penalty of evaluating this expression each time\n it is referenced. The form\n _\b#_\b._\be_\bx_\bp_\br_\be_\bs_\bs_\bi_\bo_\bn\n evaluates the expression at read time and\n returns its value.\n\n\n ____________________________________________________\n\n ; a function to test if any of bits 1 3 or 12 are set in a fixnum.\n ;\n -> _\b(_\bd_\be_\bf_\bu_\bn _\bt_\be_\bs_\bt_\bi_\bt _\b(_\bn_\bu_\bm_\b)\n _\b(_\bc_\bo_\bn_\bd _\b(_\b(_\bz_\be_\br_\bo_\bp _\b(_\bb_\bo_\bo_\bl_\be _\b1 _\bn_\bu_\bm _\b#_\b._\b(_\b+ _\b(_\bl_\bs_\bh _\b1 _\b1_\b) _\b(_\bl_\bs_\bh _\b1 _\b3_\b) _\b(_\bl_\bs_\bh _\b1 _\b1_\b2_\b)_\b)_\b)_\b)\n _\bn_\bi_\bl_\b)\n _\b(_\bt _\bt_\b)_\b)_\b)\n ____________________________________________________\n\n\n\n\n\n\n 8\b8.\b.4\b4.\b. f\bfc\bcl\blo\bos\bsu\bur\bre\bes\bs\n\n Fclosures are a type of functional object. The\n purpose is to remember the values of some variables\n between invocations of the functional object and to\n protect this data from being inadvertently overwritten\n by other Lisp functions. Fortran programs usually\n exhibit this behavior for their variables. (In fact,\n some versions of Fortran would require the variables\n to be in COMMON). Thus it is easy to write a linear\n congruent random number generator in Fortran, merely\n by keeping the seed as a variable in the function. It\n is much more risky to do so in Lisp, since any special\n variable you picked, might be used by some other func-\n tion. Fclosures are an attempt to provide most of the\n same functionality as closures in Lisp Machine Lisp,\n to users of FRANZ LISP. Fclosures are related to clo-\n sures in this way:\n (fclosure '(a b) 'foo) <==>\n (let ((a a) (b b)) (closure '(a b) 'foo))\n\n\n\n 8\b8.\b.4\b4.\b.1\b1.\b. a\ban\bn e\bex\bxa\bam\bmp\bpl\ble\be\n\n ____________________________________________________________\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-9\b9\n\n\n % l\bli\bis\bsp\bp\n Franz Lisp, Opus 38.60\n ->(\b(d\bde\bef\bfu\bun\bn c\bco\bod\bde\be (\b(m\bme\be c\bco\bou\bun\bnt\bt)\b)\n (\b(p\bpr\bri\bin\bnt\bt (\b(l\bli\bis\bst\bt '\b'i\bin\bn x\bx)\b))\b)\n (\b(s\bse\bet\btq\bq x\bx (\b(+\b+ 1\b1 x\bx)\b))\b)\n (\b(c\bco\bon\bnd\bd (\b((\b(g\bgr\bre\bea\bat\bte\ber\brp\bp c\bco\bou\bun\bnt\bt 1\b1)\b) (\b(f\bfu\bun\bnc\bca\bal\bll\bl m\bme\be m\bme\be (\b(s\bsu\bub\bb1\b1 c\bco\bou\bun\bnt\bt)\b))\b))\b))\b)\n (\b(p\bpr\bri\bin\bnt\bt (\b(l\bli\bis\bst\bt '\b'o\bou\but\bt x\bx)\b))\b))\b)\n code\n ->(\b(d\bde\bef\bfu\bun\bn t\bte\bes\bst\bte\ber\br (\b(o\bob\bbj\bje\bec\bct\bt c\bco\bou\bun\bnt\bt)\b)\n (\b(f\bfu\bun\bnc\bca\bal\bll\bl o\bob\bbj\bje\bec\bct\bt o\bob\bbj\bje\bec\bct\bt c\bco\bou\bun\bnt\bt)\b) (\b(t\bte\ber\brp\bpr\bri\bi)\b))\b)\n tester\n ->(\b(s\bse\bet\btq\bq x\bx 0\b0)\b)\n 0\n ->(\b(s\bse\bet\btq\bq z\bz (\b(f\bfc\bcl\blo\bos\bsu\bur\bre\be '\b'(\b(x\bx)\b) '\b'c\bco\bod\bde\be)\b))\b)\n fclosure[8]\n -> (\b(t\bte\bes\bst\bte\ber\br z\bz 3\b3)\b)\n (in 0)(in 1)(in 2)(out 3)(out 3)(out 3)\n nil\n ->x\bx\n 0\n ____________________________________________________________\n\n\n\n\n\n The function _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be creates a new object\n that we will call an fclosure, (although it is\n actually a vector). The fclosure contains a func-\n tional object, and a set of symbols and values for\n the symbols. In the above example, the fclosure\n functional object is the function code. The set of\n symbols and values just contains the symbol `x' and\n zero, the value of `x' when the fclosure was cre-\n ated.\n\n When an fclosure is funcall'ed:\n\n 1) The Lisp system lambda binds the symbols in\n the fclosure to their values in the fclosure.\n\n 2) It continues the funcall on the functional\n object of the fclosure.\n\n 3) Finally, it un-lambda binds the symbols in the\n fclosure and at the same time stores the cur-\n rent values of the symbols in the fclosure.\n\n\n Notice that the fclosure is saving the value\n of the symbol `x'. Each time a fclosure is cre-\n ated, new space is allocated for saving the values\n of the symbols. Thus if we execute fclosure again,\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b10\b0\n\n\n over the same function, we can have two independent\n counters:\n\n ____________________________________________________________\n\n -> (\b(s\bse\bet\btq\bq z\bzz\bz (\b(f\bfc\bcl\blo\bos\bsu\bur\bre\be '\b'(\b(x\bx)\b) '\b'c\bco\bod\bde\be)\b))\b)\n fclosure[1]\n -> (\b(t\bte\bes\bst\bte\ber\br z\bzz\bz 2\b2)\b)\n (in 0)(in 1)(out 2)(out 2)\n -> (\b(t\bte\bes\bst\bte\ber\br z\bzz\bz 2\b2)\b)\n (in 2)(in 3)(out 4)(out 4)\n -> (\b(t\bte\bes\bst\bte\ber\br z\bz 3\b3)\b)\n (in 3)(in 4)(in 5)(out 6)(out 6)(out 6)\n ____________________________________________________________\n\n\n\n\n\n\n\n 8\b8.\b.4\b4.\b.2\b2.\b. u\bus\bse\bef\bfu\bul\bl f\bfu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n Here are some quick some summaries of func-\n tions dealing with closures. They are more for-\n mally defined in S2.8.4. To recap, fclosures are\n made by _\b(_\bf_\bc_\bl_\bo_\bs_\bu_\br_\be _\b'_\bl_\b__\bv_\ba_\br_\bs _\b'_\bg_\b__\bf_\bu_\bn_\bc_\bo_\bb_\bj_\b). l_vars is a\n list of symbols (not containing nil), g_funcobj is\n any object that can be funcalled. (Objects which\n can be funcalled, include compiled Lisp functions,\n lambda expressions, symbols, foreign functions,\n etc.) In general, if you want a compiled function\n to be closed over a variable, you must declare the\n variable to be special within the function.\n Another example would be:\n\n (fclosure '(a b) #'(lambda (x) (plus x a)))\n\n Here, the #' construction will make the compiler\n compile the lambda expression.\n\n There are times when you want to share vari-\n ables between fclosures. This can be done if the\n fclosures are created at the same time using _\bf_\bc_\bl_\bo_\b-\n _\bs_\bu_\br_\be_\b-_\bl_\bi_\bs_\bt. The function _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be_\b-_\ba_\bl_\bi_\bs_\bt returns an\n assoc list giving the symbols and values in the\n fclosure. The predicate _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be_\bp returns t iff\n its argument is a fclosure. Other functions\n imported from Lisp Machine Lisp are _\bs_\by_\bm_\be_\bv_\ba_\bl_\b-_\bi_\bn_\b-\n _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be_\b, _\bl_\be_\bt_\b-_\bf_\bc_\bl_\bo_\bs_\be_\bd_\b, and _\bs_\be_\bt_\b-_\bi_\bn_\b-_\bf_\bc_\bl_\bo_\bs_\bu_\br_\be_\b.\n Lastly, the function _\bf_\bc_\bl_\bo_\bs_\bu_\br_\be_\b-_\bf_\bu_\bn_\bc_\bt_\bi_\bo_\bn returns the\n function argument.\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b11\b1\n\n\n 8\b8.\b.4\b4.\b.3\b3.\b. i\bin\bnt\bte\ber\brn\bna\bal\bl s\bst\btr\bru\buc\bct\btu\bur\bre\be\n\n Currently, closures are implemented as vec-\n tors, with property being the symbol fclosure. The\n functional object is the first entry. The remain-\n ing entries are structures which point to the sym-\n bols and values for the closure, (with a reference\n count to determine if a recursive closure is\n active).\n\n\n\n 8\b8.\b.5\b5.\b. f\bfo\bor\bre\bei\big\bgn\bn s\bsu\bub\bbr\bro\bou\but\bti\bin\bne\bes\bs a\ban\bnd\bd f\bfu\bun\bnc\bct\bti\bio\bon\bns\bs\n\n FRANZ LISP has the ability to dynamically load\n object files produced by other compilers and to call\n functions defined in those files. These functions are\n called _\bf_\bo_\br_\be_\bi_\bg_\bn functions.* There are seven types of\n foreign functions. They are characterized by the type\n of result they return, and by differences in the\n interpretation of their arguments. They come from two\n families: a group suited for languages which pass\n arguments by reference (e.g. Fortran), and a group\n suited for languages which pass arguments by value\n (e.g. C).\n\n\n There are four types in the first group:\n\n s\bsu\bub\bbr\bro\bou\but\bti\bin\bne\be\n This does not return anything. The Lisp system\n always returns t after calling a subroutine.\n\n f\bfu\bun\bnc\bct\bti\bio\bon\bn\n This returns whatever the function returns. This\n must be a valid Lisp object or it may cause the\n Lisp system to fail.\n\n i\bin\bnt\bte\beg\bge\ber\br-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\n This returns an integer which the Lisp system\n makes into a fixnum and returns.\n\n r\bre\bea\bal\bl-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\n This returns a double precision real number which\n the Lisp system makes into a flonum and returns.\n\n ____________________\n *This topic is also discussed in Report PAM-124 of the\n Center for Pure and Applied Mathematics, UCB, entitled\n ``Parlez-Vous Franz? An Informal Introduction to Interfac-\n ing Foreign Functions to Franz LISP'', by James R. Larus\n\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b12\b2\n\n\n There are three types in the second group:\n\n c\bc-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\n This is like an integer function, except for its\n different interpretation of arguments.\n\n d\bdo\bou\bub\bbl\ble\be-\b-c\bc-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\n This is like a real-function.\n\n v\bve\bec\bct\bto\bor\br-\b-c\bc-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\n This is for C functions which return a structure.\n The first argument to such functions must be a\n vector (of type vectori), into which the result\n is stored. The second Lisp argument becomes the\n first argument to the C function, and so on\n\n A foreign function is accessed through a binary object\n just like a compiled Lisp function. The difference is\n that the discipline field of a binary object for a\n foreign function is a string whose first character is\n given in the following table:\n\n\n +-------+-------------------+\n |letter | type |\n +-------+-------------------+\n | s | subroutine |\n +-------+-------------------+\n | f | function |\n +-------+-------------------+\n | i | integer-function |\n +-------+-------------------+\n | r | real-function. |\n +-------+-------------------+\n | c | c-function |\n +-------+-------------------+\n | v | vector-c-function |\n +-------+-------------------+\n | d | double-c-function |\n +-------+-------------------+\n +-------+-------------------+\n Two functions are provided for setting-up foreign\n functions. _\bC_\bf_\ba_\bs_\bl loads an object file into the Lisp\n system and sets up one foreign function binary object.\n If there are more than one function in an object file,\n _\bg_\be_\bt_\ba_\bd_\bd_\br_\be_\bs_\bs can be used to set up additional foreign\n function objects.\n\n Foreign functions are called just like other\n functions, e.g _\b(_\bf_\bu_\bn_\bn_\ba_\bm_\be _\ba_\br_\bg_\b1 _\ba_\br_\bg_\b2_\b). When a function\n in the Fortran group is called, the arguments are\n evaluated and then examined. List, hunk and symbol\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b13\b3\n\n\n arguments are passed unchanged to the foreign func-\n tion. Fixnum and flonum arguments are copied into a\n temporary location and a pointer to the value is\n passed (this is because Fortran uses call by reference\n and it is dangerous to modify the contents of a fixnum\n or flonum which something else might point to). If\n the argument is an array object, the data field of the\n array object is passed to the foreign function (This\n is the easiest way to send large amounts of data to\n and receive large amounts of data from a foreign func-\n tion). If a binary object is an argument, the entry\n field of that object is passed to the foreign function\n (the entry field is the address of a function, so this\n amounts to passing a function as an argument).\n\n When a function in the C group is called, fixnum\n and flownum arguments are passed by value. For almost\n all other arguments, the address is merely provided to\n the C routine. The only exception arises when you\n want to invoke a C routine which expects a ``struc-\n ture'' argument. Recall that a (rarely used) feature\n of the C language is the ability to pass structures by\n value. This copies the structure onto the stack.\n Since the Franz's nearest equivalent to a C structure\n is a vector, we provide an escape clause to copy the\n contents of an immediate-type vector by value. If the\n property field of a vectori argument, is the symbol\n \"value-structure-argument\", then the binary data of\n this immediate-type vector is copied into the argument\n list of the C routine.\n\n The method a foreign function uses to access the\n arguments provided by Lisp is dependent on the lan-\n guage of the foreign function. The following scripts\n demonstrate how how Lisp can interact with three lan-\n guages: C, Pascal and Fortran. C and Pascal have\n pointer types and the first script shows how to use\n pointers to extract information from Lisp objects.\n There are two functions defined for each language.\n The first (cfoo in C, pfoo in Pascal) is given four\n arguments, a fixnum, a flonum-block array, a hunk of\n at least two fixnums and a list of at least two\n fixnums. To demonstrate that the values were passed,\n each ?foo function prints its arguments (or parts of\n them). The ?foo function then modifies the second\n element of the flonum-block array and returns a 3 to\n Lisp. The second function (cmemq in C, pmemq in Pas-\n cal) acts just like the Lisp _\bm_\be_\bm_\bq function (except it\n won't work for fixnums whereas the lisp _\bm_\be_\bm_\bq will work\n for small fixnums). In the script, typed input is in\n b\bbo\bol\bld\bd, computer output is in roman and comments are in\n _\bi_\bt_\ba_\bl_\bi_\bc_\b.\n\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b14\b4\n\n\n ____________________________________________________________\n\n _\bT_\bh_\be_\bs_\be _\ba_\br_\be _\bt_\bh_\be _\bC _\bc_\bo_\bd_\be_\bd _\bf_\bu_\bn_\bc_\bt_\bi_\bo_\bn_\bs\n % c\bca\bat\bt c\bch\bh8\b8a\bau\bux\bxc\bc.\b.c\bc\n /* demonstration of c coded foreign integer-function */\n\n /* the following will be used to extract fixnums out of a list of fixnums */\n struct listoffixnumscell\n { struct listoffixnumscell *cdr;\n int *fixnum;\n };\n\n struct listcell\n { struct listcell *cdr;\n int car;\n };\n\n cfoo(a,b,c,d)\n int *a;\n double b[];\n int *c[];\n struct listoffixnumscell *d;\n {\n printf(\"a: %d, b[0]: %f, b[1]: %f0, *a, b[0], b[1]);\n printf(\" c (first): %d c (second): %d0,\n *c[0],*c[1]);\n printf(\" ( %d %d ... )\", *(d->fixnum), *(d->cdr->fixnum));\n b[1] = 3.1415926;\n return(3);\n }\n\n struct listcell *\n cmemq(element,list)\n int element;\n struct listcell *list;\n {\n for( ; list && element != list->car ; list = list->cdr);\n return(list);\n }\n\n\n _\bT_\bh_\be_\bs_\be _\ba_\br_\be _\bt_\bh_\be _\bP_\ba_\bs_\bc_\ba_\bl _\bc_\bo_\bd_\be_\bd _\bf_\bu_\bn_\bc_\bt_\bi_\bo_\bn_\bs\n % c\bca\bat\bt c\bch\bh8\b8a\bau\bux\bxp\bp.\b.p\bp\n type pinteger = ^integer;\n realarray = array[0..10] of real;\n pintarray = array[0..10] of pinteger;\n listoffixnumscell = record\n cdr : ^listoffixnumscell;\n fixnum : pinteger;\n end;\n plistcell = ^listcell;\n listcell = record\n cdr : plistcell;\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b15\b5\n\n\n car : integer;\n end;\n\n function pfoo ( var a : integer ;\n var b : realarray;\n var c : pintarray;\n var d : listoffixnumscell) : integer;\n begin\n writeln(' a:',a, ' b[0]:', b[0], ' b[1]:', b[1]);\n writeln(' c (first):', c[0]^,' c (second):', c[1]^);\n writeln(' ( ', d.fixnum^, d.cdr^.fixnum^, ' ...) ');\n b[1] := 3.1415926;\n pfoo := 3\n end ;\n\n { the function pmemq looks for the Lisp pointer given as the first argument\n in the list pointed to by the second argument.\n Note that we declare \" a : integer \" instead of \" var a : integer \" since\n we are interested in the pointer value instead of what it points to (which\n could be any Lisp object)\n }\n function pmemq( a : integer; list : plistcell) : plistcell;\n begin\n while (list <> nil) and (list^.car <> a) do list := list^.cdr;\n pmemq := list;\n end ;\n\n\n _\bT_\bh_\be _\bf_\bi_\bl_\be_\bs _\ba_\br_\be _\bc_\bo_\bm_\bp_\bi_\bl_\be_\bd\n % c\bcc\bc -\b-c\bc c\bch\bh8\b8a\bau\bux\bxc\bc.\b.c\bc\n 1.0u 1.2s 0:15 14% 30+39k 33+20io 147pf+0w\n % p\bpc\bc -\b-c\bc c\bch\bh8\b8a\bau\bux\bxp\bp.\b.p\bp\n 3.0u 1.7s 0:37 12% 27+32k 53+32io 143pf+0w\n\n\n % l\bli\bis\bsp\bp\n Franz Lisp, Opus 38.60\n _\bF_\bi_\br_\bs_\bt _\bt_\bh_\be _\bf_\bi_\bl_\be_\bs _\ba_\br_\be _\bl_\bo_\ba_\bd_\be_\bd _\ba_\bn_\bd _\bw_\be _\bs_\be_\bt _\bu_\bp _\bo_\bn_\be _\bf_\bo_\br_\be_\bi_\bg_\bn _\bf_\bu_\bn_\bc_\b-\n _\bt_\bi_\bo_\bn _\bb_\bi_\bn_\ba_\br_\by_\b. _\bW_\be _\bh_\ba_\bv_\be _\bt_\bw_\bo _\bf_\bu_\bn_\bc_\bt_\bi_\bo_\bn_\bs _\bi_\bn _\be_\ba_\bc_\bh _\bf_\bi_\bl_\be _\bs_\bo _\bw_\be _\bm_\bu_\bs_\bt\n _\bc_\bh_\bo_\bo_\bs_\be _\bo_\bn_\be _\bt_\bo _\bt_\be_\bl_\bl _\bc_\bf_\ba_\bs_\bl _\ba_\bb_\bo_\bu_\bt_\b. _\bT_\bh_\be _\bc_\bh_\bo_\bi_\bc_\be _\bi_\bs _\ba_\br_\bb_\bi_\bt_\br_\ba_\br_\by_\b.\n -> (\b(c\bcf\bfa\bas\bsl\bl '\b'c\bch\bh8\b8a\bau\bux\bxc\bc.\b.o\bo '\b'_\b_c\bcf\bfo\boo\bo '\b'c\bcf\bfo\boo\bo \"\b\"i\bin\bnt\bte\beg\bge\ber\br-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\"\b\")\b)\n /usr/lib/lisp/nld -N -A /usr/local/lisp -T 63000 ch8auxc.o -e _cfoo -o /tmp/Li7055.0 -lc\n #63000-\"integer-function\"\n -> (\b(c\bcf\bfa\bas\bsl\bl '\b'c\bch\bh8\b8a\bau\bux\bxp\bp.\b.o\bo '\b'_\b_p\bpf\bfo\boo\bo '\b'p\bpf\bfo\boo\bo \"\b\"i\bin\bnt\bte\beg\bge\ber\br-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\"\b\" \"\b\"-\b-l\blp\bpc\bc\"\b\")\b)\n /usr/lib/lisp/nld -N -A /tmp/Li7055.0 -T 63200 ch8auxp.o -e _pfoo -o /tmp/Li7055.1 -lpc -lc\n #63200-\"integer-function\"\n _\bH_\be_\br_\be _\bw_\be _\bs_\be_\bt _\bu_\bp _\bt_\bh_\be _\bo_\bt_\bh_\be_\br _\bf_\bo_\br_\be_\bi_\bg_\bn _\bf_\bu_\bn_\bc_\bt_\bi_\bo_\bn _\bb_\bi_\bn_\ba_\br_\by _\bo_\bb_\bj_\be_\bc_\bt_\bs\n -> (\b(g\bge\bet\bta\bad\bdd\bdr\bre\bes\bss\bs '\b'_\b_c\bcm\bme\bem\bmq\bq '\b'c\bcm\bme\bem\bmq\bq \"\b\"f\bfu\bun\bnc\bct\bti\bio\bon\bn\"\b\" '\b'_\b_p\bpm\bme\bem\bmq\bq '\b'p\bpm\bme\bem\bmq\bq \"\b\"f\bfu\bun\bnc\bct\bti\bio\bon\bn\"\b\")\b)\n #6306c-\"function\"\n _\bW_\be _\bw_\ba_\bn_\bt _\bt_\bo _\bc_\br_\be_\ba_\bt_\be _\ba_\bn_\bd _\bi_\bn_\bi_\bt_\bi_\ba_\bl_\bi_\bz_\be _\ba_\bn _\ba_\br_\br_\ba_\by _\bt_\bo _\bp_\ba_\bs_\bs _\bt_\bo _\bt_\bh_\be\n _\bc_\bf_\bo_\bo _\bf_\bu_\bn_\bc_\bt_\bi_\bo_\bn_\b. _\bI_\bn _\bt_\bh_\bi_\bs _\bc_\ba_\bs_\be _\bw_\be _\bc_\br_\be_\ba_\bt_\be _\ba_\bn _\bu_\bn_\bn_\ba_\bm_\be_\bd _\ba_\br_\br_\ba_\by _\ba_\bn_\bd\n _\bs_\bt_\bo_\br_\be _\bi_\bt _\bi_\bn _\bt_\bh_\be _\bv_\ba_\bl_\bu_\be _\bc_\be_\bl_\bl _\bo_\bf _\bt_\be_\bs_\bt_\ba_\br_\br_\b. _\bW_\bh_\be_\bn _\bw_\be _\bc_\br_\be_\ba_\bt_\be _\ba_\bn\n _\ba_\br_\br_\ba_\by _\bt_\bo _\bp_\ba_\bs_\bs _\bt_\bo _\bt_\bh_\be _\bP_\ba_\bs_\bc_\ba_\bl _\bp_\br_\bo_\bg_\br_\ba_\bm _\bw_\be _\bw_\bi_\bl_\bl _\bu_\bs_\be _\ba _\bn_\ba_\bm_\be_\bd\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b16\b6\n\n\n _\ba_\br_\br_\ba_\by _\bj_\bu_\bs_\bt _\bt_\bo _\bd_\be_\bm_\bo_\bn_\bs_\bt_\br_\ba_\bt_\be _\bt_\bh_\be _\bd_\bi_\bf_\bf_\be_\br_\be_\bn_\bt _\bw_\ba_\by _\bt_\bh_\ba_\bt _\bn_\ba_\bm_\be_\bd _\ba_\bn_\bd\n _\bu_\bn_\bn_\ba_\bm_\be_\bd _\ba_\br_\br_\ba_\by_\bs _\ba_\br_\be _\bc_\br_\be_\ba_\bt_\be_\bd _\ba_\bn_\bd _\ba_\bc_\bc_\be_\bs_\bs_\be_\bd_\b.\n -> (\b(s\bse\bet\btq\bq t\bte\bes\bst\bta\bar\brr\br (\b(a\bar\brr\bra\bay\by n\bni\bil\bl f\bfl\blo\bon\bnu\bum\bm-\b-b\bbl\blo\boc\bck\bk 2\b2)\b))\b)\n array[2]\n -> (\b(s\bst\bto\bor\bre\be (\b(f\bfu\bun\bnc\bca\bal\bll\bl t\bte\bes\bst\bta\bar\brr\br 0\b0)\b) 1\b1.\b.2\b23\b34\b4)\b)\n 1.234\n -> (\b(s\bst\bto\bor\bre\be (\b(f\bfu\bun\bnc\bca\bal\bll\bl t\bte\bes\bst\bta\bar\brr\br 1\b1)\b) 5\b5.\b.6\b67\b78\b8)\b)\n 5.678\n -> (\b(c\bcf\bfo\boo\bo 3\b38\b85\b5 t\bte\bes\bst\bta\bar\brr\br (\b(h\bhu\bun\bnk\bk 1\b10\b0 1\b11\b1 1\b13\b3 1\b14\b4)\b) '\b'(\b(1\b15\b5 1\b16\b6 1\b17\b7)\b))\b)\n a: 385, b[0]: 1.234000, b[1]: 5.678000\n c (first): 10 c (second): 11\n ( 15 16 ... )\n 3\n _\bN_\bo_\bt_\be _\bt_\bh_\ba_\bt _\bc_\bf_\bo_\bo _\bh_\ba_\bs _\br_\be_\bt_\bu_\br_\bn_\be_\bd _\b3 _\ba_\bs _\bi_\bt _\bs_\bh_\bo_\bu_\bl_\bd_\b. _\bI_\bt _\ba_\bl_\bs_\bo _\bh_\ba_\bd _\bt_\bh_\be\n _\bs_\bi_\bd_\be _\be_\bf_\bf_\be_\bc_\bt _\bo_\bf _\bc_\bh_\ba_\bn_\bg_\bi_\bn_\bg _\bt_\bh_\be _\bs_\be_\bc_\bo_\bn_\bd _\bv_\ba_\bl_\bu_\be _\bo_\bf _\bt_\bh_\be _\ba_\br_\br_\ba_\by _\bt_\bo\n _\b3_\b._\b1_\b4_\b1_\b5_\b9_\b2_\b6 _\bw_\bh_\bi_\bc_\bh _\bc_\bh_\be_\bc_\bk _\bn_\be_\bx_\bt_\b.\n -> (\b(f\bfu\bun\bnc\bca\bal\bll\bl t\bte\bes\bst\bta\bar\brr\br 1\b1)\b)\n 3.1415926\n\n\n _\bI_\bn _\bp_\br_\be_\bp_\ba_\br_\ba_\bt_\bi_\bo_\bn _\bf_\bo_\br _\bc_\ba_\bl_\bl_\bi_\bn_\bg _\bp_\bf_\bo_\bo _\bw_\be _\bc_\br_\be_\ba_\bt_\be _\ba_\bn _\ba_\br_\br_\ba_\by_\b.\n -> (\b(a\bar\brr\bra\bay\by t\bte\bes\bst\bt f\bfl\blo\bon\bnu\bum\bm-\b-b\bbl\blo\boc\bck\bk 2\b2)\b)\n array[2]\n -> (\b(s\bst\bto\bor\bre\be (\b(t\bte\bes\bst\bt 0\b0)\b) 1\b1.\b.2\b23\b34\b4)\b)\n 1.234\n -> (\b(s\bst\bto\bor\bre\be (\b(t\bte\bes\bst\bt 1\b1)\b) 5\b5.\b.6\b67\b78\b8)\b)\n 5.678\n -> (\b(p\bpf\bfo\boo\bo 3\b38\b85\b5 (\b(g\bge\bet\btd\bd '\b't\bte\bes\bst\bt)\b) (\b(h\bhu\bun\bnk\bk 1\b10\b0 1\b11\b1 1\b13\b3 1\b14\b4)\b) '\b'(\b(1\b15\b5 1\b16\b6 1\b17\b7)\b))\b)\n a: 385 b[0]: 1.23400000000000E+00 b[1]: 5.67800000000000E+00\n c (first): 10 c (second): 11\n ( 15 16 ...)\n 3\n -> (\b(t\bte\bes\bst\bt 1\b1)\b)\n 3.1415926\n\n _\bN_\bo_\bw _\bt_\bo _\bt_\be_\bs_\bt _\bo_\bu_\bt _\bt_\bh_\be _\bm_\be_\bm_\bq_\b'_\bs\n _\b-_\b> (\b(c\bcm\bme\bem\bmq\bq '\b'a\ba '\b'(\b(b\bb c\bc a\ba d\bd e\be f\bf)\b))\b)\n _\b(_\ba _\bd _\be _\bf_\b)\n _\b-_\b> (\b(p\bpm\bme\bem\bmq\bq '\b'e\be '\b'(\b(a\ba d\bd f\bf g\bg a\ba x\bx)\b))\b)\n _\bn_\bi_\bl\n _\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b__\b_\n\n\n\n\n\n The Fortran example will be much shorter since in\n Fortran you can't follow pointers as you can in other\n languages. The Fortran function ffoo is given three\n arguments: a fixnum, a fixnum-block array and a\n flonum. These arguments are printed out to verify\n that they made it and then the first value of the\n array is modified. The function returns a double\n\n\n Printed: October 16, 1993\n\n\n\n\n\n\n\n F\bFu\bun\bnc\bct\bti\bio\bon\bns\bs,\b, F\bFc\bcl\blo\bos\bsu\bur\bre\bes\bs,\b, a\ban\bnd\bd M\bMa\bac\bcr\bro\bos\bs 8\b8-\b-1\b17\b7\n\n\n precision value which is converted to a flonum by lisp\n and printed. Note that the entry point corresponding\n to the Fortran function ffoo is _ffoo_ as opposed to\n the C and Pascal convention of preceding the name with\n an underscore.\n\n ____________________________________________________________\n\n\n % c\bca\bat\bt c\bch\bh8\b8a\bau\bux\bxf\bf.\b.f\bf\n double precision function ffoo(a,b,c)\n integer a,b(10)\n double precision c\n print 2,a,b(1),b(2),c\n 2 format(' a=',i4,', b(1)=',i5,', b(2)=',i5,' c=',f6.4)\n b(1) = 22\n ffoo = 1.23456\n return\n end\n % f\bf7\b77\b7 -\b-c\bc c\bch\bh8\b8a\bau\bux\bxf\bf.\b.f\bf\n ch8auxf.f:\n ffoo:\n 0.9u 1.8s 0:12 22% 20+22k 54+48io 158pf+0w\n % l\bli\bis\bsp\bp\n Franz Lisp, Opus 38.60\n -> (\b(c\bcf\bfa\bas\bsl\bl '\b'c\bch\bh8\b8a\bau\bux\bxf\bf.\b.o\bo '\b'_\b_f\bff\bfo\boo\bo_\b_ '\b'f\bff\bfo\boo\bo \"\b\"r\bre\bea\bal\bl-\b-f\bfu\bun\bnc\bct\bti\bio\bon\bn\"\b\" \"\b\"-\b-l\blF\bF7\b77\b7 -\b-l\blI\bI7\b77\b7\"\b\")\b)\n /usr/lib/lisp/nld -N -A /usr/local/lisp -T 63000 ch8auxf.o -e _ffoo_\n -o /tmp/Li11066.0 -lF77 -lI77 -lc\n #6307c-\"real-function\"\n\n -> (\b(a\bar\brr\bra\bay\by t\bte\bes\bst\bt f\bfi\bix\bxn\bnu\bum\bm-\b-b\bbl\blo\boc\bck\bk 2\b2)\b)\n array[2]\n -> (\b(s\bst\bto\bor\bre\be (\b(t\bte\bes\bst\bt 0\b0)\b) 1\b10\b0)\b)\n 10\n -> (\b(s\bst\bto\bor\bre\be (\b(t\bte\bes\bst\bt 1\b1)\b) 1\b11\b1)\b)\n 11\n -> (\b(f\bff\bfo\boo\bo 3\b38\b85\b5 (\b(g\bge\bet\btd\bd '\b't\bte\bes\bst\bt)\b) 5\b5.\b.6\b67\b78\b8)\b)\n a= 385, b(1)= 10, b(2)= 11 c=5.6780\n 1.234559893608093\n -> (\b(t\bte\bes\bst\bt 0\b0)\b)\n 22\n\n ____________________________________________________________\n\n\n\n\n\n\n\n\n\n\n\n\n Printed: October 16, 1993\n\n\n\n", "meta": {"hexsha": "239c1da1e42c94edfa94a02d13b567a48dc2503a", "size": 51497, "ext": "r", "lang": "R", "max_stars_repo_path": "lisplib/manual/ch8.r", "max_stars_repo_name": "krytarowski/franz-lisp-christos", "max_stars_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-08-17T08:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T08:07:14.000Z", "max_issues_repo_path": "lisplib/manual/ch8.r", "max_issues_repo_name": "krytarowski/franz-lisp-christos", "max_issues_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lisplib/manual/ch8.r", "max_forks_repo_name": "krytarowski/franz-lisp-christos", "max_forks_repo_head_hexsha": "7f529800f415d583b4c1f0ae90dec19ad3fb1a8a", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-07-15T16:38:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-15T16:38:53.000Z", "avg_line_length": 45.856634016, "max_line_length": 204, "alphanum_fraction": 0.4637357516, "num_tokens": 19557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2450850021044189, "lm_q2_score": 0.03461883485515691, "lm_q1q2_score": 0.008484557213328662}} {"text": "subroutine succ(ksc,i,j,nadj,madj,ntot,nerror)\n\n# Find the successor of j in the adjacency list of i.\n# Called by addpt, initad, trifnd, swap, delout, dirseg, dirout.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj)\n\nnerror = -1\n\nn = nadj(i,0)\n\n# If the adjacency list of i is empty, then clearly j has no successor\n# in this adjacency list. Something's wrong; stop.\nif(n==0) {\n\tnerror = 9\n\treturn\n}\n\n# The adjacency list of i is non-empty; search through it until j is found;\n# add 1 to the location of j, and find the contents of this new location.\ndo k = 1,n {\n if(j==nadj(i,k)) {\n kp = k+1\n if(kp>n) kp = 1 # Take kp modulo n. (The adjacency list\n ksc = nadj(i,kp) # is circular.)\n return\n }\n}\n\n# The adjacency list doesn't contain j. Something's wrong.\nnerror = 10\nreturn\nend\n", "meta": {"hexsha": "39da76f3b8b4c45ab9c967a634df3699e79b84b2", "size": 891, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/succ.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/succ.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/succ.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": 25.4571428571, "max_line_length": 79, "alphanum_fraction": 0.6195286195, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149721629888, "lm_q2_score": 0.027585283226074335, "lm_q1q2_score": 0.008116003336467623}} {"text": "#Copyright 2016 Lingjiao Chen, Arun Kumar, Jeffrey Naughton, and Jignesh M. Patel, Version 0.8.\n#All rights reserved.\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\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\nlibrary(Matrix);\nNormalMatrix <- setClass (\n\t\"NormalMatrix\",\n\tslots = c (\n\t\tEntTable = \"list\",\n\t\tAttTables = \"list\",\n\t\tKFKDs = \"list\",\n\t\tTrans = \"logical\",\n\t\tSparse = \"logical\"\n\t\t),\n\tprototype=prototype(Trans=FALSE,Sparse=FALSE)\t\n\t)\n\n#############################################\n# Transpose Rule\n't.NormalMatrix' <- function( NM1)\n{\n\tNM1@Trans=!NM1@Trans;\n\treturn(NM1);\n}\n#############################################\n\n#############################################\n# Element-wise Scalar Operators\nsetMethod(\"+\", c(\"numeric\",\"NormalMatrix\"), function(e1,e2) {\n\tRnum = length(e2@AttTables);\n\tSempty = nrow(e2@EntTable[[1]])*ncol(e2@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te2@EntTable[[1]]=e2@EntTable[[1]]+e1;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te2@AttTables[[i]] = e2@AttTables[[i]]+e1;\n\t}\t\n\treturn(e2);\n})\n\nsetMethod(\"+\", c(\"NormalMatrix\",\"numeric\"), function(e1,e2) {\n\tRnum = length(e1@AttTables);\n\tSempty = nrow(e1@EntTable[[1]])*ncol(e1@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te1@EntTable[[1]]=e1@EntTable[[1]]+e2;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te1@AttTables[[i]] = e1@AttTables[[i]]+e2;\n\t}\t\n\treturn(e1);\n})\n\nsetMethod(\"-\", c(\"numeric\",\"NormalMatrix\"), function(e1,e2) {\n\tRnum = length(e2@AttTables);\n\tSempty = nrow(e2@EntTable[[1]])*ncol(e2@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te2@EntTable[[1]]=e2@EntTable[[1]]-e1;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te2@AttTables[[i]] = e2@AttTables[[i]]-e1;\n\t}\t\n\treturn(e2);\n})\n\nsetMethod(\"-\", c(\"NormalMatrix\",\"numeric\"), function(e1,e2) {\n\tRnum = length(e1@AttTables);\n\tSempty = nrow(e1@EntTable[[1]])*ncol(e1@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te1@EntTable[[1]]=e1@EntTable[[1]]-e2;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te1@AttTables[[i]] = e1@AttTables[[i]]-e2;\n\t}\t\n\treturn(e1);\n})\n\nsetMethod(\"*\", c(\"numeric\",\"NormalMatrix\"), function(e1,e2) {\n\tRnum = length(e2@AttTables);\n\tSempty = nrow(e2@EntTable[[1]])*ncol(e2@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te2@EntTable[[1]]=e2@EntTable[[1]]*e1;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te2@AttTables[[i]] = e2@AttTables[[i]]*e1;\n\t}\t\n\treturn(e2);\n})\n\nsetMethod(\"*\", c(\"NormalMatrix\",\"numeric\"), function(e1,e2) {\n\tRnum = length(e1@AttTables);\n\tSempty = nrow(e1@EntTable[[1]])*ncol(e1@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te1@EntTable[[1]]=e1@EntTable[[1]]*e2;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te1@AttTables[[i]] = e1@AttTables[[i]]*e2;\n\t}\t\n\treturn(e1);\n})\n\nsetMethod(\"/\", c(\"numeric\",\"NormalMatrix\"), function(e1,e2) {\n\tRnum = length(e2@AttTables);\n\tSempty = nrow(e2@EntTable[[1]])*ncol(e2@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te2@EntTable[[1]]=e2@EntTable[[1]]/e1;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te2@AttTables[[i]] = e2@AttTables[[i]]/e1;\n\t}\t\n\treturn(e2);\n})\n\nsetMethod(\"/\", c(\"NormalMatrix\",\"numeric\"), function(e1,e2) {\n\tRnum = length(e1@AttTables);\n\tSempty = nrow(e1@EntTable[[1]])*ncol(e1@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te1@EntTable[[1]]=e1@EntTable[[1]]/e2;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te1@AttTables[[i]] = e1@AttTables[[i]]/e2;\n\t}\t\n\treturn(e1);\n})\n\nsetMethod(\"^\", c(\"numeric\",\"NormalMatrix\"), function(e1,e2) {\n\tRnum = length(e2@AttTables);\n\tSempty = nrow(e2@EntTable[[1]])*ncol(e2@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te2@EntTable[[1]]=e2@EntTable[[1]]^e1;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te2@AttTables[[i]] = e2@AttTables[[i]]^e1;\n\t}\t\n\treturn(e2);\n})\n\nsetMethod(\"^\", c(\"NormalMatrix\",\"numeric\"), function(e1,e2) {\n\tRnum = length(e1@AttTables);\n\tSempty = nrow(e1@EntTable[[1]])*ncol(e1@EntTable[[1]]);\n\tif(Sempty!=0)\n\t{\n\t\te1@EntTable[[1]]=e1@EntTable[[1]]^e2;\n\t}\n\tfor(i in 1:Rnum)\n\t{\n\t\te1@AttTables[[i]] = e1@AttTables[[i]]^e2;\n\t}\t\n\treturn(e1);\n})\n\n#############################################\n\n#############################################\n#Aggregation\nsetMethod(\"sum\", c(\"NormalMatrix\"), function(x) {\n\tSempty = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\ty = ifelse(Sempty!=0,sum(x@EntTable[[1]]),0 );\n\tRnum = length(x@AttTables);\n\tfor(i in 1:Rnum)\n\t{\n\t\ty = y + colSums(x@KFKDs[[i]])%*%rowSums(x@AttTables[[i]]);\n\t}\t\n\treturn(y);\n})\n\nsetMethod(\"rowSums\", c(\"NormalMatrix\"), function(x) {\n\tif(x@Trans==TRUE)\n\t{\n\t\treturn(t(NormalMatrixcolSums(x)));\n\t}\n\telse\n\t{\n\t\treturn(NormalMatrixrowSums(x));\n\t}\n})\n\nsetMethod(\"colSums\", c(\"NormalMatrix\"), function(x) {\n\tif(x@Trans==TRUE)\n\t{\n\t\treturn(t(NormalMatrixrowSums(x)));\n\t}\n\telse\n\t{\n\t\treturn(NormalMatrixcolSums(x));\n\t}\n})\n\nNormalMatrixrowSums <- function(x){\n\tSempty = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\ti = 1;\n\tif(Sempty!=0)\n\t{\n\t\ty = rowSums(x@EntTable[[1]])+as.numeric(x@KFKDs[[i]]%*%rowSums(x@AttTables[[i]]));;\n\t}\n\telse\n\t{\n\t\ty = as.numeric(x@KFKDs[[i]]%*%rowSums(x@AttTables[[i]]));\n\t}\n\tRnum = length(x@AttTables);\n\ti = 2;\n\twhile(i <= Rnum)\n\t{\n\t\ty = y + as.numeric(x@KFKDs[[i]]%*%rowSums(x@AttTables[[i]]));\n\t\ti = i + 1;\n\t}\t\n\treturn(y);\n}\n\nNormalMatrixcolSums <- function(x){\n\tSempty = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\tRnum = length(x@AttTables);\n\tif(Sempty!=0)\n\t{\n\t\ty = c(colSums(x@EntTable[[1]]), colSums(x@KFKDs[[1]])%*%x@AttTables[[1]]);\n\t}\n\telse\n\t{\n\t\ty = colSums(x@KFKDs[[1]])%*%x@AttTables[[1]];\n\t}\t\n\ti = 2;\n\twhile(i <= Rnum)\n\t{\n\t\ty = c(y, colSums(x@KFKDs[[i]])%*%x@AttTables[[i]] );\n\t\ti = i + 1;\n\t}\t\n\treturn(y);\n}\n\n\n#############################################\n\n#############################################\n# Multiplication\n\n# Left Matrix Multiplication\nNormalMatrixLMM <- function(x,y)\n{\n\tSempty = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\tRnum = length(x@AttTables);\n\tif(x@Sparse==TRUE) # EntTable is empty\n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = x@KFKDs[[1]] %*% (x@AttTables[[1]] %*% y[1:(ncol(x@AttTables[[1]]) ),] );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOut1 = x@EntTable[[1]]%*% y[1:(ncol(x@EntTable[[1]]) ),] + x@KFKDs[[1]] %*% (x@AttTables[[1]] %*% y[(1+ncol(x@EntTable[[1]])):(ncol(x@AttTables[[1]])+ncol(x@EntTable[[1]]) ),] );\n\t\t}\t\t\n\t\tStartCol = ncol(x@EntTable[[1]])+ncol(x@AttTables[[1]]);\n\t\ti = 2;\n\t\twhile(i <= Rnum) # multi-table joins\n\t\t{\n\t\t\tOut1 = Out1 + (x@KFKDs[[i]]) %*% (x@AttTables[[i]] %*% y[(1+StartCol):(StartCol+ncol(x@AttTables[[i]]) ),] );\t\n\t\t\tStartCol=StartCol+(ncol(x@AttTables[[i]]) );\n\t\t\ti = i + 1;\n\t\t}\n\t\treturn (Out1);\n\t}\n\telse\n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = as.matrix(x@KFKDs[[1]] %*% (x@AttTables[[1]] %*% y[1:(ncol(x@AttTables[[1]]) ),] ));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOut1 = x@EntTable[[1]]%*% y[1:(ncol(x@EntTable[[1]]) ),] + as.matrix(x@KFKDs[[1]] %*% (x@AttTables[[1]] %*% y[(1+ncol(x@EntTable[[1]])):(ncol(x@AttTables[[1]])+ncol(x@EntTable[[1]]) ),] ));\n\t\t}\t\t\n\t\tStartCol = ncol(x@EntTable[[1]])+ncol(x@AttTables[[1]]);\n\t\ti = 2;\t\t\t\n\t\twhile(i <= Rnum) # multi-table joins\n\t\t{\n\t\t\tOut1 = Out1 + as.matrix((x@KFKDs[[i]]) %*% (x@AttTables[[i]] %*% y[(1+StartCol):(StartCol+ncol(x@AttTables[[i]]) ),] ));\t\n\t\t\tStartCol=StartCol+(ncol(x@AttTables[[i]]) );\n\t\t\ti = i + 1;\n\t\t}\n\t\treturn (Out1);\n\n\t}\n}\n\n# Right Matrix Multiplication\nNormalMatrixRMM <- function(x,y)\n{\n\tSempty = nrow(y@EntTable[[1]])*ncol(y@EntTable[[1]]);\n\tRnum = length(y@AttTables);\n\tif(y@Sparse==TRUE)# Sparse \n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = (x %*% y@KFKDs[[1]])%*%y@AttTables[[1]];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOut1 = cbind(x%*% y@EntTable[[1]],(x %*% y@KFKDs[[1]])%*%y@AttTables[[1]]);\t\n\t\t}\t\n\t\ti = 2;\t\n\t\twhile( i <= Rnum) # multi-table joins\n\t\t{\n\t\t\tOut1 = cbind(Out1,(x %*% y@KFKDs[[i]])%*%y@AttTables[[i]]);\n\t\t\ti = i + 1;\t\n\t\t}\t\t\n\t\treturn (Out1);\n\t}\n\telse\n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = as.matrix(x %*% y@KFKDs[[1]])%*%y@AttTables[[1]];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOut1 = cbind(x%*% y@EntTable[[1]],as.matrix(x %*% y@KFKDs[[1]])%*%y@AttTables[[1]]);\t\n\t\t}\t\t\n\t\ti = 2;\t\n\t\twhile( i <= Rnum) # multi-table joins\n\t\t{\n\t\t\tOut1 = cbind(Out1,as.matrix(x %*% y@KFKDs[[i]])%*%y@AttTables[[i]]);\n\t\t\ti = i + 1;\t\n\t\t}\t\t\n\t\treturn (Out1);\n\t}\n}\n\n# API for LMM and RMM with different matrix types.\n\n#LMM API.\nsetMethod(\"%*%\", c(\"NormalMatrix\",\"dgCMatrix\"), function(x,y) \n{\n\tif(x@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixLMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixRMM(t(y),x)) );\n\t}\n})\n\nsetMethod(\"%*%\", c(\"NormalMatrix\",\"matrix\"), function(x,y) \n{\n\tif(x@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixLMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixRMM(t(y),x)) );\n\t}\n})\n\nsetMethod(\"%*%\", c(\"NormalMatrix\",\"dgeMatrix\"), function(x,y) \n{\n\tif(x@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixLMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixRMM(t(y),x)) );\n\t}\n})\n\nsetMethod(\"%*%\", c(\"NormalMatrix\",\"lgCMatrix\"), function(x,y) \n{\n\tif(x@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixLMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixRMM(t(y),x)) );\n\t}\n})\n\n#RMM API.\nsetMethod(\"%*%\", c(\"dgCMatrix\",\"NormalMatrix\"), function(x,y) {\n\tif(y@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixRMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixLMM(y,t(x))) );\n\t}\n})\n\nsetMethod(\"%*%\", c(\"dgeMatrix\",\"NormalMatrix\"), function(x,y) {\n\tif(y@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixRMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixLMM(y,t(x))) );\n\t}\n})\n\nsetMethod(\"%*%\", c(\"lgCMatrix\",\"NormalMatrix\"), function(x,y) {\n\tif(y@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixRMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixLMM(y,t(x))) );\n\t}\n})\n\nsetMethod(\"%*%\", c(\"matrix\",\"NormalMatrix\"), function(x,y) {\n\tif(y@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixRMM(x,y) );\n\t}\n\telse\n\t{\n\t\treturn( t(NormalMatrixLMM(y,t(x))) );\n\t}\n})\n\n#############################################\n\n\n#############################################\n#Derived Multiplication Operators.\n#Include Crossprod and double multiplication.\n#############################################\n\n#############################################\n# Cross Product\nNormalMatrixCrossprod <- function(x)\n{\n\tSempty = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\tRnum = length(x@AttTables);\n\tif(x@Sparse==TRUE)# Sparse \n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = ( crossprod( Diagonal( x=colSums(x@KFKDs[[1]])^{1/2} ) %*% x@AttTables[[1]]) ) ;\n\t\t\ti = 2;\t\n\t\t\twhile( i <= Rnum) # multi-table joins\n\t\t\t{\n\t\t\t\t# Construct Y_21\n\t\t\t\tj = 1;\n\t\t\t\tY21 = crossprod( x@AttTables[[i]], crossprod(crossprod(x@KFKDs[[j]], x@KFKDs[[i]] ), x@AttTables[[j]]) ) ;\n\t\t\t\tj = 2;\n\t\t\t\twhile( j <=(i-1))\n\t\t\t\t{\n\t\t\t\t\tj = j + 1;\n\t\t\t\t\tY21 = cbind(Y21, crossprod( x@AttTables[[i]], crossprod(crossprod(x@KFKDs[[j]], x@KFKDs[[i]] ), x@AttTables[[j]]) )) ;\n\t\t\t\t}\n\t\t\t\tOut1 = (rbind( cbind(Out1,t(Y21) ) , cbind( Y21, (crossprod( Diagonal( x=colSums(x@KFKDs[[i]])^{1/2} ) %*% x@AttTables[[i]]) ) )) );\n\t\t\t\ti = i + 1;\n\t\t\t}\n\t\t\treturn( Out1 );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tY21 = crossprod(x@AttTables[[1]], ( crossprod(x@KFKDs[[1]], x@EntTable[[1]]) ) );\n\t\t\tOut1 = (rbind( cbind(crossprod(x@EntTable[[1]]),t(Y21) ) , cbind( Y21, (crossprod( Diagonal( x=colSums(x@KFKDs[[1]])^{1/2} ) %*% x@AttTables[[1]]) ) )) );\n\t\t\ti = 2;\t\n\t\t\twhile( i <= Rnum) # multi-table joins\n\t\t\t{\n\t\t\t\t# Construct Y_21\n\t\t\t\tY21 = crossprod(x@AttTables[[i]], ( crossprod(x@KFKDs[[i]], x@EntTable[[1]]) ) );\n\t\t\t\tfor( j in 1:(i-1))\n\t\t\t\t{\n\t\t\t\t\tY21 = cbind(Y21, crossprod( x@AttTables[[i]], crossprod(crossprod(x@KFKDs[[j]], x@KFKDs[[i]] ), x@AttTables[[j]]) )) ;\n\t\t\t\t}\n\t\t\t\tOut1 = (rbind( cbind(Out1,t(Y21) ) , cbind( Y21, (crossprod( Diagonal( x=colSums(x@KFKDs[[i]])^{1/2} ) %*% x@AttTables[[i]]) ) )) );\n\t\t\t\ti = i + 1;\n\t\t\t}\n\t\t\treturn( Out1 );\n\t\t}\t\t\n\t}\n\telse\n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = as.matrix( crossprod( Diagonal( x=colSums(x@KFKDs[[1]])^{1/2} ) %*% x@AttTables[[1]]) ) ;\n\t\t\ti = 2;\t\n\t\t\twhile( i <= Rnum) # multi-table joins\n\t\t\t{\n\t\t\t\t# Construct Y_21\n\t\t\t\tj = 1;\n\t\t\t\tY21 = crossprod( x@AttTables[[i]], as.matrix(crossprod(crossprod(x@KFKDs[[j]], x@KFKDs[[i]] ), x@AttTables[[j]]) )) ;\n\t\t\t\tj = 2;\n\t\t\t\twhile( j <=(i-1))\n\t\t\t\t{\n\t\t\t\t\tj = j + 1;\n\t\t\t\t\tY21 = cbind(Y21, crossprod( x@AttTables[[i]], as.matrix(crossprod(crossprod(x@KFKDs[[j]], x@KFKDs[[i]] ), x@AttTables[[j]]) )) ) ;\n\t\t\t\t}\n\t\t\t\tOut1 = (rbind( cbind(Out1,t(Y21) ) , cbind( Y21, as.matrix(crossprod( Diagonal( x=colSums(x@KFKDs[[i]])^{1/2} ) %*% x@AttTables[[i]]) ) )) );\n\t\t\t\ti = i + 1;\t\t\t\n\t\t\t}\n\t\t\treturn( Out1 );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tY21 = crossprod(x@AttTables[[1]], as.matrix( crossprod(x@KFKDs[[1]], x@EntTable[[1]]) ) );\n\t\t\tOut1 = (rbind( cbind(crossprod(x@EntTable[[1]]),t(Y21) ) , cbind( Y21, as.matrix(crossprod( Diagonal( x=colSums(x@KFKDs[[1]])^{1/2} ) %*% x@AttTables[[1]]) ) )) );\n\t\t\ti = 2;\t\n\t\t\twhile( i <= Rnum) # multi-table joins\n\t\t\t{\n\t\t\t\t# Construct Y_21\n\t\t\t\tY21 = crossprod(x@AttTables[[i]], ( crossprod(x@KFKDs[[i]], x@EntTable[[1]]) ) );\n\t\t\t\tfor( j in 1:(i-1))\n\t\t\t\t{\n\t\t\t\t\tY21 = cbind(Y21, crossprod( x@AttTables[[i]], as.matrix(crossprod(crossprod(x@KFKDs[[j]], x@KFKDs[[i]] ), x@AttTables[[j]]) ))) ;\n\t\t\t\t}\n\t\t\t\tOut1 = (rbind( cbind(Out1,t(Y21) ) , cbind( Y21, as.matrix(crossprod( Diagonal( x=colSums(x@KFKDs[[i]])^{1/2} ) %*% x@AttTables[[i]]) ) )) );\n\t\t\t\ti = i + 1;\t\t\t\n\t\t\t}\n\t\t\treturn( Out1 );\n\t\t}\t\n\t}\n}\n\n# Transpose Cross Product\nNormalMatrixCrossprodTrans <- function(x)\n{\n\tSempty = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\tRnum = length(x@AttTables);\n\tif(x@Sparse==TRUE)# Sparse \n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = tcrossprod(x@KFKDs[[1]] %*% tcrossprod(x@AttTables[[1]]), x@KFKDs[[1]]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOut1 = tcrossprod(x@EntTable[[1]]) + tcrossprod(x@KFKDs[[1]] %*% tcrossprod(x@AttTables[[1]]), x@KFKDs[[1]]);\n\t\t}\n\t\ti = 2;\t\n\t\twhile( i <= Rnum) # multi-table joins\n\t\t{\n\t\t\tOut1 = Out1 + tcrossprod(x@KFKDs[[i]] %*% tcrossprod(x@AttTables[[i]]), x@KFKDs[[i]]);\n\t\t\ti = i + 1;\n\t\t}\n\t\treturn( Out1 );\n\t}\n\telse\n\t{\n\t\tif(Sempty==0) # EntTable is empty\n\t\t{\n\t\t\tOut1 = as.matrix(tcrossprod(x@KFKDs[[1]] %*% tcrossprod(x@AttTables[[1]]), x@KFKDs[[1]]));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOut1 = tcrossprod(x@EntTable[[1]]) + as.matrix(tcrossprod(x@KFKDs[[1]] %*% tcrossprod(x@AttTables[[1]]), x@KFKDs[[1]]));\n\t\t}\n\t\ti = 2;\t\n\t\twhile( i <= Rnum) # multi-table joins\n\t\t{\n\t\t\tOut1 = Out1 + as.matrix(tcrossprod(x@KFKDs[[i]] %*% tcrossprod(x@AttTables[[i]]), x@KFKDs[[i]]));\n\t\t\ti = i + 1;\n\t\t}\n\t\treturn( Out1 );\n\t}\t\n}\n\n# Crossprod API\nsetMethod(\"crossprod\", c(\"NormalMatrix\"), function(x) {\n\tif(x@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixCrossprod(x) );\n\t}\n\telse\n\t{\n\t\treturn( (NormalMatrixCrossprodTrans(x)) );\n\t}\n})\n\nsetMethod(\"tcrossprod\", c(\"NormalMatrix\"), function(x) {\n\tif(x@Trans==FALSE)\n\t{\n\t\treturn( NormalMatrixCrossprodTrans(x) );\n\t}\n\telse\n\t{\n\t\treturn( (NormalMatrixCrossprod(x)) );\n\t}\n})\n#############################################\n\n\n#############################################\n#Double Multiplication\n\n#############################################\n# Cross Product Alike, i.e., t(A)%*% B \n# Warning: Only test the case when A = B.\nNormalMatrixCrossprod2M <- function(x,y)\n{\n\tSempty1 = nrow(x@EntTable[[1]])*ncol(x@EntTable[[1]]);\n\tRnum1 = length(x@AttTables);\n\tSempty2 = nrow(y@EntTable[[1]])*ncol(y@EntTable[[1]]);\n\tRnum2 = length(y@AttTables);\n\tif(x@Sparse==TRUE)# Sparse \n\t{\n\t\t# First compute attribute tables\n\t\ti = 1;\n\t\tj = 1;\n\t\tOut1 = t(x@AttTables[[i]]) %*%( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]]);\n\t\tj = j+1;\n\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t{\n\t\t\tOut1 = cbind(Out1,t(x@AttTables[[i]]) %*%( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]]));\n\t\t\tj = j+1;\n\t\t}\n\t\ti = i+1;\n\t\twhile( 2<=i && i<=Rnum1 ) # Enter this loop only if A is multi-table.\n\t\t{\n\t\t\tj = 1;\n\t\t\tTemp = t(x@AttTables[[i]]) %*%( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]]);\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t\t{\n\t\t\t\tTemp = cbind(Temp,t(x@AttTables[[i]]) %*%( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]]));\n\t\t\t\tj = j+1;\n\t\t\t}\n\t\t\tOut1 = rbind(Out1,Temp);\n\t\t\ti=i+1;\n\t\t}\n\t\t# Finish attribute tables.\n\t\t\n\t\t# Consider Entity table.\n\t\tif(Sempty1 == 0 && Sempty2 != 0 ) # No Entity table in A.\n\t\t{\n\t\t\tj = 1;\n\t\t\tTemp = t(x@AttTables[[j]]) %*%( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum1)# Enter this loop only if A is multi-table.\n\t\t\t{\n\t\t\t\tTemp = rbind(Temp,t(x@AttTables[[j]]) %*%( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ));\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = cbind(Temp,Out1);\n\t\t}\n\t\tif(Sempty1 != 0 && Sempty2 == 0 ) # No Entity table in B.\n\t\t{\n\t\t\tj = 1;\n\t\t\tTemp = (t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t\t{\n\t\t\t\tTemp = cbind(Temp,(t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = rbind(Temp,Out1);\n\t\t}\n\t\tif(Sempty1 != 0 && Sempty2 != 0 ) # Both with Entity table.\n\t\t{\n\t\t\t# EntTable in A.\n\t\t\tj = 1;\n\t\t\tTemp = t(x@AttTables[[j]]) %*%( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum1)# Enter this loop only if A is multi-table.\n\t\t\t{\n\t\t\t\tTemp = rbind(Temp,t(x@AttTables[[j]]) %*%( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = cbind(Temp,Out1);\n\t\t\t# EntTable in B.\n\t\t\tj = 1;\n\t\t\tTemp = cbind( (t(x@EntTable[[1]]) %*% y@EntTable[[1]]) , (t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] ) ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t\t{\n\t\t\t\tTemp = cbind(Temp,(t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = rbind(Temp,Out1);\n\t\t}\n\t\t\t\n\t\t\treturn(Out1);\t\n\t}\n\telse\n\t{\n\t\t# First compute attribute tables\n\t\ti = 1;\n\t\tj = 1;\n\t\tOut1 = t(x@AttTables[[i]]) %*%as.matrix(( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]]));\n\t\tj = j+1;\n\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t{\n\t\t\tOut1 = cbind(Out1,t(x@AttTables[[i]]) %*%as.matrix(( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]])));\n\t\t\tj = j+1;\n\t\t}\n\t\ti = i+1;\n\t\twhile( 2<=i && i<=Rnum1 ) # Enter this loop only if A is multi-table.\n\t\t{\n\t\t\tj = 1;\n\t\t\tTemp = t(x@AttTables[[i]]) %*%as.matrix(( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]]));\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t\t{\n\t\t\t\tTemp = cbind(Temp,t(x@AttTables[[i]]) %*%as.matrix(( t(x@KFKDs[[i]]) %*% y@KFKDs[[j]] ) %*% (y@AttTables[[j]])));\n\t\t\t\tj = j+1;\n\t\t\t}\n\t\t\tOut1 = rbind(Out1,Temp);\n\t\t\ti=i+1;\n\t\t}\n\t\t# Finish attribute tables.\n\t\t\n\t\t# Consider Entity table.\n\t\tif(Sempty1 == 0 && Sempty2 != 0 ) # No Entity table in A.\n\t\t{\n\t\t\tj = 1;\n\t\t\tTemp = t(x@AttTables[[j]]) %*%as.matrix( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum1)# Enter this loop only if A is multi-table.\n\t\t\t{\n\t\t\t\tTemp = rbind(Temp,t(x@AttTables[[j]]) %*%as.matrix( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = cbind(Temp,Out1);\n\t\t}\n\t\tif(Sempty1 != 0 && Sempty2 == 0 ) # No Entity table in B.\n\t\t{\n\t\t\tj = 1;\n\t\t\tTemp = as.matrix(t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t\t{\n\t\t\t\tTemp = cbind(Temp,as.matrix(t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = rbind(Temp,Out1);\n\t\t}\n\t\tif(Sempty1 != 0 && Sempty2 != 0 ) # Both with Entity table.\n\t\t{\n\t\t\t# EntTable in A.\n\t\t\tj = 1;\n\t\t\tTemp = t(x@AttTables[[j]]) %*%as.matrix( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum1)# Enter this loop only if A is multi-table.\n\t\t\t{\n\t\t\t\tTemp = rbind(Temp,t(x@AttTables[[j]]) %*%as.matrix( t(x@KFKDs[[j]]) %*% y@EntTable[[1]] ) );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = cbind(Temp,Out1);\n\t\t\t# EntTable in B.\n\t\t\tj = 1;\n\t\t\tTemp = cbind( (t(x@EntTable[[1]]) %*% y@EntTable[[1]]) , as.matrix(t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] ) ;\n\t\t\tj = j+1;\n\t\t\twhile( 2<=j && j<= Rnum2)# Enter this loop only if B is multi-table.\n\t\t\t{\n\t\t\t\tTemp = cbind(Temp,as.matrix(t(x@EntTable[[1]]) %*% y@KFKDs[[j]]) %*% y@AttTables[[j]] );\n\t\t\t\tj = j+1;\n\t\t\t}\t\t\t\n\t\t\tOut1 = rbind(Temp,Out1);\n\t\t}\n\t\treturn( Out1 );\n\t}\t\n}\n\n#Note: Double Multiplication is not fully optimized.\n#############################################\n\n\n\n\n#############################################\n# M:N joins\nNormalMatrixJoin <- function(S,R,SJA,RJA,IsSparse=FALSE){\n\t# Input : S, R, SJA, RJA\n\tnS = nrow(S);\n\tdS = ncol(S);\n\tnR = nrow(R);\n\tdR = ncol(R);\n\n\tSJAS = sparseMatrix(c(1:nS),SJA );\n\tRJAS = sparseMatrix(c(1:nR),RJA );\n\tif( ncol(SJAS) > ncol(RJAS) )\n\t{\n\t\tSJAS = SJAS[,1:ncol(RJAS)];\n\t}\n\tif( ncol(SJAS) < ncol(RJAS) )\n\t{\n\t\tRJAS = RJAS[,1:ncol(SJAS)];\n\t}\n\tJM = SJAS %*%t(RJAS);\n\tnT = sum(colSums((JM)));\n\tif(nT!=0)\n\t{\n\t\tJMS = summary(JM);\n\t\tSJM = sparseMatrix(c(1:nT),JMS[,1],dims=c(nT,nS),x=1);\n\t\tRJM = sparseMatrix(c(1:nT),JMS[,2],dims=c(nT,nR),x=1);\n\t}\n\tif(nT==0)\n\t{\n\t\tSJM = Matrix(0,nT,nS);\n\t\tRJM = Matrix(0,nT,nR);\n\t}\n\tS0 = matrix(0,0,0);\n\tTNM = NormalMatrix(EntTable=list(S0),AttTables=list(S,R),KFKDs=list(SJM,RJM),Sparse=IsSparse);\n\treturn (TNM);\n}\n#############################################\n#Handle conflicts with regular matrix package\nsetMethod(Ops, c(\"NormalMatrix\",\"NormalMatrix\"), function(e1,e2) {\n\treturn ();\n})\n", "meta": {"hexsha": "792c4d583f556b11647ff742ac411299fc5c42b1", "size": 21190, "ext": "r", "lang": "R", "max_stars_repo_path": "src/NormalMatrix.r", "max_stars_repo_name": "lchen001/Morpheus", "max_stars_repo_head_hexsha": "d94e6487dcf32982fb4322a4ed2a8a40c2319f56", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2017-10-30T18:39:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T16:20:23.000Z", "max_issues_repo_path": "src/NormalMatrix.r", "max_issues_repo_name": "lchen001/Morpheus", "max_issues_repo_head_hexsha": "d94e6487dcf32982fb4322a4ed2a8a40c2319f56", "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/NormalMatrix.r", "max_forks_repo_name": "lchen001/Morpheus", "max_forks_repo_head_hexsha": "d94e6487dcf32982fb4322a4ed2a8a40c2319f56", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-09-24T04:01:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T21:25:36.000Z", "avg_line_length": 25.377245509, "max_line_length": 192, "alphanum_fraction": 0.5413402548, "num_tokens": 8408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.016657043182201847, "lm_q1q2_score": 0.008003354088371247}} {"text": "individuals <- c(\"C010_pennunk\", \"C016_pennunk\", \"C018_pennunk\", \"C036_modoc\", \"C002_modoc\", \"C019_modoc\", \"C046_laevigatus\", \"C003_laevigatus\", \"C049_herculeanus\",\"C050_herculeanus\", \"C056_herculeanus\", \"C039_vicinus\", \"C005_vicinus\", \"C028_vicinus\", \"C024_vicinusunk\", \"C029_vicinusunk\", \"C006_ocreatus\")\n# species\nspecies <- unique(sapply(strsplit(individuals, \"_\"), \"[[\", 2))\nspecies\n# \"pennunk\" \"modoc\" \"laevigatus\" \"herculeanus\" \"vicinus\" \"vicinusunk\" \"ocreatus\" \n\n\n# define parameters\n# gen time = 2 * age of sexual maturity in closely-related species from ant literature (3-4 years depending on estimate)\n# age of sex. maturity = ~3 years\n# method citation = doi: 10.1016/j.cub.2015.03.047\ngen <- 6\nmu <- 1.983877e-09 #* gen # needs to be per generation\n# plotting numbers\nmin_age <- 000\nmax_age <- 1000000\nplotting_age_range <- 1000 # years for x axis\n\n\n# loop through each output directory\noutput <- list()\noutput_bootstraps <- list()\nfor(a in 1:length(individuals)) {\n\t# identify bootstraps \n\ta_bootstraps <- paste(\"output/\", individuals[a], \"_b\", seq(from=1, to=10, by=1), \".final.txt\", sep=\"\")\n\t# identify main output file\n\ta_main <- paste(\"output/\", individuals[a], \".final.txt\", sep=\"\")\n\n\t\n\t# read in main file\n\ta_rep <- read.table(a_main, sep=\"\\t\", header=T)\n\t# rearrange main file for plotting lines\n\tfor(d in 1:nrow(a_rep)) {\n\t\tif(d == 1) {\n\t\t\ta_rep2 <- rbind(c(a_rep[d,2], a_rep[d,4]), c(a_rep[d,3], a_rep[d,4]))\n\t\t} else {\n\t\t\ta_rep2 <- rbind(a_rep2, c(a_rep[d,2], a_rep[d,4]), c(a_rep[d,3], a_rep[d,4]))\n\t\t}\n\t}\n\ta_rep <- a_rep2\n\t# scale by mutation rate\n\ta_rep[,1] <- a_rep[,1] / mu * gen\n\ta_rep[,2] <- (1 / a_rep[,2]) / (2 * mu)\n\t# remove very young and old time frames prone to error\n\ta_rep <- a_rep[a_rep[,1] >= min_age & a_rep[,1] <= max_age,]\n\t# scale by plotting age range and pop size range\n\ta_rep <- a_rep / plotting_age_range\n\t# add to output list\n\toutput[[a]] <- a_rep\n\t\n\t# output for each bootstrap\n\toutput_bootstraps[[a]] <- list()\n\tfor(b in 1:length(a_bootstraps)) {\n\t\tb_rep <- read.table(a_bootstraps[b], sep=\"\\t\", header=T)\n\t\t# rearrange main file for plotting lines\n\t\tfor(d in 1:nrow(b_rep)) {\n\t\t\tif(d == 1) {\n\t\t\t\tb_rep2 <- rbind(c(b_rep[d,2], b_rep[d,4]), c(b_rep[d,3], b_rep[d,4]))\n\t\t\t} else {\n\t\t\t\tb_rep2 <- rbind(b_rep2, c(b_rep[d,2], b_rep[d,4]), c(b_rep[d,3], b_rep[d,4]))\n\t\t\t}\n\t\t}\n\t\tb_rep <- b_rep2\n\t\t# scale by mutation rate\n\t\tb_rep[,1] <- b_rep[,1] / mu * gen\n\t\tb_rep[,2] <- (1 / b_rep[,2]) / (2 * mu)\n\t\t# remove very young and old time frames prone to error\n\t\tb_rep <- b_rep[b_rep[,1] >= min_age & b_rep[,1] <= max_age,]\n\t\t# scale by plotting age range and pop size range\n\t\tb_rep <- b_rep / plotting_age_range\n\t\t# add to output list\n\t\toutput_bootstraps[[a]][[b]] <- b_rep\t\t\n\t}\n}\n\n\n\n# plot all separate\na_col <- \"darkgreen\"\npar(mfrow=c(4,5))\npar(mar=c(4.5,4.5,2,0.2))\nfor(a in 1:length(output)) {\n\tplot_name1 <- individuals[a]\n\tplot(c(-1,1), xlim=c(50, 900), ylim=c(0,500), pch=19, cex=0.01, log=\"x\", xlab=\"kya\", ylab=\"Pop. Size (1000s)\", main=\"\", xaxt=\"n\", yaxt=\"n\")\n\ttitle(main=bquote(italic(.(plot_name1))), adj=0,line=0.5, cex.main=1.5)\n\taxis(side=2, at=c(0, 150, 300, 450), labels=T)\t\t\n\taxis(side=1, at=c(20, 50, 100, 200, 500, 900), labels=T)\t\t\n\t\n\t\n\t# plot bootstraps\n\tfor(b in 1:length(output_bootstraps[[1]])) {\n\t\tlines(output_bootstraps[[a]][[b]][,1], output_bootstraps[[a]][[b]][,2], col=a_col, lwd=0.3)\n\t}\n\tlines(output[[a]][,1], output[[a]][,2], col=a_col, lwd=3)\n}\n\n\n\n\n\n\n# define current pop sizes \ncurrent_pop <- c()\nfor(a in 1:length(output)) {\n\tcurrent_pop <- c(current_pop, output[[a]][1,2])\n}\n\n# harmonic mean of pop sizes from most recent to 500k years ago\nharmonic_pop <- c()\nfor(a in 1:length(output)) {\n\tout_rep <- output[[a]]\n\t\n\t# define time series\n\ttime_series <- seq(from=as.integer(out_rep[2,1])+1, to=500, by=1)\n\t# time series pops\n\ttime_pops <- c()\n\tfor(b in 1:length(time_series)) {\n\t\ttime_pops <- c(time_pops, out_rep[time_series[b] < out_rep[,1],][1,2])\n\t}\n\t# harmonic mean of this individual\n\tharm_rep <- length(time_pops) / sum((1 / time_pops))\n\t\n\t# add to output element\n\tharmonic_pop <- c(harmonic_pop, harm_rep)\n}\n\n# read in diversity table\ndiv <- read.table(\"01_heterozygosity_per_individual.txt\", header=T, stringsAsFactors=F)\n# remove outgroups\ndiv <- div[div$number <= 17, ]\n\n\n# define output to match with diversity table\noutput <- data.frame(individual=as.character(gsub(\"C\", \"C-\", sapply(strsplit(individuals, \"_\"), \"[[\", 1))), current_pop=as.numeric(current_pop), harmonic_pop=as.numeric(harmonic_pop))\n# rearrange\noutput <- output[match(div$individual, output$individual),]\n# combine outputs\ndiv <- cbind(div, output)\n# remove duplicate individuals column after checking\ndiv <- div[,-6]\n\n#write output\nwrite.table(div, file=\"01_heterozygosity_and_pop_sizes.txt\", sep=\"\\t\", row.names=F, quote=F)\n", "meta": {"hexsha": "08bc1042694319f3233dca55e2ffb17ba5900da9", "size": 4802, "ext": "r", "lang": "R", "max_stars_repo_path": "04_msmc2/04_plot_and_calc_harmonic_means.r", "max_stars_repo_name": "jdmanthey/camponotus_genomes1", "max_stars_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "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": "04_msmc2/04_plot_and_calc_harmonic_means.r", "max_issues_repo_name": "jdmanthey/camponotus_genomes1", "max_issues_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "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": "04_msmc2/04_plot_and_calc_harmonic_means.r", "max_forks_repo_name": "jdmanthey/camponotus_genomes1", "max_forks_repo_head_hexsha": "5caf349e3f84548e24da239d6d3fabca4171dcbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-01-29T16:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-29T16:29:49.000Z", "avg_line_length": 33.3472222222, "max_line_length": 307, "alphanum_fraction": 0.6597251145, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.022977372335312288, "lm_q1q2_score": 0.007687986171138551}} {"text": "# -------------------------------------------\n# App Title: Benford's Law and Data Examples\n# Author: Jimmy Doi\n# -------------------------------------------\n\nlibrary(RColorBrewer)\nlibrary(rvest)\nlibrary(xml2)\n\n##############################################################\n## US Census ##\n##############################################################\n\n########################################\n# Download complete data set from:\n# https://www.census.gov/data/datasets/2016/demo/popest/counties-total.html\n\ncomp.cens.data <- function(){\n\n vals <- as.matrix(read.csv(\"co-est2016-alldata.csv\", header=T))\n vals[,5] <- as.integer(vals[,5])\n vals <- vals[vals[,5]!=0,] #only leave county data\n\n return(vals)\n}\n\n########################################\ncens.data <- function(census.data,ID){\n\n sequence <- as.numeric(census.data[,ID])\n\n # Convert to scientific notation\n sequence <- format(sequence,scientific=TRUE)\n\n return(sequence)\n}\n\n##############################################################\n## Census Quick Facts ##\n##############################################################\n\n\n\n########################################\n# Download complete data set from:\n# quickfacts.census.gov/qfd/download/DataSet.txt\n\ncomp.quick.data <- function(){\n\n vals <- as.matrix(read.csv(\"DataSet.txt\", header=T))\n vals <- vals[vals[,1]%%1000!=0,] #only leave county data\n\n return(vals)\n}\n\n########################################\nquick.data <- function(census.data,ID){\n\n sequence <- as.numeric(census.data[,ID])\n\n # Convert to scientific notation\n sequence <- format(sequence,scientific=TRUE)\n\n return(sequence)\n}\n\n##############################################################\n## Stock Market ##\n##############################################################\n\n########################################\ncomp.data <- function(mkt){\n\n vals <- as.matrix(read.csv(paste(\"http://online.wsj.com/public/resources/documents/\",mkt,\".csv\",sep=\"\"), header=T,skip=3))\n\n return(vals)\n}\n\n########################################\ndate.data <- function(){\n date1 <- as.matrix(read.csv(\"http://online.wsj.com/public/resources/documents/NYSE.csv\",header=F,skip=1, nrows=1))\n date2 <- as.matrix(read.csv(\"http://online.wsj.com/public/resources/documents/Nasdaq.csv\",header=F,skip=1, nrows=1))\n date3 <- as.matrix(read.csv(\"http://online.wsj.com/public/resources/documents/SCAP.csv\",header=F,skip=1, nrows=1))\n date4 <- as.matrix(read.csv(\"http://online.wsj.com/public/resources/documents/AMEX.csv\",header=F,skip=1, nrows=1))\n\n min.length <- min(nchar(date1),nchar(date2),nchar(date3),nchar(date4))\n\n if (nchar(date1)==min.length) return(date1)\n else if (nchar(date2)==min.length) return(date2)\n else if (nchar(date3)==min.length) return(date3)\n else if (nchar(date4)==min.length) return(date4)\n}\n\n\n##############################################################\n## World Stock Market ##\n##############################################################\n\n########################################\nw.comp.data <- function(mkt){\n url <- paste(\"https://www.investing.com/indices/\",mkt,sep=\"\")\n\n #vals <- as.matrix(read.csv(paste(\"http://online.wsj.com/public/resources/documents/\",mkt,\".csv\",sep=\"\"), header=T,skip=3))\n\n vals <- url %>%\n read_html() %>%\n html_nodes(xpath='//*[@id=\"cr1\"]') %>%\n html_table()\n\n vals <- vals[[1]]\n\n # Following line removes any \"0 volume\" stocks, but at\n # some points of the day volume can be 0 for all stocks\n # and that would lead to NO STOCKS READ\n #\n # vals<-vals[which(vals[,8]!=0),]\n\n return(vals)\n}\n\n########################################\nw.status <- function(mkt){\n url <- paste(\"https://www.investing.com/indices/\",mkt,sep=\"\")\n\n my.status <- url %>%\n read_html() %>%\n html_nodes(xpath='//*[@id=\"quotes_summary_current_data\"]/div[1]/div[2]/div[2]/text()') %>%\n html_text()\n\n status <- \"ACTIVE\"\n if (length(grep(\"Closed\",my.status[3]))) status <- \"CLOSED\"\n\n return(status)\n}\n\n########################################\nseq.data <- function(all.data,var){\n\n # Use gsub() to remove embedded commas if any (for volume data)\n # Will not alter data without embedded commas (open, high, low, close)\n sequence <- as.numeric(gsub(\",\",\"\",all.data[,var]))\n\n # Convert to scientific notation\n sequence <- format(sequence,scientific=TRUE)\n\n return(sequence)\n\n}\n\n########################################\ngoodness.test <- function(sequence){\n\n string <- substr(as.character(sequence),1,1)\n\n first.digits <- as.integer(string)\n\n # In the event any of the 9 possible digits is not observed in the string,\n # table(first.digits) will not display all digits 1, 2, ..., 9. An example is\n #\n # NAME 1 2 3 4 5 6 7 9\n # FREQ 12 11 9 8 6 5 4 2\n #\n # Here, obs <- as.integer(table(first.digits)) would only contain 8 elements.\n # To correct for this, initialize obs to a zero vector, loop through NAME,\n # find FREQ corresponding to NAME,then paste that FREQ in obs[NAME].\n # This will also work for the case when all 9 possible digits are observed.\n\n Obs <- seq(0,0,,9)\n\n for (i in as.numeric(names(table(first.digits)))) {\n pos <- which(as.numeric(names(table(first.digits)))==i)\n Obs[i]<- as.numeric(table(first.digits))[pos]\n }\n i <- seq(1,9)\n\n Exp <- sum(Obs)*log10(1+1/i)\n\n Digit <- seq(1,9)\n\n #print(info)\n\n chisq <- sum(((Obs-Exp)**2)/Exp)\n\n Exp <- round(Exp,3)\n info <- cbind(Digit,Obs,Exp)\n rownames(info)<-rep(\"\",nrow(info))\n\n #print(chisq)\n\n p.value <- 1-pchisq(chisq,8)\n\n text.chi <- paste(\"Chi-Square=\",format(round(chisq,3),nsmall=3),sep=\"\")\n names(text.chi)<-\"\"\n\n text.pval <- paste(\"P-Value=\",format(round(p.value,3),nsmall=3),sep=\"\")\n names(text.pval)<-\"\"\n\n print(info)\n print(text.chi,quote=F)\n print(text.pval,quote=F)\n\n}\n\n############################################\npmf.compare<-function(sequence){\n\n string <- substr(as.character(sequence),1,1)\n\n first.digits <- as.integer(string)\n\n # In the event any of the 9 possible digits is not observed in the string,\n # table(first.digits) will not display all digits 1, 2, ..., 9. An example is\n #\n # NAME 1 2 3 4 5 6 7 9\n # FREQ 12 11 9 8 6 5 4 2\n #\n # Here, obs <- as.integer(table(first.digits)) would only contain 8 elements.\n # To correct for this, initialize obs to a zero vector, loop through NAME,\n # find FREQ corresponding to NAME,then paste that FREQ in obs[NAME].\n # This will also work for the case when all 9 possible digits are observed.\n\n Obs <- seq(0,0,,9)\n\n for (i in as.numeric(names(table(first.digits)))) {\n pos <- which(as.numeric(names(table(first.digits)))==i)\n Obs[i]<- as.numeric(table(first.digits))[pos]\n }\n i <- seq(1,9)\n\n pmf.Exp <- cbind(seq(1,9)+0.065,log10(1+1/i))\n pmf.Obs <- cbind(seq(1,9)-0.065,Obs/sum(Obs))\n\n col1 <- brewer.pal(n = 8, name = \"Dark2\")[6]\n col2 <- brewer.pal(n = 8, name = \"Dark2\")[1]\n\n par(mar=c(3.5,4.5,2,0))\n\n my.lwd <- 3.75\n\n if (max(pmf.Obs[,2])>=max(pmf.Exp[,2])){\n plot(pmf.Obs[,1],pmf.Obs[,2],type=\"n\",col=col1,xlim=c(0.75,9.25),\n ylim=c(0,max(pmf.Obs[,2])),\n xlab=\"\",ylab=\"Proportion\", xaxt=\"n\", main=\"Proportion of First Digits\")\n axis(1, at=seq(1,9), labels=c(\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"))\n mtext(\"First Digit\",1,line=2.5)\n for (i in 1:nrow(pmf.Obs)){\n lines(c(pmf.Obs[i,1],pmf.Obs[i,1]),c(0,pmf.Obs[i,2]),col=col1,lwd=my.lwd)\n }\n for (i in 1:nrow(pmf.Exp)){\n lines(c(pmf.Exp[i,1],pmf.Exp[i,1]),c(0,pmf.Exp[i,2]),col=col2,lwd=my.lwd)\n legend(\"topright\", inset=.02,\n c(\"Observed Proportion\",\"Benford's Law\"), fill=c(col1,col2), horiz=F)\n }\n }\n\n if (max(pmf.Obs[,2])