1)\n\tncu = min0(n,p)\nif (jobu!=0)\n\twantu = .true.\nif (mod(job,10)!=0)\n\twantv = .true.\ninfo = 0\nnct = min0(n-1,p)\nnrt = max0(0,min0(p-2,n))\nlu = max0(nct,nrt)\nif (lu>=1)\n\tdo l = 1,lu {\n\t\tlp1 = l+1\n\t\tif (l<=nct) {\n\t\t\ts(l) = dnrm2(n-l+1,x(l,l),1)\n\t\t\tif (s(l)!=0.0d0) {\n\t\t\t\tif (x(l,l)!=0.0d0)\n\t\t\t\t\ts(l) = dsign(s(l),x(l,l))\n\t\t\t\tcall dscal(n-l+1,1.0d0/s(l),x(l,l),1)\n\t\t\t\tx(l,l) = 1.0d0+x(l,l)\n\t\t\t\t}\n\t\t\ts(l) = -s(l)\n\t\t\t}\n\t\tif (p>=lp1)\n\t\t\tdo j = lp1,p {\n\t\t\t\tif (l<=nct)\n\t\t\t\t\tif (s(l)!=0.0d0) {\n\t\t\t\t\t\tt = -ddot(n-l+1,x(l,l),1,x(l,j),1)/x(l,l)\n\t\t\t\t\t\tcall daxpy(n-l+1,t,x(l,l),1,x(l,j),1)\n\t\t\t\t\t\t}\n\t\t\t\te(j) = x(l,j)\n\t\t\t\t}\n\t\tif (wantu&&l<=nct)\n\t\t\tdo i = l,n\n\t\t\t\tu(i,l) = x(i,l)\n\t\tif (l<=nrt) {\n\t\t\te(l) = dnrm2(p-l,e(lp1),1)\n\t\t\tif (e(l)!=0.0d0) {\n\t\t\t\tif (e(lp1)!=0.0d0)\n\t\t\t\t\te(l) = dsign(e(l),e(lp1))\n\t\t\t\tcall dscal(p-l,1.0d0/e(l),e(lp1),1)\n\t\t\t\te(lp1) = 1.0d0+e(lp1)\n\t\t\t\t}\n\t\t\te(l) = -e(l)\n\t\t\tif (lp1<=n&&e(l)!=0.0d0) {\n\t\t\t\tdo i = lp1,n\n\t\t\t\t\twork(i) = 0.0d0\n\t\t\t\tdo j = lp1,p\n\t\t\t\t\tcall daxpy(n-l,e(j),x(lp1,j),1,work(lp1),1)\n\t\t\t\tdo j = lp1,p\n\t\t\t\t\tcall daxpy(n-l,-e(j)/e(lp1),work(lp1),1,x(lp1,j),1)\n\t\t\t\t}\n\t\t\tif (wantv)\n\t\t\t\tdo i = lp1,p\n\t\t\t\t\tv(i,l) = e(i)\n\t\t\t}\n\t\t}\nm = min0(p,n+1)\nnctp1 = nct+1\nnrtp1 = nrt+1\nif (nct=nctp1)\n\t\tdo j = nctp1,ncu {\n\t\t\tdo i = 1,n\n\t\t\t\tu(i,j) = 0.0d0\n\t\t\tu(j,j) = 1.0d0\n\t\t\t}\n\tif (nct>=1)\n\t\tdo ll = 1,nct {\n\t\t\tl = nct-ll+1\n\t\t\tif (s(l)==0.0d0) {\n\t\t\t\tdo i = 1,n\n\t\t\t\t\tu(i,l) = 0.0d0\n\t\t\t\tu(l,l) = 1.0d0\n\t\t\t\t}\n\t\t\telse {\n\t\t\t\tlp1 = l+1\n\t\t\t\tif (ncu>=lp1)\n\t\t\t\t\tdo j = lp1,ncu {\n\t\t\t\t\t\tt = -ddot(n-l+1,u(l,l),1,u(l,j),1)/u(l,l)\n\t\t\t\t\t\tcall daxpy(n-l+1,t,u(l,l),1,u(l,j),1)\n\t\t\t\t\t\t}\n\t\t\t\tcall dscal(n-l+1,-1.0d0,u(l,l),1)\n\t\t\t\tu(l,l) = 1.0d0+u(l,l)\n\t\t\t\tlm1 = l-1\n\t\t\t\tif (lm1>=1)\n\t\t\t\t\tdo i = 1,lm1\n\t\t\t\t\t\tu(i,l) = 0.0d0\n\t\t\t\t}\n\t\t\t}\n\t}\nif (wantv)\n\tdo ll = 1,p {\n\t\tl = p-ll+1\n\t\tlp1 = l+1\n\t\tif (l<=nrt)\n\t\t\tif (e(l)!=0.0d0)\n\t\t\t\tdo j = lp1,p {\n\t\t\t\t\tt = -ddot(p-l,v(lp1,l),1,v(lp1,j),1)/v(lp1,l)\n\t\t\t\t\tcall daxpy(p-l,t,v(lp1,l),1,v(lp1,j),1)\n\t\t\t\t\t}\n\t\tdo i = 1,p\n\t\t\tv(i,l) = 0.0d0\n\t\tv(l,l) = 1.0d0\n\t\t}\nmm = m\niter = 0\nrepeat {\n\tif (m==0)\n\t\treturn\n\tif (iter>=maxit)\n\t\tbreak 1\n\tdo ll = 1,m {\n\t\tl = m-ll\n\t\tif (l==0)\n\t\t\tbreak 1\n\t\ttest = dabs(s(l))+dabs(s(l+1))\n\t\tztest = test+dabs(e(l))\n\t\tif (ztest==test)\n\t\t\tgo to 150\n\t\t}\n\tgo to 160\n\t150 e(l) = 0.0d0\n\t160 if (l==m-1)\n\t\tkase = 4\n\telse {\n\t\tlp1 = l+1\n\t\tmp1 = m+1\n\t\tdo lls = lp1,mp1 {\n\t\t\tls = m-lls+lp1\n\t\t\tif (ls==l)\n\t\t\t\tbreak 1\n\t\t\ttest = 0.0d0\n\t\t\tif (ls!=m)\n\t\t\t\ttest = test+dabs(e(ls))\n\t\t\tif (ls!=l+1)\n\t\t\t\ttest = test+dabs(e(ls-1))\n\t\t\tztest = test+dabs(s(ls))\n\t\t\tif (ztest==test)\n\t\t\t\tgo to 170\n\t\t\t}\n\t\tgo to 180\n\t\t170 s(ls) = 0.0d0\n\t\t180 if (ls==l)\n\t\t\tkase = 3\n\t\telse if (ls==m)\n\t\t\tkase = 1\n\t\telse {\n\t\t\tkase = 2\n\t\t\tl = ls\n\t\t\t}\n\t\t}\n\tl = l+1\n\tswitch(kase) {\n\t\tcase 1:\n\t\t\tmm1 = m-1\n\t\t\tf = e(m-1)\n\t\t\te(m-1) = 0.0d0\n\t\t\tdo kk = l,mm1 {\n\t\t\t\tk = mm1-kk+l\n\t\t\t\tt1 = s(k)\n\t\t\t\tcall drotg(t1,f,cs,sn)\n\t\t\t\ts(k) = t1\n\t\t\t\tif (k!=l) {\n\t\t\t\t\tf = -sn*e(k-1)\n\t\t\t\t\te(k-1) = cs*e(k-1)\n\t\t\t\t\t}\n\t\t\t\tif (wantv)\n\t\t\t\t\tcall drot(p,v(1,k),1,v(1,m),1,cs,sn)\n\t\t\t\t}\n\t\tcase 2:\n\t\t\tf = e(l-1)\n\t\t\te(l-1) = 0.0d0\n\t\t\tdo k = l,m {\n\t\t\t\tt1 = s(k)\n\t\t\t\tcall drotg(t1,f,cs,sn)\n\t\t\t\ts(k) = t1\n\t\t\t\tf = -sn*e(k)\n\t\t\t\te(k) = cs*e(k)\n\t\t\t\tif (wantu)\n\t\t\t\t\tcall drot(n,u(1,k),1,u(1,l-1),1,cs,sn)\n\t\t\t\t}\n\t\tcase 3:\n\t\t\tscale = dmax1(dabs(s(m)),dabs(s(m-1)),dabs(e(m-1)),dabs(s(l)),dabs(e(l)))\n\t\t\tsm = s(m)/scale\n\t\t\tsmm1 = s(m-1)/scale\n\t\t\temm1 = e(m-1)/scale\n\t\t\tsl = s(l)/scale\n\t\t\tel = e(l)/scale\n\t\t\tb = ((smm1+sm)*(smm1-sm)+emm1**2)/2.0d0\n\t\t\tc = (sm*emm1)**2\n\t\t\tshift = 0.0d0\n\t\t\tif (b!=0.0d0||c!=0.0d0) {\n\t\t\t\tshift = dsqrt(b**2+c)\n\t\t\t\tif (b<0.0d0)\n\t\t\t\t\tshift = -shift\n\t\t\t\tshift = c/(b+shift)\n\t\t\t\t}\n\t\t\tf = (sl+sm)*(sl-sm)+shift\n\t\t\tg = sl*el\n\t\t\tmm1 = m-1\n\t\t\tdo k = l,mm1 {\n\t\t\t\tcall drotg(f,g,cs,sn)\n\t\t\t\tif (k!=l)\n\t\t\t\t\te(k-1) = f\n\t\t\t\tf = cs*s(k)+sn*e(k)\n\t\t\t\te(k) = cs*e(k)-sn*s(k)\n\t\t\t\tg = sn*s(k+1)\n\t\t\t\ts(k+1) = cs*s(k+1)\n\t\t\t\tif (wantv)\n\t\t\t\t\tcall drot(p,v(1,k),1,v(1,k+1),1,cs,sn)\n\t\t\t\tcall drotg(f,g,cs,sn)\n\t\t\t\ts(k) = f\n\t\t\t\tf = cs*e(k)+sn*s(k+1)\n\t\t\t\ts(k+1) = -sn*e(k)+cs*s(k+1)\n\t\t\t\tg = sn*e(k+1)\n\t\t\t\te(k+1) = cs*e(k+1)\n\t\t\t\tif (wantu&&k=s(l+1))\n\t\t\t\t\tbreak 1\n\t\t\t\tt = s(l)\n\t\t\t\ts(l) = s(l+1)\n\t\t\t\ts(l+1) = t\n\t\t\t\tif (wantv&&l0; j = j-1) {\n\tif (x(j,j)==0.0d0)\n\t\t{info = j; break}\n\tfor(l=1; l<=q; l = l+1) {\n\tb(j,l) = b(j,l)/x(j,j)\n\tif (j!=1) {\n\t\tt = -b(j,l)\n\t\tcall daxpy(j-1,t,x(1,j),1,b(1,l),1)\n\t\t}\n\t}\n}\nreturn\nend\n\nsubroutine dtrsl(t,ldt,n,b,job,info)\ninteger ldt,n,job,info\ndouble precision t(ldt,*),b(*)\ndouble precision ddot,temp\ninteger which,j,jj\n# check for zero diagonal elements.\ndo info = 1,n\n\tif (t(info,info)==0.0d0)\n\t\treturn\ninfo = 0\n# determine the task and go to it.\nwhich = 1\nif (mod(job,10)!=0)\n\twhich = 2\nif (mod(job,100)/10!=0)\n\twhich = which+2\nswitch(which) {\n\tcase 1:\n\t\tb(1) = b(1)/t(1,1)\n\t\tif (n>=2)\n\t\t\tdo j = 2,n {\n\t\t\t\ttemp = -b(j-1)\n\t\t\t\tcall daxpy(n-j+1,temp,t(j,j-1),1,b(j),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\tcase 2:\n\t\tb(n) = b(n)/t(n,n)\n\t\tif (n>=2)\n\t\t\tdo jj = 2,n {\n\t\t\t\tj = n-jj+1\n\t\t\t\ttemp = -b(j+1)\n\t\t\t\tcall daxpy(j,temp,t(1,j+1),1,b(1),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\tcase 3:\n\t\tb(n) = b(n)/t(n,n)\n\t\tif (n>=2)\n\t\t\tdo jj = 2,n {\n\t\t\t\tj = n-jj+1\n\t\t\t\tb(j) = b(j)-ddot(jj-1,t(j+1,j),1,b(j+1),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\tcase 4:\n\t\tb(1) = b(1)/t(1,1)\n\t\tif (n>=2)\n\t\t\tdo j = 2,n {\n\t\t\t\tb(j) = b(j)-ddot(j-1,t(1,j),1,b(1),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\t}\nreturn\nend\n", "meta": {"hexsha": "de4a18f0739db3326fe73a022b87c187ee407b1b", "size": 48591, "ext": "r", "lang": "R", "max_stars_repo_path": "gam/ratfor/linear.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gam/ratfor/linear.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "gam/ratfor/linear.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 19.0105633803, "max_line_length": 97, "alphanum_fraction": 0.4581301064, "num_tokens": 22258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.37694836270179066}}
{"text": "library(tidyverse)\n\n# データ読み込み\ndata <- read_csv(\"Hackathon_Ideal_Data.csv\")\n\n# ビスケットのデータを取り出す\ndata_biscuits <- data %>% filter(GRP == \"BISCUITS - CORE & NON CORE\")\n\n## 前処理\n\n# ブランドをメーカーブランドにまとめる(ブランドにフレーバー含まれることあるため)\ndata_biscuits_agg <- data_biscuits %>% \n group_by(MONTH, STORECODE, SGRP, CMP, MBRD) %>% \n summarise(across(c(QTY, VALUE), sum), .groups=\"drop\") %>% \n filter(QTY > 0) # 数量が1以上のレコードだけ残す\n\n# 同じメーカーブランドでも企業名やジャンルが違うレコードあるか確認\ndata_biscuits_agg %>% distinct(SGRP, CMP, MBRD) %>% group_by(MBRD) %>% filter(n() > 1)\n\n# メーカーの表記ゆれと同一ブランドでも違うジャンルのものがあることがわかった\n# 前処理してからもう一度メーカブランドにまとめる処理する\ndata_biscuits <- data_biscuits %>% \n # メーカーの表記ゆれ直す\n mutate(CMP = case_when(\n CMP == \"KAIRA DISTRICT CO-OP MILK\" ~ \"G C M M F\",\n CMP == \"CHAMPION\" ~ \"SUKHDATA FOODS\",\n CMP == \"PATANJALI AYURVED LTD\" ~ \"PATANJALI BISCUITS PVT LTD\",\n CMP == \"PICKWICK HYGIENIC PRODUCTS\" ~ \"PRIMLAKS\",\n TRUE ~ CMP\n )) %>% \n # メーカブランド名にジャンルも含める\n mutate(MBRD2 = paste0(MBRD, \" (\", SGRP, \")\")) %>% \n # 集計\n group_by(MONTH, STORECODE, SGRP, CMP, MBRD2) %>% \n summarise(across(c(QTY, VALUE), sum), .groups=\"drop\") %>% \n filter(QTY > 0, VALUE > 0) # 数量および金額が0より大きい\n\n# いずれかの月において1店舗でしか販売されていない商品\nbiscuits_only1shop <- data_biscuits %>% \n distinct(MONTH, STORECODE, MBRD2) %>% \n group_by(MONTH, MBRD2) %>% \n filter(n() == 1) %>% \n ungroup() %>% \n distinct(MBRD2) %>% \n pull()\n\n# いずれかの月において1店舗でしか販売されていない商品をデータから除く\ndata_biscuits <- data_biscuits %>% \n filter(!(MBRD2 %in% biscuits_only1shop))\n\n## データ構築\n\n# 潜在的市場規模\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, STORECODE) %>% \n mutate(quantity_total = sum(QTY)) %>% # 各市場の総売上数量\n group_by(STORECODE) %>% \n mutate(market_size = max(quantity_total) * 2) %>% #各店舗の最大総売上数量の2倍を潜在的市場規模とする\n ungroup()\n\n# シェアの列作る\ndata_biscuits <- data_biscuits %>% \n mutate(share = QTY / market_size) %>% # シェア\n group_by(MONTH, STORECODE) %>% \n mutate(outshare = 1 - sum(share)) %>% # 「何も買わない」のシェア\n ungroup()\n\n# 価格の列作る\ndata_biscuits <- data_biscuits %>% \n mutate(price = VALUE / QTY)\n\n# 価格の操作変数として各商品の同月他店舗平均価格\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, MBRD2) %>% \n mutate(price_instruments = (sum(price) - price) / (n() - 1)) %>% \n ungroup()\n\n# グループ内シェア\n# ジャンルをグループにする\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, STORECODE, SGRP) %>% \n mutate(within_share = share / sum(share)) %>% \n ungroup()\n\n# グループ内シェアの操作変数として各商品の同月他店舗平均グループ内シェア\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, MBRD2) %>% \n mutate(within_share_instruments = (sum(within_share) - within_share) / (n() - 1)) %>% \n ungroup()\n\n## plain logit推定\n\nplain_logit <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) | log(price_instruments),\n data = data_biscuits,\n fixed_effects = ~ MBRD2,\n clusters = MBRD2,\n se_type = 'stata'\n)\n\nsummary(plain_logit) # 推定結果\n\n## plain logit 反実仮想\n\n# 予測値を出すために商品ダミーを明示的に説明変数に入れる\nplain_logit_prediction <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) + factor(MBRD2) | log(price_instruments) + factor(MBRD2),\n data = data_biscuits\n)\n\n# オレオの価格を20%安くしてみる\ndata_biscuits_counterfactual_plain <- data_biscuits %>% \n mutate(price_original = price, # 元の価格を残す\n price = if_else(MBRD2 == \"OREO (CREAM)\", 0.8 * price, price))\n\n# 平均効用deltaを計算\ndelta_plain <- predict(plain_logit_prediction,\n newdata = data_biscuits_counterfactual_plain)\n\n# 反実仮想シェアを計算\ndata_biscuits_counterfactual_plain <- \n data_biscuits_counterfactual_plain %>% \n mutate(delta_counterfactual = delta_plain, # 反実仮想の平均効用\n delta_fitted = fitted(plain_logit) # 元の価格での平均効用のフィット\n ) %>%\n group_by(MONTH, STORECODE) %>% # 市場でグループ化\n # シェア計算\n mutate(share_counterfactual = exp(delta_counterfactual) / (1 + sum(exp(delta_counterfactual))),\n share_fitted = exp(delta_fitted) / (1 + sum(exp(delta_fitted)))) %>%\n ungroup() %>% \n # 数量と金額を計算\n mutate(quantity_counterfactual = share_counterfactual * market_size,\n quantity_fitted = share_fitted * market_size,\n value_counterfactual = price * quantity_counterfactual,\n value_fitted = price_original * quantity_fitted)\n\n# MONDELEZの実際の売上と反実仮想売上を比較\ndata_biscuits_counterfactual_plain %>% \n filter(CMP == \"MONDELEZ INTERNATIONAL\") %>% \n group_by(MBRD2) %>% \n summarise(across(c(QTY, quantity_fitted, quantity_counterfactual,\n VALUE, value_fitted, value_counterfactual),\n sum),\n .groups=\"drop\") %>% \n modelsummary::datasummary_df(fmt=1, output='markdown')\n\n## nested logit推定\n\nnested_logit <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) + log(within_share) | log(price_instruments) + log(within_share_instruments),\n data = data_biscuits,\n fixed_effects = MBRD2,\n clusters = MBRD2,\n se_type = 'stata')\n\nsummary(nested_logit) # 推定結果\n\n## nested logit 反実仮想\n\n# 予測値を出すために商品ダミーを明示的に説明変数に入れる\nnested_logit_prediction <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) + log(within_share) + factor(MBRD2) | log(price_instruments) + log(within_share_instruments) + factor(MBRD2),\n data = data_biscuits\n)\n\n# オレオの価格を20%安くしてみる\ndata_biscuits_counterfactual_nested <- data_biscuits %>% \n mutate(price_original = price,\n price = if_else(MBRD2 == \"OREO (CREAM)\", 0.8 * price, price))\n\n# 平均効用deltaを計算\n# モデルの予測値にはrho*log(within_share)の部分も含まれているのでそれを除く\nrho <- coef(nested_logit)['log(within_share)'] # rho\ndelta_nested <- \n predict(nested_logit_prediction, newdata = data_biscuits_counterfactual_nested) -\n rho * log(data_biscuits$within_share)\n\n# deltaとrhoの列を加える\ndata_biscuits_counterfactual_nested <- data_biscuits_counterfactual_nested %>% \n mutate(rho = rho,\n delta_counterfactual = delta_nested,\n delta_fitted = fitted(nested_logit) - rho * log(within_share))\n\n# 各グループの包括的価値(inclusive value)を計算する\ndata_biscuits_counterfactual_nested_inclusive <- data_biscuits_counterfactual_nested %>% \n group_by(MONTH, STORECODE, SGRP) %>% \n # 各グループの包括的価値\n summarise(inclusive_counterfactual = sum(exp(delta_counterfactual / (1 - rho))),\n inclusive_fitted = sum(exp(delta_fitted / (1 - rho))),\n .groups=\"drop\") %>%\n mutate(rho = rho) %>% \n group_by(MONTH, STORECODE) %>% \n # 包摂的価値の市場内集計\n mutate(inclusive_counterfactual_sum = 1 + sum(inclusive_counterfactual^(1-rho)),\n inclusive_fitted_sum = 1 + sum(inclusive_fitted^(1-rho))) %>%\n ungroup() %>% \n select(!rho)\n\n# 元のデータフレームに包摂的価値を引っ付ける\ndata_biscuits_counterfactual_nested <- data_biscuits_counterfactual_nested %>% \n left_join(data_biscuits_counterfactual_nested_inclusive, by = c(\"MONTH\", \"STORECODE\", \"SGRP\"))\n\n# 予測シェアと数量と売上金額を計算\ndata_biscuits_counterfactual_nested <- data_biscuits_counterfactual_nested %>% \n mutate(share_counterfactual = exp(delta_counterfactual / (1 - rho)) / (inclusive_counterfactual^rho * inclusive_counterfactual_sum),\n share_fitted = exp(delta_fitted / (1 - rho)) / (inclusive_fitted^rho * inclusive_fitted_sum),\n quantity_counterfactual = share_counterfactual * market_size,\n quantity_fitted = share_fitted * market_size,\n value_counterfactual = price * quantity_counterfactual,\n value_fitted = price_original * quantity_fitted)\n\n# MONDELEZの実際の売上と反実仮想売上を比較\ndata_biscuits_counterfactual_nested %>% \n filter(CMP == \"MONDELEZ INTERNATIONAL\") %>% \n group_by(MBRD2) %>% \n summarise(across(c(QTY, quantity_fitted, quantity_counterfactual,\n VALUE, value_fitted, value_counterfactual),\n sum),\n .groups=\"drop\") %>% \n modelsummary::datasummary_df(fmt=1)\n", "meta": {"hexsha": "e1274f9d33a8cf112ac41694f65a85106ab143ca", "size": 7558, "ext": "r", "lang": "R", "max_stars_repo_path": "demand_estimation.r", "max_stars_repo_name": "mns54/tokyor-demand-estimation", "max_stars_repo_head_hexsha": "27aeb9d7a5585e0174a5f9ecfaf6a2d407f9cdf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-29T07:02:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T18:38:42.000Z", "max_issues_repo_path": "demand_estimation.r", "max_issues_repo_name": "mns54/tokyor-demand-estimation", "max_issues_repo_head_hexsha": "27aeb9d7a5585e0174a5f9ecfaf6a2d407f9cdf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demand_estimation.r", "max_forks_repo_name": "mns54/tokyor-demand-estimation", "max_forks_repo_head_hexsha": "27aeb9d7a5585e0174a5f9ecfaf6a2d407f9cdf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1990950226, "max_line_length": 161, "alphanum_fraction": 0.7013760254, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3768863999423516}}
{"text": "\n## ########################################### ##\n## SOFTWARE LICENSE AGREEMENT ##\n## ########################################### ##\n\n# This work is licensed under a Creative Commons Attribution 4.0 International License.\n# See http://creativecommons.org/licenses/by/4.0/ for details on license restrictions.\n# Please attribute any work that makes use or is derived from this work\n# by refering to https://github.com/jalmar/openmx-models\n\n\n## ########################################### ##\n## DESCRIPTION OF FILE ##\n## ########################################### ##\n\n# In this R script, a measurement model with two latent factors (nf=2) is provided.\n# This measurement model can be used to obtain a estimate of the association between\n# the reliable components of two constructs that is free of random measurement error.\n# In this example, there are two constructs with a total of three observed variables (nv=3).\n# Two parallel scores \"M1_H1\" and \"M1_H2\" are available for the first construct \"M1\".\n# The first latent factor \"F1\" is derived from these two parallel scores.\n# Since the two parallel scores are measurements of the same construct,\n# their expected means are constrained to be equal.\n# The second latent factor \"F1\" is derived from the single score of the second construct \"M2\".\n# If there are repeated measurements of the second construct \"M2\", the measurement model\n# can easily be expanded for reliablity modelling of the second construct \"M2\".\n# The quality of the fit is assessed with the Comparative Fit Index (CFI),\n# the Tucker-Lewis Index (TLI), and the Root Mean Square Error of the Approximation (RMSEA).\n# These fit indices are based on the comparison between the measurement model to\n# a saturated model and an independence (or null) model. The saturated model is a model that\n# estimates all means, variances and covariances freely for all variables (i.e. unconstrained).\n# The independence model estimates only the means and variances with covariances fixed to zero.\n# Finally, a summary of the most relevant parameters is printed.\n# For more details, see https://github.com/jalmar/openmx-models/reliability\n\n\n## ############################################################################\n\n\n## ########################################### ##\n## LOAD LIBRARIES AND SET OPTIONS ##\n## ########################################### ##\n\n## load OpenMx library\nrequire(OpenMx) # SEM\noptions(warn=1)\n\n\n## ########################################### ##\n## INPUT DATASETS AND SELECTED VARIABLES ##\n## ########################################### ##\n\n## INPUT: a data frame data_df with the parallel and single scores measurements\ndata_df <- readRDS(\"ExampleData.rds\")\nselVars <- c(\"FC_Z_H1\", \"FC_Z_H2\", \"BHV\")\n\n\n## ########################################### ##\n## CALCULATE MEANS AND (CO)VARIANCES ##\n## ########################################### ##\n\n## calculate initial mean and variance of measures\ninit_means <- apply(data_df[,selVars, drop=F], 2, mean, na.rm=T)\ninit_vars <- apply(data_df[,selVars, drop=F], 2, var, na.rm=T)\ninit_sds <- apply(data_df[,selVars, drop=F], 2, sd, na.rm=T)\n\n## calculate initial covariance matrices between measures\ninit_covars <- var(data_df[,selVars, drop=F], na.rm=T)\ninit_corrs <- cor(data_df[,selVars, drop=F], method=\"pearson\", use=\"pairwise.complete.obs\")\n\n\n## ########################################### ##\n## MEASUREMENT MODEL PARAMETERS ##\n## ########################################### ##\n\n## number of observed variables\nnf=2 # number of factors\nnv=3 # number of measurements\n\n## initial guess at factor variances [nf x nf matrices]; NOTE: standardized symmetric matrix with variances on diagnoal fixed to 1.0!\n# initialize with rough estimate of expected correlation; e.g. corr(M1_H1, M2)\ninit_factor_variance_values = c(1.0, 0.5,\n 0.5, 1.0)\ninit_factor_variance_paths = c(F, T,\n T, F)\ninit_factor_variance_labels = c(\"varF1\", \"covF12\",\n \"covF12\", \"varF2\")\n\n## loading of factors on the measures [nf x nv matrices]:\n# factor 1 loads on the two parallel scores of measure 1\n# factor 2 loads on the single score of measure 2\n# initialize with rough estimate of factor loadings; e.g. cov(M1_H1, M1_H2))\ninit_factor_loading_values = c(0.70, 0.70, 0.00, # factor 1\n 0.00, 0.00, 1.00) # factor 2\ninit_factor_loading_paths = c(T, T, F, # factor 1\n F, F, F) # factor 2; NOTE: third position fixed for single score measurement\ninit_factor_loading_labels = c(\"f1\", \"f1\", NA, # factor 1\n NA, NA, \"f2\") # factor 2\n\n## loadings of residual variances on the measures [1 x nv matrices]\n# initialize with rough estimate of residual variance; e.g. 1 - sqrt(corr(M1_H1, M1_H2)) or 1 - factor loading\ninit_es_loading_values = c(0.30, 0.30, 0.00)\ninit_es_loading_paths = c(T, T, F) # NOTE: third position fixed for single score measurement\ninit_es_loading_labels = paste0(\"es\", 1:nv)\n\n## restrict the means of variables to be equal through shared labels [1 x nv matrices]\n# Here, the means for parallel scores of the same construct are contrained to be equal\ninit_means_labels = c(\"mean_FC_Z\", \"mean_FC_Z\", \"mean_BHV\")\n\n\n## ########################################### ##\n## OPENMX SPECIFICATION OF MEASUREMENT MODEL ##\n## ########################################### ##\n\n## measurement model\nMeasurementModel <- mxModel(\"mm\",\n \n # variance matrix Vf to store total variance for latent phenotypic factor; NOTE: standardized with variance on diagonals fixed to 1.0\n mxMatrix(type=\"Full\", nrow=nf, ncol=nf, free=init_factor_variance_paths, values=init_factor_variance_values, labels=init_factor_variance_labels, name=\"Vf\", lbound=-1, ubound=1),\n \n # matrices for correlations between latent factors (only nf>1)\n mxMatrix(type=\"Iden\", ncol=nf, nrow=nf, name=\"Idnf\"), # identity matrix of size nf x nf\n mxAlgebra(expression=solve(sqrt(Idnf*Vf)) %*% Vf %*% solve(sqrt(Idnf*Vf)), name=\"Rphf\"),\n \n # matrix fs to store path coefficients for latent phenotypic factors loading on observed variables\n mxMatrix(type=\"Full\", nrow=nv, ncol=nf, free=init_factor_loading_paths, values=init_factor_loading_values*init_vars, labels=init_factor_loading_labels, name=\"fs\", lbound=0),\n \n # matrix es to store path coefficients for measurement-specific factors loading on each measurement; NOTE: fixing off-diagonals to zero assumes no correlation between residual variances of measurements\n mxMatrix(type=\"Diag\", nrow=nv, ncol=nv, free=init_es_loading_paths, values=init_es_loading_values*init_vars, labels=init_es_loading_labels, name=\"es\", lbound=0),\n \n # matrix Es to store variance for measurement-specific factors\n mxAlgebra(expression=es%*%t(es), name=\"Es\"),\n \n # total variance of the measures is the proportion of variance explained by the factor(s) plus residual variances\n mxAlgebra(expression=fs%&%Vf+Es, name=\"Vm\"), # (co)variances between the measures\n mxMatrix(type=\"Iden\", nrow=nv, ncol=nv, free=F, name=\"Inv\"),\n mxAlgebra(expression=solve(sqrt(Inv*Vm)), name=\"SDm\"), # standard deviation of the measures\n \n # phenotypic correlation between measures\n mxAlgebra(expression=solve(sqrt(Inv*Vm)) %*% Vm %*% solve(sqrt(Inv*Vm)), name=\"Rphm\"),\n \n # standardized estimates for loadings on latent factor\n mxAlgebra(expression=SDm%*%fs, \"Fs_std\"),\n mxAlgebra(expression=Fs_std*Fs_std, \"Fs_std2\"),\n \n # standardized estimates for measurement-specific factors\n mxAlgebra(expression=SDm%*%es, name=\"Es_std\"),\n mxAlgebra(expression=Es_std*Es_std, name=\"Es_std2\"),\n \n # observed data of subjects\n mxData(observed=data_df, type=\"raw\"),\n \n # expected means vector\n mxMatrix(type=\"Full\", nrow=1, ncol=nv, free=T, values=init_means, labels=init_means_labels, name=\"expMeans\"),\n \n # expected covariance matrix; NOTE: %&% is quadratic product (A %&% B == ABA'); same as Vm\n mxAlgebra(expression=mm.fs %&% mm.Vf + mm.Es, name=\"expCov\"),\n \n # optimization objective\n mxExpectationNormal(means=\"expMeans\", covariance=\"expCov\", dimnames=selVars),\n mxFitFunctionML(),\n \n # calculate confidence intervals of freely estimated parameters\n mxCI(sprintf(\"mm.Fs_std2[%s]\", apply(which(matrix(init_factor_loading_paths, nrow=nv, ncol=nf), arr.ind = TRUE), MARGIN=1, paste0, collapse=\",\")), interval = 0.95, type=\"both\"), # standardized factor loadings\n mxCI(sprintf(\"mm.Rphf[%s]\", apply(which(lower.tri(matrix(1,nf,nf)), arr.ind = TRUE), MARGIN=1, paste0, collapse=\",\")), interval = 0.95, type=\"both\"), # correlation between factors\n mxCI(sprintf(\"mm.Rphm[%s]\", apply(which(lower.tri(matrix(1,nv,nv)), arr.ind = TRUE), MARGIN=1, paste0, collapse=\",\")), interval = 0.95, type=\"both\") # correlation between measures\n \n) # END of mxModel MeasurementModel\n\n## assign first value to parameters with same labels but different starting values\nMeasurementModel <- omxAssignFirstParameters(MeasurementModel)\n\n\n## ########################################### ##\n## FIT THE MEASUREMENT MODEL ##\n## ########################################### ##\n\nMeasurementModelFit <- mxTryHard(MeasurementModel, extraTries=30, checkHess=F, intervals=T, silent=T)\n\n\n## ########################################### ##\n## EXTRACT PARAMETERS OF INTEREST FROM MODEL ##\n## ########################################### ##\n\n## summary of measurement model model fit\nprint(summary(MeasurementModelFit))\n\n## corrected/reliable association between the two constructs\nmessage(sprintf(\"Corrected association between the two constructs = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphf[2,1], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphf[2,1]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphf[2,1]\",\"ubound\"]))\n\n## standardized factor loading on parallel scores of the first construct\nmessage(sprintf(\"Standardized factor loading on first parallel score = %2.1f%% [%2.1f%%; %2.1f%%]\", MeasurementModelFit$output$algebras$mm.Fs_std2[1,1]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[1,1]\",\"lbound\"]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[1,1]\",\"ubound\"]*100))\nmessage(sprintf(\"Standardized factor loading on second parallel score = %2.1f%% [%2.1f%%; %2.1f%%]\", MeasurementModelFit$output$algebras$mm.Fs_std2[2,1]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[2,1]\",\"lbound\"]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[2,1]\",\"ubound\"]*100))\n\n## test-retest reliability between the two parallel scores\nmessage(sprintf(\"Test-retest reliability between the two parallel scores = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphm[2,1], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[2,1]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[2,1]\",\"ubound\"]))\n\n## uncorrected associations of the individual parallel scores with the second measurement\nmessage(sprintf(\"Uncorrected association between the first parallel score and second construct = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphm[3,1], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,1]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,1]\",\"ubound\"]))\nmessage(sprintf(\"Uncorrected association between the second parallel score and second construct = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphm[3,2], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,2]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,2]\",\"ubound\"]))\n\n\n## ########################################### ##\n## DETERMINE GOODNESS OF FIT ##\n## ########################################### ##\n\n## specification of the saturated model\nSaturatedModel <- mxModel(\"sat\",\n \n # expected (co)variance matrix; unconstrained variances and covariance estimates\n mxMatrix(type=\"Symm\", nrow=nv, ncol=nv, free=T, values=vech(init_covars), name=\"expCov\"),\n \n # observed data of subjects\n mxData(observed=data_df, type=\"raw\"),\n \n # expected means vector; unconstrained means estimates\n mxMatrix(type=\"Full\", nrow=1, ncol=nv, free=T, values=init_means, labels=paste0(\"mean_m\",1:nv), name=\"expMeans\"),\n \n # optimization objective\n mxExpectationNormal(means=\"expMeans\", covariance=\"expCov\", dimnames=selVars),\n mxFitFunctionML()\n \n) # END of mxModel SaturatedModel\n\nSaturatedModel <- omxAssignFirstParameters(SaturatedModel)\n\n## specification of the independence/null model\nIndependenceModel <- mxModel(\"indep\",\n \n # expected (co)variance matrix; unconstrained variances and covariance estimates\n mxMatrix(type=\"Diag\", nrow=nv, ncol=nv, free=T, values=init_vars, name=\"expCov\"),\n \n # observed data of subjects\n mxData(observed=data_df, type=\"raw\"),\n \n # expected means vector; same means constraints as substantive model\n mxMatrix(type=\"Full\", nrow=1, ncol=nv, free=T, values=init_means, labels=init_means_labels, name=\"expMeans\"),\n \n # optimization objective\n mxExpectationNormal(means=\"expMeans\", covariance=\"expCov\", dimnames=selVars),\n mxFitFunctionML()\n \n) # END of mxModel IndependenceModel\n\nIndependenceModel <- omxAssignFirstParameters(IndependenceModel)\n\n## fit saturated and independence model\nSaturatedModelFit <- mxTryHard(SaturatedModel, extraTries=10, checkHess=F, intervals=F)\nIndependenceModelFit <- mxTryHard(IndependenceModel, extraTries=10, checkHess=F, intervals=F)\n\n## print goodness of fit indices\ntmp_summary <- summary(MeasurementModelFit, refModels=list(Saturated=SaturatedModelFit, Independence=IndependenceModelFit))\nmessage(sprintf(\"Goodness of fit indices are CFI=%0.3f, TLI=%0.3f, and RMSEA=%0.3f\", tmp_summary$CFI, tmp_summary$TLI, tmp_summary$RMSEA))\n\n", "meta": {"hexsha": "ff92a2e0dcea98605a1a22aa69a68e47a24d6ed3", "size": 13983, "ext": "r", "lang": "R", "max_stars_repo_path": "reliability/MeasurementModel.r", "max_stars_repo_name": "jalmar/openmx-models", "max_stars_repo_head_hexsha": "550ba901a395d793739b2d4dcb9163159848528f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-25T10:48:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T18:18:43.000Z", "max_issues_repo_path": "reliability/MeasurementModel.r", "max_issues_repo_name": "jalmar/openmx-models", "max_issues_repo_head_hexsha": "550ba901a395d793739b2d4dcb9163159848528f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reliability/MeasurementModel.r", "max_forks_repo_name": "jalmar/openmx-models", "max_forks_repo_head_hexsha": "550ba901a395d793739b2d4dcb9163159848528f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.8352941176, "max_line_length": 318, "alphanum_fraction": 0.6709575914, "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.37686967907388924}}
{"text": "#' Extract the midpoint of an interval assigned to a data frame.\r\n#'\r\n#' \\code{interval_mid} Calculates the mid-point of an interval to be used as an\r\n#' attractive label for plot axes when binning an axis. Intervals as defined by\r\n#' functions such as base-R \\code{\\link{cut}}.\r\n#'\r\n#' @author Alex M Trueman\r\n#'\r\n#' @param x A numeric vector or data frame column with intervals typically\r\n#' applied using the base-R \\code{cut} function.\r\n#' @param dp A numeric scalar (default 1) defining the number of decimal places\r\n#' for the base-R \\code{round} function. May be needed to ensure that\r\n#' mid-points are unique.\r\n#' @return A numeric vector containing the mid points of the intervals.\r\n#' @keywords internal\r\ninterval_mid <- function(x, dp = 1) {\r\n # Extract lower and upper bounds of the intervals.\r\n lower <- as.double(gsub(\",.*\", \"\", gsub(\"\\\\(|\\\\[|\\\\)|\\\\]\", \"\", x)))\r\n upper <- as.double(gsub(\".*,\", \"\", gsub(\"\\\\(|\\\\[|\\\\)|\\\\]\", \"\", x)))\r\n # Return midpoint.\r\n return(as.double(round(lower + (upper - lower) / 2, dp)))\r\n}\r\n\r\n#' Calculate Data for Contact Analysis\r\n#'\r\n#' \\code{contact_data} generates data from domain-coded drillhole data suitable\r\n#' for plotting contact analysis plots. For each possible pairing of categorical\r\n#' domain codes it reports the distance and grade of drillhole samples from each\r\n#' contact of the domain pairing. The distance for the first domain in the\r\n#' pairing ('left' side) is reported as a negative distance for plotting\r\n#' purposes.\r\n#'\r\n#' Uses nested for loops, which is not ideal for speed. I am sure that more can\r\n#' be done by vecorizing one or more loops, but, for now, it works and is fast\r\n#' enought to be practical. For example: the dataset 'dholes' contains 24,673\r\n#' records in 371 drillholes with 13 valid domain contact pairings. This dataset\r\n#' takes <50 seconds to process on a fast laptop (2018 i9 CPU).\r\n#'\r\n#' @param df Data frame with columns defined in the following arguments.\r\n#' @param grade Name of column in \\code{df} containing numeric values to be\r\n#' averaged by contact distance.\r\n#' @param bhid Name of column in \\code{df} containing character or numeric\r\n#' categorical hole ID (default `bhid`) identifying each unique drillhole.\r\n#' @param from,to Name of numeric columns of \\code{df} with the downhole\r\n#' distance to the start and end of sample intervals (defaults \\code{from} and\r\n#' \\code{to}).\r\n#' @param x,y,z Name of numeric columns of \\code{df} with the cartesian\r\n#' coordinates of the sample mid-points (defaults \\code{x}, \\code{y}, and\r\n#' \\code{z}).\r\n#' @param domain Name of the column in \\code{df} containing the character or\r\n#' numeric categorical codes for domains across which contact analysis will be\r\n#' performed (default \\code{domain}).\r\n#' @param pairs Matrix of domain pairs to be used in the contact analysis.\r\n#' Organized in columns of pairs with two rows each.\r\n#' @param max_dist Positive numeric scalar for the maximum contact distance to\r\n#' be calculated (default \\code{15}).\r\n#' @param min_samp Positive integer scalar for the minimum number of samples on\r\n#' each side of the contact (default \\code{5}). If less than this the data\r\n#' won't be returned. This helps remove domain pairings with too few data.\r\n#'\r\n#' @return A list of two data frames 'detail' and 'summary'. 'detail' contains\r\n#' all data points while 'summary' contains mean grade by binned distances.\r\n#' @export\r\n#' @importFrom assertthat assert_that is.scalar\r\n#' @importFrom dplyr group_by select mutate summarise\r\n#' @importFrom magrittr %<>% %>%\r\n#' @importFrom rlang !! .data enquo quo_name\r\n#' @importFrom stats na.omit\r\n#' @importFrom utils combn\r\n#' @examples\r\n#' # Smaller dataset for speed.\r\n#' dholes_sub <- dholes[dholes$domain < 4000,]\r\n#' ca <- contact_data(dholes_sub, grade, max_dist = 20)\r\n#'\r\n#' # Extract only certain contacts from contact data.\r\n#' ca_1100 <- purrr::map(ca, ~dplyr::filter(.x, grepl(\"1100\", contact)))\r\ncontact_data <- function(df, grade, bhid = bhid, from = from, to = to,\r\n x = x, y = y, z= z, domain = domain, max_dist = 15, min_samp = 5,\r\n pairs = NULL) {\r\n\r\n grade <- enquo(grade)\r\n grade_str <- quo_name(grade)\r\n domain <- enquo(domain)\r\n domain_str <- quo_name(domain)\r\n\r\n # All args passed as symbols (rather than strings) to be consistent.\r\n bhid_str <- quo_name(enquo(bhid))\r\n from_str <- quo_name(enquo(from))\r\n to_str <- quo_name(enquo(to))\r\n x_str <- quo_name(enquo(x))\r\n y_str <- quo_name(enquo(y))\r\n z_str <- quo_name(enquo(z))\r\n\r\n # Assertions on arguments.\r\n # 'df' is a data frame containing the columns defined by other arguments.\r\n assert_that(is.data.frame(df),\r\n msg = \"Argument `df` is not a data frame.\")\r\n assert_that(all(\r\n c(bhid_str, domain_str, grade_str, from_str, to_str, x_str, y_str, z_str)\r\n %in% colnames(df)),\r\n msg = paste0(\r\n \"One of the required columns not in the supplied data frame.\"))\r\n # 'grade' , 'from', 'to', 'x', 'y', 'z' are all numeric.\r\n assert_that(is.numeric(df[[grade_str]]),\r\n msg = \"`grade` must be numeric.\")\r\n assert_that(is.numeric(df[[from_str]]),\r\n msg = \"`from` must be numeric.\")\r\n assert_that(is.numeric(df[[to_str]]),\r\n msg = \"`to` must be numeric.\")\r\n assert_that(is.numeric(df[[x_str]]),\r\n msg = \"`x` must be numeric.\")\r\n assert_that(is.numeric(df[[y_str]]),\r\n msg = \"`y` must be numeric.\")\r\n assert_that(is.numeric(df[[z_str]]),\r\n msg = \"`z` must be numeric.\")\r\n # 'max_dist' is positive numeric scalar > 0.\r\n assert_that(is.scalar(max_dist))\r\n assert_that(max_dist > 0, msg = \"`max_dist` must be > 0\")\r\n # 'min_samp' is positive whole number scalar >= 1.\r\n assert_that(is.scalar(min_samp))\r\n assert_that(\r\n (function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol)\r\n (min_samp),\r\n msg = \"`min_samp` must be a whole number\")\r\n assert_that(min_samp >= 1, msg = \"`min_samp` must be >= 1\")\r\n\r\n all_holes <- sort(unique(df[[bhid_str]]))\r\n sample_count <- nrow(df)\r\n cnt <- 0\r\n\r\n for (dom in 1:ncol(pairs)) {\r\n # Reset for each domain pairing.\r\n counti <- 0\r\n countj <- 0\r\n disti <- rep(NA_real_, sample_count)\r\n valuei <- rep(NA_real_, sample_count)\r\n distj <- rep(NA_real_, sample_count)\r\n valuej <- rep(NA_real_, sample_count)\r\n for (hole in 1:length(all_holes)) {\r\n samples <- df[df[[bhid_str]] == all_holes[hole],]\r\n samples <- samples[order(samples[[from_str]], samples[[to_str]]),]\r\n count_samples <- nrow(samples)\r\n # Make sure at least 2 samples in the drillhole.\r\n if(count_samples < 2) next\r\n for (sample in 2:count_samples) {\r\n this_samp <- samples[sample,]\r\n last_samp <- samples[sample - 1,]\r\n if (this_samp[[domain_str]] == pairs[2, dom] &\r\n last_samp[[domain_str]] == pairs[1, dom]) {\r\n xc <- (this_samp[[x_str]] + last_samp[[x_str]]) * 0.5\r\n yc <- (this_samp[[y_str]] + last_samp[[y_str]]) * 0.5\r\n zc <- (this_samp[[z_str]] + last_samp[[z_str]]) * 0.5\r\n for (consamp in (sample - 1):1) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[1, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n counti <- counti + 1\r\n disti[counti] <- d\r\n valuei[counti] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n for (consamp in sample:count_samples) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[2, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n countj <- countj + 1\r\n distj[countj] <- d\r\n valuej[countj] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n }\r\n if (this_samp[[domain_str]] == pairs[1, dom] &\r\n last_samp[[domain_str]] == pairs[2, dom]) {\r\n xc <- (this_samp[[x_str]] + last_samp[[x_str]]) * 0.5\r\n yc <- (this_samp[[y_str]] + last_samp[[y_str]]) * 0.5\r\n zc <- (this_samp[[z_str]] + last_samp[[z_str]]) * 0.5\r\n for (consamp in (sample - 1):1) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[2, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n countj <- countj + 1\r\n distj[countj] <- d\r\n valuej[countj] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n for (consamp in sample:count_samples) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[1, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n counti <- counti + 1\r\n disti[counti] <- d\r\n valuei[counti] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n # Skip to next if not enough samples.\r\n if(counti < min_samp & countj < min_samp) next\r\n # Build the detailed dataframe.\r\n cnt <- cnt + 1\r\n tempdatai <- data.frame(dist = -disti, value = valuei)\r\n tempdatai[,\"domain\"] <- pairs[1, dom]\r\n tempdataj <- data.frame(dist = distj, value = valuej)\r\n tempdataj[,\"domain\"] <- pairs[2, dom]\r\n tempdata <- na.omit(rbind(tempdatai, tempdataj))\r\n # Create a contact label with the total number of samples.\r\n ni <- nrow(tempdata[tempdata[[\"domain\"]] == pairs[1, dom], ])\r\n nj <- nrow(tempdata[tempdata[[\"domain\"]] == pairs[2, dom], ])\r\n tempdata[, \"contact\"] <-\r\n paste0(\r\n pairs[1, dom], \"(\", ni, \"):\", pairs[2, dom], \"(\", nj, \")\"\r\n )\r\n if(cnt == 1) {\r\n cdata_detail <- tempdata\r\n } else {\r\n cdata_detail <- rbind(cdata_detail, tempdata)\r\n }\r\n }\r\n\r\n cdata_detail <- cdata_detail[,c(\"contact\", \"domain\", \"dist\", \"value\")]\r\n\r\n # Create summary data.\r\n cdata_summary <- cdata_detail %>%\r\n group_by(.data$contact, .data$domain, bin = cut(.data$dist, seq(-max_dist, max_dist))) %>%\r\n summarise(value = mean(.data$value, na.rm = TRUE)) %>%\r\n mutate(dist = interval_mid(.data$bin, 1)) %>%\r\n select(-.data$bin)\r\n\r\n return(list(detail = cdata_detail, summary = cdata_summary))\r\n}\r\n\r\n#' Produce Basic Contact Analysis Plots.\r\n#'\r\n#' \\code{contact_plot} produces a minimally formatted contact analysis plot\r\n#' facetted by domain using \\code{\\link{ggplot2}}. The input data is created by\r\n#' \\code{\\link{contact_data}}. Additonal formatting can be applied using\r\n#' \\code{\\link{ggplot2}} functions (see example).\r\n#'\r\n#' @param data List of data frames created by \\code{\\link{contact_data}} with\r\n#' 'detail' and 'summary' contact data.\r\n#'\r\n#' @return A \\code{\\link{ggplot2}} plot object.\r\n#' @export\r\n#' @importFrom ggplot2 aes ggplot geom_smooth geom_line geom_vline facet_wrap\r\n#' @importFrom rlang .data\r\n#' @examples\r\n#' library(ggplot2)\r\n#' cdata <- contact_data(dholes, grade)\r\n#' p <- contact_plot(cdata)\r\n#' p +\r\n#' labs(x = \"Distance (m)\", y = \"Mean grade (g/t)\") +\r\n#' theme_bw()\r\ncontact_plot <- function(data) {\r\n ggplot() +\r\n geom_smooth(\r\n data = data$detail,\r\n aes(x = .data$dist, y = .data$value, group = .data$domain),\r\n method = \"lm\",\r\n linetype = \"dashed\",\r\n colour = \"black\",\r\n fill = \"grey75\",\r\n alpha = 0.5,\r\n size = 0.25\r\n ) +\r\n geom_line(\r\n data = data$summary,\r\n aes(.data$dist, .data$value, group = .data$domain),\r\n size = 0.25, colour = \"black\"\r\n ) +\r\n geom_vline(xintercept = 0, colour = \"black\") +\r\n facet_wrap(~contact, scales = \"free_y\")\r\n}\r\n", "meta": {"hexsha": "afdefe11c15347a61e17e2cfcfe5fc052019b508", "size": 12304, "ext": "r", "lang": "R", "max_stars_repo_path": "R/contact-analysis.r", "max_stars_repo_name": "truemoid/contactr", "max_stars_repo_head_hexsha": "16df43c224d01b77f4ecef637ad07c3d80bc1b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/contact-analysis.r", "max_issues_repo_name": "truemoid/contactr", "max_issues_repo_head_hexsha": "16df43c224d01b77f4ecef637ad07c3d80bc1b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-22T17:30:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-22T17:30:18.000Z", "max_forks_repo_path": "R/contact-analysis.r", "max_forks_repo_name": "truemoid/contactr", "max_forks_repo_head_hexsha": "16df43c224d01b77f4ecef637ad07c3d80bc1b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7417218543, "max_line_length": 95, "alphanum_fraction": 0.5826560468, "num_tokens": 3382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3765671062094403}}
{"text": "# --------------------------------------------------------------------------------------\n# Programmer: Jason Thorpe\n# Date 03/17/2011\n# Language: R (Version 2.12.0)\n# Purpose: \n# Comments: \n# --------------------------------------------------------------------------------------\n\n#' Estimate the PEB parameters\n#'\n#' Estimate the PEB parameters from a set of marker values (x) from individuals\n#'\n#' @export\n#' @param x observations of the for the variable of intereset\n#'\n#' @param id a 'factor' with identifiers for the individuals who contributed \n#' the observations in \\code{x}\n#'\n#' @param method Either 'ICC1' or 'iterative' (matched via match.arg). \n#' If method == 'ICC1' (default) multilevel::ICC1 is used to estimate the \n#' within and between group variation. Otherwise an iterative approach is used.\n#'\n#' @param iterations The number of iterations for estimating the tau \n#' squared parameter (and it's error variance) (default = 2)\n#'\n#' @param conf.level The width of the confidence interval for sigma-squared \n#' and tau-squared \n#'\n#' @family peb\n#' @return a list with the following values:\n#' s2: sigma quared\n#' s2.ev: the error variance for sigma squared\n#' t2: tau squared\n#' t2.ev: the error variance for tau squared\n#' mu: mu \n#' mu.ev: the error variance for mu\n#' m: the number of individuals contributing to the estimates\n#' N: the nubmer so observations contributing to the estimates\n#' mu.ci: confidence interval for mu\n#' t2.ci: confidence interval for tau squared\n#' s2.ci: confidence interval for sigma squared\n#' nstar: an average sample size for use in calcualing the CI for tau sauqred\n#'\n#' @examples\n#' n = 10\n#' m = 200\n#' PEBparams(x = rnorm(m*n) + rep(rnorm(m),each=n), id=gl(m,n,m*n))\n#'\n#' @importFrom multilevel ICC1\n\nPEBparams <- function(x,\n\t\t\t\t\t id,\n\t\t\t\t\t method='ICC1',\n\t\t\t\t\t iterations =2 ,\n\t\t\t\t\t conf.level = 0.9,\n\t\t\t\t\t verbose=FALSE){\n\n\tmethod = match.arg(method,c('ICC1','iterative'))\n\tif(method == 'ICC1' && !missing(iterations))\n\t\tstop(\"parameter 'iterations' is not used when method == 'ICC1'\")\n\n\tstopifnot(all(is.finite(x)))\n\tif(!inherits(id,'factor'))\n\t\tstop(\"parameter 'id' must be a factor\")\n\tif(! all(levels(id) %in% id)){\n\t\twarning(paste(\"unused factor levels in 'id':\",\n\t\t\t\t\t paste(levels(id)[!levels(id) %in% id],\n\t\t\t\t\t\t\tcollapse = ', ')))\n\t\tid <- factor(as.character(id))\n\t}\n\n\n\tN <- length(id)\n\tm <- length(levels(id))\n\n\tif(method == 'ICC1'){\n\t\ttryCatch({\n\t\t\tAOV = aov(formula(x~id))\n\t\t},error=function(err){\n\t\t\tstop('Internal call to `aov()` failed with error message: \"%s\". \\n\\nSuggest using: PEBparams( ... , method=\"iterative\")')\n\t\t})\n\t\t(B1 = multilevel::ICC1(AOV))\n\t\tV <- var(x)\n\t\tout <- list(s2 = (1-B1) * V,\n\t\t\t\t\t\t t2 = B1 * V,\n\t\t\t\t\t\t mu = mean(x),\n\t\t\t\t\t\t m = m,\n\t\t\t\t\t\t N = N,\n\t\t\t\t\t\t method=method)\n\t\tclass(out) <- c('PEBparams','list')\n\t\treturn(out)\n\n\t}else{#(method == )\n\t\t# --------------------------------------------------\n\t\t# part 1: non-iterative calculations\n\t\t# --------------------------------------------------\n\n\t\t#calcualte various constants\t\n\t\tnresults <- tapply(id,id,length) # results per person\n\t\tybari <- tapply(x,id,mean)\n\n\t\t#############################################\n\t\t# estiamte sigma^2\n\t\t#############################################\n\t\ts2i \t<- tapply(x,id,var)\n#-- \t\tif(!all(is.na(s2i) == (nresults == 1)))\n#-- \t\t\tbrowser()\n\n\t\tstopifnot(is.na(s2i) == (nresults == 1))\n\n\t\t#relative error variances of \n\t\ts2i_weights\t<- (nresults - 1) / 2\n\t\tstopifnot( (s2i_weights ==0) == is.na(s2i))\n\n\t\ts2 <- sum((s2i_weights[!is.na(s2i)])*(s2i[!is.na(s2i)])) / sum(s2i_weights[!is.na(s2i)])\n\t\ts2ev <- 2*(s2^2)/(N - m)\n\n\t\trm(s2i,s2i_weights)\n\n\t\t# --------------------------------------------------\n\t\t# --------------------------------------------------\n\t\t# part 2: iterative calculations of mu and Tau^2\n\t\t# --------------------------------------------------\n\t\t# --------------------------------------------------\n\n\t\t# ------------------------------\n\t\t# part 2a: fixed parameters for the iterative processes\n\t\t# ------------------------------\n\t\ttr <- table(nresults)\n\t\tuk <- as.numeric(names(tr[tr>1]))\n\t\trm(tr)\n\n\t\t# estimates of the t2k's \n\t\tt2k <- numeric(0)\n\t\tfor(k in uk)\n\t\t\tt2k \t<- c(t2k, var(ybari[nresults == k] ) - (s2/k) )\n\n\t\t# initialize the variables involved in the iterative process\n\t\tt2kev_list <- list()\n\t\tt2ev <- muev <- t2 <- numeric(0)\n\n\t\t# ------------------------------\n\t\t# part 2b: initial estiamte of EV(T_k^2) from the tk's\n\t\t# ------------------------------\n\t\t# Next, estimate the error variances which DOES depend on the estimate for tau^2\n\t\t# We use the unweighted average of the t2k's because the t2k's are unbaiased.\n\t\t# We cannot weight them according to their value because then underestimates \n\t\t# become overweitghted and underestimated become underweighted and the result \n\t\t# is a biased estimate of t2k and of it's error variance. we do however weight \n\t\t# them according to their m_k's becaue there is not bias there.\n\n\t\tt2kev_temp <- numeric(0)#initialization\n\t\tfor(k in uk){# this would be more efficient with an apply stmt.\n\t\t\tm_k \t\t<- sum(nresults == k)\n\t\t\t#in the alternate version we estimate all the t2k's then estimate the t2kev's\n\t\t\t#this estimate DOES depend on the estimate for tau^2\n\t\t\tt2kev_temp \t <- c(t2kev_temp, \n\t\t\t\t\t\t\t\t\t2*((mean(t2k) + s2/k)^2) / (m_k - 1) + (s2ev/(k^2))\n\t\t\t\t\t\t\t\t\t)\n\t\t}\n\t\tt2kev_list <- list(t2kev_temp)\n\t\trm(k,m_k)\n\n\t\t# ------------------------------\n\t\t# part 2c: iterative re-estimation of Tau2 and mu\n\t\t# ------------------------------\n\t\tt2 <- mu <- t2ev <- muev <- numeric(0)\n\t\t# This function nested for lexical scoping \n\t\tt2_mu <- function(){\n\t\t\t#re-estimate t2 using the latest t2kev estimates\n\t\t\tt2new <- sum((1/(t2kev_list[[j]]))*(t2k))/sum(1/(t2kev_list[[j]]))\n\n\t\t\t#re-estimate t2_ev using the latest t2 estimates\n\t\t\tt2kev_temp <- numeric(0) #initialize\n\t\t\tfor(k in uk){\n\t\t\t\tm_k \t\t<- sum(nresults == k)\n\t\t\t\tt2kev_temp \t<- c(t2kev_temp, \n\t\t\t\t\t\t\t\t\t2*((t2new + s2/k)^2) / (m_k - 1) + (s2ev/(k^2)))\n\t\t\t}\n\t\t\tt2kev_list <<- c(t2kev_list,list(t2kev_temp))\n\n\t\t\t#############################################\n\t\t\t# estimate mu (which depends on the estimate for tau^2)\n\t\t\t#############################################\n\t\t\tybari_weights\t<- 1/(t2new + (s2/nresults))\n\t\t\tbn <- (t2new)/((t2new) + (s2/nresults))\n\n\t\t\t# extend the lists of estmates\n\t\t\tt2 <<- c(t2,t2new )\n\t\t\tmu <<- c(mu, sum(ybari_weights*ybari) / sum(ybari_weights))\n\n\t\t\tt2ev <<- c(t2ev, 1/sum(1/t2kev_temp)) #estimate t2ev from the new t2kev's\n\t\t\tmuev <<- c(muev, (t2new)/sum(bn))\n\n\t\t}\n\n\t\tstopifnot(iterations>0)\n\n\t\tprobs <- c(((1-conf.level)/2),1-((1-conf.level)/2)) # probabilities for the CI\n\n\t\tfor(j in 1:iterations){\n\t\t\tt2_mu()\n\t\t\tif(verbose){\n\t\t\t\tnstar <- ((m-length(uk))/sqrt((t2ev[j]) / (2*((t2[j])^2)/(m-length(uk)))))\n\t\t\t\tcat('iteration:',j,\n\t\t\t\t\t'| Tau Squared CI width: ',\n\t\t\t\t\tformat(diff((t2[j]*(nstar))/qchisq(p=probs[2:1],df = nstar)),8),\n\t\t\t\t\t'| Mu CI width: ',\n\t\t\t\t\tformat(diff(mu[j] + sqrt(muev[j])*qnorm(p=probs)),8),'\\n')\n\t\t\t}\n\t\t}\n\n\t\t#############################################\n\t\t# return the estimates\n\t\t#############################################\n\n\t\tnstar <- ((m-length(uk))/sqrt((t2ev[j]) / (2*((t2[j])^2)/(m-length(uk)))))\n\n\t\tout <- list(s2 = s2,\n\t\t\t\t s2.ev = s2ev,\n\t\t\t\t t2 = t2[iterations],\n\t\t\t\t t2.ev = t2ev[iterations],\n\t\t\t\t mu = mu[iterations],\n\t\t\t\t mu.ev = muev[iterations],\n\t\t\t\t m = m,\n\t\t\t\t N = N,\n\t\t\t\t mu.ci = mu[iterations] + sqrt(muev[iterations])*qnorm(p=probs),\n\t\t\t\t t2.ci = t2[iterations]*qchisq(p=probs[2:1],df = nstar)/nstar,\n\t\t\t\t s2.ci = s2*qchisq(p=probs[2:1],df = N-m )/(N-m),\n\t\t\t\t nstar = nstar,\n\t\t\t\t conf.level = conf.level, \n\t\t\t\t method=method)\n\t\tclass(out) <- c('PEBparams','list')\n\t\treturn(out)\n\n\t}\n\n}\n\n\n#' @export\nprint.PEBparams <- function(x,digits=4){\n\tcat('mu:',format(x$mu[1],digits=digits))\n\tif(x$method == 'iterative')\n\t\tcat(' [',format(x$mu.ci[1],digits=digits),\n\t\t \t',',format(x$mu.ci[2],digits=digits),']')\n\tcat('\\n')\n\n\tcat('sigma^2:',format(x$s2[1],digits=digits))\n\tif(x$method == 'iterative')\n\t\tcat(' [',format(x$s2.ci[1],digits=digits),\n\t\t \t',',format(x$s2.ci[2],digits=digits),']')\n\tcat('\\n')\n\n\tcat('tau^2:',format(x$t2[1],digits=digits))\n\tif(x$method == 'iterative')\n\t\tcat(' [',format(x$t2.ci[1],digits=digits),\n\t\t \t',',format(x$t2.ci[2],digits=digits),']')\n\tcat('\\n')\n\n\tcat('Calculated using',x$N,'observations, from ',x$m, 'inidividuals.\\n',sep = ' ')\n\tif(x$method == 'iterative')\n\t\tcat('([x,y] indicates the ',format(100*x$conf.level,2),'% confidence interval for each parameter)\\n',sep = '')\n}\n\n\nqpeb.alt<-function(p,...,n,ybar,conf.level,details=FALSE) {\n\twith(pebVarArgs(...),{\n\t\t\t\tbn <- bn(n)\n\t\t\t\tsd_n <<- sqrt(sigma + (tau*(1-bn)))\n\t\t\t\tmu_n <<- mu*(1-bn) + ybar*bn\n\t\t\t\t})\n\tif(length(p) == 1)\n\t\treturn(qnorm(p,mean = mu_n,sd=sd_n))\n\tout <- matrix(NA,length(n),length(p))\n\tfor(i in 1:length(p))\n\t\tout[,i] <- qnorm(p[i],mean = mu_n,sd=sd_n)\n\tdimnames(out) <- list(if(!is.null(names(n)))names(N) else seq(length(n)),\n\t\t\t\t\t\t paste('p =',p))\n\treturn(out)\n}\n\n", "meta": {"hexsha": "074e929f8594e6bb00a8714aa3b07e5a6e8dc3cb", "size": 9028, "ext": "r", "lang": "R", "max_stars_repo_path": "R/PEB-parameters.r", "max_stars_repo_name": "jdthorpe/PEB", "max_stars_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/PEB-parameters.r", "max_issues_repo_name": "jdthorpe/PEB", "max_issues_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/PEB-parameters.r", "max_forks_repo_name": "jdthorpe/PEB", "max_forks_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9010600707, "max_line_length": 125, "alphanum_fraction": 0.5476295968, "num_tokens": 2822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3761544232526937}}
{"text": "#!/usr/bin/env Rscript\n\n#########################################################################################\n# __ o __ __ __ |__ __ #\n# |__) | | ' (__( | ) | ) (__( # \n# | #\n# #\n# File: 2logeB10.r (Rscript) #\n# VERSION=\"v1.2\" #\n# Author: Justin C. Bagley #\n# Date: Created by Justin Bagley on Fri, 19 Aug 2016 00:23:07 -0300. #\n# Last update: March 6, 2019 #\n# Copyright (c) 2016-2021 Justin C. Bagley. All rights reserved. #\n# Please report bugs to . #\n# #\n# Description: #\n# #\n#########################################################################################\n\n####################################### START ###########################################\n\ncat('INFO | $(date) |----------------------------------------------------------------\\n')\ncat('INFO | $(date) | 2logeB10.r, v1.2 March 2019 (part of PIrANHA v0.3a2) \\n')\ncat('INFO | $(date) | Copyright (c) 2016-2021 Justin C. Bagley. All rights reserved. \\n')\ncat('INFO | $(date) |----------------------------------------------------------------\\n')\n\n# Load needed library, R code, or package stuff. Install package if not present.\n#source(\"2logeB10.R\", chdir = TRUE)\npackages <- c(\"psych\")\nif (length(setdiff(packages, rownames(installed.packages()))) > 0) {\n install.packages(setdiff(packages, rownames(installed.packages())))\n}\n\nlibrary(psych)\n\n########### Read data and output to file\n# Read in the data, output from STEP #1 of MLEResultsProc.sh script.\ndata <- read.table(file=\"MLE.output.txt\", header=TRUE, sep=\"\\t\")\n\nsink(\"2logeB10.output.txt\")\ncat(\"############################# MARGINAL-LIKELIHOOD ESTIMATES ##############################\\n\")\ndata\ncat(\"\\n \\n\")\nsink()\n\n\n########### Get marginal likelihood values and calculate 2loge B10 Bayes factors (2loge(B10))\n# Raw path-sampling (PS) log-marginal likelihood estimates:\nPS_vec <- data[,2]\nPS_vec\n\n# Raw stepping-stone (SS) sampling log-marginal likelihood estimates:\nSS_vec <- data[,3]\nSS_vec\n\n# Make matrix of zeros for correcting signs of each BF below:\nif(length(PS_vec) > 0){\n\tzeros <- c()\n\tfor(i in 1:length(PS_vec)){\n\t\tzeros[i] <- 0\n\t}\n}\nif(length(SS_vec) > 0){\n\tzeros <- c()\n\tfor(i in 1:length(SS_vec)){\n\t\tzeros[i] <- 0\n\t}\n}\nzeros\nzeros_mat <- 2*(outer(zeros, zeros, '-'))\nzeros_mat\n\n# Matrix of 2loge BFs calculated from PS log-marginal likelihood estimates:\nPS_2logeB10 = 2*(outer(PS_vec, PS_vec, '-'))\nPS_2logeB10 <- zeros_mat - PS_2logeB10\n\n# Matrix of 2loge BFs calculated from SS log-marginal likelihood estimates:\nSS_2logeB10 = 2*(outer(SS_vec, SS_vec, '-'))\nSS_2logeB10 <- zeros_mat - SS_2logeB10\n\n\n########### Summarize results and output to file\n# Use psych package function to combine the resulting matrices into a single, nice\n# output table with Bayes factors (BF) from PS MLEs below the diagonal and BFs from SS \n# MLEs above the diagonal:\nsink(\"2logeB10.output.txt\", append=TRUE)\ncat(\"##################################### BAYES FACTORS ######################################\nBelow diagonal: 2loge(B10) values based on path sampling (PS) log-marginal likelihood estimates\nAbove diagonal: 2loge(B10) values based on stepping-stone (SS) log-marginal likelihood estimates\\n\")\nif(sum(PS_vec) == '0'){ \n\tBF_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=FALSE)\n\tBF_mat[lower.tri(BF_mat)] <- NA\n\trownames(BF_mat) <- 1:length(PS_vec)\n\tcolnames(BF_mat) <- 1:length(PS_vec)\n\tBF_mat\n}\nif(sum(SS_vec) == '0'){ \n\tBF_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=FALSE)\n\tBF_mat[upper.tri(BF_mat)] <- NA\n\trownames(BF_mat) <- 1:length(PS_vec)\n\tcolnames(BF_mat) <- 1:length(PS_vec)\n\tBF_mat\n}\nif( (sum(PS_vec) != '0') & (sum(SS_vec) != '0') ){ \n\tBF_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=FALSE)\n\trownames(BF_mat) <- 1:length(PS_vec)\n\tcolnames(BF_mat) <- 1:length(PS_vec)\n\tBF_mat\n}\ncat(\"\\n \\n\")\nsink()\n\n# Next, report PS MLE BFs below the diagonal and report the difference between PS- and \n# SS-based BF matrices, placing the results in the above-the-diagonal entries. However, \n# we only report the differences if both PS- and SS-based BFs could be calculated; otherwise,\n# we do not report the differences at all! If PS MLEs or SS MLEs were missing in the input \n# (as is usually the case for BEAST2 MLE runs), then either PS_vec or SS_vec would be filled \n# with zeros. If we computed differences in such a case, then we would be left with a square \n# matrix in which the above-diagonal elements were the same as the below-diagonal elements, \n# only with the opposite sign. Such a table would be equivalent to the Bayes factors table \n# already written to file in the step above, and thus would be unnecessary.\n\nsink(\"2logeB10.output.txt\", append=TRUE)\nif( (sum(PS_vec) != '0') & (sum(SS_vec) != '0') ){ \ncat(\"################################ BAYES FACTOR DIFFERENCES ################################\nBelow diagonal: 2loge(B10) values based on path sampling (PS) log-marginal likelihood estimates\nAbove diagonal: differences between PS- and SS-based BF values\\n\")\n\tBF_diff_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=TRUE)\n\trownames(BF_diff_mat) <- 1:length(PS_vec)\n\tcolnames(BF_diff_mat) <- 1:length(PS_vec)\n\tBF_diff_mat\n}\ncat(\"\\n \\n\")\nsink()\n\n\n######################################## END ############################################\n", "meta": {"hexsha": "fc2e32900e207dac7343a55ab85db0923ad0964c", "size": 6143, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/2logeB10.r", "max_stars_repo_name": "justincbagley/PAmPAS", "max_stars_repo_head_hexsha": "4a27375170b2c01fe30fd7460ec7b7313f2cd8c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-07-26T19:17:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T21:12:26.000Z", "max_issues_repo_path": "bin/2logeB10.r", "max_issues_repo_name": "justincbagley/PAmPAS", "max_issues_repo_head_hexsha": "4a27375170b2c01fe30fd7460ec7b7313f2cd8c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-07-30T02:49:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T13:04:55.000Z", "max_forks_repo_path": "bin/2logeB10.r", "max_forks_repo_name": "justincbagley/PAmPAS", "max_forks_repo_head_hexsha": "4a27375170b2c01fe30fd7460ec7b7313f2cd8c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-31T23:16:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T07:17:53.000Z", "avg_line_length": 44.5144927536, "max_line_length": 100, "alphanum_fraction": 0.5196158229, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37615440761906216}}
{"text": "#' Data Fit Assessment\n#' \n#' Calculates \\eqn{R^2} values for correct and incorrect mean reaction times and RMSE values\n#' for the proportions of correct answers per reaction times cuantiles. \n#' @export\n#' @param experim_dat Experimental data in the form produced by \\code{\\link{experimental_data_processing}}.\n#' @param experim_dat Simulated data in the form produced by \\code{\\link{simulDat}}.\n#' @param model_name Optional name for the model to distinguish to which data/model the\n#' function was applied to. Default is 'NAME_UNDEFINED'.\n#' \n#' @return Prints a table with RMSE and \\eqn{R^2} values.\nfit_quality <- function(experim_dat, simul_dat, model_name='NAME_UNDEFINED'){\n \n experim_dat$cond <- \"Data\"\n \n dat <- rbind(experim_dat, simul_dat$data)\n \n ##########\n nbins <- 6\n \n dat_cuants <- quantile(experim_dat$rt, probs = seq(0, 1, length.out = nbins+1)) \n dat_cuants[length(dat_cuants)] <- tail(dat_cuants, n=1)+0.1\n \n sim_cuants <- quantile(simul_dat$data$rt, probs = seq(0, 1, length.out = nbins+1)) \n sim_cuants[length(sim_cuants)] <- tail(sim_cuants, n=1)+0.1\n \n dat$cuants[dat$cond=='Data'] <- experim_dat %>%\n select(-cond) %>%\n split(experim_dat$suj) %>% map(c('rt')) %>%\n map(function(x) {cut(x, breaks = dat_cuants, right=FALSE, na.rm = TRUE)}) %>%\n as_tibble() %>% tidyr::pivot_longer(cols=everything(), names_to = 'variable', values_to = 'value') %>% .$value\n \n dat$cuants[dat$cond=='Sim'] <- simul_dat$data %>%\n split(simul_dat$data$suj) %>% map(c('rt')) %>%\n map(function(x) {cut(x, breaks = sim_cuants, right=FALSE, na.rm = TRUE)}) %>%\n as_tibble() %>% tidyr::pivot_longer(cols=everything(), names_to = 'variable', values_to = 'value') %>% .$value\n \n dat$cuants <- unlist(dat$cuants) %>% as.factor()\n dat$cor <- as.numeric(levels(dat$cor))[dat$cor]\n #########\n \n a <- dat %>% group_by(cond, cuants) %>%\n dplyr::summarise(mean = mean(cor)) %>% \n spread(cond,mean) %>%\n select(-cuants) %>%\n rmse()\n \n \n b <- dat %>% \n group_by(suj, cond) %>% \n dplyr::summarize(mean_rt = mean(rt)) %>%\n spread(cond, mean_rt) %>%\n ungroup() %>%\n dplyr::summarise(rmse = rmse(.)) %>%\n pull()\n \n c <- dat %>% \n group_by(suj, cond) %>% \n dplyr::summarize(mean_rt = mean(rt)) %>%\n spread(cond, mean_rt) %>%\n ungroup() %>%\n dplyr::summarise(r2 = summary(lm(data=., Data~Sim))$adj.r.squared) %>%\n pull() \n \n d <- dat %>% group_by(cor, cond, suj) %>%\n dplyr::summarise(mean = mean(rt)) %>% \n ungroup() %>%\n spread(cond,mean) %>%\n nest(-cor) %>%\n mutate(data = map(data, ~ rmse(as.data.frame(.x)))) %>%\n mutate(data = unlist(data)) %>%\n pull(data)\n \n e <- dat %>% group_by(cor, cond, suj) %>%\n dplyr::summarise(mean = mean(rt)) %>% \n ungroup() %>%\n spread(cond,mean) %>%\n nest(-cor) %>%\n mutate(data = map(data, ~ summary(lm(data=as.data.frame(.x), Data~Sim))$adj.r.squared)) %>%\n mutate(data = unlist(data)) %>%\n pull(data) \n \n stats <- list(\"RMSE (Correct answers per RT cuantiles)\" = a,\n \"RMSE (Overall Means of RTs aggr. by Subj.)\" = b,\n \"R2 (Overall Means of RTs aggr. by Subj.)\" = c,\n \"RMSE (For Incorrect Mean RTs aggr. by Subj.)\" = d[1],\n \"RMSE (For Correct Mean RTs aggr. by Subj.)\" = d[2], \n \"R2 (For Incorrect Mean RTs aggr. by Subj.)\" = e[1],\n \"R2 (For Correct Mean RTs aggr. by Subj.)\" = e[2]\n )\n \n print(data.frame(stats=unlist(stats)))\n \n}", "meta": {"hexsha": "8a9d7eee3d8891fac7d034c7eca647265f202bc6", "size": 3733, "ext": "r", "lang": "R", "max_stars_repo_path": "R/fit_quality.r", "max_stars_repo_name": "Seneketh/StanDDM", "max_stars_repo_head_hexsha": "994c96fb00e6719f5e22c130e4844c62f14fc928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-06-04T13:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T15:53:37.000Z", "max_issues_repo_path": "R/fit_quality.r", "max_issues_repo_name": "Seneketh/StanDDM", "max_issues_repo_head_hexsha": "994c96fb00e6719f5e22c130e4844c62f14fc928", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-02T06:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T20:36:29.000Z", "max_forks_repo_path": "R/fit_quality.r", "max_forks_repo_name": "Seneketh/StanDDM", "max_forks_repo_head_hexsha": "994c96fb00e6719f5e22c130e4844c62f14fc928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-23T01:52:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T12:36:06.000Z", "avg_line_length": 39.7127659574, "max_line_length": 119, "alphanum_fraction": 0.5563889633, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37615440761906216}}
{"text": "BoundModwpt<- function(x, wf=\"la8\", n.levels=4, oldtargets)\n{\n \n N <- length(x); storage.mode(N) <- \"integer\"\n J <- n.levels\n if(2^J > N) stop(\"Too many depth levels in the wavelet transform\")\n \n dict <- wave.filter(wf)\n L <- dict$length\n storage.mode(L) <- \"integer\"\n ht <- dict$hpf/sqrt(2)\n storage.mode(ht) <- \"double\"\n gt <- dict$lpf/sqrt(2)\n storage.mode(gt) <- \"double\"\n \n targets=prepareTargets(oldtargets)#encoding targets using gray code\n \n y <- vector(\"list\", sum(2^(1:J)))\n yn <- length(y)\n crystals1 <- rep(1:J, 2^(1:J))\n crystals2 <- unlist(apply(as.matrix(2^(1:J) - 1), 1, seq, from=0))\n names(y) <- paste(\"w\", crystals1, \".\", crystals2, sep=\"\")\n \n W <- numeric(N);V<- numeric(N)\n storage.mode(W) <- \"double\"; storage.mode(V)<- \"double\"\n for(j in 1:J) {\n index <- 0\n jj <- min((1:yn)[crystals1 == j])\n for(n in 0:(2^j / 2 - 1)) {\n index <- index + 1\n #should filter parent node j-1,n\n sc=shouldCompute(c(j-1,n),targets)\n if(sum(sc)>0){\n if(j > 1)\n x <- y[[(1:yn)[crystals1 == j-1][index]]]\n if(n %% 2 == 0) {\n z <- .C(\"pmodwpt\", as.double(x), N, as.integer(j),as.integer(2), L, ht, gt,\n W = W, V = V, PACKAGE=\"RHRV\")[8:9]\n y[[jj + 2*n + 1]] <- z$W\n y[[jj + 2*n]] <- z$V\n }\n else {\n z <- .C(\"pmodwpt\", as.double(x), N, as.integer(j),as.integer(2), L, ht, gt,\n W = W, V = V, PACKAGE=\"RHRV\")[8:9]\n y[[jj + 2*n]] <- z$W\n y[[jj + 2*n + 1 ]] <- z$V\n }\n }\n \n }\n }\n \n return(y)\n}\n\n\nshouldCompute2intCode<-function(sc){\n if (codeEquals(sc,c(1,0))){ intCode=0}\n if (codeEquals(sc,c(0,1))) { intCode=1}\n if (codeEquals(sc,c(1,1))){intCode=2}\n return (intCode)\n}\n\nprepareTargets <- function(targets){\n newTargets=list()\n numberTargets=length(targets)/2;\n for (n in 1:numberTargets){ \n newTargets[[n]]=getC(targets[[2*n-1]],targets[[2*n]])\n }\n return(newTargets)\n}\n\nshouldCompute <- function(node,targets){\n \n #compute should be c(0,0)(none), c(1,0)(left),c(0,1)(right), c(1,1) (both)\n compute=c(0,0)\n # node c(0,0) must be computed\n if (nodeEquals(node,c(0,0))){\n len=length(targets)\n for (j in 1:len){\n if (targets[[j]][1]==0){\n compute[[1]]=1;\n }else{\n compute[[2]]=1;\n }\n if (codeEquals(compute,c(1,1))) break \n }\n \n }else{\n len=length(targets)\n nodeCode=getC(node[[1]],node[[2]])\n codeLen=length(nodeCode)\n compute=c(0,0)\n for (j in 1:len){\n if (length(targets[[j]])>codeLen){\n equals=codeEquals(nodeCode,targets[[j]][1:codeLen])\n if (equals){\n ntc=nodeToCompute(targets[[j]][[codeLen+1]])\n compute=compute+ntc\n compute=compute/max(compute)## avoid (2,0) or (0,2)\n if (codeEquals(compute,c(1,1))) break\t\n \n }\n }\n }\n return (compute)\n }\n \n \n \n return(compute);\n}\n\n\nnodeToCompute<-function(number){\n if (number==1){##high pass filter\n return (c(0,1))\n }else{## low pass filter\n return (c(1,0))\n }\n}\n\ncodeEquals<-function(c1,c2){\n if (length(c1)!=length(c2))\n { \n return (FALSE)\n }else{\n return (prod(c1==c2)==1)\n }\t\n}\n\nnodeEquals<-function(n1,n2){\n return ((n1[1]==n2[1])&&(n1[2]==n2[2]));\n \n}\n", "meta": {"hexsha": "25b39dae92abb7a4a1b7a5bb089d82440c1fba50", "size": 3290, "ext": "r", "lang": "R", "max_stars_repo_path": "RHRV/BoundModwpt.r", "max_stars_repo_name": "med-material/ArduinoLoggerShinyApp", "max_stars_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RHRV/BoundModwpt.r", "max_issues_repo_name": "med-material/ArduinoLoggerShinyApp", "max_issues_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-01-23T08:30:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:58:03.000Z", "max_forks_repo_path": "RHRV/BoundModwpt.r", "max_forks_repo_name": "med-material/ArduinoLoggerShinyApp", "max_forks_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-30T09:42:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T09:42:11.000Z", "avg_line_length": 24.1911764706, "max_line_length": 85, "alphanum_fraction": 0.526443769, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.37593710616989773}}
{"text": "#' Creates a new ARTMAP network.\n#' \n#' This function creates a new ARTMAP network with the specified number\n#' features and classes. The network is created to expand the number of \n#' categories as needed. The vigilance parameter defaults to 0.75.\n#' The initial number of categories is set to 1. The maximum number\n#' of categories defaults to 100. The bias defaults to 0.000001, the\n#' number of epochs defaults to 100, and the learning rate defaults \n#' to 1.0 (fast-learning).\n#' @title ARTMAP_Create_Network\n#' @param numFeatures Number of features that the network expects of the input data. Must be a positive integer.\n#' @param numClasses Number of classes that exist for the supervisory signal. Must be a positive integer greater than 1.\n#' @param maxNumCategories Maximum number of categories that can be activated during the training process. Defaults to 1000.\n#' @param vigilance Vigilance parameter that defines the minimum similarity allowed between the input pattern and the weights. Defaults to 0.75.\n#' @param bias Constant that is used to differentiate between very similar category activation values. Defaults to 0.000001\n#' @param numEpochs Maximum number of training iterations allowed. Defaults to 100.\n#' @param learningRate Learning rate. Defaults to 1.\n#' @return Structure that holds all of the information for the network. It must be passed into both ARTMAP_LEARN() and \n#' ARTMAP_CLASSIFY(). The fields of this structure are numFeatures, numCategories, maxNumCategories, numClasses, weight \n#' (an initialized weight vector with the right dimensions), mapField (an initialized map field with the right dimensions), \n#' vigilance, bias, numEpochs, neededEpochs (the number of epochs needed in the last training) and learningRate.\n#' @export\nARTMAP_Create_Network=function(numFeatures, numClasses,\n maxNumCategories = 1000, vigilance=0.75, \n bias=0.000001, numEpochs=100, learningRate=1.0)\n{\n if(is.null(numFeatures) || is.null(numClasses))\n {\n stop('You must specify the number of features and the number of classes.');\n }\n \n # Check the ranges of the input parameters.\n numFeatures = round(numFeatures);\n if(numFeatures < 1)\n {\n stop('The number of features must be a positive integer.');\n }\n numClasses = round(numClasses);\n if(numClasses < 2)\n {\n stop('The number of classes must be a positive integer greater than 1.');\n }\n \n # Create and initialize the weight matrix.\n weight = matrix(1,0,numFeatures);\n \n # Create and initialize the map field.\n mapField = matrix(0,0,1);\n \n # Create the structure and return.\n artmap_network = list(\"numFeatures\"= numFeatures, \"numCategories\" = 0, \"maxNumCategories\" = maxNumCategories, \n \"numClasses\"=numClasses, \"weight\"=weight, \"mapField\"=mapField, \n \"vigilance\"=vigilance, \"bias\"=bias, \"numEpochs\"=numEpochs, \n \"neededEpochs\"=0,\"learningRate\"=learningRate);\n \n return(artmap_network);\n}", "meta": {"hexsha": "b707ade0789a2d53bd6abaf07d13a05bd2417876", "size": 3026, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ARTMAP_Create_Network.r", "max_stars_repo_name": "gbaquer/fuzzyARTMAP", "max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ARTMAP_Create_Network.r", "max_issues_repo_name": "gbaquer/fuzzyARTMAP", "max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ARTMAP_Create_Network.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0877192982, "max_line_length": 144, "alphanum_fraction": 0.7204230007, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3752009507935019}}
{"text": " E04MTJ Example Program Results\n\n++++++++++ Use the Primal-Dual algorithm ++++++++++\n\n ----------------------------------------------\n E04MT, Interior point method for LP problems\n ----------------------------------------------\n\n Original Problem Statistics\n\n Number of variables 7\n Number of constraints 7\n Free variables 0\n Number of nonzeros 41\n\n\n Presolved Problem Statistics\n\n Number of variables 13\n Number of constraints 7\n Free variables 0\n Number of nonzeros 47\n\n\n ------------------------------------------------------------------------------\n it| pobj | dobj | optim | feas | compl | mu | mcc | I\n ------------------------------------------------------------------------------\n 0 -7.86591E-02 1.71637E-02 1.27E+00 1.06E+00 8.89E-02 1.5E-01\n 1 5.74135E-03 -2.24369E-02 6.11E-16 1.75E-01 2.25E-02 2.8E-02 0\n 2 1.96803E-02 1.37067E-02 5.06E-16 2.28E-02 2.91E-03 3.4E-03 0\n 3 2.15232E-02 1.96162E-02 7.00E-15 9.24E-03 1.44E-03 1.7E-03 0\n 4 2.30321E-02 2.28676E-02 1.15E-15 2.21E-03 2.97E-04 3.4E-04 0\n 5 2.35658E-02 2.35803E-02 1.32E-15 1.02E-04 8.41E-06 9.6E-06 0\n 6 2.35965E-02 2.35965E-02 1.64E-15 7.02E-08 6.35E-09 7.2E-09 0\nIteration 7\n monit() reports good approximate solution (tol = 1.20E-08):\n 7 2.35965E-02 2.35965E-02 1.35E-15 3.52E-11 3.18E-12 3.6E-12 0\n ------------------------------------------------------------------------------\n Status: converged, an optimal solution found\n ------------------------------------------------------------------------------\n Final primal objective value 2.359648E-02\n Final dual objective value 2.359648E-02\n Absolute primal infeasibility 4.168797E-15\n Relative primal infeasibility 1.350467E-15\n Absolute dual infeasibility 5.084353E-11\n Relative dual infeasibility 3.518607E-11\n Absolute complementarity gap 2.685778E-11\n Relative complementarity gap 3.175366E-12\n Iterations 7\n\n Primal variables:\n idx Lower bound Value Upper bound\n 1 -1.00000E-02 -1.00000E-02 1.00000E-02\n 2 -1.00000E-01 -1.00000E-01 1.50000E-01\n 3 -1.00000E-02 3.00000E-02 3.00000E-02\n 4 -4.00000E-02 2.00000E-02 2.00000E-02\n 5 -1.00000E-01 -6.74853E-02 5.00000E-02\n 6 -1.00000E-02 -2.28013E-03 inf\n 7 -1.00000E-02 -2.34528E-04 inf\n\n Box bounds dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.00000E-02 3.30098E-01 1.00000E-02 0.00000E+00\n 2 -1.00000E-01 1.43844E-02 1.50000E-01 0.00000E+00\n 3 -1.00000E-02 0.00000E+00 3.00000E-02 9.09967E-02\n 4 -4.00000E-02 0.00000E+00 2.00000E-02 7.66124E-02\n 5 -1.00000E-01 3.51391E-11 5.00000E-02 0.00000E+00\n 6 -1.00000E-02 3.42902E-11 inf 0.00000E+00\n 7 -1.00000E-02 8.61040E-12 inf 0.00000E+00\n\n Constraints dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.30000E-01 0.00000E+00 -1.30000E-01 1.43111E+00\n 2 -inf 0.00000E+00 -4.90000E-03 4.00339E-10\n 3 -inf 0.00000E+00 -6.40000E-03 1.54305E-08\n 4 -inf 0.00000E+00 -3.70000E-03 3.80136E-10\n 5 -inf 0.00000E+00 -1.20000E-03 4.72629E-11\n 6 -9.92000E-02 1.50098E+00 inf 0.00000E+00\n 7 -3.00000E-03 1.51661E+00 2.00000E-03 0.00000E+00\n\n++++++++++ Use the Self-Dual algorithm ++++++++++\n\n ----------------------------------------------\n E04MT, Interior point method for LP problems\n ----------------------------------------------\n\n Original Problem Statistics\n\n Number of variables 7\n Number of constraints 7\n Free variables 0\n Number of nonzeros 41\n\n\n Presolved Problem Statistics\n\n Number of variables 13\n Number of constraints 7\n Free variables 0\n Number of nonzeros 47\n\n\n ------------------------------------------------------------------------------\n it| pobj | dobj | p.inf | d.inf | d.gap | tau | mcc | I\n ------------------------------------------------------------------------------\n 0 -6.39941E-01 4.94000E-02 1.07E+01 2.69E+00 5.54E+00 1.0E+00\n 1 -8.56025E-02 -1.26938E-02 2.07E-01 2.07E-01 2.07E-01 1.7E+00 0\n 2 4.09196E-03 1.24373E-02 4.00E-02 4.00E-02 4.00E-02 2.8E+00 0\n 3 1.92404E-02 2.03658E-02 6.64E-03 6.64E-03 6.64E-03 3.2E+00 1\n 4 1.99631E-02 2.07574E-02 3.23E-03 3.23E-03 3.23E-03 2.3E+00 1\n 5 2.03834E-02 2.11141E-02 1.68E-03 1.68E-03 1.68E-03 1.4E+00 0\n 6 2.22419E-02 2.25057E-02 5.73E-04 5.73E-04 5.73E-04 1.4E+00 1\n 7 2.35051E-02 2.35294E-02 6.58E-05 6.58E-05 6.58E-05 1.4E+00 6\n 8 2.35936E-02 2.35941E-02 1.19E-06 1.19E-06 1.19E-06 1.4E+00 0\nIteration 9\n monit() reports good approximate solution (tol = 1.20E-08):\n 9 2.35965E-02 2.35965E-02 5.37E-10 5.37E-10 5.37E-10 1.4E+00 0\nIteration 10\n monit() reports good approximate solution (tol = 1.20E-08):\n 10 2.35965E-02 2.35965E-02 2.68E-13 2.68E-13 2.68E-13 1.4E+00 0\n ------------------------------------------------------------------------------\n Status: converged, an optimal solution found\n ------------------------------------------------------------------------------\n Final primal objective value 2.359648E-02\n Final dual objective value 2.359648E-02\n Absolute primal infeasibility 2.853383E-12\n Relative primal infeasibility 2.677658E-13\n Absolute dual infeasibility 1.485749E-12\n Relative dual infeasibility 2.679654E-13\n Absolute complementarity gap 7.228861E-13\n Relative complementarity gap 2.683908E-13\n Iterations 10\n\n Primal variables:\n idx Lower bound Value Upper bound\n 1 -1.00000E-02 -1.00000E-02 1.00000E-02\n 2 -1.00000E-01 -1.00000E-01 1.50000E-01\n 3 -1.00000E-02 3.00000E-02 3.00000E-02\n 4 -4.00000E-02 2.00000E-02 2.00000E-02\n 5 -1.00000E-01 -6.74853E-02 5.00000E-02\n 6 -1.00000E-02 -2.28013E-03 inf\n 7 -1.00000E-02 -2.34528E-04 inf\n\n Box bounds dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.00000E-02 3.30098E-01 1.00000E-02 0.00000E+00\n 2 -1.00000E-01 1.43844E-02 1.50000E-01 0.00000E+00\n 3 -1.00000E-02 0.00000E+00 3.00000E-02 9.09967E-02\n 4 -4.00000E-02 0.00000E+00 2.00000E-02 7.66124E-02\n 5 -1.00000E-01 3.66960E-12 5.00000E-02 0.00000E+00\n 6 -1.00000E-02 2.47652E-11 inf 0.00000E+00\n 7 -1.00000E-02 7.82645E-13 inf 0.00000E+00\n\n Constraints dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.30000E-01 0.00000E+00 -1.30000E-01 1.43111E+00\n 2 -inf 0.00000E+00 -4.90000E-03 1.07904E-10\n 3 -inf 0.00000E+00 -6.40000E-03 1.14799E-09\n 4 -inf 0.00000E+00 -3.70000E-03 4.09190E-12\n 5 -inf 0.00000E+00 -1.20000E-03 1.52421E-12\n 6 -9.92000E-02 1.50098E+00 inf 0.00000E+00\n 7 -3.00000E-03 1.51661E+00 2.00000E-03 0.00000E+00\n", "meta": {"hexsha": "033d40f6369c4057adcec6a79baa20b0168f53fb", "size": 7604, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/e04mtje.r", "max_stars_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_stars_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-03T22:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T01:44:03.000Z", "max_issues_repo_path": "simple_examples/baseresults/e04mtje.r", "max_issues_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_issues_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_examples/baseresults/e04mtje.r", "max_forks_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_forks_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-03T22:55:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T01:00:53.000Z", "avg_line_length": 46.6503067485, "max_line_length": 79, "alphanum_fraction": 0.5084166228, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.37496098464567024}}
{"text": "############################################################################################################\n############################################################################################################\n## Loading necessary libraries\n############################################################################################################\n############################################################################################################\n\nlibrary(ggplot2)\nlibrary(gridExtra)\nlibrary(lme4)\nlibrary(lmerTest)\nlibrary(robustlmm)\nlibrary(MCMCglmm)\nlibrary(xtable)\nlibrary(shinyBS)\nlibrary(nlme)\nlibrary(combinat)\n\n############################################################################################################\n############################################################################################################\n## Global functions\n############################################################################################################\n############################################################################################################\n\nggCaterpillar=function(re, QQ=TRUE, likeDotplot=TRUE) \n{\n require(ggplot2)\n f = function(x) {\n pv=attr(x, \"postVar\")\n cols=1:(dim(pv)[1])\n se=unlist(lapply(cols, function(i) sqrt(pv[i, i, ])))\n ord=unlist(lapply(x, order)) + rep((0:(ncol(x) - 1)) * nrow(x), each=nrow(x))\n pDf=data.frame(y=unlist(x)[ord],ci=1.96*se[ord],nQQ=rep(qnorm(ppoints(nrow(x))), ncol(x)),\n ID=factor(rep(rownames(x), ncol(x))[ord], levels=rownames(x)[ord]), ind=gl(ncol(x), nrow(x), labels=names(x)))\n \n if(QQ) { \n p = ggplot(pDf, aes(nQQ, y))\n p = p + facet_wrap(~ ind, scales=\"free\")\n p = p + xlab(\"Standard normal quantiles\") + ylab(\"Random effect quantiles\")\n } else { \n p = ggplot(pDf, aes(ID, y)) + coord_flip() + ggtitle(\"Caterpillar plot showing the group-level\\nerror terms for each random effect\") \n if(likeDotplot) { \n p = p + facet_wrap(~ ind)\n } else { \n p = p + facet_grid(ind ~ ., scales=\"free_y\")\n }\n p = p + xlab(\"Groups\") + ylab(\"Deviations\")\n }\n \n p = p + theme_bw() + theme(legend.position=\"none\") + geom_hline(yintercept=0) + \n geom_errorbar(aes(ymin=y-ci, ymax=y+ci), width=0, colour=\"black\") + geom_point(aes(size=2), shape=1) \n \n return(p)\n }\n lapply(re, f)\n}\n\n############################################################################################################\n############################################################################################################\n## Loading sample data sets\n############################################################################################################\n############################################################################################################\n\nkentucky=read.csv(\"data/KentuckyMathScores.csv\")\nmusic=read.csv(\"data/musicdata.csv\")\n\n############################################################################################################\n############################################################################################################\n## Shiny server\n############################################################################################################\n############################################################################################################\n\nshinyServer(function(input, output, session) {\n \n ############################################################################################################\n ############################################################################################################\n ## Upload Data Panel\n ############################################################################################################\n ############################################################################################################\n \n data = reactive({\n if(is.null(input$file) & !input$usesample) \n {\n return(NULL)\n } else if(!is.null(input$file) & !input$usesample)\n {\n file = read.csv(input$file$datapath, header=input$header, sep=input$sep, quote=input$quote)\n return(file)\n } else if(input$usesample)\n {\n return(music)\n }\n })\n \n output$datatable = renderDataTable({\n if(!input$usesample)\n {\n return(data())\n }\n })\n \n output$sampledata = renderDataTable({\n data()\n })\n \n output$selectresponse = renderUI({ \n selectInput(\"response\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel1fixedpred = renderUI({\n selectInput(\"level1.fixed.pred\",\"Level 1 fixed predictors:\",choices=names(data()),multiple=TRUE,selectize=TRUE)\n })\n \n output$selectlevel1randpred = renderUI({\n selectInput(\"level1.rand.pred\",\"Level 1 random predictors:\",choices=names(data()),multiple=TRUE,selectize=TRUE)\n })\n \n output$selectlevel2id = renderUI({\n selectInput(\"level2.id\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n output$selectlevel2pred = renderUI({\n selectInput(\"level2.pred\",\"Level 2 predictors\",choices=names(data()),multiple=TRUE,selectize=TRUE)\n })\n \n ############################################################################################################\n ############################################################################################################\n ## HLM Study Panel\n ############################################################################################################\n ############################################################################################################\n \n ############################################################################################################\n ############################################################################################################\n ## Varying-Intercept Only\n ############################################################################################################\n ############################################################################################################\n \n output$selectresponse1 = renderUI({ \n selectInput(\"response1\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id1 = renderUI({\n selectInput(\"level2.id1\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n dat.nopred = reactive({\n if(!input$usesample)\n {\n dat = data.frame(response = data()[,paste(input$response1)],\n level2.id = factor(data()[,paste(input$level2.id1)]))\n return(dat)\n } else if (input$usesample)\n {\n dat = data.frame(response = data()$negative_affect,\n level2.id = factor(data()$id))\n }\n })\n \n output$datatab1 = renderDataTable({\n if(!input$usesample) return(dat.nopred())\n })\n \n label = reactive({\n if(!input$usesample)\n {\n return(c(paste(input$response1),paste(input$level2.id1)))\n }else if(input$usesample)\n {\n return(c(\"negative affect\",\"musicians\"))\n }\n })\n \n ############################################################################################################\n ## Pooled Regression 1\n ############################################################################################################\n \n output$poolednopredgraph = renderPlot({\n ggplot(data=dat.nopred()) + geom_histogram(aes(x=response),fill=\"white\",color=\"navy\") + \n xlab(paste(label()[1])) + ylab(\"Frequency\") + ggtitle(paste(\"Histogram of\",label()[1],\"with pooled mean imposed\")) + \n theme_bw() + geom_vline(aes(xintercept=mean(response)),linetype=\"dashed\",color=\"navy\")\n })\n \n pooled.mod.nopred = reactive({\n lm(response~1, data=dat.nopred())\n })\n \n output$pooled.nopred.info = renderUI({\n mean = round(mean(dat.nopred()$response,na.rm=TRUE),digits=3)\n p(HTML(\" y̅all = pooled mean =\"), code(paste0(mean)))\n })\n \n ############################################################################################################\n ## Unpooled Regression 1\n ############################################################################################################\n \n output$unpooled.nopred.graph = renderPlot({\n ggplot(data=dat.nopred(),aes(x=level2.id,y=response)) + geom_hline(aes(yintercept=mean(response)),linetype=\"dashed\",color=\"navy\") + \n geom_boxplot(fill=\"white\",color=\"navy\") + xlab(paste(label()[2])) + ylab(paste(label()[1])) + \n ggtitle(paste(\"Boxplots of\",label()[1],\"by\",label()[2],\"with pooled and unpooled means imposed\")) +\n theme_bw() + theme(axis.text.x=element_text(angle=90)) +\n stat_summary(fun.y=\"mean\", geom=\"point\", shape=1, size=3, fill=\"white\", color=\"gold2\") \n })\n \n unpooled.mod.nopred = reactive({\n lm(response~level2.id+0, data=dat.nopred())\n })\n \n output$unpooled.mod.summary = renderTable({\n anova(unpooled.mod.nopred())\n })\n \n output$unpooled.nopred.info = renderDataTable({\n mean.dat = data.frame(tapply(dat.nopred()$response,dat.nopred()$level2.id,mean,na.rm=TRUE))\n mean = round(as.numeric(mean.dat[,1]),digits=3)\n var = round(as.numeric(tapply(dat.nopred()$response,dat.nopred()$level2.id,var,na.rm=TRUE)))\n n = as.numeric(tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) length(!is.na(x))))\n \n dat = data.frame(ID=rownames(mean.dat),Mean=mean,Variance=var,n=n)\n return(dat) \n })\n \n ############################################################################################################\n ## Hierarchical Linear Model 1\n ############################################################################################################\n \n hlm.mod.nopred = reactive({\n lmer(response ~ 1 + (1|level2.id), data=dat.nopred(),\n control=lmerControl(optCtrl=list(maxfun=50000)))\n })\n \n output$hlm.nopred1 = renderPrint({\n summary(hlm.mod.nopred())\n })\n\n coefs = reactive({\n data.frame(coef=coef(hlm.mod.nopred())$level2.id,ran=ranef(hlm.mod.nopred())$level2.id)\n })\n \n output$hlm.nopred2 = renderTable({\n conf = confint(hlm.mod.nopred(),method=\"boot\")\n colnames(conf) = c(\"95% Lower Bound\",\"95% Upper Bound\")\n rownames(conf) = c(\"Between-group SD\",\"Within-group SD\",\"Intercept\")\n return(conf)\n })\n \n output$intraclass1 = renderUI({\n withMathJax(\"$$\\\\hat{\\\\rho} = \\\\frac{\\\\hat{\\\\sigma}_\\\\alpha^{2}}{\\\\hat{\\\\sigma}_\\\\alpha^{2}+\\\\hat{\\\\sigma}_y^{2}}$$\")\n })\n \n variances = reactive({\n c(round(as.numeric(attr(VarCorr(hlm.mod.nopred())[[1]],\"stddev\")^2),digits=3),\n round(as.numeric(attr(VarCorr(hlm.mod.nopred()),\"sc\")^2),digits=3))\n })\n \n output$calcintraclass1 = renderUI({\n icc = round(variances()[1]/sum(variances()),digits=3)\n \n p(\"ICC =\",code(paste(variances()[1])),\" / (\",\n code(paste(variances()[1])),\"+\",\n code(paste(variances()[2])),\") = \",\n code(paste(icc)))\n })\n \n output$ratio1 = renderUI({\n withMathJax(\"$$Variance\\\\,ratio = \\\\frac{\\\\hat{\\\\sigma}_y^{2}}{\\\\hat{\\\\sigma}_\\\\alpha^{2}}$$\")\n })\n \n output$calcratiovariances1 = renderUI({\n ratio = round(variances()[2]/variances()[1],digits=3)\n \n p(\"Ratio =\",code(paste(variances()[2])),\" / \",\n code(paste(variances()[1])), \" = \", code(paste(ratio)))\n })\n \n output$hlmdist1 = renderPlot({ \n ggplot(data=coefs(),aes(x=X.Intercept.)) + geom_histogram(color=\"seagreen2\",fill=\"white\") +\n xlab(\"HLM means\") + ylab(\"Frequency\") + ggtitle(\"Histogram of HLM means\") + theme_bw()\n })\n\n output$hlmdisterror1 = renderPlot({\n ggplot(data=coefs(),aes(x=X.Intercept..1)) + geom_histogram(color=\"salmon\",fill=\"white\") +\n xlab(\"Group-level intercept errors\") + ylab(\"Frequency\") + \n ggtitle(\"Histogram of group-level intercept errors\") + theme_bw()\n })\n\n output$hlmdistinfo1 = renderUI({\n p(HTML(\"- \"),withMathJax(\"\\\\(\\\\hat{\\\\mu}_{\\\\alpha} =\\\\)\"),code(paste(round(as.numeric(fixef(hlm.mod.nopred())),digits=3))),\n HTML(\"
- \"),withMathJax(\"\\\\(\\\\hat{\\\\sigma}_\\\\alpha^{2} =\\\\)\"),code(paste(variances()[1])),HTML(\"
\"))\n })\n \n output$hlmtable = renderDataTable({\n mean.dat = data.frame(tapply(dat.nopred()$response,dat.nopred()$level2.id,mean,na.rm=TRUE))\n n = as.numeric(tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) length(!is.na(x))))\n rancoefs = round(coefs()$X.Intercept..1,digits=3)\n coefs = round(coefs()$X.Intercept.,digits=3)\n \n dat = matrix(c(rownames(mean.dat),coefs,rancoefs,n),ncol=4)\n colnames(dat) = c(\"Group\",\"Estimated intercept\",\"Group-level error\",\"Sample size\")\n return(dat) \n })\n \n output$ggcat1 = renderPlot({\n ggCaterpillar(ranef(hlm.mod.nopred(), condVar=TRUE), QQ=FALSE)\n })\n \n ############################################################################################################\n ## Comparison of Methods 1\n ############################################################################################################\n \n output$shrinkplot = renderPlot({\n samplesize = tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) length(x))\n ind = order(samplesize)\n hlmmean = as.vector(unlist(coef(hlm.mod.nopred())))\n hlmmean = hlmmean[ind]\n hlmse = sqrt(attr(ranef(hlm.mod.nopred(), condVar = TRUE)[[1]], \"postVar\")[1, , ])/samplesize\n hlmse = hlmse[ind]\n unpooledse = tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) sd(x,na.rm=TRUE)/sqrt(length(x)))\n unpooledse = unpooledse[ind]\n unpooledmean = tapply(dat.nopred()$response,dat.nopred()$level2.id,mean,na.rm=TRUE)\n unpooledmean = unpooledmean[ind]\n groups = levels(factor(dat.nopred()$level2.id))\n groups = groups[ind]\n samplesize1 = samplesize[ind]\n dat = data.frame(hlmse=hlmse,hlmmean=hlmmean,unpooledse=unpooledse,unpooledmean=unpooledmean,groups=groups,\n n=samplesize1)\n mean = data.frame(x=mean(dat.nopred()$response),na.rm=TRUE)\n \n g1=ggplot() + theme_bw() + geom_point(data=dat,aes(x=groups,y=unpooledmean,color=\"Unpooled\"),shape=1) +\n geom_point(data=dat,aes(x=groups,y=hlmmean,color=\"HLM\"),shape=16) + \n geom_hline(data=mean,aes(yintercept=x,color=\"Pooled\"),linetype=\"dashed\") + \n geom_errorbar(data=dat,aes(x=groups,y=unpooledmean,ymin=unpooledmean-1.96*unpooledse,ymax=unpooledmean+1.96*unpooledse,color=\"Unpooled\")) +\n geom_errorbar(data=dat,aes(x=groups,y=hlmmean,ymin=hlmmean-1.96*hlmse,ymax=hlmmean+1.96*hlmse,color=\"HLM\")) +\n ylab(\"Mean\") + xlab(\"Group\") + ggtitle(\"Shrinkage plot: 95% CIs using unpooled method and HLM with pooled mean imposed\") +\n scale_color_manual(name=\"Modelling method\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + theme(legend.position=\"bottom\")\n \n g2=ggplot() + theme_bw() + geom_histogram(data=dat,aes(x=unpooledmean,y=..density..,fill=\"Unpooled\"),alpha=.5) +\n geom_histogram(data=dat,aes(x=hlmmean,y=..density..,fill=\"HLM\"),alpha=.5) +\n geom_density(data=dat,aes(x=unpooledmean),color=\"gold2\") +\n geom_density(data=dat,aes(x=hlmmean),color=\"tomato\") +\n geom_vline(data=mean,aes(xintercept=x,fill=\"Pooled\"),color=\"navy\",linetype=\"dashed\") +\n scale_fill_manual(name=\"Modelling method\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + \n theme(legend.position=\"bottom\") + ylab(\"Relative frequency\") + xlab(\"Mean\") + ggtitle(\"Histogram of unpooled and HLM means with pooled mean imposed\") \n \n g3 = arrangeGrob(g1,g2,nrow=1)\n return(g3)\n },height=500)\n\n ############################################################################################################\n ## Bayesian Hierarchical Linear Model 1\n ############################################################################################################\n\n hlmbayes1 = reactive({\n MCMCglmm(response ~ 1, random=~level2.id, data=dat.nopred(), verbose=FALSE, pr=TRUE)\n })\n\n output$hlm.bayes1 = renderPrint({\n summary(hlmbayes1())\n })\n\n output$postdist = renderPlot({\n group.error = data.frame(x=as.vector(hlmbayes1()$VCV[,1]))\n indiv.error = data.frame(x=as.vector(hlmbayes1()$VCV[,2]))\n int = data.frame(x=as.vector(hlmbayes1()$Sol[,1]))\n \n group.plot = ggplot(data=group.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Between-group var in response\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n group.trace = ggplot(data=group.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Between-group\\nvar in response\")\n indiv.plot = ggplot(data=indiv.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Within-group var in response\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n indiv.trace = ggplot(data=indiv.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Within-group\\nvar in response\")\n int.plot = ggplot(data=int) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Intercept\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n int.trace = ggplot(data=int) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Intercept\")\n graph = arrangeGrob(group.trace,group.plot,indiv.trace,indiv.plot,int.trace,int.plot,nrow=3,ncol=2,\n main=textGrob(\"Traceplots and Posterior Distributions\",gp=gpar(fontsize=15)))\n graph\n },height=500)\n\n ############################################################################################################\n ############################################################################################################\n ## Varying-intercept and varying-slope \n ############################################################################################################\n ############################################################################################################\n\n output$selectresponse2 = renderUI({ \n selectInput(\"response2\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id2 = renderUI({\n selectInput(\"level2.id2\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n\n output$selectlevel1pred1 = renderUI({\n selectInput(\"level1.pred1\",\"Level 1 predictor:\",choices=names(data()),selectize=TRUE)\n })\n\n dat.pred1 = reactive({\n if(!input$usesample)\n {\n dat = data.frame(predictor = data()[,paste(input$level1.pred1)],\n response = data()[,paste(input$response2)],\n level2.id = factor(data()[,paste(input$level2.id2)]))\n } else if (input$usesample)\n {\n dat = data.frame(predictor = data()$previous,\n response = data()$negative_affect,\n level2.id = factor(data()$id))\n return(dat)\n }\n })\n\n label1 = reactive({\n if(!input$usesample)\n {\n return(c(paste(input$response2),paste(input$level1.pred1),paste(input$level2.id2)))\n }else if(input$usesample)\n {\n return(c(\"negative affect\",\"previous\",\"musicians\"))\n }\n })\n \n ############################################################################################################\n ## Pooled Regression 2\n ############################################################################################################\n \n output$pooled.graph = renderPlot({\n ggplot(data=dat.pred1(), aes(x=predictor,y=response)) + \n geom_point(position = \"jitter\", size=3, shape=1) +\n geom_smooth(method=\"lm\",color=\"navy\",se=FALSE) + xlab(paste(label1()[2])) + ylab(paste(label1()[1])) +\n ggtitle(paste(\"Scatterplot of\",label1()[1],\"versus\", label1()[2],\"with pooled line imposed\")) + theme_bw()\n })\n \n pooled.mod = reactive({\n lm(response~predictor, data=dat.pred1())\n })\n \n output$pooled.output = renderTable({\n return(summary(pooled.mod()))\n })\n \n output$pooled.info = renderText({\n paste0(\"R-squared=\",round(summary(pooled.mod())$r.squared,digits=3),\"; Residual df=\",pooled.mod()$df.residual)\n })\n \n ############################################################################################################\n ## Unpooled Regression 2\n ############################################################################################################\n \n output$unpooled.graph = renderPlot({\n ggplot(data=dat.pred1(), aes(x=predictor,y=response)) + geom_point(position = \"jitter\", size=3, shape=1) +\n geom_smooth(aes(group=level2.id),method=\"lm\",color=\"gold2\",se=FALSE) + \n geom_smooth(aes(group=1),method=\"lm\",color=\"navy\",se=FALSE) + xlab(paste(label1()[2])) + ylab(paste(label1()[1])) +\n ggtitle(paste(\"Scatterplot of\",label1()[1],\"versus\",label1()[2],\"with unpooled lines imposed\")) + theme_bw()\n })\n \n unpooled.mod = reactive({\n lm(response~0+predictor+factor(level2.id)+factor(level2.id)*predictor, data=dat.pred1())\n })\n \n output$unpooled.output = renderTable({\n return(anova(unpooled.mod()))\n })\n \n output$unpooled.info = renderText({\n paste0(\"R-squared=\",round(sum(anova(unpooled.mod())$Sum[1:3])/sum(anova(unpooled.mod())$Sum),digits=3))\n })\n \n slope.intercept = reactive({\n id = unique(dat.pred1()$level2.id)\n slope=NULL\n intercept=NULL\n n=NULL\n i=0\n while(i\"),withMathJax(\"\\\\(\\\\hat{\\\\mu}_{\\\\alpha} =\\\\)\"),code(paste(round(as.numeric(fixef(hlm.mod.nopred())),digits=3))),\n HTML(\"\"),withMathJax(\"\\\\(\\\\hat{\\\\sigma}_\\\\alpha^{2} =\\\\)\"),code(paste(variances()[2])),HTML(\"\"))\n })\n\n output$hlmparamdist2 = renderPlot({\n dat = data.frame(ranef(hlm())$level2.id)\n plot1 = ggplot(dat) + geom_histogram(aes(x=X.Intercept.), color=\"salmon\",fill=\"white\") +\n xlab(\"Group-level intercept errors\") + ylab(\"Frequency\") +\n ggtitle(\"Histogram of group-level\\nintercept errors\") + theme_bw()\n plot2 = ggplot(dat) + geom_histogram(aes(x=predictor), color=\"salmon\",fill=\"white\") +\n xlab(\"Group-level slope errors\") + ylab(\"Frequency\") +\n ggtitle(\"Histogram of group-level\\nslope errors\") + theme_bw()\n plot3 = arrangeGrob(plot1,plot2,nrow=1)\n return(plot3)\n })\n\n output$ggcat2 = renderPlot({\n ggCaterpillar(ranef(hlm(), condVar=TRUE), QQ=FALSE)\n })\n \n ############################################################################################################\n ## Comparison of Methods 2\n ############################################################################################################\n \n output$slopeint.comp = renderPlot({\n dat = dat.pred1()\n mod = lm(response~predictor,data=dat)\n datline = data.frame(x=as.numeric(mod$coef[1]),y=as.numeric(mod$coef[2]))\n \n intercept = ggplot() + geom_histogram(data=slope.intercept(),aes(x=intercept,y=..density..,fill=\"Unpooled\"),alpha=.5) +\n geom_histogram(data=hlm.slope.intercept(),aes(x=int.vec,y=..density..,fill=\"HLM\"),alpha=.5) + \n geom_density(data=slope.intercept(),aes(x=intercept),color=\"gold2\") + \n geom_vline(data=datline,aes(xintercept=x),color=\"navy\",linetype=\"dashed\") +\n geom_density(data=hlm.slope.intercept(),aes(x=int.vec),color=\"tomato\") +\n ggtitle(\"Histogram of sample intercepts\") + xlab(\"Sample intercepts\") + ylab(\"Relative frequency\") +\n scale_fill_manual(name=\"Model\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + \n guides(fill=FALSE) + theme_bw()\n \n slope = ggplot() + geom_histogram(data=slope.intercept(),aes(x=slope,y=..density..,fill=\"Unpooled\"),alpha=.5) +\n geom_histogram(data=hlm.slope.intercept(),aes(x=slope.vec,y=..density..,fill=\"HLM\"),alpha=.5) + \n geom_density(data=slope.intercept(),aes(x=slope),color=\"gold2\") + \n geom_vline(data=datline,aes(xintercept=y),color=\"navy\",linetype=\"dashed\") +\n geom_density(data=hlm.slope.intercept(),aes(x=slope.vec),color=\"tomato\") + \n ggtitle(\"Histogram of sample slopes\") + xlab(\"Sample slopes\") + ylab(\"Relative frequency\") +\n scale_fill_manual(name=\"Model\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + \n guides(fill=FALSE) + theme_bw()\n \n graph1 = arrangeGrob(intercept,slope,nrow=1)\n \n graph2 = ggplot() + geom_vline(data=datline,aes(xintercept=x),color=\"navy\",linetype=\"dashed\") + \n geom_hline(data=datline,aes(yintercept=y),color=\"navy\",linetype=\"dashed\") + \n geom_point(data=hlm.slope.intercept(),aes(x=int.vec,y=slope.vec,color=\"HLM\"),size=3,shape=1) +\n geom_point(data=slope.intercept(),aes(x=intercept,y=slope,color=\"Unpooled\"),size=3,shape=1) +\n geom_smooth(data=hlm.slope.intercept(),aes(x=int.vec,y=slope.vec,color=\"HLM\"),method=\"lm\",se=FALSE) + \n geom_smooth(data=slope.intercept(),aes(x=intercept,y=slope,color=\"Unpooled\"),method=\"lm\",se=FALSE) + \n ggtitle(\"Scatterplot of sample slopes versus intercepts with pooled estimates imposed\") +\n xlab(\"Intercepts\") + ylab(\"Slopes\") + scale_color_manual(name=\"Modelling method\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\")) +\n theme_bw() + theme(legend.position=\"bottom\")\n \n graph3 = arrangeGrob(graph2,graph1,ncol=1)\n \n return(graph3)\n },height=800)\n\n output$comp.method = renderPlot({\n dat = dat.pred1()\n dat$hlmpred = fitted(hlm())\n \n mod = lm(response~predictor,data=dat)\n dat$x=as.numeric(mod$coef[1])\n dat$y=as.numeric(mod$coef[2])\n \n ggplot(data=dat) + geom_point(aes(x=predictor,y=response),shape=1) + facet_wrap(~level2.id) + theme_bw() +\n geom_smooth(aes(x=predictor,y=response, color=\"Unpooled\"), method=\"lm\", se=FALSE) +\n geom_abline(aes(intercept=x,slope=y, color=\"Pooled\"),size=.5) +\n geom_smooth(aes(x=predictor,y=hlmpred,color=\"HLM\"),method=\"lm\",se=FALSE) +\n scale_color_manual(name=\"Modelling method\", values=c(\"Pooled\"=\"navy\",\"Unpooled\"=\"gold2\",\"HLM\"=\"tomato\")) +\n theme(legend.position=\"bottom\", legend.direction=\"horizontal\") + xlab(paste(label1()[2])) + ylab(paste(label1()[1])) +\n ggtitle(\"Comparison of the three modelling methods\")\n },height=800)\n\n ############################################################################################################\n ## Bayesian Hierarchical Linear Model 2\n ############################################################################################################\n\n hlmbayes2 = reactive({\n MCMCglmm(response ~ predictor, random=~level2.id+predictor, data=dat.pred1(), \n verbose=FALSE, pr=TRUE)\n })\n \n output$hlm.bayes2 = renderPrint({\n summary(hlmbayes2())\n })\n \n output$postdist2 = renderPlot({\n slope.error = data.frame(x=as.vector(hlmbayes2()$VCV[,2]))\n indiv.error = data.frame(x=as.vector(hlmbayes2()$VCV[,3]))\n group.error = data.frame(x=as.vector(hlmbayes2()$VCV[,1]))\n int = data.frame(x=as.vector(hlmbayes2()$Sol[,1]))\n group.slope.plot = ggplot(data=slope.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Between-group var in slopes\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n group.slope.trace = ggplot(data=slope.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Between-group\\nvar in slopes\")\n group.error.plot = ggplot(data=group.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Between-group var in intercepts\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n group.error.trace = ggplot(data=group.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Between-group\\nvar in intercepts\")\n indiv.plot = ggplot(data=indiv.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Within-group var in response\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n indiv.trace = ggplot(data=indiv.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Within-group\\nvar in response\")\n int.plot = ggplot(data=int) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Intercept\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n int.trace = ggplot(data=int) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Intercept\")\n graph = arrangeGrob(group.error.trace,group.error.plot,group.slope.trace,group.slope.plot,indiv.trace,\n indiv.plot,int.trace,int.plot,nrow=4,ncol=2,main=textGrob(\"Traceplots and Posterior Distributions\",gp=gpar(fontsize=15)))\n return(graph)\n },height=600)\n\n ############################################################################################################\n ############################################################################################################\n ## Varying-intercept and varying-slope with level 2 predictor\n ############################################################################################################\n ############################################################################################################\n\n output$selectresponse3 = renderUI({ \n selectInput(\"response3\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id3 = renderUI({\n selectInput(\"level2.id3\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n output$selectlevel1pred2 = renderUI({\n selectInput(\"level1.pred2\",\"Level 1 predictor:\",choices=names(data()),selectize=TRUE)\n })\n\n output$selectlevel2pred1 = renderUI({\n selectInput(\"level2.pred1\",\"Level 2 predictor:\",choices=names(data()),selectize=TRUE)\n })\n\n dat.pred2 = reactive({\n if(!input$usesample)\n {\n dat = data.frame(predictor = data()[,paste(input$level1.pred2)],\n response = data()[,paste(input$response3)],\n level2.id = factor(data()[,paste(input$level2.id3)]),\n level2.predictor = data()[,paste(input$level2.pred1)])\n return(dat)\n }else if(input$usesample)\n {\n dat = data.frame(predictor = data()$previous,\n response = data()$negative_affect,\n level2.id = factor(data()$id),\n level2.predictor = data()$years_study)\n return(dat)\n }\n })\n\n label2 = reactive({\n if(!input$usesample)\n {\n return(c(paste(input$response3),paste(input$level1.pred2),paste(input$level2.id3),paste(input$level2.pred1)))\n } else if(input$usesample)\n {\n return(c(\"negative affect\",\"previous\",\"musicians\",\"years study\"))\n }\n })\n\n ############################################################################################################\n ## Two stage modelling\n ############################################################################################################\n\n stage2 = reactive({\n dat.pred2()[!duplicated(dat.pred2()$level2.id),]\n })\n\n output$int.mod = renderTable({ \n dat = data.frame(intercept=slope.intercept()$intercept,level2.predictor=stage2()$level2.predictor)\n \n lm(intercept ~ level2.predictor, data=dat)\n })\n\n output$slope.mod = renderTable({ \n dat = data.frame(slope=slope.intercept()$slope,level2.predictor=stage2()$level2.predictor)\n \n lm(slope ~ level2.predictor, data=dat)\n })\n\n output$stage2graph = renderPlot({\n dat = data.frame(int=slope.intercept()$intercept,slope=slope.intercept()$slope,pred=stage2()$level2.predictor)\n \n g1 = ggplot(data=dat,aes(x=pred,y=int)) + geom_point(shape=1) + geom_smooth(method=\"lm\",se=FALSE,color=\"gold2\") +\n xlab(paste(label2()[4])) + ylab(\"Unpooled intercepts\") + theme_bw() + \n ggtitle(paste(\"Scatterplot of unpooled\\nintercepts versus\",label2()[4]))\n \n g2 = ggplot(data=dat,aes(x=pred,y=slope)) + geom_point(shape=1) + geom_smooth(method=\"lm\",se=FALSE,color=\"gold2\") +\n xlab(paste(label2()[4])) + ylab(\"Unpooled slopes\") + theme_bw() +\n ggtitle(paste(\"Scatterplot of unpooled\\nslopes versus\",label2()[4]))\n \n g3 = arrangeGrob(g1,g2,nrow=1)\n return(g3)\n })\n\n ############################################################################################################\n ## Hierarchical Linear Model 3\n ############################################################################################################\n\n hlm2 = reactive({\n return(lmer(response ~ predictor + level2.predictor + predictor:level2.predictor + \n (1 + predictor|level2.id), data=dat.pred2(),\n control=lmerControl(optCtrl=list(maxfun=50000))))\n })\n \n output$hlm.summary1 = renderPrint({\n summary(hlm2())\n })\n\n output$hlm.confint2 = renderTable({\n conf = confint(hlm2(),method=\"boot\")\n colnames(conf) = c(\"95% Lower Bound\",\"95% Upper Bound\")\n rownames(conf) = c(\"Between-group Intercept SD\",\"Correlation\",\"Between-group Slope SD\",\"Within-group SD\",\n \"Intercept\",\"Level 1 Predictor\",\"Level 2 Predictor\",\"Cross-level Interaction\")\n return(conf)\n })\n\n output$hlmhyper1 = renderTable({\n vec = as.vector(fixef(hlm2()))\n tab = matrix(vec,nrow=1)\n colnames(tab) = c(\"Intercept\",\"Level 1 Predictor\",\"Level 2 Predictor\",\"Cross-level Interaction\")\n rownames(tab) = \"Estimates\"\n return(tab)\n })\n\n output$hlmhyper2 = renderPrint({\n VarCorr(hlm2())\n })\n\n output$ggcat3 = renderPlot({\n ggCaterpillar(ranef(hlm2(), condVar=TRUE), QQ=FALSE)\n })\n\n ############################################################################################################\n ## Comparison of Methods 3\n ############################################################################################################\n\n output$compgraph = renderPlot({\n dat = data.frame(int=slope.intercept()$intercept,slope=slope.intercept()$slope,pred=stage2()$level2.predictor)\n dat1 = data.frame(int1=fixef(hlm2())[1],slope1=fixef(hlm2())[3],int2=fixef(hlm2())[2],slope2=fixef(hlm2())[4])\n \n g1 = ggplot() + geom_point(data=dat,aes(x=pred,y=int,color=\"Unpooled\"),shape=1) + \n geom_smooth(data=dat,aes(x=pred,y=int,color=\"Unpooled\"),method=\"lm\",se=FALSE) +\n xlab(paste(label2()[4])) + ylab(\"Intercepts\") + theme_bw() +\n geom_abline(data=dat1,aes(intercept=int1,slope=slope1,color=\"HLM\")) +\n scale_color_manual(name=\"Modelling method\", values=c(\"Unpooled\"=\"gold2\",\"HLM\"=\"tomato\")) +\n theme(legend.position=\"bottom\", legend.direction=\"horizontal\") +\n ggtitle(paste(\"Scatterplot of intercepts versus\",label2()[4],\"\\ncomparing the unpooled method and HLM\"))\n \n g2 = ggplot() + geom_point(data=dat,aes(x=pred,y=slope,color=\"Unpooled\"),shape=1) + \n geom_smooth(data=dat,aes(x=pred,y=slope,color=\"Unpooled\"),method=\"lm\",se=FALSE) +\n xlab(paste(label2()[4])) + ylab(\"Slopes\") + theme_bw() +\n geom_abline(data=dat1,aes(intercept=int2,slope=slope2,color=\"HLM\")) +\n scale_color_manual(name=\"Modelling method\", values=c(\"Unpooled\"=\"gold2\",\"HLM\"=\"tomato\")) +\n theme(legend.position=\"bottom\", legend.direction=\"horizontal\") +\n ggtitle(paste(\"Scatterplot of slopes versus\",label2()[4],\"\\ncomparing the unpooled method and HLM\"))\n \n g3 = arrangeGrob(g1,g2,nrow=1)\n return(g3)\n },height=500)\n \n\n ############################################################################################################\n ############################################################################################################\n ## Analyze Data Tab\n ############################################################################################################\n ############################################################################################################\n \n output$selectresponse.analyze = renderUI({ \n selectInput(\"responseanalyze\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id.anaylze = renderUI({\n selectInput(\"level2.idanalyze\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n output$selectlevel1pred.analyze = renderUI({\n selectizeInput(\"level1.predanalyze\",\"Level 1 predictor(s):\",choices=names(data()),\n multiple=TRUE,options=list(placeholder=\"level 1 predictor(s)\"))\n })\n\n output$selectlevel1pred.analyze.rand = renderUI({\n selectizeInput(\"level1.predanalyze.rand\",\"Random predictor(s):\",choices=input$level1.predanalyze,\n multiple=TRUE,options=list(placeholder=\"random predictor(s)\"))\n })\n \n output$selectlevel2pred.analyze = renderUI({\n selectizeInput(\"level2.predanalyze\",\"Level 2 predictor(s):\",choices=names(data()),\n multiple=TRUE,options=list(placeholder=\"level 2 predictor(s)\"))\n })\n\n output$selectcrosslevint = renderUI({\n selectizeInput(\"crosslevelint\", \"Cross-level interaction(s):\", \n choices=as.vector(outer(input$level1.predanalyze.rand, input$level2.predanalyze, paste, sep=\":\")),\n multiple=TRUE,options=list(placeholder=\"cross-level interaction(s)\"))\n })\n\n dat.analyze = reactive({\n dat.pred1=matrix(nrow=dim(data())[1],ncol=length(input$level1.predanalyze))\n i=0\n formula1 = NULL\n formula1 = input$level1.predanalyze[1]\n while(i1) formula1 = paste0(formula1,\"+\",input$level1.predanalyze[i])\n }\n colnames(dat.pred1) = input$level1.predanalyze\n dat.pred1 = data.frame(dat.pred1)\n \n formula2=NULL\n dat.pred2=matrix(nrow=dim(data())[1],ncol=length(input$responseanalyze))\n if(length(input$level2.predanalyze)>0)\n {\n j=0\n formula2 = paste(\"+\",input$level2.predanalyze[1])\n while(j1) formula2 = paste0(formula2,\"+\",input$level2.predanalyze[j])\n }\n colnames(dat.pred2) = input$level2.predanalyze\n dat.pred2 = data.frame(dat.pred2)\n }\n \n formula3=NULL\n if(length(input$level1.predanalyze.rand)>0)\n {\n k=1\n formula3 = paste0(\"+\",input$level1.predanalyze.rand[1])\n while(k0)\n {\n l=1\n formula4 = paste0(\"+\",input$crosslevelint[1])\n while(l0)\n {\n summary = summary(mod.analyze())\n summary$call=NULL\n return(summary)\n }\n })\n }) \n\n})", "meta": {"hexsha": "061ac26c97ba035acc5babc7a781be0e0d4232e2", "size": 44032, "ext": "r", "lang": "R", "max_stars_repo_path": "Hierarchical_Models/server.r", "max_stars_repo_name": "townsenddw/shiny1", "max_stars_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hierarchical_Models/server.r", "max_issues_repo_name": "townsenddw/shiny1", "max_issues_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hierarchical_Models/server.r", "max_forks_repo_name": "townsenddw/shiny1", "max_forks_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T12:48:05.000Z", "avg_line_length": 45.7237798546, "max_line_length": 156, "alphanum_fraction": 0.5285928416, "num_tokens": 11249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.37483677006187954}}
{"text": "# 3. faza: Vizualizacija podatkov\n#Delež ljudi glede na BDP, ki je v zadnjih 3 mesecih opravilo spletni nakup\ngraf1 <- ggplot(tabela1) + aes(x = BDPpc, y = Value, color = Education) + geom_point() + xlab(\"BDP na prebivalca\") + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih opravil spletni nakup\") + ggtitle(\"Delež ljudi glede na BDP na prebivalca, ki je opravil spletni nakup v zadnjih 3 mesecih\") + labs(color = \"Odstotek prebivalstva s 3. stopnjo izobrazbe\")\n\"Delež ljudi glede na delež ljudi s tretjo st izobrazbe, ki je opravil spletni nakup v zadnjih 3 mesecih\"\ngraf2 <- ggplot(tabela1) + aes(x = Education, y = Value, color = Area ) + geom_point() + xlab(\"Delež ljudi s tretjo stopnjo izobrazbe\") + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih opravil spletni nakup\") + ggtitle(\"Delež ljudi glede na delež ljudi s tretjo stopnjo izobrazbe, ki je opravilo spletni nakup v zadnjih 3 mesecih\") + scale_color_discrete(name=\"Predel\", labels=c(\"Živeči v mestih\", \"Živeči na ruralnih območjih\"))\n\n\n#tabela2 %>%\n# ggplot(\n# mapping = aes(x = tabela2)\n# ) +\n# geom_histogram() \n#\n\ngraf3 <- tabela1 %>%\n ggplot(\n mapping = aes(group= Country, x = Country, y = Value)\n ) +\n geom_boxplot() + \n xlab(\"Država\") + ylab(\"Kolikšen delež ljudi je v zadnjih 3 mesecih kupil nekaj preko spleta\") + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))\n\n\nn <- tabela1 %>% dplyr::group_by(Country) %>% dplyr::summarise(mean = mean(Value, na.rm = TRUE))\nv <- tabela1 %>% dplyr::group_by(Country) %>% dplyr::summarise(BDPmean = mean(BDPpc, na.rm = TRUE))\nn$BDP_mean <- v$BDPmean\n\n\ngraf4 <- ggplot(data = tabela1, aes(x = Year, y = Value, color = Country)) +\n geom_line() + xlab(\"Leto\") + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih kupil nekaj prek spleta\") + ggtitle(\"Spreminjanje odstotka ljudi po državah, ki so nakupovali prek spleta, čez leta\") + labs(color = \"Država\")\n\ngraf5 <- ggplot(data = tabela1, aes(x = Year, y = Value, color = Area)) +\n geom_line() +\n facet_wrap(facets = vars(Country)) + xlab('Leto') + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih kupil nekaj prek spleta\") + ggtitle(\"Spreminjanje odstotka ljudi po državah, ki so nakupovali prek spleta, čez leta\") + scale_color_discrete(name=\"Predel\", labels=c(\"Živeči v mestih\", \"Živeči na ruralnih območjih\"))\n\n\ngraf6 <- ggplot(data = tabela2, mapping = aes(x = Year, y = Koliko_vseh_nakupov_je_opravila_ta_skupina, color = Stopnja)) +\n geom_line() +\n facet_wrap(facets = vars(Country)) + xlab('Leto') + ylab(\"Kolikšen delež vseh nakupov je opravila določena skupina\") + ggtitle(\"Spreminjanje odstotka ljudi po državah in doseženi izobrazbi, ki so nakupovali prek spleta, čez leta\") + scale_color_discrete(name=\"Dosežena stopnja izobrazbe\", labels=c(\"Posamezniki z visoko formalno izobrazbo\", \"Posamezniki s srednjo formalno izobrazbo\", \"Posamezniki brez ali z nizko izobrazbo\", \"Študenti\"))\n\n\ngraf7 <- ggplot(data=n, aes(x=Country, y=mean, fill = BDP_mean)) +\n geom_bar(stat=\"identity\") + coord_flip() + scale_fill_gradient(low=\"pink\", high=\"magenta\")+ xlab('Država') + ylab('Povprečen odstotek ljudi, ki kupuje prek spleta v tej državi') + labs(fill = \"Povprečni BDP per capita\") + ggtitle(\"Odstotek ljudi, ki nakupuje prek spleta glede na BDP\")\n\n\nspr <- tabela1\nspr[\"Education\"] <- as.integer(unlist(spr[\"Education\"]))\nizobrazba <- spr %>% dplyr::group_by(Country) %>% dplyr::summarise(Edmean = mean(Education, na.rm = TRUE))\n\n\nn$Edmean <- izobrazba$Edmean\ngraf8 <- ggplot(data=n, aes(x=Country, y=mean, fill = Edmean)) +\n geom_bar(stat=\"identity\") + coord_flip() + scale_fill_gradient(low=\"yellow\", high=\"red\")+ ylab('Povprečen odstotek ljudi, ki nakupuje prek spleta v tej državi') + xlab('Država') + labs(fill = \"Povprečen delež ljudi s tretjo stopnjo izobrazbe\") + ggtitle(\"Odstotek ljudi, ki nakupuje prek spleta glede na odstotek ljudi z doseženo tretjo stopnjo izobrazbe\")\n\n\n\ntabela3_c[,3] <- as.integer(as.character(unlist(tabela3_c[,3])))\ntabela3_c[,4] <- as.integer(unlist(tabela3_c[,4]))\ntabela3_c[,5] <- as.integer(unlist(tabela3_c[,5]))\ntabela3_c[,6] <- as.integer(unlist(tabela3_c[,6]))\ntabela3_c[,7] <- as.integer(unlist(tabela3_c[,7]))\n\nttt <- tabela3_c %>% dplyr::filter(year == 2019, country == 'Slovenia') %>% pivot_longer(c(3, 4, 5, 6, 7), names_to = 'type', values_to = \"value\")\ngraf9 <- ggplot(data = ttt, mapping = aes(x = country, y = value, fill = type)) +\n geom_bar(width = 1, stat = 'identity') + coord_polar(\"y\", start=0) + xlab('') + ylab('') + ggtitle(\"Kaj kupujejo ljudje v posamezni državi?\") + scale_fill_discrete(name = \"Vrsta kupljenega izdelka\", labels = c(\"Knjige, revije, učenje,...\", \"Obleke, šport\", \"Filmi, glasba\", \"Gospodinjski pripomočki\", \"Potovanja, hoteli,...\"))\n\ntabela2_c[,4] <- as.integer(unlist(tabela2_c[,4]))\ntabela2_c[,5] <- as.integer(unlist(tabela2_c[,5]))\nfff1 <- tabela2_c %>% dplyr::filter(year == 2019, country == 'United Kingdom', stopnja == 'Individuals with high formal education') %>% pivot_longer(c(4, 5), names_to = 'type', values_to = 'value')\ngraf10 <- ggplot(data = fff1, mapping = aes(x = country, y = value, fill = type)) +\n geom_bar(width = 1, stat = 'identity') + coord_polar(\"y\", start=0) + ggtitle(\"Kaj kupujejo ljudje\\nz doseženo visoko izobrazbo\\nv Združenem kraljestvu?\") + xlab('') + ylab('') + scale_fill_discrete(name = 'Vrsta kupljenega izdelka', labels = c('Knjige, revije, učenje,...', \"Obleke, šport\")) +\n theme(legend.position = \"none\", axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank())\n\nfff2 <- tabela2_c %>% dplyr::filter(year == 2019, country == 'United Kingdom', stopnja == 'Individuals with no or low formal education') %>% pivot_longer(c(4, 5), names_to = 'type', values_to = 'value')\ngraf11 <- ggplot(data = fff2, mapping = aes(x = country, y = value, fill = type)) +\n geom_bar(width = 1, stat = 'identity') + coord_polar(\"y\", start=0) + ggtitle(\"Kaj kupujejo ljudje \\nbrez izobrazbe ali \\nnizko izobrazbo\\nv Združenem kraljestvu?\") + xlab('') + ylab('') + scale_fill_discrete(name = 'Vrsta kupljenega izdelka', labels = c('Knjige, revije, učenje,...', \"Obleke, šport\")) +\n theme(axis.text = element_blank(),\n axis.ticks = element_blank(),\n panel.grid = element_blank())\n\n\n\n\nlibrary(tmap)\n\nworld <- ne_countries(scale = \"medium\", returnclass = \"sf\")\nEurope <- world[which(world$continent == \"Europe\"),]\nggplot(Europe) +\n geom_sf() +\n coord_sf(xlim = c(-25,50), ylim = c(35,70), expand = FALSE) +\n aes(fill = 'pink')\n\nlvls <-(Europe$sovereignt)\nprimerjava <- data.frame(Country = lvls) %>% left_join(tabela1, by = \"Country\")\nmanjkajoci <- primerjava[is.na(primerjava$BDPpc), ]\n\n\ndf = data.frame(drzava = manjkajoci$Country, Country = c(\"Albania\", \n \"Andorra\",\n \"Bosnia and Herzegovina\",\n \"Belarus\",\n \"Czechia\",\n \"Germany (until 1990 former territory of the FRG)\",\n \"Kosovo\",\n \"Liechtenstein\",\n \"Monaco\",\n \"Moldova\",\n \"North Macedonia\",\n \"Montenegro\",\n \"Russia\",\n \"San Marino\",\n \"Serbia\",\n \"Ukraine\",\n \"Vatican\"))\ntabela1 <- tabela1 %>% left_join(df) %>% dplyr::mutate(Country=ifelse(is.na(drzava), Country, drzava))\ntabela1 <- tabela1 %>% dplyr::select(-drzava)\nn2 <- tabela1 %>% dplyr::group_by(sovereignt = Country) %>% dplyr::summarise(mean = mean(Value, na.rm = TRUE))\nm <- merge(Europe, n2)\nz3 <- ggplot(m) +\n geom_sf() +\n coord_sf(xlim = c(-25,50), ylim = c(35,70), expand = FALSE) +\n aes(fill = mean) +\n scale_fill_gradient(low=\"yellow\", high=\"magenta\") + ggtitle('Katera država v povprečju največ spletno nakupuje?') + labs(fill = \"Odstotek ljudi,\\nki je v zadnjih 3 mesecih\\nspletno nakupoval\\n(povprečno)\")\n\n\n\n\n", "meta": {"hexsha": "6bc80729d7929bc65c073e8f1969d33bfab287ce", "size": 8461, "ext": "r", "lang": "R", "max_stars_repo_path": "vizualizacija/vizualizacija.r", "max_stars_repo_name": "pavlanovak/APPR-2021-22", "max_stars_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vizualizacija/vizualizacija.r", "max_issues_repo_name": "pavlanovak/APPR-2021-22", "max_issues_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-03T11:13:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T22:29:08.000Z", "max_forks_repo_path": "vizualizacija/vizualizacija.r", "max_forks_repo_name": "pavlanovak/APPR-2021-22", "max_forks_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.6220472441, "max_line_length": 442, "alphanum_fraction": 0.6184848127, "num_tokens": 2768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.37483677006187954}}
{"text": "#Tutorial and Tips for Numerai\n\n#***\n#The stock market is the hardest data science problem in the world.\n#If it seems easy, you're doing it wrong.\n#We don't know how to solve this problem. But here is what we know.\n#We need your help. You take it from here.\n#***\nlibrary(Metrics)\nlibrary(gbm)\nlibrary(randomForest)\n\n# for automatic download of data and upload of submissions have a look at the package Rnumerai\n# for the latest development release use devtools::install_github(\"Omni-Analytics-Group/Rnumerai\") or pak::pkg_install(\"Omni-Analytics-Group/Rnumerai\")\n# for the CRAN version use install.packages(\"Rnumerai\")\n\nprint(\"THIS SCRIPT DOWNSAMPLES DATA AND WILL LIKELY UNDERPERFORM THE example_predictions.csv\")\n\n#the training data is used to train your model how to predict the targets\ntraining_data<-read.csv(\"numerai_training_data.csv\", header=T)\n#the tournament data is the data that Numerai uses to evaluate your model\ntournament<-read.csv(\"numerai_tournament_data.csv\", header=T)\n#the tournament data contains validation data, test data and live data\n#validation is a hold out set out of sample and further in time (higher eras) than the training data\nvalidation<-tournament[tournament$data_type==\"validation\",]\n\nbenchmark<-0.002\nconsistency<-function(data_with_probs, target_name){\n unique_eras<-unique(data_with_probs$era)\n era_correlation<-vector()\n i<-1\n while(i<=length(unique_eras)){\n this_data<-data_with_probs[data_with_probs$era==unique_eras[i],]\n era_correlation[i]<-cor(this_data[,names(this_data)==target_name], this_data$prediction, method=\"spearman\")\n i<-i+1\n }\n consistency<-sum(era_correlation>benchmark)/length(era_correlation)\n consistency\n}\n\n#the training data is large so we reduce it by 10x in order to speed up this script\n#NB reducing the training data like this is not recommended for a production ready model\nnrow(training_data)\nset.seed(10)\n#remove the following line to not downsample. Note: it will take much longer to run\nsample_rows<-sample(1:nrow(training_data), ceiling(nrow(training_data)/10))\ntrain<-training_data[sample_rows,]\n\n#we remove the id, era, and data_type columns for now\ntrain<-train[,-c(1:3)]\nnrow(train)\n\n#there are a large number of features\nncol(train)\n#features are a number of feature groups of different sizes (intelligence, charisma, strength, dexterity, constitution, wisdom)\n#Numerai does not disclose what the features or feature groups mean; they are abstract and obfuscated\n#however, features within feature groups tend to be related in some way\n#models which have large feature importance in one group tend to do badly for long stretches of time (eras).\nhead(names(train),20)\n\n#the target variable has 5 ordinal outcomes (0,0.25,0.5,0.75,1)\n#we train a model on the features to predict this target\nsummary(train$target)\n\n#on this dataset, feature importance analysis is very important\n#we build a random forest to understand which features tend to improve the model out of bag\n#because stocks within eras are not independent, we use small bag sizes (sampsize=10%) so the out of bag estimate is meaningful\n#we use a small subset of features for each tree to build a more feature balanced forest (mtry=10%)\nset.seed(10)\nforest<-randomForest(target~., data=train, ntree=50, mtry=ceiling(0.1*ncol(train)-1), sampsize=ceiling(0.1*nrow(train)), importance=T, maxnodes=5)\n#a good model might drop the bad features according to the forest before training a final model\n#if a feature group or feature is too good, it might also be a good idea to drop to improve the feature balance and improve consistency of the model\nimp<-importance(forest)\nimp<-imp[order(imp[,1], decreasing = FALSE),]\nhead(imp)\n\n#based on the forest we can generate predictions on the validation set\n#the validation set contains eras further in time than the training set\n#the validation set is not \"representative of the live data\"; no one knows how the live data will behave\n#usually train performance < validation performance < live performance because live data is many eras into the future from the training data\npredictions<-predict(forest, validation)\nhead(predictions)\n#Numerai measures performance based on Rank Correlation between your predictions and the true targets\ncor(validation$target, predictions, method=\"spearman\")\nval<-validation\nval$prediction<-predictions\n#consistency is the fraction of months where the model achieves better correlation with the targets than the benchmark\nconsistency(val, \"target\")\n\n#we try a gbm model; we also choose a low bag fraction of 10% as a strategy to deal with within-era non-independence (which is a property of this data)\n#(if you take a sample from one era and a different sample from the same era that sample is not really out of sample because the observations occured in the same era)\n#having small bags also improves the out of bag estimate for the optimal number of trees\nset.seed(10)\nmodel<-gbm(target~., data=train, n.trees=50, shrinkage=0.01, interaction.depth=5, train.fraction=1, bag.fraction=0.1, verbose=T)\n#looking at the relative importance of the features we can see the model relies more on some features than others\nhead(summary(model))\nbest.iter <- gbm.perf(model, method=\"OOB\")\nbest.iter\n\n#we check performance of the gbm model on the out of sample validation data\npredictions<-predict.gbm(model, validation, n.trees=best.iter, type=\"response\")\nhead(predictions)\ncor(validation$target, predictions, method=\"spearman\")\nval<-validation\nval$prediction<-predictions\nconsistency(val, \"target\")\n\n#the gbm model and random forest model have the same consistency (number of eras where correlation > benchmark) even though correlation are different\n#improving consistency can be more important than improving standard machine learning metrics like RMSE\n#good models might train in such a way as to minimize the error across eras (improve consistency) not just reduce the error on each training example\n\n#so far we have ignored eras for training\n#eras are in order of time; for example, era4 is before era5\n#the reason to use eras is that cross validation on rows will tend to overfit (rows within eras are not independent)\n#so it's much better to cross validate within eras for example: take a subset of eras, build a model and test on the out of sample subset of eras\n#this will give a better estimate of how well your model will generalize\n#the validation set is not special; it is just an out of sample set of eras greater than the training set\n#some users might choose to train on the validation set as well\n\n#to give you a sense of how to use eras we train a model on the first half of the eras and test it on the second half\n#we take another 10x smaller sample of data to speed up the script\nordered_eras<-unique(training_data$era)\ntrain<-training_data[sample_rows,]\nfirst_half<-train[train$era%in%ordered_eras[1:ceiling(length(ordered_eras)/2)],]\nsecond_half<-train[!(train$id%in%first_half$id),]\n\n#we remove id, era, data_type column and train a gbm model on the first half of the data\nset.seed(10)\nmodel<-gbm(target~., data=first_half[,-c(1:3)], n.trees=100, shrinkage=0.01, interaction.depth=5, train.fraction=1, bag.fraction=0.1, verbose=T)\nbest.iter <- gbm.perf(model, method=\"OOB\")\nbest.iter\n\npredictions<-predict.gbm(model, second_half, n.trees=best.iter, type=\"response\")\n#our correlation score is good; what we appeared to learn generalizes well on the second half of the eras\n0.5+cor(second_half$target, predictions, method=\"spearman\")\nsec<-second_half\nsec$prediction<-predictions\n#consistency is the fraction of months where the model achieves better correlation with the targets than the benchmark\nconsistency(sec, \"target\")\n\n#but now we try build a model on the second half of the eras and predict on the first half\nset.seed(10)\nmodel<-gbm(target~., data=second_half[,-c(1:3)], n.trees=100, shrinkage=0.01, interaction.depth=5, train.fraction=1, bag.fraction=0.1, verbose=T)\nbest.iter <- gbm.perf(model, method=\"OOB\")\nbest.iter\n\npredictions<-predict.gbm(model, first_half, n.trees=best.iter, type=\"response\")\n#our correlation score is surprisingly low and surprisingly different from when we trained on the first half\n#this means our model is not very consistent, and it's possible that we will see unexpectedly low performance on the test set or live set\n#it also shows that our validation performance is likely to greatly overestimate our performance--this era-wise cross validation is more valuable\n#a model whose performance when training on the first half is the same as training on the second half would likely be more consistent\n#and would likely perform better on the tournament data and the live data\ncor(first_half$target, predictions, method=\"spearman\")\nfir<-first_half\nfir$prediction<-predictions\n#consistency is the fraction of months where the model achieves better correlation with the targets than the benchmark\nconsistency(fir, \"target\")\n\n#Numerai only pays models with correlations that beat the benchmark on the live portion of the tournament data\n#to submit predictions from your model to Numerai, predict on the entire tournament data\n#we choose use our original forest model for our final submission\ntournament$prediction<-predict(forest, tournament)\n\n#create your submission\nsubmission<-subset(tournament, select=c(id, prediction))\nhead(submission)\n\n#save your submission and now upload it to https://numer.ai\nwrite.csv(submission, file=\"submission.csv\", row.names=F)\n", "meta": {"hexsha": "c6dddf0e7da770b34cae3715937b53af034333e1", "size": 9424, "ext": "r", "lang": "R", "max_stars_repo_path": "src/round_254/numerai_dataset_254/example_model.r", "max_stars_repo_name": "gregoryverghese/numerai", "max_stars_repo_head_hexsha": "a15b9c71634fbaaf9eaf1eeceb34ed1b25b6584a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-30T18:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T18:53:01.000Z", "max_issues_repo_path": "example_model.r", "max_issues_repo_name": "JosephLazarus/Numerai", "max_issues_repo_head_hexsha": "f0d0c950068a4bf9b60dc6d512d856d69a34597a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_model.r", "max_forks_repo_name": "JosephLazarus/Numerai", "max_forks_repo_head_hexsha": "f0d0c950068a4bf9b60dc6d512d856d69a34597a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4352941176, "max_line_length": 166, "alphanum_fraction": 0.7876697793, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3729784282988859}}
{"text": "\r\n# This function is intended to simulate random drift of 4 alleles in a population, given starting and ending\r\n# frequencies for each allele, by resampling population of given allele frequency.\r\n# Revision of a script by Melissa Hardstone (FourAlleleDrift.r), reviewed and minor edits JCF 2018.\r\n# The MH copy of FourAlleleDrift.r script HAS AN ERROR- in the reporting of results for A2 and can give incorrect results.\r\n# What I changed:\r\n #\r\n # Results were previously only kept for current simulation, I routed them to a larger matrix that stores \r\n # results for all sims during function. If raw simulation data is desired, default \"raw_data=FALSE\" can \r\n # be changed to true and all data will be returned. (Good for making sure everything is working as intended, \r\n # and plotting if desired.)\r\n # Also quieted down the function a bit, there were unnecessary print commands everywhere.\r\n # Added comments for clarity\r\n \r\n\r\n# last edit: 2019-1-8 JCF\r\n\r\n# R sessionInfo of last edit.\r\n# > sessionInfo()\r\n# R version 3.5.1 (2018-07-02)\r\n# Platform: x86_64-w64-mingw32/x64 (64-bit)\r\n# Running under: Windows >= 8 x64 (build 9200)\r\n# \r\n# Matrix products: default\r\n# \r\n# locale:\r\n# [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252\r\n# [4] LC_NUMERIC=C LC_TIME=English_United States.1252 \r\n# \r\n# attached base packages:\r\n# [1] stats graphics grDevices utils datasets methods base \r\n# \r\n# loaded via a namespace (and not attached):\r\n# [1] compiler_3.5.1 tools_3.5.1 \r\n\r\n\r\n\r\n#\r\n# Input:\r\n#\r\n# SIMS is # simulations desired\r\n# gens is # generations between starting & ending allele frequencies\r\n# size_of_pop is # of diploid individuals in the population\r\n# A1-A4 are starting allele frequencies \r\n# A1-A4 are starting allele frequencies\r\n\r\n#\r\n# Output:\r\n#\r\n# Vector of 4 p-values (1 for each allele), calculated as the number of simulations where the allele frequency change is as extreme as the\r\n# observed allele frequency change. Null hypothesis here is that allele frequency change could be due to drift.\r\n# raw_data is set to FALSE as default, but if set to TRUE function will return a matrix \r\n\r\n\r\nFourAlleleDrift<-function(SIMS, gens, size_of_pop, A1, A2, A3, A4, end_A1, end_A2, end_A3, end_A4, raw_data=FALSE)\r\n{\r\n \r\n # Set up 4 matrices to track allele frequency over gens (dimensions #gens X #sims)\r\n # Fill first row with the starting allele frequency\r\n\tresultA1<-matrix(NA, nrow=gens, ncol=SIMS) # Declare results matrix\r\n\tresultA1[1,]=A1 # Fill first row with the starting allele frequency\r\n\tresultA2<-matrix(NA, nrow=gens, ncol=SIMS)\r\n\tresultA2[1,]=A2\r\n\tresultA3<-matrix(NA, nrow=gens, ncol=SIMS)\r\n\tresultA3[1,]=A3\r\n resultA4<-matrix(NA, nrow=gens, ncol=SIMS)\r\n resultA4[1,]=A4\r\n\r\n \r\n # Now will loop through SIMS (j) & generations (i)\r\n # \r\n\tfor (j in 1:SIMS) # For each of j simulations\r\n\t{\r\n\r\n\t \r\n gen<-gens # no. of generations\r\n\t\tpop_size<-size_of_pop # size_of_pop\r\n\t\ti=1 # Initialize for generation\r\n\r\n\t\t# starting with the inputed allele frequencies\r\n\t\tA1_allele<-A1 # A1 start freq\r\n\t\tA2_allele<-A2 # A2 start freq\r\n\t\tA3_allele<-A3 # A3 start freq\r\n\t\tA4_allele<-A4 # A4 start freq\r\n\r\n\t\t# Create a population with the starting allele frequencies (*2 for diploid)\r\n\t\tpop_alleles<-c( rep('A1',2*pop_size*A1_allele), rep('A2',2*pop_size*A2_allele),\r\n\t\t rep('A3',2*pop_size*A3_allele), rep('A4',2*pop_size*A4_allele) )\r\n\r\n\t\t# take a sample with replacement from the whole population to make next generation (panmictic, random mating)\r\n\t\tpop_alleles<-sample( pop_alleles, 2*pop_size, replace=TRUE )\r\n\r\n\t\t# Add the simulated allele frequency to results matrices: find # of entries in pop_alleles for each allele & divide by 2*pop_size\r\n\t\tresultA1[i+1,j]<-( length(pop_alleles[pop_alleles=='A1']) )/(2*pop_size) # freq of A1 allele, add to results matrix\r\n\t\tresultA2[i+1,j]<-( length(pop_alleles[pop_alleles=='A2']) )/(2*pop_size) # freq of A2 allele\r\n\t\tresultA3[i+1,j]<-( length(pop_alleles[pop_alleles=='A3']) )/(2*pop_size) # freq of A3 allele\r\n\t\tresultA4[i+1,j]<-( length(pop_alleles[pop_alleles=='A4']) )/(2*pop_size) # freq of A4 allele\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n # each loop, allele freq ending from previous loop used as the start allele freq\r\n\t\tfor(i in 2:gen-1)\r\n\t\t{\r\n\t\t A1_allele<-resultA1[(i+1)-1,j] # uses A1 freq from last generation\r\n\t\t\tA2_allele<-resultA2[(i+1)-1,j] # uses new A2 freq\r\n\t\t\tA3_allele<-resultA3[(i+1)-1,j] # uses new A3 freq\r\n\t\t\tA4_allele<-resultA4[(i+1)-1,j] # uses new A4 freq\r\n\r\n # Simulate population with new allele frequencies\r\n pop_alleles<-c(rep('A1',2*pop_size*A1_allele),rep('A2',2*pop_size*A2_allele),rep('A3',2*pop_size*A3_allele),rep('A4',2*pop_size*A4_allele));\r\n\r\n\t\t\t# take a sample from the whole population to make next generation\r\n pop_alleles<-sample(pop_alleles,2*pop_size,replace=TRUE)\r\n resultA1[i+1,j]<-(length(pop_alleles[pop_alleles=='A1']))/(2*pop_size) # freq of A1 allele, add to results matrix\r\n resultA2[i+1,j]<-(length(pop_alleles[pop_alleles=='A2']))/(2*pop_size) # freq of A2 allele\r\n resultA3[i+1,j]<-(length(pop_alleles[pop_alleles=='A3']))/(2*pop_size) # freq of A3 allele\r\n resultA4[i+1,j]<-(length(pop_alleles[pop_alleles=='A4']))/(2*pop_size) # freq of A4 allele\r\n\r\n\t }\r\n\r\n\t} \r\n \r\n # Now have full matrix of results for each allele.\r\n # Now calculate p-values from simulation results.\r\n\r\n # count times A1 allele freq at generation of interest is equal to or more extreme than obs freq\r\n # need to designate which direction of the extreme values is wanted\r\n if(end_A1 < A1)\r\n {\r\n\t\t A1_p<-length( which( resultA1[gen,] <= end_A1 ) )/SIMS;\r\n\t\t #cat(\"probability of getting end A1 freq or smaller is\", A1_p, '\\n');\r\n\t }else{\r\n\t A1_p<-length( which( resultA1[gen,] >= end_A1 ) )/SIMS;\r\n\t\t #cat(\"probability of getting end A1 freq or larger is\", A1_p, '\\n');\r\n\t }\r\n\r\n \t# Count times A2 allele freq at generation of interest is equal to or more extreme than obs freq\r\n\t# Need to designate which direction of the extreme values is wanted\r\n if(end_A2 < A2)\r\n {\r\n A2_p<-length( which( resultA2[gen,] <= end_A2 ) )/SIMS;\r\n # cat(\"probability of getting end A2 freq or smaller is\", A2_p, '\\n');\r\n }else{\r\n A2_p<-length( which( resultA2[gen,] >= end_A2 ) )/SIMS;\r\n # cat(\"probability of getting end A2 freq or larger is\", A2_p, '\\n');\r\n }\r\n\r\n\t# count times A3 allele freq at generation of interest is equal to or more extreme than obs freq\r\n\t# need to designate which direction of the extreme values is wanted\r\n if(end_A3 < A3)\r\n {\r\n A3_p<-length( which( resultA3[gen,] <= end_A3 ) )/SIMS;\r\n #cat(\"probability of getting end A3 freq or smaller is\", A3_p, '\\n');\r\n }else{\r\n A3_p<-length( which( resultA3[gen,] >= end_A3 ) )/SIMS;\r\n #cat(\"probability of getting end A3 freq or larger is\", A3_p, '\\n');\r\n }\r\n\t\r\n\t# count times A4 allele freq at generation of interest is equal to or more extreme than obs freq\r\n\t# need to designate which direction of the extreme values is wanted\r\n if(end_A4 < A4)\r\n {\r\n A4_p<-length( which( resultA4[gen,] <= end_A4 ) )/SIMS;\r\n #cat(\"probability of getting end A4 freq or smaller is\", A4_p, '\\n');\r\n }else{\r\n A4_p<-length( which( resultA4[gen,] >= end_A4 ) )/SIMS;\r\n #cat(\"probability of getting end A4 freq or larger is\", A4_p, '\\n');\r\n }\r\n \r\n \r\n # Function by default returns a vector of 4 p-values, 1 for each allele. Null hypothesis here is that allele frequency change could be due to drift.\r\n # If raw_data==TRUE, will also return a matrix of simulation results (intended for plotting). \r\n \r\n # Create vector of p-values\r\n p.vals=c(A1_p,A2_p,A3_p,A4_p)\r\n \r\n \r\n if( raw_data==TRUE ){\r\n print( list(\"A1_results\"=resultA1, \"A2_results\"=resultA2, \"A3_results\"=resultA3, \"A4_results\"=resultA4, p.vals) )\r\n } else { print(p.vals) }\r\n \r\n \r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "ee2e76c3492e3c2e39b9d9a70bcde508d9e09b04", "size": 8597, "ext": "r", "lang": "R", "max_stars_repo_path": "FourAlleleDrift_JCF.r", "max_stars_repo_name": "JamieCFreeman/Scott_et-al-2020_Genetic_drift_sims", "max_stars_repo_head_hexsha": "2dc55665b73849240ecf633dab127a72c4519c4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FourAlleleDrift_JCF.r", "max_issues_repo_name": "JamieCFreeman/Scott_et-al-2020_Genetic_drift_sims", "max_issues_repo_head_hexsha": "2dc55665b73849240ecf633dab127a72c4519c4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FourAlleleDrift_JCF.r", "max_forks_repo_name": "JamieCFreeman/Scott_et-al-2020_Genetic_drift_sims", "max_forks_repo_head_hexsha": "2dc55665b73849240ecf633dab127a72c4519c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0104712042, "max_line_length": 151, "alphanum_fraction": 0.6291729673, "num_tokens": 2437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37203700524285854}}
{"text": "## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n## Demographic component functions\n##\n## x - size this autumn\n## y - size next autumn\n## S - sex\n## A - age\n## G - genotype\n## Nt - standardised population density\n## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nmk.flist <- function(sets) {\n mydims <- sapply(sets,length)\n mylist <- vector(\"list\", prod(mydims))\n dim(mylist) <- mydims\n dimnames(mylist) <- sets\n return(mylist)\n}\n\n## ~~~~~~~~~ SURVIVAL ~~~~~~~~~\n\np.surv.list <- mk.flist(list(S=c(\"F\",\"M\"), A=c(0,+1)))\n\np.surv.list[[\"F\", \"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"s.a0.F.(Intercept)\"]+mPar[\"s.a0.F.capWgt\"]*x+\n mPar[\"s.a0.F.Nt\"]*Nt+mPar[\"s.a0.F.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.surv.list[[\"F\", \"1\"]] <- function(x, G, A, Nt, mPar, gSwitch) {\n prefix <- \"s.a1.F\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"s.a1.F.(Intercept)\"]+mPar[\"s.a1.F.capWgt\"]*x+\n mPar[\"s.a1.F.APS071add\"]*G+\n mPar[\"s.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A+mPar[\"s.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2+\n mPar[\"s.a1.F.Nt\"]*Nt+mPar[\"s.a1.F.Nt:APS071add\"]*G*Nt+mPar[\"s.a1.F.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.surv.list[[\"M\", \"0\"]] <- function(x, G, Nt, mPar, gSwitch) {\n prefix <- \"s.a0.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"s.a0.M.(Intercept)\"]+mPar[\"s.a0.M.capWgt\"]*x+\n mPar[\"s.a0.M.Nt\"]*Nt+mPar[\"s.a0.M.capWgt:Nt\"]*x*Nt+mPar[\"s.a0.M.obsY\"]*mPar[\"obsY\"]+\n mPar[\"s.a0.M.APS071add\"]*G\n return(invlogit(nu))\n}\np.surv.list[[\"M\", \"1\"]] <- function(x, G, A, Nt, mPar, gSwitch) {\n prefix <- \"s.a1.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"s.a1.M.(Intercept)\"]+mPar[\"s.a1.M.capWgt\"]*x+\n mPar[\"s.a1.M.APS071add\"]*G+mPar[\"s.a1.M.ageY\"]*A+\n mPar[\"s.a1.M.Nt\"]*Nt+mPar[\"s.a1.M.obsY:APS071add\"]*G*mPar[\"obsY\"]+\n mPar[\"s.a1.M.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\n\np.surv <- function(x, G, S, A, Nt, mPar, gSwitch=numeric(0))\n{\n ## expect S and A to have length=1\n if (length(S) != 1 | length(A) != 1)\n stop(\"survival function not vectorised for S(ex) and (A)ge\")\n ## assign the required function\n if (S==\"F\") {\n if (A == 0) {\n f <- p.surv.list[[\"F\", \"0\"]]\n } else if (A >= 1) {\n f <- p.surv.list[[\"F\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else if (S==\"M\") {\n if (A == 0) {\n f <- p.surv.list[[\"M\", \"0\"]]\n } else if (A >= 1) {\n f <- p.surv.list[[\"M\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else stop(\"invalid (S)ex\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ GROWTH ~~~~~~~~~\n\nd.grow.list <- mk.flist(list(S=c(\"F\",\"M\"), A=c(0,+1)))\n\nd.grow.list[[\"F\",\"0\"]] <- function(y, x, Nt, mPar) {\n mu <- mPar[\"g.a0.F.(Intercept)\"]+mPar[\"g.a0.F.capWgt\"]*x+mPar[\"g.a0.F.Nt\"]*Nt\n sg <- mPar[\"g.a0.F.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.grow.list[[\"F\",\"1\"]] <- function(y, x, G, A, Nt, mPar) {\n mu <- mPar[\"g.a1.F.(Intercept)\"] + mPar[\"g.a1.F.capWgt\"]*x + mPar[\"g.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A +\n mPar[\"g.a1.F.Nt\"]*Nt + mPar[\"g.a1.F.ageY:Nt\"]*Nt*A + mPar[\"g.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2\n sg <- mPar[\"g.a1.F.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.grow.list[[\"M\",\"0\"]] <- function(y, x, Nt, mPar) {\n mu <- mPar[\"g.a0.M.(Intercept)\"]+mPar[\"g.a0.M.capWgt\"]*x+mPar[\"g.a0.M.Nt\"]*Nt+mPar[\"g.a0.M.obsY\"]*mPar[\"obsY\"]\n sg <- mPar[\"g.a0.M.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.grow.list[[\"M\",\"1\"]] <- function(y, x, G, A, Nt, mPar) {\n mu <- mPar[\"g.a1.M.(Intercept)\"] + mPar[\"g.a1.M.capWgt\"]*x\n sg <- mPar[\"g.a1.M.sigma\"]\n return(dnorm(y,mu,sg))\n}\n\nd.grow <- function(y, x, G, S, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(S) != 1 | length(A) != 1)\n stop(\"growth function not vectorised for S(ex) and (A)ge\")\n ## assign the required function\n if (S==\"F\") {\n if (A == 0) {\n f <- d.grow.list[[\"F\", \"0\"]]\n } else if (A >= 1) {\n f <- d.grow.list[[\"F\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else if (S==\"M\") {\n if (A == 0) {\n f <- d.grow.list[[\"M\", \"0\"]]\n } else if (A >= 1) {\n f <- d.grow.list[[\"M\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else stop(\"invalid (S)ex\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ FEMALE PROBABILITY OF REPRODUCTION ~~~~~~~~~\n\np.repr.list <- mk.flist(list(A=c(0,+1)))\n\np.repr.list[[\"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"r.a0.F.(Intercept)\"]+mPar[\"r.a0.F.capWgt\"]*x+\n mPar[\"r.a0.F.Nt\"]*Nt+mPar[\"r.a0.F.obsY\"]*mPar[\"obsY\"]+\n mPar[\"r.a0.F.capWgt:obsY\"]*x*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.repr.list[[\"1\"]] <- function(A, Nt, mPar) {\n nu <- mPar[\"r.a1.F.(Intercept)\"]+\n mPar[\"r.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A+mPar[\"r.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2+\n mPar[\"r.a1.F.obsY\"]*mPar[\"obsY\"]+mPar[\"r.a1.F.ageY:obsY\"]*A*mPar[\"obsY\"]\n return(invlogit(nu))\n}\n\np.repr <- function(x, G, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"female P(reproduction) function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n f <- p.repr.list[[\"0\"]]\n } else if (A >= 1) {\n f <- p.repr.list[[\"1\"]]\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ FEMALE PROBABILITY OF TWINNING ~~~~~~~~~\n\np.twin.list <- mk.flist(list(A=c(0,+1)))\n\np.twin.list[[\"0\"]] <- function(x, Nt, mPar) {\n return(0)\n}\np.twin.list[[\"1\"]] <- function(x, A, Nt, mPar) {\n nu <- mPar[\"t.a1.F.(Intercept)\"]+mPar[\"t.a1.F.capWgt\"]*x+\n mPar[\"t.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A+mPar[\"t.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2+\n mPar[\"t.a1.F.Nt\"]*Nt+mPar[\"t.a1.F.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\n\np.twin <- function(x, G, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"female P(twinning) function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n f <- p.twin.list[[\"0\"]]\n } else if (A >= 1) {\n f <- p.twin.list[[\"1\"]]\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ OFFSPRING SPRING SURVIVAL FUNCTION ~~~~~~~~~\n\np.offsurv.list <- mk.flist(list(A=c(0,+1), S.off=c(\"F\",\"M\"), T.off=c(\"0\",\"1\")))\n\np.offsurv.list[[\"0\",\"F\",\"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"s.off.a0.(Intercept)\"]+mPar[\"s.off.a0.capWgtMum\"]*x+\n mPar[\"s.off.a0.Ntm1\"]*Nt+mPar[\"s.off.a0.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"0\",\"M\",\"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"s.off.a0.(Intercept)\"]+mPar[\"s.off.a0.capWgtMum\"]*x+\n mPar[\"s.off.a0.Ntm1\"]*Nt+mPar[\"s.off.a0.obsY\"]*mPar[\"obsY\"]+mPar[\"s.off.a0.sexM\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"F\",\"0\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"M\",\"0\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]+mPar[\"s.off.a1.sexM\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"F\",\"1\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]+mPar[\"s.off.a1.isTwnMat\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"M\",\"1\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]+\n mPar[\"s.off.a1.sexM\"]+mPar[\"s.off.a1.isTwnMat\"]\n return(invlogit(nu))\n}\n\np.offsurv <- function(x, G, A, Nt, mPar, S.off, T.off)\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"offspring survival function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"0\",\"F\",\"0\"]]\n } else if (T.off == 1) {\n return(0) # age 0 females cannot twin\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"0\",\"M\",\"0\"]]\n } else if (T.off == 1) {\n return(0) # age 0 females cannot twin\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else if (A >= 1) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"1\",\"F\",\"0\"]]\n } else if (T.off == 1) {\n f <- p.offsurv.list[[\"1\",\"F\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"1\",\"M\",\"0\"]]\n } else if (T.off == 1) {\n f <- p.offsurv.list[[\"1\",\"M\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ OFFSPRING SIZE DISTRIBUTION ~~~~~~~~~\n\nd.offsize.list <- mk.flist(list(S.off=c(\"F\",\"M\"), T.off=c(\"0\",\"1\")))\n\nd.offsize.list[[\"F\",\"0\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.offsize.list[[\"M\",\"0\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.sexM\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.offsize.list[[\"F\",\"1\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.isTwnMat\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.offsize.list[[\"M\",\"1\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.sexM\"]+mPar[\"sz.off.isTwnMat\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\n\nd.offsize <- function(y, x, G, A, Nt, mPar, S.off, T.off)\n{\n ## expect S and A to have length=1\n if (length(S.off) != 1 | length(T.off) != 1)\n stop(\"offspring size function not vectorised for offspring S(ex), female (A)ge and (T)win status\")\n ## assign the required function\n if (all(A >= 0)) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- d.offsize.list[[\"F\",\"0\"]]\n } else if (T.off == 1) {\n f <- d.offsize.list[[\"F\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- d.offsize.list[[\"M\",\"0\"]]\n } else if (T.off == 1) {\n f <- d.offsize.list[[\"M\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ MALE MATING SUCCESS ~~~~~~~~~\n\nn.mrepro.list <- mk.flist(list(A=c(\"0\",\"1\")))\n\nn.mrepro.list[[\"0\"]] <- function(x, G, Nt, mPar, gSwitch) {\n prefix <- \"n.off.a0.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"n.off.a0.M.(Intercept)\"] + mPar[\"n.off.a0.M.capWgt\"]*x +\n mPar[\"n.off.a0.M.APS071add\"]*G + mPar[\"n.off.a0.M.Nt\"]*Nt + mPar[\"n.off.a0.M.obsY\"]*mPar[\"obsY\"]\n return(exp(nu))\n}\nn.mrepro.list[[\"1\"]] <- function(x, G, Nt, mPar, gSwitch) {\n prefix <- \"n.off.a1.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"n.off.a1.M.(Intercept)\"] + mPar[\"n.off.a1.M.capWgt\"]*x +\n mPar[\"n.off.a1.M.APS071add\"]*G + mPar[\"n.off.a1.M.APS071add:Nt\"]*G*Nt +\n mPar[\"n.off.a1.M.Nt\"]*Nt + mPar[\"n.off.a1.M.obsY\"]*mPar[\"obsY\"]\n return(exp(nu))\n}\n\nn.mrepro <- function(x, G, A, Nt, mPar, gSwitch=numeric(0))\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"male reproduction function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n f <- n.mrepro.list[[\"0\"]]\n } else if (A >= 1) {\n f <- n.mrepro.list[[\"1\"]]\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n", "meta": {"hexsha": "c09db1dbe490054023df03a6c0ecc3337240ee7e", "size": 14629, "ext": "r", "lang": "R", "max_stars_repo_path": "code_r/imported/demog_fun.r", "max_stars_repo_name": "tdjames1/soay_ibm", "max_stars_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_r/imported/demog_fun.r", "max_issues_repo_name": "tdjames1/soay_ibm", "max_issues_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_r/imported/demog_fun.r", "max_forks_repo_name": "tdjames1/soay_ibm", "max_forks_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8989637306, "max_line_length": 114, "alphanum_fraction": 0.508168706, "num_tokens": 5352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.37156020001406675}}
{"text": "#' ## START MODULE 2.4\n#' Objective: Edit extent, projection, dimension, resolution of raster layers or shapefiles\n#' \n#' tested on R versions 3.1.X, 3.2.X\n#' \n#' Load packages and set working directory\n#+ load packages\n library(rgdal) # fxns: readOGR, writeOGR\n library(raster) # fxns: crop, mask\n# set path\n path.root <- \"~/Documents/Intro-Spatial-R/\"\n path.mod <- paste(path.root, \"module2\", sep = \"\")\n setwd(path.mod)\n#'\n#' ### Crop a polygon file to another polygon\n#' Import shapefile to be altered\n#' \n#+ import shapefile \n# CP study area; the \"mask\" for cropping\n cp.region <- readOGR(dsn = \"data\", layer = \"COP_boundpoly_aea\")\n class(cp.region) # examine class\n\n# North American states/provinces to be altered\n states <- readOGR(dsn = \"data\", layer = \"na_states_aea\")\n class(states) # examine class\n#'\n#' Subset states (UT, AZ, CO, NM) in Colorado Plateau region \n#' - NOTE: str() to determine shapefile characteristics\n#' here, states$CODE returns all state-based codes\n#' - NOTE: rgdal can be squirrelly, requiring NAs to be excluded, it crashes if NA present\n#'\n#+ subset states\n head(states@data) # examine shapepoly data\n states$CODE # state codes\n cp.states <- states[states$CODE == \"UT\" | states$CODE == \"CO\" | \n states$CODE == \"NM\" | states$CODE == \"AZ\", ]\n \n# cp.states <- states[states$CODE == \"UT\" & !is.na(states$CODE) | \n# states$CODE == \"CO\" & !is.na(states$CODE) | \n# states$CODE == \"NM\" & !is.na(states$CODE) | \n# \t states$CODE == \"AZ\" & !is.na(states$CODE), ]\n cp.states@data # examine subsetted states\n#'\n#+ giggle plots\n plot(states)# all of North America\n plot(cp.states, add = T, col = \"blue\")# the subsetted states\n plot(cp.region, add = T, col = \"red\")# the study region, taking long time\n#'\n#' Crop states to the CP region\n#' \n#+ crop states \n cp.statesCROP <- crop(cp.states,cp.region)\n plot(cp.states) # giggle plot\n## output shapefile if desired; examine in ArcGIS if desired\n # writeOGR(cp.statesCROP, dsn = \"./outdata\", layer = \"cp.statesCROP\", \n # morphToESRI = T, driver = \"ESRI Shapefile\")\n#'\n#' ### Polygon crop of raster\n#' This is a 2-step process that is easy to construct as function if desired.\n#' \n#+ import raster\n tave <- raster(\"data/tave_yr_av.img\")\n tave # examine raster\n summary(cp.region) # examine crop polygon (from above)\n#' \n#' Note the different projections; must convert 1 to match other (see Module 2.2)\n#' \n#+ transform to match projections\n cp.regionWGS <- spTransform(cp.region, CRS = CRS(projection(tave)))\n cp.regionWGS # now same projection as tave\n \n## giggle plots; goal is crop of tave to match red in plot\n plot(tave)\n plot(cp.regionWGS, add = T, col = \"red\")\n#' \n#' Step #1; `mask()` function w/CP polygon as the mask applied to tave\n#' \n#+ mask tave\n taveCROP.1 <- mask(tave, cp.regionWGS)\n \n## giggle plots; LOL here .....\n plot(taveCROP.1)# NOTE extent is extent of tave\n plot(extent(taveCROP.1), add = T)\n#' \n#' Step #2; `crop()` function to subset the masked tave to the extent of the CP region\n#' \n#+ crop tave to CP region\n taveCROP.2 <- crop(taveCROP.1, cp.regionWGS)\n \n## giggle plots ...\n plot(taveCROP.2)\n plot(cp.regionWGS, add = T)\n \n## outfile cropped raster if desired\n #writeRaster(taveCROP.2, filename = \"outdata/cp.taveCROP2.img\", format = \"HFA\")\n#'\n#' ### Crop raster using another raster\n#' Assume raster of region to serve as crop; here cp.rast (see Module 2.2)\n#'\n#+ crop raster by raster \n ext.rast <- raster(resolution = 0.008333333, extent(cp.regionWGS))\n cp.rast <- rasterize(cp.regionWGS, field = \"Id\", ext.rast)\n cp.rast # examine\n \n## raster to be cropped\n## same projection/resolution as cp.rast? if not see Module 2.3\n tave # examine\n \n## some giggle plots; crop goal is red\n plot(tave)\n plot(cp.rast, add = T, col = \"red\")\n \n## crop tave raster w/cp.rast raster\n taveCROP.3 <- crop(tave, cp.rast)\n \n## write out file of cropped raster if desired\n #writeRaster(taveCROP.3, filename = \"outdata/cp.taveCROP3.img\", format = \"HFA\")\n \n## giggle plots; NOTE that crop is the cp.rast extent, not just CP region\n plot(taveCROP.3)\n plot(cp.rast, add = T, col = \"red\")\n \n## giggle plots\n par(mfrow = c(1, 2))\n plot(taveCROP.3)\n plot(cp.regionWGS, add = T, border = \"black\")\n\n## outfile cropped raster if desired\n #writeRaster(taveCROP.3, filename = \"outdata/cp.taveCROP3.img\", format = \"HFA\")\n#'\n#' Crop a polygon to a raster\n#'\n#+ load shapefile \n soil <- readOGR(dsn = \"data\", layer = \"soils\") # be patient here ... ~3 min runtime\n soil # examine polygon\n cp.rast # examine raster; both have same projection? if not see Module 2.2/2.3\n \n## crop polygon w/extent of raster\n soilCROP.1 <- crop(soil,extent(cp.rast))\n## giggle plots\n par(mfrow = c(1, 2))\n plot(soil)\n plot(cp.regionWGS, add = T, col = \"red\")\n plot(soilCROP.1)\n plot(cp.rast, add = T, col = \"red\")\n#'\n#' ## END MODULE 2.4\n#' \n#' Create R markdown file from R script \n#+\n knitr::spin(\"Rscripts/M2.4-alterextent_shapefileraster.r\", knit = F, format = \"Rmd\")\n", "meta": {"hexsha": "6f779ec210cc6c453ead96824cffd9b8ac048c5a", "size": 5190, "ext": "r", "lang": "R", "max_stars_repo_path": "module2/Rscripts/M2.4-alterextent_shapefileraster.r", "max_stars_repo_name": "f-tonini/Intro-Spatial-R", "max_stars_repo_head_hexsha": "6bbd65c7fad7d64573964a8981f9bd5cded66f98", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-01-23T12:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-02T18:02:28.000Z", "max_issues_repo_path": "module2/Rscripts/M2.4-alterextent_shapefileraster.r", "max_issues_repo_name": "f-tonini/Intro-Spatial-R", "max_issues_repo_head_hexsha": "6bbd65c7fad7d64573964a8981f9bd5cded66f98", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module2/Rscripts/M2.4-alterextent_shapefileraster.r", "max_forks_repo_name": "f-tonini/Intro-Spatial-R", "max_forks_repo_head_hexsha": "6bbd65c7fad7d64573964a8981f9bd5cded66f98", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-10-05T16:12:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T18:02:32.000Z", "avg_line_length": 34.1447368421, "max_line_length": 91, "alphanum_fraction": 0.6425818882, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3712553856849222}}
{"text": "#' Bumblebee: Quantify Disease Transmission Within and Between Population Groups\n#' \n#' @description\n#' Bumblebee uses counts of directed transmission pairs identified between samples\n#' from population groups of interest to estimate the flow of transmissions within \n#' and between those population groups accounting for sampling heterogeneity.\n#' \n#' Population groups might include: communities, geographical regions, age-gender \n#' groupings or arms of a randomized-clinical trial.\n#' \n#' Counts of observed directed transmission pairs can be obtained from deep-sequence \n#' phylogenetic data (via phyloscanner) or known epidemiological contacts. Note: \n#' Deep-sequence data is also commonly referred to as high-throughput or\n#' next-generation sequence data. See references to learn more about phyloscanner.\n#' \n#' @section The \\code{estimate_transmission_flows()} function:\n#' To estimate transmission flows, that is, the relative probability of transmission \n#' within and between population groups accounting for variable sampling the among\n#' the population groups the function: \\code{estimate_transmission_flows_and_ci()}\n#' computes the conditional probability, \\code{theta_hat} that a pair of pathogen\n#' sequences is from a specific population group pairing given that the pair is\n#' linked.\n#' \n#' For two population groups of interest \\eqn{(u,v)} \\code{theta_hat} is denoted by \n#' \n#' \\deqn{\\hat{\\theta_{ij}} = Pr(pair from groups (i,j) | pair is linked), where i = u,v and j = u,v .}\n#' \n#' To learn more and try some examples, see documentation of the \n#' \\code{estimate_transmission_flows()} function and the bumblebee package\n#' website \\url{https://magosil86.github.io/bumblebee/}.\n#' \n#' @seealso See the following functions for details on estimating transmission flows\n#' and corresponding confidence intervals: \\code{estimate_transmission_flows_and_ci}, \n#' \\code{estimate_theta_hat} and \\code{estimate_multinom_ci}.\n#' \n#' @section Cite the package:\n#' Please cite the package using the following reference:\n#' Lerato E. Magosi, Marc Lipsitch (2021). Bumblebee: Quantify Disease\n#' Transmission Within and Between Population Groups. R package version\n#' 0.1.0 \\url{https://magosil86.github.io/bumblebee/}\n#' \n#' @author \n#' Lerato E. Magosi \\email{lmagosi@hsph.harvard.edu} or \n#' \\email{magosil86@gmail.com}\n#' \n#' @references\n#' \\enumerate{\n#'\n#' \\item Magosi LE, et al., Deep-sequence phylogenetics to quantify patterns of \n#' HIV transmission in the context of a universal testing and treatment\n#' trial – BCPP/ Ya Tsie trial. To submit for publication, 2021.\n#'\n#' \\item Carnegie, N.B., et al., Linkage of viral sequences among HIV-infected\n#' \t\t village residents in Botswana: estimation of linkage rates in the \n#' \t\t presence of missing data. PLoS Computational Biology, 2014. 10(1): \n#' \t\t p. e1003430.\n#' \n#' \\item Goodman, L. A. On Simultaneous Confidence Intervals for Multinomial Proportions \n#' \t\t Technometrics, 1965. 7, 247-254.\n#' \n#' \\item Glaz, J., Sison, C.P. Simultaneous confidence intervals for multinomial proportions. \n#' \t\t Journal of Statistical Planning and Inference, 1999. 82:251-262.\n#' \n#' \\item May, W.L., Johnson, W.D. Constructing two-sided simultaneous confidence intervals for \n#' \t\t multinomial proportions for small counts in a large number of cells. \n#' \t\t Journal of Statistical Software, 2000. 5(6).\n#' \t\t Paper and code available at https://www.jstatsoft.org/v05/i06.\n#' \n#' \\item Ratmann, O., et al., Inferring HIV-1 transmission networks and sources of \n#' \t\t epidemic spread in Africa with deep-sequence phylogenetic analysis. \n#' \t\t Nature Communications, 2019. 10(1): p. 1411.\n#' \n#' \\item Sison, C.P and Glaz, J. Simultaneous confidence intervals and sample size determination\n#' \t\t for multinomial proportions. Journal of the American Statistical Association, \n#' \t\t 1995. 90:366-369.\n#' \n#' \\item Wymant, C., et al., PHYLOSCANNER: Inferring Transmission from Within- and\n#' \t\t Between-Host Pathogen Genetic Diversity. Molecular Biology and Evolution,\n#' \t\t 2017. 35(3): p. 719-733.\n#' }\n#' \n#' @docType package\n#' @name bumblebee-package\n#' @aliases bumblebee\n#' \n#' @keywords internal\n#' @importFrom dplyr %>%\n\"_PACKAGE\"\n", "meta": {"hexsha": "2adb8b80be23c0aeb6a1abe5437c2cf5e2b98d14", "size": 4243, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bumblebee.r", "max_stars_repo_name": "magosil86/bumblebee", "max_stars_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/bumblebee.r", "max_issues_repo_name": "magosil86/bumblebee", "max_issues_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-04-29T03:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T12:38:24.000Z", "max_forks_repo_path": "R/bumblebee.r", "max_forks_repo_name": "magosil86/bumblebee", "max_forks_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6741573034, "max_line_length": 102, "alphanum_fraction": 0.7329719538, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36971524648927734}}
{"text": "thresh<-function(x,lam){\n\t# s=solve(A)%*%x\n# \tif(lam==0) return(s)\n# \tmax(1-lam/crossprod(x,s)^(1/2),0)*s\n\tif(lam==0) return(x)\n\tmax(1-lam/sum(x^2)^(1/2) , 0)*x\n}\n\nadmmSel<-function(dat,lam,m1,m2,rho=1,cores=1,elist=NULL){\n\tn=dim(dat)[1]\n\tprint(\"Calculating Statistics:\")\n\td=dim(dat)[2]\n\tif(is.null(elist)) elist= get.edgelist(graph.full(d))\n\tg=graph.edgelist(elist,directed=F)\n\tK = Kvec2(dat,m1,m2,elist)\n\tG = Gamma.ret2(dat,m1,m2,cores=dim(dat)[2],ge=elist)\n\tdd=dim(G[[1]]$v)[1]\n\t#dd=dim(G[[1]])[1]\n\n\tGinv=mclapply(1:d,function(x) G[[x]]$v %*% ((1/((1/n)*G[[x]]$d^2+rho)) * t(G[[x]]$v)),mc.cores=d)\n\t#Ginv=mclapply(1:d,function(x) solve(G[[x]]+rho*diag(dd)),mc.cores=cores)\n\tprint(\"Done.\")\n\tznode = matrix(rnorm(d*m1)*1e-10,d,m1)\n\tzedge = array(rnorm(m2*m2*dim(elist)[1])*1e-10,dim=c(m2,m2,dim(elist)[1]))\n\ttol=Inf\n\tx=xold=y=zz=lapply(1:d,function(x)rep(0,dim(G[[x]]$v)[1]))\n\tadmmout=list()\n\tlam=rev(sort(lam))\n\tif(d>=100) cores = detectCores()\n\tfor(lamind in 1:length(lam)){\n\t\tprint(paste(\"Run \",lamind,\" Begun\"))\n\t\tif(lamind>1){\n\t\t\tx=admmout[[lamind-1]]$x\n\t\t\ty=admmout[[lamind-1]]$y\n\t\t\tzz=admmout[[lamind-1]]$zz\n\t\t}\n\t\ttol=Inf\n\t\titer=0\n\t\twhile(tol>1e-3 & iter<500){\n\t\titer=iter+1\n\t\t# x step\n\t\txold=x\n\t\tzedge_old=zedge\n\t\tznode_old=znode\n\t\t#print(lapply(y,function(x)length(x)))\n\t\tx=mclapply(1:d,function(i){\n\t\t#\tprint(dim(Ginv[[i]]))\n\t\t#\tprint(length(K[[i]]))\n\t\t#\tprint(length(y[[i]]))\n\t\t\tGinv[[i]]%*%(-K[[i]] - y[[i]] + rho*zz[[i]]) \n\t\t},mc.cores=cores)\n\t\t#z-y step\n\t\tfor(i in 1:d){\n\t\t\tii=sum(neighbors(g,i)i , m1 + (j-2)*m2+1 ,(j-1)*m2+1 )\n\t\t\t\t\t#c2 = ifelse(j=100) cores = detectCores()\n\tfor(lamind in 1:length(lam)){\n\t\tprint(paste(\"Run \",lamind,\" Begun\"))\n\t\tif(lamind>1){\n\t\t\tx=admmout[[lamind-1]]$x\n\t\t\ty=admmout[[lamind-1]]$y\n\t\t\tzz=admmout[[lamind-1]]$zz\n\t\t}\n\t\ttol=Inf\n\t\titer=0\n\t\twhile(tol>1e-3 & iter<500){\n\t\titer=iter+1\n\t\t# x step\n\t\txold=x\n\t\tzedge_old=zedge\n\t\tznode_old=znode\n\t\t#print(lapply(y,function(x)length(x)))\n\t\tx=mclapply(1:d,function(i){\n\t\t#\tprint(dim(Ginv[[i]]))\n\t\t#\tprint(length(K[[i]]))\n\t\t#\tprint(length(y[[i]]))\n\t\t\tGinv[[i]]%*%(-K[[i]] - y[[i]] + rho*zz[[i]]) \n\t\t},mc.cores=cores)\n\t\t#z-y step\n\t\tfor(i in 1:d){\n\t\t\tii=sum(neighbors(g,i)i , m1 + (j-2)*m2+1 ,(j-1)*m2+1 )\n\t\t\t\t\t#c2 = ifelse(j1e-3){\n# \t\tfor(i in 1:d){\n# \t\t\tfor(j in i:d){\n# \t\t\t\tA = (gn[[i]][[j]]+gn[[j]][[i]])\n# \t\t\t\tif(i!=j){\n# \t\t\t\t\tee= which(elist[,1]==i & elist[,2]==j)\n# \t\t\t\t\tind11 = which( (elist[,1]==j | elist[,2]==j) & elist[,1]!=i)\n# \t\t\t\t\tind12 = which( (elist[,1]==i | elist[,2]==i) & elist[,2]!=j)\n# \t\t\t\t\txx=crossprod(gr[[i]][[ee]] , out.node[i,])+\n# \t\t\t\t\t gr[[j]][[ee]] %*% out.node[j,] +\n# \t\t\t\t\t c(kve[,,ee])\n# \t\t\t\t}else{\n# \t\t\t\t\tind11 = which( (elist[,1]==j | elist[,2]==j) )\n# \t\t\t\t\tind12 = which( (elist[,1]==i | elist[,2]==i) )\n# \t\t\t\t\txx = kvn[i,]\t\t\t\t\t\n# \t\t\t\t}\n# \t\t\t\t#print(paste(i,\" \" ,j))\n# \t\t\t\t#print(elist[ind11,])\n# \t\t\t\t#print(elist[ind12,])\n# \t\t\t\txx=xx+Reduce(\"+\",lapply(1:length(ind11), function(x){\n# \t\t\t\t\t if(elist[ind11[x],1]==j){\n# \t\t\t\t\t \tgr[[i]][[ind11[x]]] %*% c(out.edge[,,ind12[x]]) \n# \t\t\t\t\t }else{\n# \t\t\t\t\t \tt(gr[[i]][[ind11[x]]]) %*% c(out.edge[,,ind12[x]]) \n# \t\t\t\t\t }\n# \t\t\t\t\t }))\n# \t\t\t\txx=xx+Reduce(\"+\",lapply(1:length(ind11), function(x){\n# \t\t\t\t if(elist[ind12[x],1]==i){\n# \t\t\t\t\t gr[[j]][[ind12[x]]] %*% c(out.edge[,,ind11[x]]) \n# \t\t\t\t}else{\n# \t\t\t\t\tt(gr[[j]][[ind12[x]]]) %*% c(out.edge[,,ind11[x]]) \n# \t\t\t\t}\n# \t\t\t\t \n# \t\t\t\t }))\n# \t\t\t\tif(i==j){\n# \t\t\t\t\tout.node[i,]=thresh(-xx,A,lam)\n# \t\t\t\t}else{\n# \t\t\t\t\tout.edge[,,ee] = matrix( thresh(-xx,A,lam) , m2,m2)\n# \t\t\t\t}\n# \t\t\t}\n# \t\t}\n# \t\t#print(out.edge)\n# \t\t#print(out.node)\n# \t\t#break\n# \t\ttol = mean(abs(out.edge-out.edge.old))\n# \t\ttol= tol + mean(abs(out.node.old-out.node))\n# \t\tprint(tol)\n# \t\tout.node.old = out.node\n# \t\tout.edge.old=out.edge\n# \t}\n# \treturn(list(edge=out.edge,node=out.node))\n# }", "meta": {"hexsha": "4083e34cd4c65c4e3c3f30c491be556e79e37d3b", "size": 8234, "ext": "r", "lang": "R", "max_stars_repo_path": "admm.r", "max_stars_repo_name": "geb5101h/quasr", "max_stars_repo_head_hexsha": "f0b6aa5bb8bc3784977807c04017af5587ec0c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "admm.r", "max_issues_repo_name": "geb5101h/quasr", "max_issues_repo_head_hexsha": "f0b6aa5bb8bc3784977807c04017af5587ec0c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "admm.r", "max_forks_repo_name": "geb5101h/quasr", "max_forks_repo_head_hexsha": "f0b6aa5bb8bc3784977807c04017af5587ec0c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0510948905, "max_line_length": 109, "alphanum_fraction": 0.5246538742, "num_tokens": 3572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.3693971972053876}}
{"text": "# Solution by Ismail Prada & Andreas Säuberli\n\n# Lena Jäger\n# Eyetracking: From experiment design to statistical and machine learning-based data analysis\n# Assignment 4: Frequentist statistical analysis of a psycholinguistic eye-tracking-while-reading experiment\n\n# Data set:\n# For a detailed description of the data set used in this assignment, please refer to: \n# Jäger, Mertzen, Van Dyke, & Vasishth: 'Interference patterns for subject-verb \n# agreement and reflexives revisited: A large-sample study', \n# Journal of Memory and Language, 2020\n\n# Experimental design: \n# 2x2x2 fully crossed factorial desing:\n# Factor I: Dependency type: {subject-verb agreement; reflexive-antecedent binding}\n# Factor II: Grammaticality: {grammatical; ungrammatical}\n# Factor III: Similarity-based interference: {interference; no-intererence}\n\n# Condition labels: \n# a Agreement; grammatical; interference\n# b. Agreement; grammatical; no interference\n# c. Agreement; ungrammatical; no interference\n# d. Agreement; ungrammatical; interference\n# e. Reflexive; grammatical; interference\n# f. Reflexive; grammatical; no interference\n# g. Reflexive; ungrammatical; no interference\n# h. Reflexive; ungrammatical; interference\n\n# Column names:\n# subj: subject id\n# item: item id\n# cond: condition id\n# acc: comprehension question response accuracy\n# roi: region of interest \n# FPRT: first-pass reading times in ms\n# TFT: total fixation times in ms\n# FPR: first-pass regression (binary)\n\nlibrary(coda)\nlibrary(plyr)\nlibrary(ggplot2)\nlibrary(xtable)\nlibrary(dplyr)\nrequire(tidyr)\nlibrary(tidyverse)\nextrafont::loadfonts()\nlibrary(reshape2)\nrequire(lme4)\n\n\n### RESEARCH QUESTIONS:\n# 1. Are fixation times different in subject-verb agreement versus reflexive-antecedent dependencies?\n# --> main effect of dependency type\n# 2. Are fixation times different in ungrammatical versus grammatical conditions?\n# --> main effect of grammaticality\n# 3. Are fixation times affected by interference?\n# --> main effect of interference\n# 4. Does the grammaticality effect differ between the two dependency types?\n# --> interaction between grammaticality and dependency type\n# 5. Does the interference effect differ between grammatical and ungrammatical conditions?\n# --> interaction between interference and grammaticality\n# 6. Does the interference effect differ between dependency types?\n# --> interaction between interference and dependency type\n# 7. Does the (possible) difference in the sensitivity to the interference manipulation of \n# grammatical versus ungrammatical conditions differ between subject-verb agreement and reflexive-antecedent dependencies?\n# --> 3-way interaction between interference, grammaticality and dependency type\n\n\n# Critical region: were/was/himself/themselves (= roi 12)\n# Dependent variable: total fixation times\n\n\n#### Load and format the data\nd <- read.table(file='dataJMVV.txt', sep = '\\t')\n\n#### Inspect the data and answer the following questions: \n# How many conditions are there? How many instances of each condition?\n# 8 conditions (+filler), counts:\n# a b c d e f filler g h \n# 22659 22659 22659 22596 22680 22638 482412 22680 22617\n# How many subjects and items are there?\n# 181 subjects\n# 176 items\n# NOTE: This could also be answered by converting these columns to factors first and then use str()\n# How many times did each subject see each item? Hint: use xtabs() )\n# 21 times\n# What was the average response accuracy for each of the conditions? Hint: use tapply()\n# a b c d e f \n# -0.05560704 -0.05838740 -0.05004634 -0.06133829 -0.07129630 -0.05751391 \n# filler g h \n# -0.04718788 -0.05185185 -0.05292479\n########################################################\nhead(d, 3)\nd$cond <- factor(d$cond)\nsummary(d$cond)\nlength(unique(d$subj))\nlength(unique(d$item))\nxtabs(~subj+item, d)\ntapply(d$acc, d$cond, mean)\n########################################################\n\n\n### Convert the subj, item and cond columns to factors\n########################################################\nd$subj <- factor(d$subj)\nd$item <- factor(d$item)\nd$cond <- factor(d$cond)\nstr(d)\n########################################################\n\n# Exlcude filler trials and remove all rows from other than the critical region (roi 12)\n########################################################\nd_crit <- d[d$cond != \"filler\" & d$roi == 12, ]\n########################################################\n\n# Note: when removing all rows with a certain level of a factor, this level still exists, it simply has 0 instances:\nsummary(d$cond) # before removing the fillers\nsummary(d_crit$cond) # after removing the fillers\n# We can fix this by simply conveting cond to a factor again: \n########################################################\nd_crit$cond <- factor(d_crit$cond)\n########################################################\n\n\n#### Define contrasts \n# Create hypothesis matrix from the given research questions\n# main effects of dependency and grammaticality and their interaction (applied in Model 1 and 2)\nX_H <- matrix(c( 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, # Intercept\n 1/4, 1/4, 1/4, 1/4, -1/4, -1/4, -1/4, -1/4, # Main effect dependency type\n -1/4, -1/4, 1/4, 1/4, -1/4, -1/4, 1/4, 1/4, # Main effect grammaticality\n 1/4, -1/4, -1/4, 1/4, 1/4, -1/4, -1/4, 1/4, # Main effect of interference\n -1/4, -1/4, 1/4, 1/4, 1/4, 1/4, -1/4, -1/4, # Grammaticality x Dependency\n -1/4, 1/4, -1/4, 1/4, -1/4, 1/4, -1/4, 1/4, # Interference x Grammaticality\n 1/4, -1/4, -1/4, 1/4, -1/4, 1/4, 1/4, -1/4, # Interference x Dependency type\n -1/4, 1/4, -1/4, 1/4, 1/4, -1/4, 1/4, -1/4 # Interference x Grammaticality x Dependency\n), byrow=TRUE, nrow = 8)\n\n# Compute the inverse of X_H\n########################################################\nlibrary(MASS) # need this for ginv()\nX_C <- ginv(X_H)\n########################################################\n\n# For better readibility add column and row names: \nrownames(X_C) <- c('a','b','c','d','e','f','g','h')\ncolnames(X_C) <- c('Intercept','Dep','Gram','Int','Gram_x_Dep','Int_x_Gram','Int_x_Dep','Int_x_Gram_x_Dep')\n\n# Remove intercept column\n########################################################\nX_C_bar <- X_C[,2:ncol(X_C)]\n########################################################\n\n# Apply the contrasts to the cond column\n########################################################\ncontrasts(d_crit$cond) <- X_C_bar\n########################################################\n\n\n#--------------------------------------------------------\n#--------------------------------------------------------\n# OR: \n# Alternative: code contrasts as numerical columns in the dataframe and use these as predictors in the model\n\n# NOTE: Why did they use d and not d_crit here?\nd_crit$Dep <- ifelse(d_crit$cond %in% c('a', 'b', 'c', 'd'), .5, -.5) # main effect of dependency type: agr=0.5, refl=-0.5\nd_crit$Gram <- ifelse(d_crit$cond %in% c('a', 'b', 'e', 'f'), -.5, .5) # main effect of grammaticality: gram=-.5, ungram=.5\n# ... add the other contrasts\n########################################################\nd_crit$Int <- ifelse(d_crit$cond %in% c('a', 'd', 'e', 'h'), .5, -.5)\nd_crit$Gram_x_Dep <- ifelse(d_crit$cond %in% c('c', 'd', 'e', 'f'), .5, -.5)\nd_crit$Int_x_Gram <- ifelse(d_crit$cond %in% c('b', 'd', 'f', 'h'), .5, -.5)\nd_crit$Int_x_Dep <- ifelse(d_crit$cond %in% c('a', 'd', 'f', 'g'), .5, -.5)\nd_crit$Int_x_Gram_x_Dep <- ifelse(d_crit$cond %in% c('b', 'd', 'e', 'g'), .5, -.5)\n########################################################\n\n#--------------------------------------------------------\n#--------------------------------------------------------\n\n# Remove trials in which the dependent variable (TFT) is zero (i.e., trials in which the critical region was never fixated)\n########################################################\nd_crit_tft <- d_crit[d_crit$TFT != 0, ]\n########################################################\n# How many trials (=rows) in % are removed by selecting only the ones with TFT larger than 0? \n# 0.07765415 => 7.77% of all trials were removed\n########################################################\n1 - nrow(d_crit_tft) / nrow(d_crit)\n########################################################\n\n# Fit a linear mixed model with log transformed total fixation times as dependent variable and the above defined contrasts as predictor variables (independent variables)\nlibrary(lme4)\n########################################################\n# With contrasts coded as columns:\nm <- lmer(log(TFT)~\n Dep+\n Gram+\n Int+\n Gram_x_Dep+\n Int_x_Gram+\n Int_x_Dep+\n Int_x_Gram_x_Dep+\n (1|subj)+\n (1|item),\n data=d_crit_tft)\n########################################################\n# With contrasts coded using contrasts():\nm <- lmer(log(TFT)~cond+(1|subj)+(1|item), data=d_crit_tft)\nsummary(m)\n\n# Interpret the model output verbally.\n########################################################\n# t values for Dep and Gram are large enough to be significant,\n# i.e. dependency type and grammaticality have a significant\n# effect on logarithmic total fixation time.\n# The estimated betas for these contrasts are positive, which means:\n# - Subject-verb agreement has larger TFT than reflexive-antecedent binding\n# - Ungrammatical items have larger TFT than grammatical ones\n# The other contrasts do not show significant effects.\n########################################################\n\n# We have modeled log(TFT). However, for the conceptual interpretation, it is often easier to express the effect sizes on the ms-scale rather than the log-ms scale\n# Compute the effect sizes of the predictors to the ms-scale. H\n\n# Effect of dependency type on the ms scale \n########################################################\n# NOTE: Not sure if this is really what they mean...\n\n# A change from \"reflexive\" to \"agreement\" dependency type increases log(TFT) by 0.2775904\n# This corresponds to multiplying TFT by e^0.2775904 = 1.319945\nms_effects <- exp(fixef(m))\nms_effects[\"condDep\"]\n\n# For example, the average TFT for the \"reflexive\" dependency type is 553.5267 ms:\naverage_reflexive_tft <-\n d_crit_tft %>%\n filter(cond %in% c(\"e\", \"f\", \"g\", \"h\")) %>%\n summarize(mean(TFT))\n\n# Applying a factor of 1.319945 would mean an expected increase by 177.0983 ms\n# when changing the dependency type to \"agreement\":\nms_increase <- average_reflexive_tft * ms_effects[\"condDep\"] - average_reflexive_tft\n########################################################\n", "meta": {"hexsha": "a1c76adb128ea13930df827adce61feceb0ad839", "size": 10834, "ext": "r", "lang": "R", "max_stars_repo_path": "linear_modeling/Assignment_4_Frequentist_Data_Analysis.r", "max_stars_repo_name": "raykyn/eyetracking", "max_stars_repo_head_hexsha": "8757e101c8de292b025939e27eab8aabd0749363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_modeling/Assignment_4_Frequentist_Data_Analysis.r", "max_issues_repo_name": "raykyn/eyetracking", "max_issues_repo_head_hexsha": "8757e101c8de292b025939e27eab8aabd0749363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_modeling/Assignment_4_Frequentist_Data_Analysis.r", "max_forks_repo_name": "raykyn/eyetracking", "max_forks_repo_head_hexsha": "8757e101c8de292b025939e27eab8aabd0749363", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7685950413, "max_line_length": 169, "alphanum_fraction": 0.5792874285, "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.36906116094483415}}
{"text": "#!/usr/local/bin/Rscript --vanilla\n\n###############################################################################\n# METAREP : High-Performance Comparative Metagenomics Framework (http://www.jcvi.org/metarep)\n# Copyright(c) J. Craig Venter Institute (http://www.jcvi.org)\n#\n# Licensed under The MIT License\n# Redistributions of files must retain the above copyright notice.\n#\n# link http://www.jcvi.org/metarep METAREP Project\n# package metarep\n# version METAREP v 1.3.2\n# author Johannes Goll\n# lastmodified 2010-07-09\n# license http://www.opensource.org/licenses/mit-license.php The MIT License\n###############################################################################\n\nlibrary(edgeR);\nlibrary(methods);\n\n## get command line arguments\nargs \t\t\t\t\t= commandArgs(TRUE)\n\ninfile \t\t\t\t\t= args[1];\noutfile \t\t\t\t= args[2];\npropround \t\t\t\t= as.numeric(args[3]);\npvalround \t\t\t\t= as.numeric(args[4]);\nstartIndexPopulationB\t= as.numeric(args[5]);\npopulationNameA\t\t\t= args[6];\npopulationNameB\t\t\t= args[7];\n\n## get edgeR DGE List object\ntargets = read.delim(infile,stringsAsFactors=F);\ndgeList = readDGE(targets);\nfeatures = rownames(dgeList$counts); \nm = as.matrix(dgeList$counts);\n\n## get number of datasets\nncols = as.numeric(length(m[1,]));\nnrows = as.numeric(length(m[,1]));\n\n## get counts for each population\nposA = seq(1,(startIndexPopulationB-1));\n\nposB = seq(startIndexPopulationB,ncols);\ncntA = apply(m[,posA],1,sum);\ncntB = apply(m[,posB],1,sum);\n\n## estimate common dispersion\ncommonDispersion = estimateCommonDisp(dgeList);\n\n## execute exact negative binomial test\nedgeResults = exactTest(commonDispersion,pair=c(populationNameA,populationNameB));\nedgeResultTable = edgeResults$table;\n\n## top ten results for smear plot\n#topTenEdgeResults = topTags(edgeResults);\n#pdf(outfile||\".pdf\");\n\n## init metarep result matrix\ncolumns = c(\"id\",\"count1\",\"count2\",\"logConc\",\"logFC\",\"disp\",\"p_value\",\"b_value\",\"q_value\");\nmetarepResults = data.frame(matrix(rep(NA,9*nrows),ncol=9),stringsAsFactors=F);\t\t\ncolnames(metarepResults) = columns;\n\n## set metarep result values\nmetarepResults[,1] = features;\nmetarepResults[,2] = cntA;\nmetarepResults[,3] = cntB;\nmetarepResults[,4] = round(edgeResultTable$logConc,4);\nmetarepResults[,5] = round(edgeResultTable$logFC,4);\nmetarepResults[,6] = round(commonDispersion$common.dispersion,4);\nmetarepResults[,7] = round(edgeResultTable$p.value,pvalround);\nmetarepResults[,8] = round(p.adjust(edgeResultTable$p.value, method = \"fdr\"),pvalround);\nmetarepResults[,9] = round(p.adjust(edgeResultTable$p.value, method = \"bonferroni\"),pvalround);\n\n## write results to tab delimites output file\nwrite.table(metarepResults,file=outfile,row.names=F,sep =\"\\t\",eol=\"\\n\",append=F,quote=F);\n\n## exit\nq(status=0)", "meta": {"hexsha": "d85a7a31ae70c367471dcd71a5adf10b47a07f5c", "size": 2728, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/r/edge_r_test.r", "max_stars_repo_name": "allenlab/PhyloMetarep", "max_stars_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/r/edge_r_test.r", "max_issues_repo_name": "allenlab/PhyloMetarep", "max_issues_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/r/edge_r_test.r", "max_forks_repo_name": "allenlab/PhyloMetarep", "max_forks_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1, "max_line_length": 95, "alphanum_fraction": 0.6946480938, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.36888686041209756}}
{"text": "stem <- c(\"甲\", \"乙\", \"丙\", \"丁\", \"戊\", \"己\", \"庚\", \"辛\", \"壬\", \"癸\")\nbranch <- c(\"子\", \"丑\", \"寅\", \"卯\", \"辰\", \"巳\", \"午\", \"未\", \"申\", \"酉\", \"戌\", \"亥\")\nstembranch <- function(year) {\n return(paste0(stem[(year-3)%%10], branch[(year-3)%%12]))\n}\n", "meta": {"hexsha": "82757aa57b8d2b67d41efe453a0c5ee421737745", "size": 224, "ext": "r", "lang": "R", "max_stars_repo_path": "stembranch.r", "max_stars_repo_name": "liu-sun/stembranch", "max_stars_repo_head_hexsha": "daa5b32c2a532dbfc796103133fa1657bdc790bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stembranch.r", "max_issues_repo_name": "liu-sun/stembranch", "max_issues_repo_head_hexsha": "daa5b32c2a532dbfc796103133fa1657bdc790bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stembranch.r", "max_forks_repo_name": "liu-sun/stembranch", "max_forks_repo_head_hexsha": "daa5b32c2a532dbfc796103133fa1657bdc790bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3333333333, "max_line_length": 71, "alphanum_fraction": 0.4107142857, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3686789263911349}}
{"text": "########################### BayesKin ###########################\n## Bayesian estimates of rigid body kinematics\n## Andy Pohl\n## UofC - Faculty of Kinesiology\n\n## Written by: Andy Pohl\n## UofC - Faculty of Kinesiology\n## June-Dec 2020\n## Revision 1: April 2021\n################################################################\n\n##################### generate_results.r ###################\n## processes_results table for a batch of simulations\n#############################################################\n\n\n# preliminaries \nrm(list = ls()) # clear workspace\n\nlibrary('dplyr')\nlibrary('latex2exp')\nlibrary('xtable')\nlibrary('coda')\nWORKING_DIR = \"\" # Replace with the location of the BayesKin/src directory on the local PC.\nsetwd(WORKING_DIR)\nRESULTS_DIR = paste0(WORKING_DIR, \"/src/\") # location of results directory\n\nsetwd(RESULTS_DIR)\n# Load results file\n\nFILENAME = \"\" # Filename of .rda result file produced by process_results.r\nresults = readRDS(FILENAME)\nresults = data.frame(results, stringsAsFactors = F)\nresults$model = factor(results$model, levels = c('LS', \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\", \"Bayes_p4\", \"Bayes_p5\"))\nresults$parameter = factor(results$parameter, levels = c('r1', \"r2\", \"theta1\", \"theta2\", \"theta3\", \"sigma\"))\n# Convert r/sigma to mm\nresults[results$parameter %in% c('r1', 'r2', 'sigma'),c('est', 'quantile.1', 'quantile.2', 'quantile.3', 'quantile.4', 'quantile.5')] = results[results$parameter %in% c('r1', 'r2', 'sigma'),c('est', 'quantile.1', 'quantile.2', 'quantile.3', 'quantile.4', 'quantile.5')]*1000\n\n# Set constants\nPOSES = c(\"SingleLink\", \"DoubleLink\", \"TripleLink\")\nMODELS = c(\"LS\", \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\", \"Bayes_p4\", \"Bayes_p5\")\nPARMS = c(\"r1\", \"r2\", \"theta1\", \"theta2\", \"theta3\", \"sigma\")\nPARMLABS = list(r1=TeX(\"$r_1 \\\\, (mm)$\"), r2=TeX(\"$r_2 \\\\, (mm)$\"), theta1=TeX(\"$\\\\theta_1 \\\\, (^o)$\"), \n theta2=TeX(\"$\\\\theta_2 \\\\, (^o)$\"), theta3=TeX(\"$\\\\theta_3\\\\, (^o) \"), sigma=TeX(\"$\\\\sigma \\\\, (mm)$\"))\nMODELLABS = c(\"LS\", \"Bayes P1\", \"Bayes P2\", \"Bayes P3\", \"Bayes P4\", \"Bayes P5\")\n\nTRUEVALS = list(r1 = 0.07*1000, r2 = 0.03*1000, \n theta1 = -55, theta2 = -110, theta3 = -10, sigma = 1.5/1000 *1000)\n\n################################################################################\n## FILTERING Poor MCMC convergence\n################################################################################\n# identify poor MCMC convergence\nbad_seeds = results %>% group_by(pose) %>% filter(rhat>1.1) %>% select(pose, model, seed) %>% distinct()\nbad_seeds %>% summarise(n_distinct(seed))\n\nresults = results[!((results$seed %in% bad_seeds$seed[bad_seeds$pose == 'SingleLink']) & (results$pose == 'SingleLink')),]\nresults = results[!((results$seed %in% bad_seeds$seed[bad_seeds$pose == 'DoubleLink']) & (results$pose == 'DoubleLink')),]\nresults = results[!((results$seed %in% bad_seeds$seed[bad_seeds$pose == 'TripleLink']) & (results$pose == 'TripleLink')),]\n\n# filter to only 1000 iterations per pose\nresults_temps = results[results$pose =='SingleLink',]\ntemp_seeds = unique(results_temps$seed)\nresults_temps = results_temps[results_temps$seed %in% temp_seeds[1:1000],]\n\nresults_tempd = results[results$pose =='DoubleLink',]\ntemp_seeds = unique(results_tempd$seed)\nresults_tempd = results_tempd[results_tempd$seed %in% temp_seeds[1:1000],]\n\nresults_tempt = results[results$pose =='TripleLink',]\ntemp_seeds = unique(results_tempt$seed)\nresults_tempt = results_tempt[results_tempt$seed %in% temp_seeds[1:1000],]\n\nresults = rbind(results_temps, results_tempd, results_tempt)\n\nresults %>% group_by(pose) %>% summarise(n_distinct(seed))\n\n################################################################################\n## MCMC convergence summary\n################################################################################\n\nMCMC_summary = results %>% filter(model != \"LS\") %>% \n group_by(pose, model, parameter) %>% \n summarise( mean_neff = mean(rhat), sd_neff = sd(rhat))\n\nxtable(MCMC_summary)\n\n\n################################################################################\n## Table 1: Bias, variance, mse and RMSE\n################################################################################\n\ntab1 = results %>% group_by(pose, model, parameter) %>% summarize(bias = mean(est), var = sd(est)^2)\n\nparms = c(\"r1\", \"r2\", \"theta1\", \"theta2\", \"theta3\", \"sigma\")\nfor(i in 1:length(parms)){\n tab1$bias[tab1$parameter == parms[i]] = tab1$bias[tab1$parameter == parms[i]] - TRUEVALS[[parms[i]]]\n}\ntab1$bias[tab1$parameter %in% c('r1', 'r2', 'sigma')] = tab1$bias[tab1$parameter %in% c('r1', 'r2', 'sigma')] \ntab1$mse = tab1$bias^2 + tab1$var\ntab1$rmse = sqrt(tab1$mse)\n\n\nprint(xtable(tab1[,c('pose', 'model', 'parameter', 'rmse')], digits = 3), include.rowname=F)\n\n################################################################################\n## FIGURE 1 strip charts\n################################################################################\ndeltadeg = 2\ndeltar = .02 *1000\naxislimits = list(r1 = TRUEVALS[[1]] + c(-deltar, deltar),\n r2 = TRUEVALS[[2]] + c(-deltar, deltar),\n theta1 = TRUEVALS[[3]] + c(-deltadeg, deltadeg),\n theta2 = TRUEVALS[[4]] + c(-deltadeg, deltadeg),\n theta3 = TRUEVALS[[5]] + c(-deltadeg, deltadeg),\n sigma = c(0, 0.01))\naxislimits$sigma = axislimits$sigma*1000\n\ncolors = list(grey = rgb(97/255, 97/255,97/255, 0.2),\n orange = rgb(241/255, 136/255,5/255, 1),\n blue = rgb(18/255, 78/255,120/255, 0.2),\n red = rgb(162/255, 0/255,33/255, 0.2),\n green = rgb(76/255, 159/255, 112/255, 0.2),\n purple = rgb(217/255, 187/255, 249/255, 0.2),\n pink = rgb(217/255, 3/255, 104/255, 0.2))\n\npoint_cols = list(colors$pink, colors$blue, colors$green, colors$purple)\n\n# Adjust the following to choose what is plotted in the nparmsx4 grid of plots.\nMODELS = c(\"LS\", \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\")\nMODELLABS = c(\"LS\", \"Bayes P1\", \"Bayes P2\", \"Bayes P3\")\n################################################################################\n## Single Link\n################################################################################\nsl_results = results %>% filter(pose == 'SingleLink')\npar(mfcol = c(4,4), mar = c(3, 1, 1,1), mgp = c(2,0.5,0), cex.lab = 1.2, cex.main = 1.2)\nfor(i in 1:length(MODELS)){\n m_results = sl_results %>% filter(model == MODELS[i])\n ps = unique(m_results$parameter)\n for(j in 1:length(ps)){\n est = m_results %>% filter(parameter == ps[j]) %>% select(est)\n if(j ==1){\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS),\n ylab =NA, yaxt='n', bty = 'n',\n main = MODELLABS[i])\n }else{\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), bty = 'n',\n ylab =NA, yaxt='n')\n }\n \n segments(x0=TRUEVALS[[ps[j]]], y0=-0.02, x1=TRUEVALS[[ps[j]]], y1=0.12, col = colors$orange, lwd=1.5)\n }\n}\n\n################################################################################\n## Double Link\n################################################################################\nsl_results = results %>% filter(pose == 'DoubleLink')\npar(mfcol = c(5,4), mar = c(3, 1, 1,1), mgp = c(2,0.5,0), cex.lab = 1.2, cex.main = 1.2)\nfor(i in 1:length(MODELS)){\n m_results = sl_results %>% filter(model == MODELS[i])\n ps = unique(m_results$parameter)\n for(j in 1:length(ps)){\n est = m_results %>% filter(parameter == ps[j]) %>% select(est)\n if(j ==1){\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n',\n main = MODELLABS[i])\n }else{\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits),ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n')\n }\n \n segments(x0=TRUEVALS[[ps[j]]], y0=-0.02, x1=TRUEVALS[[ps[j]]], y1=0.12, col = colors$orange, lwd=1.5)\n }\n}\n\n################################################################################\n## Triple Link\n################################################################################\nsl_results = results %>% filter(pose == 'TripleLink')\npar(mfcol = c(6,4), mar = c(3, 1, 1,1), mgp = c(2,0.5,0), cex.lab = 1.2, cex.main = 1.2)\nfor(i in 1:length(MODELS)){\n m_results = sl_results %>% filter(model == MODELS[i])\n ps = unique(m_results$parameter)\n for(j in 1:length(ps)){\n est = m_results %>% filter(parameter == ps[j]) %>% select(est)\n if(j ==1){\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n',\n main = MODELLABS[i])\n }else{\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1),\n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n')\n }\n segments(x0=TRUEVALS[[ps[j]]], y0=-0.02, x1=TRUEVALS[[ps[j]]], y1=0.12, col = colors$orange, lwd=1.5)\n }\n}\n\n\n################################################################################\n## Table 2: EQULIIVANCE\n################################################################################\n\n## Prior 1\np1 = results %>% filter(model =='Bayes_p1' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p1 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p1') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p1\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p1 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 2\np2 = results %>% filter(model =='Bayes_p2' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p2 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p2') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p2\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p2 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 3\np3 = results %>% filter(model =='Bayes_p3' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p3 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p3') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p3\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p3 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 4\np4 = results %>% filter(model =='Bayes_p4' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p4 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p4') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p4\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p4 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 5\np5 = results %>% filter(model =='Bayes_p5' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p5 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p5') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p5\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p5 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\nBayes_perf = rbind(Bayes_perf_p1, Bayes_perf_p2, Bayes_perf_p3, Bayes_perf_p4, Bayes_perf_p5)\n\nBayes_perf\n\n\n################################################################################\n## Computational time.\n################################################################################\ncomp_time = results %>% select(pose, seed, model, run_time) %>% group_by(pose, model) \ncomp_time = unique(comp_time)\ncomp_time = comp_time %>% summarise(run_time_mean = mean(run_time), run_time_sd = sd(run_time))\n\n# temp = Bayes_perf %>% group_by(pose, model, parameter) %>% summarise(equilivance = mean(coverage), perf = mean(outperformed))\nxtable(comp_time, digits = 2)\n\n\n#####################################################################################\n## Plot likelihoods\n#####################################################################################\nsource('./library.r')\n\nset.seed(4)\n\n## 1) Specify parameters\nn.links = 3 # Number of links.\nseg.length = c(0.45, 0.35, 0.25) # Length of segment specified in m. NB: Pataky pg 2.\nr_true = c(0.07, 0.03) # Origin location in m.\ntheta_true = c(-55, -110, -10) # Rotation angle in deg. NB: specified to avoid 0/360 issue\n# and mirroring solutions.\nsigma_true = 1.5/1000 # Measurement noise in m. NB Noise specified as 1.5mm\n# midpoint of range explored by Pataky et al.\ntrue_vals = c(r_true = r_true, theta_true = theta_true, sigma_true = sigma_true)\n\n\n# Generate posture\nlinks = list(gen_link(seg.length = seg.length[1],\n plate.center = 0.7*seg.length[1]),\n gen_link(seg.length = seg.length[2],\n plate.center = 0.5*seg.length[2]),\n gen_link(seg.length = seg.length[3],\n plate.center = 0.5*seg.length[3]))\nposture = gen_posture(links, r = r_true, theta = theta_true)\ny = gen_obs(posture, sigma_true)\n\nLS_result = LS_soln(y, links, \n inits = true_vals,\n init_type = 'random' )\ninits = c(0.0446749866008758, 0.012961977859959, -40.1004006620497, 88.534386176616, 142.351554371417)\n# lik for r\nrs = seq(-1, 1, by = 0.01)\ncosts = matrix(NA, nrow = length(rs), ncol = length(rs))\nfor(i in 1:length(rs)){\n for(j in 1:length(rs)){\n costs[i,j] = cost(params = c(rs[i], rs[j], true_vals[3:5]), y =y, links = links)\n }\n}\n\nfilled.contour(x=rs, y = rs, z=costs, \n color = function(n) rev(hcl.colors(n, \"Spectral\")),\n main = 'Cost for R', xlab = 'r1', ylab = 'r2', nlevels = 30,\n plot.axes={points(true_vals[1], true_vals[2], pch = 3, col = 'green')\n points(LS_result$r.hat[1], LS_result$r.hat[2], pch = 3, col = 'blue')\n points(inits[1], inits[2], pch = 3, col = 'black')\n axis(1, seq(-1, 1, by = 0.1))\n axis(2, seq(-1, 1, by = 0.1))})\n\n# lik for theta 1 vs 2\nthetas = seq(-360, 360, by = 1)\ncosts = matrix(NA, nrow = length(thetas), ncol = length(thetas))\nfor(i in 1:length(thetas)){\n for(j in 1:length(thetas)){\n costs[i,j] = cost(params = c(true_vals[1:2], thetas[i], thetas[j], true_vals[5]), y =y, links = links)\n }\n}\n\nfilled.contour(x=thetas, y = thetas, z=costs, \n color = function(n) rev(hcl.colors(n, \"Spectral\")),\n main = 'Cost for theta', xlab = 'theta1', ylab = 'theta2', nlevels = 30,\n plot.axes={points(true_vals[3], true_vals[4], pch = 3, col = 'green')\n points(LS_result$theta.hat[1], LS_result$theta.hat[2], pch = 3, col = 'blue')\n points(inits[3], inits[4], pch = 3, col = 'black')\n axis(1, seq(-360, 360, by = 45))\n axis(2, seq(-360, 360, by = 45))})\n\n\n# lik for theta 2 vs 3\nthetasi = seq(-135, 135, length.out = 500)\nthetasj = seq(-45, 270, length.out = 500)\n\ncosts = matrix(NA, nrow = length(thetasi), ncol = length(thetasj))\nfor(i in 1:length(thetasi)){\n for(j in 1:length(thetasj)){\n costs[i,j] = cost(params = c(true_vals[1:3], thetasi[i], thetasj[j]), y=y, links = links)\n }\n}\n\nfilled.contour(x=thetasi, y = thetasj, z=costs, \n color = function(n) rev(hcl.colors(n, \"Spectral\")),\n main = \"LS Cost\", xlab = TeX('$\\\\theta_2$'), ylab = TeX('$\\\\theta_3$'), nlevels = 30,\n plot.axes={points(true_vals[4], true_vals[5], pch = 19, col = rgb(241/255, 136/255,5/255, 1))\n points(LS_result$theta.hat[2], LS_result$theta.hat[3], pch = 19, col = rgb(217/255, 3/255, 104/255, 1))\n points(inits[4], inits[5], pch = 19, col = 'black')\n axis(1, seq(-135, 135, by = 45))\n axis(2, seq(-45, 270, by = 45))})\n\n\n\n## lik for sigma\nsigmas = seq(1e-3, 1, length.out = 10000)\nlls = rep(NA, length(sigmas))\nfor(i in 1:length(sigmas)){\n lls[i] = loglikelihood(hat = c(true_vals[1:5], log(sigmas[i])), y=y, links = links)\n}\n\nplot(x = log(sigmas), y=lls, type = 'l', main = 'LL for sigma', xlab = 'log(sigma)')\nabline(v=log(true_vals[6]), col = 'red')\n\n\n\nplot_system(posture, y)\nposture_hat = gen_posture(links = links, r = LS_result$r.hat, theta = LS_result$theta.hat)\nplot_system(posture_hat, y, add=T)\n\n", "meta": {"hexsha": "8a2f0792aace54c6a23425c90b570434a5e39002", "size": 26668, "ext": "r", "lang": "R", "max_stars_repo_path": "src/analyse_results.r", "max_stars_repo_name": "AndyPohlNZ/BayesKin", "max_stars_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analyse_results.r", "max_issues_repo_name": "AndyPohlNZ/BayesKin", "max_issues_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analyse_results.r", "max_forks_repo_name": "AndyPohlNZ/BayesKin", "max_forks_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2986111111, "max_line_length": 274, "alphanum_fraction": 0.5112869357, "num_tokens": 7700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.36829040165574684}}
{"text": "model_updatephase <- function (cumulTT = 354.582294511779,\n leafNumber_t1 = 4.620511621863958,\n cumulTTFromZC_39 = 0.0,\n isMomentRegistredZC_39 = 0,\n gAI = 0.3255196285135,\n grainCumulTT = 0.0,\n dayLength = 12.7433275303389,\n vernaprog = 1.0532526829571554,\n minFinalNumber = 6.879410413987549,\n fixPhyll = 91.2,\n isVernalizable = 1,\n dse = 105.0,\n pFLLAnth = 2.22,\n dcd = 100.0,\n dgf = 450.0,\n degfm = 0.0,\n maxDL = 15.0,\n sLDL = 0.85,\n ignoreGrainMaturation = FALSE,\n pHEADANTH = 1.0,\n choosePhyllUse = 'Default',\n p = 120.0,\n phase_t1 = 1.0,\n cumulTTFromZC_91 = 0.0,\n phyllochron = 91.2,\n hasLastPrimordiumAppeared_t1 = 0,\n finalLeafNumber_t1 = 0.0){\n #'- Name: UpdatePhase -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: UpdatePhase Model\n #' * Author: Pierre MARTRE\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA Montpellier\n #' * Abstract: This strategy advances the phase and calculate the final leaf number\n #' \t\n #'- inputs:\n #' * name: cumulTT\n #' ** description : cumul thermal times at current date\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 354.582294511779\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: leafNumber_t1\n #' ** description : Actual number of phytomers\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 4.620511621863958\n #' ** unit : leaf\n #' ** inputtype : variable\n #' * name: cumulTTFromZC_39\n #' ** description : cumul of the thermal time ( DeltaTT) since the moment ZC_39\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0\n #' ** unit : °C d-1\n #' ** inputtype : variable\n #' * name: isMomentRegistredZC_39\n #' ** description : true if ZC_39 is registered in the calendar\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0\n #' ** unit : \n #' ** inputtype : variable\n #' * name: gAI\n #' ** description : used to calculate Terminal spikelet\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0.3255196285135\n #' ** unit : \n #' ** inputtype : variable\n #' * name: grainCumulTT\n #' ** description : cumulTT used for the grain developpment\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: dayLength\n #' ** description : length of the day\n #' ** datatype : DOUBLE\n #' ** variablecategory : auxiliary\n #' ** min : 0\n #' ** max : 24\n #' ** unit : h\n #' ** default : 12.7433275303389\n #' ** inputtype : variable\n #' * name: vernaprog\n #' ** description : progression on a 0 to 1 scale of the vernalization\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10\n #' ** default : 1.0532526829571554\n #' ** unit : \n #' ** inputtype : variable\n #' * name: minFinalNumber\n #' ** description : minimum final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 6.879410413987549\n #' ** unit : leaf\n #' ** inputtype : variable\n #' * name: fixPhyll\n #' ** description : Phyllochron with sowing date fix\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 91.2\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: isVernalizable\n #' ** description : true if the plant is vernalizable\n #' ** parametercategory : species\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** default : 1\n #' ** inputtype : parameter\n #' * name: dse\n #' ** description : Thermal time from sowing to emergence\n #' ** parametercategory : genotypic\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 105\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: pFLLAnth\n #' ** description : Phyllochronic duration of the period between flag leaf ligule appearance and anthesis\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : \n #' ** default : 2.22\n #' ** inputtype : parameter\n #' * name: dcd\n #' ** description : Duration of the endosperm cell division phase\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 100\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: dgf\n #' ** description : Grain filling duration (from anthesis to physiological maturity)\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 450\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: degfm\n #' ** description : Grain maturation duration (from physiological maturity to harvest ripeness)\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 50\n #' ** default : 0\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: maxDL\n #' ** description : Saturating photoperiod above which final leaf number is not influenced by daylength\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 24\n #' ** default : 15\n #' ** unit : h\n #' ** inputtype : parameter\n #' * name: sLDL\n #' ** description : Daylength response of leaf production\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0.85\n #' ** unit : leaf h-1\n #' ** inputtype : parameter\n #' * name: ignoreGrainMaturation\n #' ** description : true to ignore grain maturation\n #' ** parametercategory : species\n #' ** datatype : BOOLEAN\n #' ** default : FALSE\n #' ** unit : \n #' ** inputtype : parameter\n #' * name: pHEADANTH\n #' ** description : Number of phyllochron between heading and anthesiss\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 1\n #' ** unit : \n #' ** inputtype : parameter\n #' * name: choosePhyllUse\n #' ** description : Switch to choose the type of phyllochron calculation to be used\n #' ** parametercategory : species\n #' ** datatype : STRING\n #' ** unit : \n #' ** default : Default\n #' ** inputtype : parameter\n #' * name: p\n #' ** description : Phyllochron (Varietal parameter)\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 120\n #' ** unit : °C d leaf-1\n #' ** inputtype : parameter\n #' * name: phase_t1\n #' ** description : the name of the phase\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** default : 1\n #' ** unit : \n #' ** inputtype : variable\n #' * name: cumulTTFromZC_91\n #' ** description : cumul of the thermal time (DeltaTT) since the moment ZC_91\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** default : 0\n #' ** unit : °C d-1\n #' ** inputtype : variable\n #' * name: phyllochron\n #' ** description : Phyllochron\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 91.2\n #' ** unit : °C d leaf-1\n #' ** inputtype : variable\n #' * name: hasLastPrimordiumAppeared_t1\n #' ** description : if Last Primordium has Appeared\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0\n #' ** unit : \n #' ** inputtype : variable\n #' * name: finalLeafNumber_t1\n #' ** description : final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 0\n #' ** unit : leaf\n #' ** inputtype : variable\n #'- outputs:\n #' * name: finalLeafNumber\n #' ** description : final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** unit : leaf\n #' * name: phase\n #' ** description : the name of the phase\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** unit : \n #' * name: hasLastPrimordiumAppeared\n #' ** description : if Last Primordium has Appeared\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n hasLastPrimordiumAppeared <- hasLastPrimordiumAppeared_t1\n finalLeafNumber <- finalLeafNumber_t1\n phase <- phase_t1\n if (phase_t1 >= 0.0 && phase_t1 < 1.0)\n {\n if (cumulTT >= dse)\n {\n phase <- 1.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 1.0 && phase_t1 < 2.0)\n {\n if (isVernalizable == 1 && vernaprog >= 1.0 || isVernalizable == 0)\n {\n if (dayLength > maxDL)\n {\n finalLeafNumber <- minFinalNumber\n hasLastPrimordiumAppeared <- 1\n }\n else\n {\n appFLN <- minFinalNumber + (sLDL * (maxDL - dayLength))\n if (appFLN / 2.0 <= leafNumber_t1)\n {\n finalLeafNumber <- appFLN\n hasLastPrimordiumAppeared <- 1\n }\n else\n {\n phase <- phase_t1\n }\n }\n if (hasLastPrimordiumAppeared == 1)\n {\n phase <- 2.0\n }\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 2.0 && phase_t1 < 4.0)\n {\n if (isMomentRegistredZC_39 == 1)\n {\n if (phase_t1 < 3.0)\n {\n ttFromLastLeafToHeading <- 0.0\n if (choosePhyllUse == 'Default')\n {\n ttFromLastLeafToHeading <- (pFLLAnth - pHEADANTH) * fixPhyll\n }\n else if ( choosePhyllUse == 'PTQ')\n {\n ttFromLastLeafToHeading <- (pFLLAnth - pHEADANTH) * phyllochron\n }\n else if ( choosePhyllUse == 'Test')\n {\n ttFromLastLeafToHeading <- (pFLLAnth - pHEADANTH) * p\n }\n if (cumulTTFromZC_39 >= ttFromLastLeafToHeading)\n {\n phase <- 3.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else\n {\n phase <- phase_t1\n }\n ttFromLastLeafToAnthesis <- 0.0\n if (choosePhyllUse == 'Default')\n {\n ttFromLastLeafToAnthesis <- pFLLAnth * fixPhyll\n }\n else if ( choosePhyllUse == 'PTQ')\n {\n ttFromLastLeafToAnthesis <- pFLLAnth * phyllochron\n }\n else if ( choosePhyllUse == 'Test')\n {\n ttFromLastLeafToAnthesis <- pFLLAnth * p\n }\n if (cumulTTFromZC_39 >= ttFromLastLeafToAnthesis)\n {\n phase <- 4.0\n }\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 == 4.0)\n {\n if (grainCumulTT >= dcd)\n {\n phase <- 4.5\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 == 4.5)\n {\n if (grainCumulTT >= dgf || gAI <= 0.0)\n {\n phase <- 5.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 5.0 && phase_t1 < 6.0)\n {\n localDegfm <- degfm\n if (ignoreGrainMaturation)\n {\n localDegfm <- -1.0\n }\n if (cumulTTFromZC_91 >= localDegfm)\n {\n phase <- 6.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 6.0 && phase_t1 < 7.0)\n {\n phase <- phase_t1\n }\n return (list (\"finalLeafNumber\" = finalLeafNumber,\"phase\" = phase,\"hasLastPrimordiumAppeared\" = hasLastPrimordiumAppeared))\n}", "meta": {"hexsha": "5b0470b359b3ff229c82c98c0e8e59be607c26a2", "size": 19293, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Updatephase.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Updatephase.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Updatephase.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 43.4527027027, "max_line_length": 134, "alphanum_fraction": 0.3359767791, "num_tokens": 4091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.36818775662645664}}
{"text": "#' Create a bias-corrected distribution model\n#' \n#' This function implements an occupancy-detection model assuming that:\n#' \\itemize{\n#' \t\t\\item{Detection varies by state but not between counties in a state.\n#' \t\t\\item{False detections can occur when the species does not occupy a county but does not occur when it does.\n#'\t\t\\item{Occupancy is a function of the occupancy of neighboring counties.\n#' }\n#' @param shape SpatialPolygonsDataFrame\n#' @param effort Character, name of field in \\code{shape} indicating collection effort.\n#' @param detect Character, name of field in \\code{shape} indicating number of detections of focal species.\n#' @param stateProv Character, name of field with state/province.\n#' @param county Character, name of field with county.\n#' @param niter Positive integer, number of MCMC iterations (including burn-in). The default is 2000, but this is often too low for most cases (i.e., try numbers in the range 10000, 100000, etc.).\n#' @param nburnin Positive integer, number of burn-in samples (less than \\code{niter}). The default is 1000, but this is often too low for most cases (i.e., try numbers in the range 10000, 100000, etc.).\n#' @param nchains Positive integer, number of MCMC chains (default is 4).\n#' @param thin Positive integer, number of MCMC samples by which to thin the results (default is 1; i.e., no thinning). To reduce memory requirements, you can use \\code{thin} while increasing \\code{niter} and/or \\code{nburnin}.\n#' @param raf Logical, if \\code{TRUE} (default), dynamically change the value for niter using the Raftery-Lewis method for assessing number of iterations needed for convergence. The number used will the the number suggested rounded up to the nearest 1000. The total number of iterations (including burn-in) will be this number plus \\code{nburnin}.\n#' @param minIter Minimum number of iterations to require (not including burn-in).\n#' @param maxIter Maximum number of iterations to allow in output. The final number of recommended iterations will be \\code{min(maxIter, rl)} where \\code{rl} is the number recommend by the RL method, rounded up to the nearest 1000. If \\code{rl} is > \\code{maxIter} a warning will be issued.\n#' @param nsamples Number of samples desired (after burn-in and thinning). Only used if \\code{raf} is \\code{TRUE}. Used to reset the value of \\code{thin} after estimating the number of iterations using the Raftery-Lewis method.\n#' @param na.rm Logical, if \\code{TRUE} (default), then remove rows in \\code{shape} that have \\code{NA} in any input field. If this is \\code{FALSE} and \\code{NA}s occur in any fields then an error may occur.\n#' @param verbose Logical, if \\code{TRUE} (default) display progress.\n#' @param ... Arguments to pass to \\code{\\link[nimble]{configureMCMC}}, \\code{\\link[nimble]{runMCMC}}, and \\code{rafLewis}.\n#' @return A list object with three elements, one with the MCMC chains, a second with the object \\code{shape} with model output appended to the data portion of the object, and a third with model information. The new columns in \\code{shape} represent:\n#' \\itemize{\n#' \t\t\\item{\\code{psi}} Probability of occurrence\n#' \t\t\\item{\\code{psi95CI}} 95% credibility interval for probability of occurrence\n#' \t\t\\item{\\code{p}} Probability of detecting the focal species assuming it is present\n#' \t\t\\item{\\code{p95CI}} 95% credibility interval for probability of detection\n#' }\n#' @examples\n#' @export\n\ntrainBayesODM_pMaxVarByState_psiCar <- function(\n\tshape,\n\teffort,\n\tdetect,\n\tstateProv,\n\tcounty,\n\tniter = 2000,\n\tnburnin = 1000,\n\tnchains = 4,\n\tthin = 1,\n\traf = TRUE,\n\tminIter = 2000,\n\tmaxIter = 11000,\n\tnsamples = 1000,\n\tna.rm = TRUE,\n\tverbose = TRUE,\n\t...\n) {\n\n\t### prepare data\n\t################\n\n\t\t# remove missing\n\t\tif (na.rm) {\n\t\t\tok <- complete.cases(shape@data[ , c(effort, detect)])\n\t\t\tshape <- shape[ok, ]\n\t\t}\n\t\t\t\n\t\t### CAR setup for counties\n\t\t\n\t\tneighs <- spdep::poly2nb(shape, queen=TRUE)\n\t\tneighIndex <- which(!sapply(neighs, function(shape) { length(shape == 1) && (shape == 0) }))\n\t\tislandIndex <- which(sapply(neighs, function(shape) { length(shape == 1) && (shape == 0) }))\n\n\t\thasNeighs <- length(neighIndex) > 0\n\t\thasIslands <- length(islandIndex) > 0\n\t\t\n\t\tif (hasIslands) {\n\t\t\tshapeNoIslands <- shape[neighIndex, ]\n\t\t\tneighs <- spdep::poly2nb(shapeNoIslands, queen=TRUE)\n\t\t}\n\n\t\tnumNeighs <- length(neighIndex)\n\t\tnumIslands <- length(islandIndex)\n\t\t\n\t\tnumCounties <- nrow(shape)\n\t\tnumStates <- length(unique(shape@data[ , stateProv]))\n\t\t\n\t\t### input\n\t\tdata <- list()\n\t\tconstants <- list(\n\t\t\tnumStates = numStates\n\t\t)\n\t\t\n\t\tinits <- list(\n\t\t\tq = 0.01,\n\t\t\tqConstraint = rep(1, numStates),\n\t\t\tp_max = rep(0.6, numStates),\n\t\t\tp_min_star = rep(0.95, numStates)\n\t\t)\n\n\t\t# some counties have neighbors\n\t\tif (hasNeighs) {\n\t\t\t\n\t\t\t# remove islands\n\t\t\tneighsList <- spdep::nb2WB(neighs)\n\t\t\tcarAdjCounty <- neighsList$adj\n\t\t\tcarWeightCounty <- neighsList$weights\n\t\t\tcarNumCounty <- neighsList$num\n\n\t\t\tdata <- c(\n\t\t\t\tdata,\n\t\t\t\tlist(\n\t\t\t\t\ty_neigh = shape@data[neighIndex, detect],\n\t\t\t\t\tN_neigh = shape@data[neighIndex, effort],\n\t\t\t\t\tcarAdjCounty = carAdjCounty,\n\t\t\t\t\tcarWeightCounty = carWeightCounty,\n\t\t\t\t\tcarNumCounty = carNumCounty\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tconstants <- c(\n\t\t\t\tconstants,\n\t\t\t\tlist(\n\t\t\t\t\tnumNeighs = numNeighs,\n\t\t\t\t\tstate_neigh = as.numeric(as.factor(shape@data[neighIndex, stateProv])),\n\n\t\t\t\t\tlengthAdjCounties = length(carAdjCounty)\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tinits <- c(\n\t\t\t\tinits,\n\t\t\t\tlist(\n\t\t\t\t\tp_star_neigh = runif(numNeighs, inits$p_min_star * inits$p_max, inits$p_max),\n\t\t\t\t\n\t\t\t\t\tz_neigh = rep(1, numNeighs),\n\t\t\t\t\tpsi_neigh = runif(numNeighs, 0.4, 0.6),\n\t\t\t\t\t\n\t\t\t\t\tpsi_tau = 0.1,\n\t\t\t\t\tpsi_car = rnorm(numNeighs)\n\t\t\t\t)\n\t\t\t)\n\t\t\t\n\t\t}\n\t\t\n\t\t# some counties are islands\n\t\tif (hasIslands) {\n\t\t\n\t\t\tdata <- c(\n\t\t\t\tdata,\n\t\t\t\tlist(\n\t\t\t\t\ty_island = shape@data[islandIndex, detect],\n\t\t\t\t\tN_island = shape@data[islandIndex, effort]\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tnumStates_island <- length(shape@data[islandIndex, stateProv])\n\t\t\t\n\t\t\tconstants <- c(\n\t\t\t\tconstants,\n\t\t\t\tlist(\n\t\t\t\t\tnumIslands = numIslands,\n\t\t\t\t\tstate_island = as.numeric(as.factor(shape@data[islandIndex, stateProv]))\n\t\t\t\t)\n\t\t\t)\n\t\t\t\n\t\t\tpsi_island <- runif(numIslands, 0.4, 0.6)\n\t\t\t\n\t\t\tinits <- c(\n\t\t\t\tinits,\n\t\t\t\tlist(\n\t\t\t\t\tp_star_island = runif(numIslands, 0.1, 0.5),\n\t\t\t\t\tz_island = rep(1, numIslands),\n\t\t\t\t\tpsi_island = psi_island,\n\t\t\t\t\tlogit_psi_island = logit(psi_island),\n\t\t\t\t\tpsi_islandMean = 0,\n\t\t\t\t\tpsi_islandTau = 1\n\t\t\t\t)\n\t\t\t)\n\t\t\t\n\t\t}\n\t\t\n\t\t### monitors\n\t\tmonitors <- names(inits)\n\t\tif (hasNeighs) monitors <- c(monitors, 'p_star_neigh')\n\t\tif (hasIslands) monitors <- c(monitors, 'p_star_island')\n\n\t### model setup\n\t###############\n\t\n\t\tcode <- if (hasNeighs & hasIslands) {\n\t\t\t.trainBayesODM_pMaxVarByState_psiCar_neighsIslands\n\t\t} else if (hasNeighs & !hasIslands) {\n\t\t\t.trainBayesODM_pMaxVarByState_psiCar_neighsOnly\n\t\t} else if (!hasNeighs & hasIslands) {\n\t\t\t.trainBayesODM_pMaxVarByState_psiCar_islandsOnly\n\t\t}\n\n\t\t### construct and compile model\n\t\t###############################\n\t\t\n\t\t\tmodel <- nimble::nimbleModel(code=code, constants=constants, data=data, inits=inits, check=TRUE)\n\t\t\tflush.console()\n\n\t\t\tconf <- nimble::configureMCMC(model, monitors = monitors, print = verbose, enableWAIC = TRUE)\n\t\t\t\n\t\t\t### modify samplers\n\t\t\tnode <- 'q'\n\t\t\tconf$removeSamplers(node)\n\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t\n\t\t\tif (hasNeighs) {\n\t\t\t\tnode <- 'psi_tau'\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t}\n\t\t\t\n\t\t\tif (hasIslands) {\n\t\t\t\tnode <- 'psi_islandTau'\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\n\t\t\t\t# for (i in 1:numIslands) {\n\t\t\t\t\t# node <- paste0('logit_psi_island[', i, ']')\n\t\t\t\t\t# conf$removeSamplers(node)\n\t\t\t\t\t# conf$addSampler(target=node, type='slice')\n\t\t\t\t# }\n\t\t\t}\n\t\t\t\n\t\t\tfor (i in 1:numStates) {\n\n\t\t\t\tnode <- paste0('p_max[', i, ']')\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t\t\n\t\t\t\tnode <- paste0('p_min_star[', i, ']')\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tconfBuild <- nimble::buildMCMC(conf)\n\t\t\tcompiled <- nimble::compileNimble(model, confBuild)\n\n\t### variables to ignore when assessing convergence\n\t##################################################\n\n\t\texact <- NULL\n\t\t# pattern <- c('qConstraint[[]', 'p_star_neigh[[]', 'p_star_island[[]', 'logit_psi_island[[]')\n\t\tpattern <- c('qConstraint[[]')\n\t\n\t### use Raftery-Lewis statistic to see how many iterations are needed\n\t#####################################################################\n\n\t\tif (raf) {\n\n\t\t\trl <- rafLewis(\n\t\t\t\tcomp=compiled$confBuild,\n\t\t\t\tinits = inits,\n\t\t\t\tniter = niter,\n\t\t\t\tnburnin = nburnin,\n\t\t\t\tnsamples = nsamples,\n\t\t\t\tthin = thin,\n\t\t\t\tminIter = minIter,\n\t\t\t\tmaxIter = maxIter,\n\t\t\t\tretry = TRUE,\n\t\t\t\texact = exact,\n\t\t\t\tpattern = pattern,\n\t\t\t\tpropInsufficient = minUnconverged,\n\t\t\t\tverbose = verbose\n\t\t\t)\n\n\t\t\trl$mcmc <- .removeVariablesFromMcmc(rl$mcmc, exact=exact, pattern=pattern)\n\n\t\t\trand <- round(1E6 * runif(1))\n\t\t\ttempFile <- paste0('./temp/temp', rand, '.rda')\n\t\t\tsave(rl, file=tempFile)\n\t\t\trm(rl)\n\t\t\tgc()\n\t\t\tload(tempFile)\n\t\t\tfile.remove(tempFile)\n\t\t\t\n\t\t}\n\t\t\n\t\tif (rl$sufficient) {\n\t\t\n\t\t\tniter <- rl$recIter\n\t\t\tthin <- rl$recThin\n\t\t\t\n\t\t\tif (coda::niter(rl$mcmc) < nsamples) {\n\t\t\t\tif (verbose) omnibus::say('Adding iterations to Raftery-Lewis MCMC chain...')\n\t\t\t\tadd <- (niter - burnin - coda::niter(rl$mcmc)) * thin\n\t\t\t\trl$mcmc <- addToMcmc(comp = comp, mcmc = rl$mcmc, inits = inits, add = add, thin = thin)\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\t\n\t### add MCMC chains\n\t###################\n\t\t\n\t\tif (nchains > 1 | !raf) {\n\n\t\t\tstartChain <- if (raf) { 2 } else { 1 }\n\t\t\tthisNumChains <- if (raf) { nchains - 1 } else { nchains }\n\t\t\n\t\t\tmcmc <- runMCMC(compiled$confBuild, niter = niter, nburnin = nburnin, thin = thin, nchains = thisNumChains, inits = inits, progressBar = verbose, samplesAsCodaMCMC = TRUE, summary = FALSE, WAIC = FALSE)\n\t\t\tflush.console()\n\n\t\t\tmcmc <- .removeVariablesFromMcmc(mcmc, exact=exact, pattern=pattern)\n\t\t\t\t\n\t\t}\n\t\t\n\t\t# combine all chains\n\t\tnrowRafMcmc <- coda::niter(rl$mcmc)\n\t\tnrowNewMcmc <- coda::niter(mcmc)\n\t\t\n\t\tif (nrowRafMcmc > nrowNewMcmc) {\n\t\t\trl$mcmc <- rl$mcmc[1:nrowNewMcmc, ]\n\t\t\trl$mcmc <- as.mcmc(rl$mcmc)\n\t\t}\n\t\t\n\t\tmcmc[[1 + coda::nchain(mcmc)]] <- rl$mcmc\n\t\tnames(mcmc)[coda::nchain(mcmc)] <- paste0('chain', coda::nchain(mcmc))\n\n\t\tsave(mcmc, file=tempFile)\n\t\trm(mcmc)\n\t\tgc()\n\t\tload(tempFile)\n\t\tdone <- file.remove(tempFile)\n\t\t\n\t### WAIC and LOO\n\t################\n\t\n\t\t# combine chains\n\t\tniter <- coda::niter(mcmc) * nchains\n\t\tcombined <- mcmc[[1]]\n\t\tif (nchains > 1) {\n\t\t\tfor (chain in 2:nchains) {\n\t\t\t\tcombined <- rbind(combined, mcmc[[chain]])\n\t\t\t}\n\t\t}\n\t\t\n\t\t# counties with neighborhoods (not islands)\n\t\tif (hasNeighs) {\n\t\t\n\t\t\tneigh_ll <- matrix(NA, nrow=niter, ncol=length(data$y_neigh))\n\n\t\t\t# detection and occupancy\n\t\t\tfor (iter in 1:niter) {\n\n\t\t\t\t# detection\n\t\t\t\tz_neigh <- combined[iter, grepl(colnames(combined), pattern='z_neigh[[]'), drop=TRUE]\n\t\t\t\tp_max <- combined[iter, grepl(colnames(combined), pattern='p_max[[]'), drop=TRUE]\n\t\t\t\tp_min_star <- combined[iter, grepl(colnames(combined), pattern='p_min_star[[]'), drop=TRUE]\n\n\t\t\t\tq <- combined[iter, 'q', drop=TRUE]\n\n\t\t\t\tp_max_ll <- dbeta(p_max, 1, 1, log=TRUE)\n\t\t\t\tp_min_star_ll <- dbeta(p_min_star, 10, 1, log=TRUE)\n\t\t\t\tq_ll <- dbeta(q, 1, 2, log=TRUE)\n\t\t\t\t\n\t\t\t\t# CAR component\n\t\t\t\tpsi_tau <- combined[iter, 'psi_tau', drop=TRUE]\n\t\t\t\tpsi_tau_ll <- dgamma(psi_tau, 0.001, 0.001, log=TRUE)\n\t\t\t\t\n\t\t\t\tpsi_car <- combined[iter, grepl(colnames(combined), pattern='psi_car[[]')]\n\t\t\t\tpsi_car_ll <- dcar_normal(psi_car, adj=data$carAdjCounty[1:constants$lengthAdjCounties], weights=data$carWeightCounty[1:constants$lengthAdjCounties], num=data$carNumCounty[1:constants$numNeighs], tau=psi_tau, c=3, zero_mean=0, log=TRUE)\n\n\t\t\t\tp_star_neigh <- combined[iter, grepl(colnames(combined), pattern='p_star_neigh[[]'), drop=TRUE]\n\t\t\t\tp_neigh <- z_neigh * p_star_neigh + (1 - z_neigh) * q\n\t\t\t\t\n\t\t\t\tneigh_ll[iter, ] <-\n\t\t\t\t\tdbinom(data$y_neigh, size=data$N_neigh, prob=p_neigh, log = TRUE) +\t# detection\n\t\t\t\t\tp_max_ll[constants$state_neigh] +\t\t\t\t\t\t\t\t\t# state effect\n\t\t\t\t\tq_ll +\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# false detection\n\t\t\t\t\tpsi_car_ll\t\t\t\t\t\t\t\t\t\t\t\t\t\t# occupancy ~ CAR\n\n\t\t\t} # next iteration\n\t\t\t\n\t\t} # has neighbors\n\n\t\t# island counties\n\t\tif (hasIslands) {\n\t\t\n\t\t\tisland_ll <- matrix(NA, nrow=niter, ncol=length(data$y_island))\n\n\t\t\t# detection and occupancy\n\t\t\tfor (iter in 1:niter) {\n\n\t\t\t\t# detection\n\t\t\t\tz_island <- combined[iter, grepl(colnames(combined), pattern='z_island[[]'), drop=TRUE]\n\t\t\t\tp_max <- combined[iter, grepl(colnames(combined), pattern='p_max[[]'), drop=TRUE]\n\t\t\t\tp_min_star <- combined[iter, grepl(colnames(combined), pattern='p_min_star[[]'), drop=TRUE]\n\n\t\t\t\tq <- combined[iter, 'q', drop=TRUE]\n\n\t\t\t\tp_max_ll <- dbeta(p_max, 1, 1, log=TRUE)\n\t\t\t\tp_min_star_ll <- dbeta(p_min_star, 10, 1, log=TRUE)\n\t\t\t\tq_ll <- dbeta(q, 1, 2, log=TRUE)\n\t\t\t\t\n\t\t\t\tp_star_island <- combined[iter, grepl(colnames(combined), pattern='p_star_island[[]'), drop=TRUE]\n\t\t\t\tp_island <- z_island * p_star_island + (1 - z_island) * q\n\n\t\t\t\tpsi_islandMean <- combined[iter, 'psi_islandMean', drop=TRUE]\n\t\t\t\tpsi_islandTau <- combined[iter, 'psi_islandTau', drop=TRUE]\n\t\t\t\t\n\t\t\t\tpsi_islandMean_ll ~ dnorm(psi_islandMean, 0, sd=1000)\n\t\t\t\tpsi_islandTau_ll ~ dgamma(psi_islandTau, 1, 0.001)\n\t\t\t\n\t\t\t\tisland_ll[iter, ] <-\n\t\t\t\t\tdbinom(data$y_island, size=data$N_island, prob=p_island, log = TRUE) +\n\t\t\t\t\tp_max_ll[constants$state_island] +\n\t\t\t\t\tp_min_star_ll[constants$state_island] +\n\t\t\t\t\tq_ll +\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# false detection\n\t\t\t\t\tpsi_islandMean_ll +\t\t\t\t\t\t\t\t\t\t\t\t# psi for islands\n\t\t\t\t\tpsi_islandTau_ll\t\t\t\t\t\t\t\t\t\t\t\t# psi for islands\n\n\t\t\t} # next iteration\n\t\t\t\n\t\t} # if has islands\n\n\t\t# LL of neighbors and islands, one row per iteration, one column per county\n\t\tll <- if (hasNeighs & !hasIslands) {\n\t\t\tneigh_ll\n\t\t} else if (!hasNeighs & hasIslands) {\n\t\t\tisland_ll\n\t\t} else {\n\t\t\tcbind(neigh_ll, island_ll)\n\t\t}\n\t\n\t\twaic <- loo::waic(ll)\n\t\tloo <- loo::loo(ll, cores=4)\n\t\t\n\t### process model output\n\t########################\n\n\t\tmcmc <- .removeVariablesFromMcmc(mcmc, exact=exact, pattern=c('z_neigh[[]', 'z_island[[]'))\n\n\t\tmcmcModel <- .processBayesODM(shape=shape, mcmc=mcmc, effort=effort, detect=detect, neighIndex=neighIndex, islandIndex=islandIndex, pByState=TRUE, stateProv=stateProv)\n\n\t\tmeta <- list(\n\t\t\tniter=niter,\n\t\t\tnburnin=nburnin,\n\t\t\tnchains=nchains,\n\t\t\tthin=thin,\n\t\t\teffort=effort,\n\t\t\tdetect=detect,\n\t\t\tstateProv=stateProv,\n\t\t\tcounty=county,\n\t\t\thasIslands=hasIslands,\n\t\t\tna.rm=na.rm,\n\t\t\t...\n\t\t)\n\t\t\n\t\tmcmcModel <- c(mcmcModel, list(code=code), meta=list(meta), waic=list(waic), loo=list(loo))\n\t\tmcmcModel\n\n}\n\n.trainBayesODM_pMaxVarByState_psiCar_neighsIslands <- nimble::nimbleCode({\n\t\t\t\n\t### likelihood for counties with neighborhoods\n\tfor (g in 1:numNeighs) {\n\n\t\t# detection\n\t\ty_neigh[g] ~ dbin(p_neigh[g], N_neigh[g])\n\t\tp_neigh[g] <- z_neigh[g] * p_star_neigh[g] + (1 - z_neigh[g]) * q\n\t\tp_star_neigh[g] ~ dunif(p_min[state_neigh[g]], p_max[state_neigh[g]])\n\n\t\t# occupancy\n\t\tz_neigh[g] ~ dbern(psi_neigh[g])\n\t\tlogit(psi_neigh[g]) <- psi_car[g]\n\t\n\t}\n\n\t# county occupancy CAR\n\tpsi_tau ~ dgamma(0.001, 0.001)\n\tpsi_car[1:numNeighs] ~ dcar_normal(adj=carAdjCounty[1:lengthAdjCounties], weights=carWeightCounty[1:lengthAdjCounties], num=carNumCounty[1:numNeighs], tau=psi_tau, c=3, zero_mean=0)\t\n\n\t### likelihood for island counties\n\tfor (h in 1:numIslands) {\n\n\t\t# detection\n\t\ty_island[h] ~ dbin(p_island[h], N_island[h])\n\t\tp_island[h] <- z_island[h] * p_star_island[h] + (1 - z_island[h]) * q\n\t\tp_star_island[h] ~ dunif(p_min[state_island[h]], p_max[state_island[h]])\n\n\t\t# occupancy\n\t\tz_island[h] ~ dbern(psi_island[h])\n\t\tlogit(psi_island[h]) ~ dnorm(psi_islandMean, sd=psi_islandTau)\n\n\t}\n\n\tpsi_islandMean ~ dnorm(0, tau=0.001)\n\tpsi_islandTau ~ dgamma(1, 0.001)\n\n\t\n\t# false detection\n\tq ~ dbeta(1, 2)\n\t\n\t# detection\n\tfor (j in 1:numStates) {\n\t\tp_max[j] ~ dbeta(1, 1)\n\t\tp_min[j] <- p_min_star[j] * p_max[j]\n\t\tp_min_star[j] ~ dbeta(10, 1)\n\t\tqConstraint[j] ~ dconstraint(p_min[j] > q)\n\t}\n\t\t\n})\n\n.trainBayesODM_pMaxVarByState_psiCar_neighsOnly <- nimble::nimbleCode({\n\t\t\t\n\t### likelihood for counties with neighborhoods\n\tfor (g in 1:numNeighs) {\n\n\t\t# detection\n\t\ty_neigh[g] ~ dbin(p_neigh[g], N_neigh[g])\n\t\tp_neigh[g] <- z_neigh[g] * p_star_neigh[g] + (1 - z_neigh[g]) * q\n\t\tp_star_neigh[g] ~ dunif(p_min[state_neigh[g]], p_max[state_neigh[g]])\n\n\t\t# occupancy\n\t\tz_neigh[g] ~ dbern(psi_neigh[g])\n\t\tlogit(psi_neigh[g]) <- psi_car[g]\n\t\n\t}\n\n\t# county occupancy CAR\n\tpsi_tau ~ dgamma(0.001, 0.001)\n\tpsi_car[1:numNeighs] ~ dcar_normal(adj=carAdjCounty[1:lengthAdjCounties], weights=carWeightCounty[1:lengthAdjCounties], num=carNumCounty[1:numNeighs], tau=psi_tau, c=3, zero_mean=0)\t\n\n\t# false detection\n\tq ~ dbeta(1, 2)\n\t\n\t# detection\n\tfor (j in 1:numStates) {\n\t\tp_max[j] ~ dbeta(1, 1)\n\t\tp_min[j] <- p_min_star[j] * p_max[j]\n\t\tp_min_star[j] ~ dbeta(10, 1)\n\t\tqConstraint[j] ~ dconstraint(p_min[j] > q)\n\t}\n\t\t\n})\n", "meta": {"hexsha": "3384606699f73786060cbeba4ef0cc44d037a326", "size": 16868, "ext": "r", "lang": "R", "max_stars_repo_path": "code/trainBayesODM_pMaxVarByState_psiCar.r", "max_stars_repo_name": "adamlilith/tropicosMassModeling", "max_stars_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/trainBayesODM_pMaxVarByState_psiCar.r", "max_issues_repo_name": "adamlilith/tropicosMassModeling", "max_issues_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-10T23:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T23:54:10.000Z", "max_forks_repo_path": "code/trainBayesODM_pMaxVarByState_psiCar.r", "max_forks_repo_name": "adamlilith/tropicosMassModeling", "max_forks_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3531598513, "max_line_length": 347, "alphanum_fraction": 0.6557979606, "num_tokens": 5477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.36711337725387905}}
{"text": "#' Compute absolute distances between intervals.\n#'\n#' Computes the absolute distance between the midpoint of each `x` interval and\n#' the midpoints of each closest `y` interval.\n#'\n#' @details Absolute distances are scaled by the inter-reference gap for the\n#' chromosome as follows. For `Q` query points and `R` reference\n#' points on a chromosome, scale the distance for each query point `i` to\n#' the closest reference point by the inter-reference gap for each chromosome.\n#' If an `x` interval has no matching `y` chromosome,\n#' `.absdist` is `NA`.\n#'\n#' \\deqn{d_i(x,y) = min_k(|q_i - r_k|)\\frac{R}{Length\\ of\\ chromosome}}\n#'\n#' Both absolute and scaled distances are reported as `.absdist` and\n#' `.absdist_scaled`.\n#'\n#' @param x [tbl_interval()]\n#' @param y [tbl_interval()]\n#' @param genome [tbl_genome()]\n#'\n#' @return\n#' [tbl_interval()] with `.absdist` and `.absdist_scaled` columns.\n#'\n#' @template stats\n#'\n#' @family interval statistics\n#'\n#' @seealso\n#' \\url{http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002529}\n#'\n#' @examples\n#' genome <- read_genome(valr_example('hg19.chrom.sizes.gz'))\n#'\n#' x <- bed_random(genome, seed = 1010486)\n#' y <- bed_random(genome, seed = 9203911)\n#'\n#' bed_absdist(x, y, genome)\n#'\n#' @export\nbed_absdist <- function(x, y, genome) {\n if (!is.tbl_interval(x)) x <- as.tbl_interval(x)\n if (!is.tbl_interval(y)) y <- as.tbl_interval(y)\n if (!is.tbl_genome(genome)) genome <- as.tbl_genome(genome)\n\n # establish grouping with shared groups (and chrom)\n groups_xy <- shared_groups(x, y)\n groups_xy <- unique(as.character(c(\"chrom\", groups_xy)))\n groups_vars <- rlang::syms(groups_xy)\n\n # type convert grouping factors to characters if necessary and ungroup\n x <- convert_factors(x, groups_xy)\n y <- convert_factors(y, groups_xy)\n\n x <- group_by(x, !!! groups_vars)\n y <- group_by(y, !!! groups_vars)\n\n if (utils::packageVersion(\"dplyr\") < \"0.7.99.9000\"){\n x_cpp <- update_groups(x)\n y_cpp <- update_groups(y)\n grp_indexes <- shared_group_indexes(x_cpp, y_cpp)\n res <- dist_impl(x_cpp, y_cpp,\n grp_indexes$x,\n grp_indexes$y,\n distcalc = \"absdist\")\n } else {\n grp_indexes <- shared_group_indexes(x, y)\n res <- dist_impl(x, y,\n grp_indexes$x, grp_indexes$y,\n distcalc = \"absdist\")\n }\n\n # convert groups_xy to character vector\n if (!is.null(groups_xy)) {\n groups_xy <- as.character(groups_xy)\n }\n\n # calculate reference sizes\n genome <- filter(genome, genome$chrom %in% res$chrom)\n genome <- inner_join(genome, get_labels(y), by = c(\"chrom\"))\n\n ref_points <- summarize(y, .ref_points = n())\n genome <- inner_join(genome, ref_points, by = c(\"chrom\", groups_xy))\n\n genome <- mutate(genome, .ref_gap = .ref_points / size)\n genome <- select(genome, -size, -.ref_points)\n\n # calculate scaled reference sizes\n res <- full_join(res, genome, by = c(\"chrom\", groups_xy))\n res <- mutate(res, .absdist_scaled = .absdist * .ref_gap)\n res <- select(res, -.ref_gap)\n\n # report back original x intervals not found\n x_missing <- anti_join(x, res, by = c(\"chrom\", groups_xy))\n x_missing <- ungroup(x_missing)\n x_missing <- mutate(x_missing, .absdist = NA, .absdist_scaled = NA)\n res <- bind_rows(res, x_missing)\n\n res <- bed_sort(res)\n\n res\n}\n", "meta": {"hexsha": "ab519f20f611e2c022c86dd890ca22ebd1cdb4e5", "size": 3365, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bed_absdist.r", "max_stars_repo_name": "kriemo/valr", "max_stars_repo_head_hexsha": "6355681e84b1aece2fc3800da4c15ed29c8f754c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/bed_absdist.r", "max_issues_repo_name": "kriemo/valr", "max_issues_repo_head_hexsha": "6355681e84b1aece2fc3800da4c15ed29c8f754c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/bed_absdist.r", "max_forks_repo_name": "kriemo/valr", "max_forks_repo_head_hexsha": "6355681e84b1aece2fc3800da4c15ed29c8f754c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6699029126, "max_line_length": 86, "alphanum_fraction": 0.6579494799, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.36579149153507556}}
{"text": "#!/usr/local/bin/env Rscript --vanilla\nargs <- commandArgs(TRUE)\nif (is.null(args[1])) {\n stop(\"No expression matrix provided!\")\n}\n\nif (is.null(args[2])) {\n stop(\"No signature matrix provided!\")\n}\n\n# CIBERSORT R script v1.04 (last updated 10-24-2016)\n# Note: Signature matrix construction is not currently available; use java version for full functionality.\n# Author: Aaron M. Newman, Stanford University (amnewman@stanford.edu)\n# Requirements:\n# R v3.0 or later. (dependencies below might not work properly with earlier versions)\n# install.packages('e1071')\n# install.pacakges('parallel')\n# install.packages('preprocessCore')\n# if preprocessCore is not available in the repositories you have selected, run the following:\n# source(\"http://bioconductor.org/biocLite.R\")\n# biocLite(\"preprocessCore\")\n# Windows users using the R GUI may need to Run as Administrator to install or update packages.\n# This script uses 3 parallel processes. Since Windows does not support forking, this script will run\n# single-threaded in Windows.\n#\n# Usage:\n# Navigate to directory containing R script\n#\n# In R:\n# source('CIBERSORT.R')\n# results <- CIBERSORT('sig_matrix_file.txt','mixture_file.txt', perm, QN, absolute, abs_method)\n#\n# Options:\n# i) perm = No. permutations; set to >=100 to calculate p-values (default = 0)\n# ii) QN = Quantile normalization of input mixture (default = TRUE)\n# iii) absolute = Run CIBERSORT in absolute mode (default = FALSE)\n# - note that cell subsets will be scaled by their absolute levels and will not be\n# represented as fractions (to derive the default output, normalize absolute\n# levels such that they sum to 1 for each mixture sample)\n# - the sum of all cell subsets in each mixture sample will be added to the ouput\n# ('Absolute score'). If LM22 is used, this score will capture total immune content.\n# iv) abs_method = if absolute is set to TRUE, choose method: 'no.sumto1' or 'sig.score'\n# - sig.score = for each mixture sample, define S as the median expression\n# level of all genes in the signature matrix divided by the median expression\n# level of all genes in the mixture. Multiple cell subset fractions by S.\n# - no.sumto1 = remove sum to 1 constraint\n#\n# Input: signature matrix and mixture file, formatted as specified at http://cibersort.stanford.edu/tutorial.php\n# Output: matrix object containing all results and tabular data written to disk 'CIBERSORT-Results.txt'\n# License: http://cibersort.stanford.edu/CIBERSORT_License.txt\n\n\n#dependencies\nlibrary(e1071)\nlibrary(parallel)\nlibrary(preprocessCore)\n\n#Core algorithm\nCoreAlg <- function(X, y, absolute, abs_method){\n\n #try different values of nu\n svn_itor <- 3\n\n res <- function(i){\n if(i==1){nus <- 0.25}\n if(i==2){nus <- 0.5}\n if(i==3){nus <- 0.75}\n model<-svm(X,y,type=\"nu-regression\",kernel=\"linear\",nu=nus,scale=F)\n model\n }\n\n if(Sys.info()['sysname'] == 'Windows') out <- mclapply(1:svn_itor, res, mc.cores=1) else\n out <- mclapply(1:svn_itor, res, mc.cores=svn_itor)\n\n nusvm <- rep(0,svn_itor)\n corrv <- rep(0,svn_itor)\n\n #do cibersort\n t <- 1\n while(t <= svn_itor) {\n weights = t(out[[t]]$coefs) %*% out[[t]]$SV\n weights[which(weights<0)]<-0\n w<-weights/sum(weights)\n u <- sweep(X,MARGIN=2,w,'*')\n k <- apply(u, 1, sum)\n nusvm[t] <- sqrt((mean((k - y)^2)))\n corrv[t] <- cor(k, y)\n t <- t + 1\n }\n\n #pick best model\n rmses <- nusvm\n mn <- which.min(rmses)\n model <- out[[mn]]\n\n #get and normalize coefficients\n q <- t(model$coefs) %*% model$SV\n q[which(q<0)]<-0\n if(!absolute || abs_method == 'sig.score') w <- (q/sum(q)) #relative space (returns fractions)\n if(absolute && abs_method == 'no.sumto1') w <- q #absolute space (returns scores)\n\n mix_rmse <- rmses[mn]\n mix_r <- corrv[mn]\n\n newList <- list(\"w\" = w, \"mix_rmse\" = mix_rmse, \"mix_r\" = mix_r)\n\n}\n\n#do permutations\ndoPerm <- function(perm, X, Y, absolute, abs_method){\n itor <- 1\n Ylist <- as.list(data.matrix(Y))\n dist <- matrix()\n\n while(itor <= perm){\n #print(itor)\n\n #random mixture\n yr <- as.numeric(Ylist[sample(length(Ylist),dim(X)[1])])\n\n #standardize mixture\n yr <- (yr - mean(yr)) / sd(yr)\n\n #run CIBERSORT core algorithm\n result <- CoreAlg(X, yr, absolute, abs_method)\n\n mix_r <- result$mix_r\n\n #store correlation\n if(itor == 1) {dist <- mix_r}\n else {dist <- rbind(dist, mix_r)}\n\n itor <- itor + 1\n }\n newList <- list(\"dist\" = dist)\n}\n\n#main function\nCIBERSORT <- function(sig_matrix, mixture_file, perm=0, QN=FALSE, absolute=FALSE, abs_method='sig.score'){\n\n if(absolute && abs_method != 'no.sumto1' && abs_method != 'sig.score') stop(\"abs_method must be set to either 'sig.score' or 'no.sumto1'\")\n\n #read in data\n #X <- read.table(sig_matrix,header=T,sep=\"\\t\",row.names=1,check.names=F)\n X <- read.csv(sig_matrix, sep = \"\\t\", row.names = 1,check.names=F)\n #Y <- read.table(mixture_file, header=T, sep=\"\\t\",check.names=F)\n Y <- read.csv(mixture_file, sep = \"\\t\",check.names=F)\n #to prevent crashing on duplicated gene symbols, add unique numbers to identical names\n dups <- dim(Y)[1] - length(unique(Y[,1]))\n if(dups > 0) {\n warning(paste(dups,\" duplicated gene symbol(s) found in mixture file!\",sep=\"\"))\n rownames(Y) <- make.names(Y[,1], unique=TRUE)\n }else {rownames(Y) <- Y[,1]}\n Y <- Y[,-1]\n\n X <- data.matrix(X)\n Y <- data.matrix(Y)\n\n #order\n X <- X[order(rownames(X)),]\n Y <- Y[order(rownames(Y)),]\n\n P <- perm #number of permutations\n\n #anti-log if max < 50 in mixture file\n if (max(Y, na.rm = TRUE) < 50) {\n Y <- 2^Y\n Y[is.na(Y)] <- 0.0\n }\n\n #quantile normalization of mixture file\n if(QN == TRUE){\n tmpc <- colnames(Y)\n tmpr <- rownames(Y)\n Y <- normalize.quantiles(Y)\n colnames(Y) <- tmpc\n rownames(Y) <- tmpr\n }\n\n #store original mixtures\n Yorig <- Y\n Ymedian <- max(median(Yorig),1)\n\n #intersect genes\n Xgns <- row.names(X)\n Ygns <- row.names(Y)\n YintX <- Ygns %in% Xgns\n Y <- Y[YintX,]\n XintY <- Xgns %in% row.names(Y)\n X <- X[XintY,]\n\n #standardize sig matrix\n X <- (X - mean(X)) / sd(as.vector(X))\n\n #empirical null distribution of correlation coefficients\n if(P > 0) {nulldist <- sort(doPerm(P, X, Y, absolute, abs_method)$dist)}\n\n header <- c('Mixture',colnames(X),\"P-value\",\"Correlation\",\"RMSE\")\n if(absolute) header <- c(header, paste('Absolute score (',abs_method,')',sep=\"\"))\n\n output <- matrix()\n itor <- 1\n mixtures <- dim(Y)[2]\n pval <- 9999\n\n #iterate through mixtures\n while(itor <= mixtures){\n\n\n y <- Y[,itor]\n\n #standardize mixture\n y <- (y - mean(y)) / sd(y)\n\n #run SVR core algorithm\n result <- CoreAlg(X, y, absolute, abs_method)\n\n #get results\n w <- result$w\n mix_r <- result$mix_r\n mix_rmse <- result$mix_rmse\n\n if(absolute && abs_method == 'sig.score') {\n w <- w * median(Y[,itor]) / Ymedian\n }\n\n #calculate p-value\n if(P > 0) {pval <- 1 - (which.min(abs(nulldist - mix_r)) / length(nulldist))}\n\n #print output\n out <- c(colnames(Y)[itor],w,pval,mix_r,mix_rmse)\n if(absolute) out <- c(out, sum(w))\n if(itor == 1) {output <- out}\n else {output <- rbind(output, out)}\n\n itor <- itor + 1\n\n }\n\n #save results\n #write.table(rbind(header,output), file=\"CIBERSORT-Results.txt\", sep=\"\\t\", row.names=F, col.names=F, quote=F)\n\n #return matrix object containing all results\n obj <- rbind(header,output)\n obj <- obj[,-1]\n obj <- obj[-1,]\n obj <- matrix(as.numeric(unlist(obj)),nrow=nrow(obj))\n rownames(obj) <- colnames(Y)\n if(!absolute){colnames(obj) <- c(colnames(X),\"P-value\",\"Correlation\",\"RMSE\")}\n else{colnames(obj) <- c(colnames(X),\"P-value\",\"Correlation\",\"RMSE\",paste('Absolute score (',abs_method,')',sep=\"\"))}\n obj[, 1:(dim(X)[2])]\n}\n\ntryCatch(\n expr = {\n cs <- CIBERSORT(args[2], args[1])\n write.table(t(cs), file=\"deconvoluted.tsv\", quote = FALSE, col.names = NA, sep = \"\\t\")\n },\n error = function(e){\n # (Optional)\n # Do this if an error is caught...\n print(e)\n X <- read.csv(args[2], sep = \"\\t\", row.names = 1)\n Y <- read.csv(args[1], sep = \"\\t\")\n cs <- matrix(0, nrow = length(colnames(Y)) - 1, ncol = length(colnames(X)), dimnames = list(colnames(Y)[2:length(colnames(Y))], colnames(X)))\n write.table(t(cs), file=\"deconvoluted.tsv\", quote = FALSE, col.names = NA, sep = \"\\t\")\n }\n)\n", "meta": {"hexsha": "a3b51435e1319f662d9dff8ef44837b6b09e978c", "size": 8541, "ext": "r", "lang": "R", "max_stars_repo_path": "tumorDeconvAlgs/cibersort/cibersort.r", "max_stars_repo_name": "PNNL-CompBio/proteomicsTumorDeconv", "max_stars_repo_head_hexsha": "a88c3ee729a0dab267ebd5d802a486ebacbf0c0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-07-18T17:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T05:20:31.000Z", "max_issues_repo_path": "tumorDeconvAlgs/cibersort/cibersort.r", "max_issues_repo_name": "sgosline/proteomicsTumorDeconv", "max_issues_repo_head_hexsha": "a88c3ee729a0dab267ebd5d802a486ebacbf0c0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2020-10-14T20:37:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T15:36:22.000Z", "max_forks_repo_path": "tumorDeconvAlgs/cibersort/cibersort.r", "max_forks_repo_name": "sgosline/proteomicsTumorDeconv", "max_forks_repo_head_hexsha": "a88c3ee729a0dab267ebd5d802a486ebacbf0c0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-18T01:21:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T15:44:27.000Z", "avg_line_length": 31.750929368, "max_line_length": 147, "alphanum_fraction": 0.6263903524, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.36524156249333783}}
{"text": "library(dplyr)\nlibrary(CHNOSZ)\nlibrary(stringr)\n\n\n### helper functions\n\n# trims away leading and trailing spaces and condenses multiple spaces between words\ntrimspace <- function(str){\n gsub(\"(?<=[\\\\s])\\\\s*|^\\\\s+|\\\\s+$\", \"\", str, perl=TRUE)\n}\n\n# isolate a substring by trimming off the portions before and after it\nisolate_block <- function(str, begin_str, end_str){\n return(sub(end_str, \"\", sub(begin_str, \"\", str)))\n}\n\n### main functions\n\nmine_3o <- function(this_file,\n this_pressure,\n rxn_table,\n get_aq_dist=T,\n get_mass_contribution=T,\n get_mineral_sat=T,\n get_redox=T,\n get_charge_balance=T,\n get_ion_activity_ratios=T,\n get_fugacity=T,\n get_basis_totals=T,\n get_solid_solutions=T,\n get_affinity_energy=T,\n negative_energy_supplies=F,\n not_limiting=c(\"H+\", \"OH-\", \"H2O\"),\n mass_contribution_other=T,\n verbose=1){\n \n # set directory to rxn_3o folder where .3o files are kept\n setwd(\"rxn_3o\")\n \n # read .3o file as a string\n fileName <- this_file\n extractme <- readChar(fileName, file.info(fileName)$size) # readChar requires filesize, which is obtained from file.info()$size\n\n # get sample name\n this_name <- trimspace(isolate_block(extractme, begin_str=\"^.*\\\\|Sample:\\\\s+\", end_str=\"\\\\|\\\\n\\\\|.*$\"))\n\n if(verbose > 1){\n writeLines(paste0(\"Processing EQ3 output for \", this_name))\n }\n\n # check if file experienced errors. If so, skip processing the file:\n if (grepl(\"Normal exit\", extractme) == FALSE | grepl(\"\\\\* Error\", extractme)){\n if(verbose > 0){\n writeLines(paste0(\"\\nSample \", this_name, \" experienced errors during speciation:\"))\n\n output_error <- str_extract_all(extractme, regex(\"\\\\* Error.*?\\n(\\n|$)\", dotall=T))\n \n output_error <- lapply(output_error, function(x) gsub(\"\\n\", \" \", x))\n output_error <- lapply(output_error, str_squish)\n \n for(i in 1:length(output_error)){\n writeLines(output_error[[i]])\n }\n \n }\n\n setwd(\"../\")\n return(list())\n }\n\n sample_3o <- list()\n\n sample_3o[[\"filename\"]] <- this_file\n sample_3o[[\"name\"]] <- this_name\n \n ### Begin mining temperature, pressure, water properties\n \n # mine params\n sample_3o[[\"temperature\"]] <- isolate_block(str=extractme, begin_str=\"^.*Temperature=\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"pressure\"]] <- this_pressure #isolate_block(str=extractme, begin_str=\"^.*Pressure=\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"logact_H2O\"]] <- isolate_block(str=extractme, begin_str=\"^.*Log activity of water=\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"H2O_density\"]] <- isolate_block(str=extractme, begin_str=\"^.*Solution density =\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"H2O_molality\"]] <- 55.348/as.numeric(sample_3o[[\"H2O_density\"]])\n sample_3o[[\"H2O_log_molality\"]] <- log10(sample_3o[[\"H2O_molality\"]])\n\n ### Begin extracting 'Distribution of Aqueous Solute Species' ###\n if (get_aq_dist){\n # string to isolate the aqueous species distribution section:\n front_trim <- \"^.*\\n\\n\\n\\n --- Distribution of Aqueous Solute Species ---\\n\\n Species Molality Log Molality Log Gamma Log Activity\\n\\n\\\\s+\"\n\n # isolate species distribution block\n species_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split into substrings, each representing a separate row in the table\n species_block <- strsplit(species_block, \"\\n\")\n \n #create an empty data frame to store results\n df <- data.frame(species = character(0),\n molality = character(0),\n log_molality = character(0),\n log_gamma = character(0),\n log_activity = character(0),\n stringsAsFactors = FALSE)\n\n # convert into dataframe\n for(this_row in species_block[[1]]){\n\n # mine row data\n this_row <- trimspace(this_row)\n this_row_data <- strsplit(this_row, \" \")[[1]]\n\n # create a dataframe with results\n this_df <- data.frame(species=this_row_data[1],\n molality=this_row_data[2],\n log_molality=this_row_data[3],\n log_gamma=this_row_data[4],\n log_activity=this_row_data[5],\n stringsAsFactors=FALSE)\n\n # bind distribution of aqueous species to dataframe\n df <- rbind(df, this_df)\n\n }\n\n if(!(\"H2O\" %in% df$species)){\n # add a row for water\n df <- rbind(df, data.frame(species=\"H2O\",\n molality=sample_3o[[\"H2O_molality\"]],\n log_molality=sample_3o[[\"H2O_log_molality\"]],\n log_gamma=1,\n log_activity=sample_3o[[\"logact_H2O\"]],\n stringsAsFactors=FALSE))\n }\n\n # set rownames of aqueous species block as species names\n rownames(df) <- df$species\n df$species <- NULL\n \n # add aqueous block to this sample data\n sample_3o[[\"aq_distribution\"]] <- df\n \n } # end of 'aqueous distribution' extraction\n \n\n if(get_mass_contribution){\n ### begin extracting 'Major Species by Contribution to Aqueous Mass Balances' ###\n \n # string to isolate the species saturation section:\n front_trim <- \"^.*\\n\\n\\n --- Major Species by Contribution to Aqueous Mass Balances ---\\n\\n\\n\"\n\n # isolate contribution block\n contrib_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n\\n\\n.*$\")\n \n # split into substrings, each representing a separate row in the table\n contrib_block <- strsplit(contrib_block, \"\\n\")\n # remove blank linkes\n contrib_block[[1]] <- contrib_block[[1]][contrib_block[[1]] != \"\"]\n \n # loop through rows in this block and mine contributions\n mine_vals <- FALSE\n for(this_row in contrib_block[[1]]){\n if(grepl(\"Accounting for\", this_row)){\n # get basis species for this block\n this_basis <- sub(\" Species Accounting for 99% or More of Aqueous \", \"\", this_row)\n } else if (grepl(\"Per Cent\", this_row)){\n # get ready to mine data for this basis species\n mine_vals <- TRUE\n df_basis <- data.frame(species=character(0),\n molality=character(0),\n factor=character(0),\n percent=character(0),\n stringsAsFactors = FALSE)\n } else if (mine_vals && !grepl(\" - - - - - - - - -\", this_row)){\n # mine data from this row\n row_data <- trimspace(this_row)\n row_data <- strsplit(row_data, \" \")[[1]]\n df_basis <- rbind(df_basis, data.frame(species=row_data[1], factor=row_data[2],\n molality=row_data[3], percent=row_data[4], stringsAsFactors = FALSE))\n } else if (grepl(\" - - - - - - - - -\", this_row)){\n # stop mining for this basis species\n mine_vals <- FALSE\n # specify rownames for this contribution block\n rownames(df_basis) <- df_basis$species\n df_basis$species <- NULL\n # add contribution data to list of sample data\n sample_3o[[\"mass_contribution\"]][[this_basis]] <- df_basis\n }\n }\n } # end 'aqueous contribution' extraction\n\n\n ### Begin mining mineral saturation section \n if(get_mineral_sat){\n \n # string to isolate the mineral saturation section:\n front_trim <- \"^.*\\n\\n\\n\\n --- Saturation States of Pure Solids ---\\n\\n Phase Log Q/K Affinity, kcal\\n\\n\\\\s+\"\n\n # isolate mineral block\n mineral_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split into substrings, each representing a separate row in the table\n mineral_block <- strsplit(mineral_block, \"\\n\")\n\n # create an empty data frame to store results\n df <- data.frame(mineral = character(0),\n logQoverK = character(0),\n affinity = character(0),\n stringsAsFactors = FALSE)\n\n # convert into dataframe\n for(this_row in mineral_block[[1]]){\n # get row data\n this_row_data <- strsplit(trimspace(this_row), \" \")[[1]]\n \n # create a dataframe with mined data\n this_df <- data.frame(mineral = this_row_data[1],\n logQoverK = this_row_data[2],\n affinity = this_row_data[3],\n stringsAsFactors = FALSE)\n \n # bind results to dataframe\n df <- rbind(df, this_df)\n }\n rownames(df) <- df$mineral\n df$mineral <- NULL\n \n # add mineral saturation block to this sample data\n sample_3o[[\"mineral_sat\"]] <- df\n\n if(get_solid_solutions){\n if(grepl(\"--- Saturation States of Hypothetical Solid Solutions ---\", extractme)){\n # string to isolate the solid solution saturation section:\n front_trim <- \"^.*\\n\\n\\n --- Saturation States of Hypothetical Solid Solutions ---\\n\\n\"\n\n # isolate solid solution block\n ss_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n --- Fugacities ---.*$\") # end_str might be different if fugacity section is not present\n\n # split into substrings, each representing a separate solid solution\n ss_block <- strsplit(ss_block, \"\\n\\n\\n --- \")[[1]]\n\n ss_entries <- list()\n\n for(ss_entry in ss_block){\n ss_entry <- strsplit(ss_entry, \" ---\\n\\n \")[[1]]\n ss_name <- ss_entry[1]\n ss_name <- sub(\"\\n --- \", \"\", ss_name) # needed to clean up the first ss_entry name\n ss_data <- ss_entry[2]\n ss_data <- sub(\"Ideal solution\\n\\n Component x Log x Log lambda Log activity\\n\\n\", \"\", ss_data)[[1]]\n ss_entry <- strsplit(ss_data, \"\\n\\n\\n Mineral Log Q/K Aff, kcal State\\n\\n\")\n\n\n\n ss_entry <- lapply(ss_entry, FUN=strsplit, \"\\n\")[[1]]\n ss_entry <- lapply(ss_entry, FUN=trimws, \"l\")\n ss_entry <- lapply(ss_entry, FUN=strsplit, \"[ ]{2,}\", perl=TRUE)\n names(ss_entry) <- c(\"ideal solution\", \"mineral\")\n\n\n ideal_sol_df <- data.frame(component=character(),\n x=numeric(),\n `Log x`=numeric(),\n `Log lambda`=numeric(),\n `Log activity`=numeric(),\n stringsAsFactors = FALSE)\n for(row in ss_entry[[\"ideal solution\"]]){\n\n x <- suppressWarnings(as.numeric(row[2]))\n if(is.na(x)){\n x <- 0\n }\n\n ideal_sol_df <- rbind(ideal_sol_df, data.frame(component=as.character(row[1]),\n x = x,\n `Log x` = as.numeric(row[3]),\n `Log lambda` = as.numeric(row[4]),\n `Log activity` = as.numeric(row[5])),\n stringsAsFactors=FALSE)\n }\n names(ideal_sol_df) <- c(\"component\", \"x\", \"Log x\", \"Log lambda\", \"Log activity\") # rename columns because check.names doesn't work when creating the dataframes\n ss_entry[[\"ideal solution\"]] <- ideal_sol_df\n\n mineral_ss_df <- data.frame(mineral=character(), \n `Log Q/K`=numeric(),\n `Aff, kcal`=numeric(),\n `State`=character(),\n stringsAsFactors = FALSE)\n for(row in ss_entry[[\"mineral\"]]){\n\n\n if(length(row) == 3){\n row <- c(row, \"\")\n }\n mineral_ss_df <- rbind(mineral_ss_df, data.frame(mineral=as.character(row[1]),\n `Log Q/K`=as.numeric(row[2]),\n `Aff, kcal`=as.numeric(row[3]),\n `State`=row[4]),\n stringsAsFactors = FALSE)\n }\n names(mineral_ss_df) <- c(\"mineral\", \"Log Q/K\", \"Aff, kcal\", \"State\") # rename columns because check.names doesn't work when creating the dataframes\n ss_entry[[\"mineral\"]] <- mineral_ss_df\n\n ss_entries[[ss_name]] <- ss_entry\n }\n sample_3o[[\"solid_solutions\"]] <- ss_entries\n }\n }\n } # end 'mineral saturation affinity' extraction\n \n\n ### Begin mining redox data\n if(get_redox){\n # string to isolate the redox section:\n front_trim <- \"^.*\\n\\n\\n\\n --- Aqueous Redox Reactions ---\\n\\n Couple Eh, volts pe- log fO2 Ah, kcal\\n\\n\\\\s+\"\n\n # isolate redox block\n redox_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split into substrings, each representing a separate row in the table\n redox_block <- strsplit(redox_block, \"\\n\")\n\n #create an empty data frame to store results\n df <- data.frame(couple = character(0),\n Eh = character(0),\n pe = character(0),\n logfO2 = character(0),\n Ah = character(0),\n stringsAsFactors = FALSE)\n\n # convert into dataframe\n for(this_row in redox_block[[1]]){\n \n # get row data\n this_row_data <- strsplit(trimspace(this_row), \" \")[[1]]\n\n # create a dataframe with results\n this_df <- data.frame(couple = this_row_data[1],\n Eh = this_row_data[2],\n pe = this_row_data[3],\n logfO2 = this_row_data[4],\n Ah = this_row_data[5],\n stringsAsFactors = FALSE)\n \n # bind results to dataframe\n df <- rbind(df, this_df)\n }\n rownames(df) <- df$couple\n df$couple <- NULL\n \n # add mineral saturation block to this sample data\n sample_3o[[\"redox\"]] <- df\n } # end redox extraction\n \n\n ### begin mining charge balance data\n if(get_charge_balance){\n # string to isolate ionic strength:\n front_trim <- \"^.*Ionic strength \\\\(I\\\\)=\\\\s+\"\n\n # isolate ionic strength\n IS <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\\\s+.*$\")\n names(IS) <- \"ionic strength\"\n\n # string to isolate stoichiometric ionic strength:\n front_trim <- \"^.*Stoichiometric ionic strength=\\\\s+\"\n\n IS_stoich <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\\\s+.*$\")\n names(IS_stoich) <- \"stoichiometric ionic strength\"\n\n # string to isolate the electrical balance section:\n front_trim <- \"^.*Sigma\\\\(mz\\\\) cations=\\\\s+\"\n\n elec_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split electrical block into strings and numerics\n elec_block <- strsplit(elec_block, \"=\\\\s+|\\n\\\\s+\")[[1]]\n\n elec_block <- c(\"sigma(mz) cations\"=elec_block[1],\n \"sigma(mz) anions\"=elec_block[3],\n \"total charge\"=elec_block[5],\n \"mean charge\"=elec_block[7],\n \"charge imbalance\"=elec_block[9])\n\n # string to isolate charge balance:\n front_trim <- \"^.*The electrical imbalance is:\\n\\n\\\\s+\"\n\n cbal_bal <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split electrical block into strings and numerics\n cbal_block <- strsplit(cbal_bal, \" per cent|\\n\\\\s+\")[[1]]\n\n cbal_block <- c(\"charge imbalance % of total charge\"=cbal_block[1],\n \"charge imbalance % of mean charge\"=cbal_block[3])\n \n sample_3o[[\"charge_balance\"]] <- c(IS, IS_stoich, elec_block, cbal_block)\n } # end charge balance extraction\n\n\n if(get_ion_activity_ratios){\n ion_ratio_block <- isolate_block(extractme, \"^.*--- Ion-H\\\\+ Activity Ratios ---\\n\\n\", \"\\n\\n.*$\")\n ion_ratio_block_split <- strsplit(ion_ratio_block, \"\\n\")[[1]]\n ion_ratio_block_split <- strsplit(ion_ratio_block_split, \"=\")\n \n if (!identical(ion_ratio_block_split, character(0))){\n \n ion_ratio_logs <- trimspace(lapply(ion_ratio_block_split, `[[`, 1))\n ion_ratio_values <- suppressWarnings(as.numeric(lapply(ion_ratio_block_split, `[[`, 2)))\n \n which_to_divide <- grepl(\"/\", ion_ratio_logs) # which of these ratios divide by H+ (instead of multiply?)\n hydrogen_exponents <- unlist(lapply(lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\)xx \"), `[[`, 2), as.numeric))\n ion <- unlist(lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\) [x|/] a\\\\(\"), `[[`, 1))\n ion_times <- lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\) x a\\\\(\")[!which_to_divide], `[[`, 1)\n ion_divide <- lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\) / a\\\\(\")[which_to_divide], `[[`, 1)\n \n names(ion_ratio_values)[!which_to_divide] <- paste0(\"Log(\", ion_times, \" x H+**\", hydrogen_exponents[!which_to_divide], \")\")\n names(ion_ratio_values)[which_to_divide] <- paste0(\"Log(\", ion_divide, \" / H+**\", hydrogen_exponents[which_to_divide], \")\")\n \n ion_ratio_values[is.na(ion_ratio_values)] <- \"NA\"\n\n df <- data.frame(\"values\"=ion_ratio_values,\n \"H_exponent\"=hydrogen_exponents,\n \"divide\"=which_to_divide,\n \"ion\"=ion)\n\n df <- transform(transform(df, values = as.character(values)), values=as.numeric(values))\n df <- transform(df, ion = as.character(ion))\n sample_3o[[\"ion_activity_ratios\"]] <- df\n }\n }\n\n ### begin fugacity mining\n if(get_fugacity){\n fugacity_block <- isolate_block(extractme, \"^.*--- Fugacities ---\\n\\n\", \"\\n\\n\\n.*$\")\n str <- str_squish(strsplit(fugacity_block, \"\\n\")[[1]])\n str <- str[3:length(str)]\n split_str <- strsplit(str, \" \")\n df <- data.frame(gas=unlist(lapply(split_str, `[[`, 1)),\n log_fugacity=as.numeric(unlist(lapply(split_str, `[[`, 2))),\n stringsAsFactors=F, row.names=1)\n\n # fix an annoying behavior with R dataframes ignoring rownames when there is\n # only one row\n if(nrow(df) == 1){\n rownames(df) <- unlist(lapply(split_str, `[[`, 1))[1]\n df <- df[ , !(names(df)==\"gas\")]\n }\n\n sample_3o[[\"fugacity\"]] <- df\n }\n\n \n ### begin sensible composition mining (\"basis totals\")\n if(get_basis_totals){\n sc_block <- isolate_block(extractme, \"^.*--- Sensible Composition of the Aqueous Solution ---\\n\\n\", \"\\n\\n The above data have.*$\")\n str <- str_squish(strsplit(sc_block, \"\\n\")[[1]])\n str <- str[3:length(str)]\n split_str <- strsplit(str, \" \")\n sc_names <- unlist(lapply(lapply(split_str, `[[`, 1), paste0, \"_total\"))\n df <- data.frame(species=sc_names,\n `mg/L`=as.numeric(unlist(lapply(split_str, `[[`, 2))),\n `mg/kg.sol`=as.numeric(unlist(lapply(split_str, `[[`, 3))),\n `molarity`=as.numeric(unlist(lapply(split_str, `[[`, 4))),\n `molality`=as.numeric(unlist(lapply(split_str, `[[`, 5))),\n stringsAsFactors=F, row.names=1)\n \n # fix an annoying behavior with R dataframes ignoring rownames when there is\n # only one row\n if(nrow(df) == 1){\n rownames(df) <- sc_names[1]\n df <- df[ , !(names(df)==\"species\")]\n }\n \n sample_3o[[\"basis_totals\"]] <- df\n\n }\n\n ### begin energy mining\n if(get_affinity_energy){\n \n this_temp <- as.numeric(sample_3o[[\"temperature\"]])\n this_logact_H2O <- as.numeric(sample_3o[[\"logact_H2O\"]])\n this_H2O_log_molality <- as.numeric(sample_3o[[\"H2O_log_molality\"]])\n\n df <- sample_3o[[\"aq_distribution\"]]\n \n # get a list of mineral names in CHNOSZ\n CHNOSZ_cr_names <- unlist(thermo()$OBIGT %>% filter(state == \"cr\") %>% select(name))\n\n # clear any molal values upon moving to this sample\n remaining_react_molal_with_product_molal <- c()\n other_reactants_and_prod_names <- c()\n other_reactants_and_prod <- c()\n \n # create a dataframe for storing results\n df_rxn <- data.frame(rxn = character(0),\n affinity = numeric(0),\n energy_supply = numeric(0),\n mol_rxn = numeric(0),\n electrons= numeric(0),\n reaction = character(0),\n limiting = character(0),\n stringsAsFactors = FALSE)\n \n for(rxn in rxn_table){\n \n rxn_split <- unlist(strsplit(rxn, \"\\t\"))\n rxn_name <- rxn_split[1]\n electrons <- as.numeric(rxn_split[2])\n full_rxn <- rxn_split[3:length(rxn_split)]\n if(length(full_rxn) %% 2 != 0){\n stop(paste(\"Error: Number of reaction coefficients and species do not match in reaction\", rxn_name))\n }\n\n stoichs <- as.numeric(full_rxn[c(TRUE, FALSE)])\n species_EQ3 <- full_rxn[c(FALSE, TRUE)]\n# species_CHNOSZ <- gsub(\",AQ\", \"\", species_EQ3) # this won't work for mineral names, gases, etc.!\n# species_CHNOSZ <- gsub(\"METHANE\", \"CH4\", species_CHNOSZ) # temporary fix for methane\n# species_CHNOSZ <- gsub(\"SULFUR\", \"S\", species_CHNOSZ) # temporary fix for sulfur\n# species_CHNOSZ <- gsub(\"Ca(CO3)\", \"CaCO3\", species_CHNOSZ) # temporary fix for calcium carbonate\n# species_CHNOSZ <- gsub(\"Ca(CO3),AQ\", \"CaCO3\", species_CHNOSZ) # temporary fix for calcium carbonate\n\n species_CHNOSZ <- species_EQ3 # assuming no differences between EQ3 and CHNOSZ naming\n \n # handle minerals\n for(species in species_CHNOSZ){\n if(species %in% CHNOSZ_cr_names){\n #species_CHNOSZ <- gsub(species, lowercase_species, species_CHNOSZ)\n # add the mineral to master_df and master_df_mol dataframes assuming an\n # activity of 1 (log activity 0)\n df[species, \"log_activity\"] <- 0\n not_limiting <- c(not_limiting, species)\n }\n }\n\n ### calculate Q using EQ3-speciated activities\n # get speciated activities from master_df\n activities <- c()\n molalities <- c()\n \n for(species in species_EQ3){\n \n if(species %in% rownames(df)){\n \n activities <- c(activities, 10^as.numeric(df[species, \"log_activity\"]))\n\n if(!grepl(\"sub$\", rxn_name)){\n molalities <- c(molalities, as.numeric(df[species, \"molality\"]))\n } else {\n molalities <- c(molalities, remaining_react_molal_with_product_molal[species])\n }\n \n } else {\n \n activities <- c(activities, NA)\n molalities <- c(molalities, NA)\n }\n }\n \n if(!(NA %in% activities) & !is.null(molalities) & !is.null(activities)){\n \n names(activities) <- species_EQ3\n names(molalities) <- species_EQ3\n\n if(grepl(\"sub$\", rxn_name)){\n other_reactants_and_prod_names <- setdiff(names(remaining_react_molal_with_product_molal), names(molalities))\n other_reactants_and_prod <- remaining_react_molal_with_product_molal[other_reactants_and_prod_names]\n }\n\n # calculate Q\n reactant_stoich <- stoichs[which(stoichs < 0)]\n reactant_activities <- activities[which(stoichs < 0)]\n reactant_molalities <- molalities[which(stoichs < 0)]\n product_stoich <- stoichs[which(stoichs > 0)]\n product_activities <- activities[which(stoichs > 0)]\n product_molalities <- molalities[which(stoichs > 0)]\n this_logQ <- sum(abs(product_stoich)*log10(product_activities)) - sum(abs(reactant_stoich)*log10(reactant_activities))\n\n\n \n if(!is.na(this_logQ)){\n \n ### calculate K using subcrt() function in CHNOSZ\n this_logK <- suppressMessages(subcrt(species=species_CHNOSZ,\n coeff=stoichs,\n #state=phase,\n T=this_temp,\n P=this_pressure)$out$logK)\n }else{\n this_logK <- NA\n }\n \n ### calculate affinity, A\n affinity_per_mol_rxn <- 0.008314*(this_temp+273.15)*2.302585*(this_logK-this_logQ) # in kJ/mol, A=RT*ln(K/Q)=RT*2.302585*(logK-logQ)\n affinity_per_mol_e <- ((affinity_per_mol_rxn*1000)/4.184)/electrons # in cal/mol e-\n\n ### calculate activity of limiting reactant\n reactant_names <- species_EQ3[which(stoichs < 0)]\n product_names <- species_EQ3[which(stoichs > 0)]\n not_lim_index <- which(reactant_names %in% not_limiting)\n\n names(reactant_molalities) <- reactant_names\n \n if(length(not_lim_index) == 0){\n molality_div_stoich <- reactant_molalities/abs(reactant_stoich)\n }else if(all(reactant_names %in% not_limiting)){\n\n # if there are no limiting reactants (e.g., reactants are all minerals)\n # then append NAs and continue...\n df_rxn <- rbind(df_rxn, data.frame(rxn=rxn_name,\n affinity=affinity_per_mol_e,\n energy_supply=NA,\n mol_rxn=1,\n electrons=electrons,\n reaction=paste(full_rxn,collapse=\" \"),\n limiting=NA,\n stringsAsFactors=FALSE))\n \n next\n }else{\n molality_div_stoich <- reactant_molalities[-not_lim_index]/abs(reactant_stoich[-not_lim_index])\n }\n limiting_reactant <- min(molality_div_stoich)\n \n which_limiting <- which(reactant_molalities/abs(reactant_stoich) == limiting_reactant)\n\n # create a string of all limiting reactants\n limiting_reactants <- paste(reactant_names[which_limiting], collapse=\" \")\n\n ### If there is more than one limiting reactant, pick the first one.\n # Prevents warnings when calculating reactant molalities when the limiting\n # reactant runs out. The math should work out the same regardless of which limiting\n # reactant is chosen.\n which_limiting <- which_limiting[1]\n\n # calculate moles of rxn before limiting reactant runs out\n mol_rxn <- reactant_molalities[which_limiting] / abs(reactant_stoich[which_limiting])\n \n # calculate reactant molalities that remain when the limiting reactant runs out\n remaining_reactant_molalities <- reactant_molalities - abs(reactant_stoich) * mol_rxn\n \n # if 'nonlimiting' species are specified by user, restore their molalities back to their original values.\n if(length(not_lim_index) > 0){\n remaining_reactant_molalities[not_lim_index] <- reactant_molalities[not_lim_index]\n }\n\n remaining_react_molal_with_product_molal <- c(remaining_reactant_molalities, product_molalities)\n names(remaining_react_molal_with_product_molal) <- c(reactant_names, product_names)\n\n # attach molalities of other reactants and products that are in the \"mother\" reaction\n if(grepl(\"sub$\", rxn_name)){\n remaining_react_molal_with_product_molal <- c(remaining_react_molal_with_product_molal, other_reactants_and_prod)\n }\n\n ### calculate 'energy' in kJ/kg H2O by multiplying affinity (kJ/mol) by activity (mol/kg) of limiting reactant\n this_energy <- affinity_per_mol_rxn * limiting_reactant\n \n if(!negative_energy_supplies && this_energy < 0){\n this_energy <- 0\n }\n\n } else { # if there is an NA in one of the activities\n affinity_per_mol_rxn <- NA\n affinity_per_mol_e <- NA\n this_energy <- NA\n mol_rxn <- NA\n limiting_reactants <- NA\n }\n\n # unit conversion\n energy_supply <- (this_energy*1000)/4.184 # in cal/kg\n \n # append results\n df_rxn <- rbind(df_rxn, data.frame(rxn=rxn_name,\n affinity=affinity_per_mol_e,\n energy_supply=energy_supply,\n mol_rxn=mol_rxn,\n electrons=electrons,\n reaction=paste(full_rxn,collapse=\" \"),\n limiting=limiting_reactants,\n stringsAsFactors=FALSE))\n } # end rxn loop\n \n rownames(df_rxn) <- df_rxn$rxn\n df_rxn$rxn <- NULL\n\n # create a dataframe for storing results\n df_rxn_sum <- data.frame(affinity = numeric(0),\n energy_supply = numeric(0),\n electrons = numeric(0),\n reaction = character(0),\n stringsAsFactors = FALSE)\n \n ### sum reaction clusters (a reaction and its subreactions)\n if(sum(grepl(\"_sub$\", rownames(df_rxn))) > 0){\n # perform this chunk of code if \"_sub\" rxns are present\n rxn_list_sub <- c() # initialize vector of sub-reaction names\n df_rxn[, \"mol_rxn_perc\"] <- NA # add a new column to df_rxn to store percent mol rxn\n \n for(rxn in c(rownames(df_rxn), \"final_energy\")){\n # loop through columns (plus a dummy \"final_energy\" column)\n \n if(grepl(\"_sub\", rxn)){\n # if the rxn represents a sub-reaction in the cluster, add column name to vector\n rxn_list_sub <- c(rxn_list_sub, rxn)\n \n } else {\n # if the rxn does not represent a sub-reaction...\n if(rxn != \"final_energy\"){\n reaction <- df_rxn[rxn, \"reaction\"]\n }\n \n if(length(rxn_list_sub) != 0){\n # sum the previous reaction cluster and append to dataframe\n rxn_sum_sub_E <- colSums(df_rxn[rxn_list_sub, \"energy_supply\", drop=FALSE])\n rxn_sum_sub_mol <- colSums(df_rxn[rxn_list_sub, \"mol_rxn\", drop=FALSE])\n rxn_clust_sub_A <- df_rxn[rxn_list_sub, , drop=FALSE] %>% mutate(A_weighted=affinity*(mol_rxn/rxn_sum_sub_mol))\n rxn_clust_sub_mol_perc <- df_rxn[rxn_list_sub, , drop=FALSE] %>% mutate(mol_perc=round(100*(mol_rxn/rxn_sum_sub_mol), 1))\n df_rxn[rxn_list_sub, \"mol_rxn_perc\"] <- rxn_clust_sub_mol_perc[, \"mol_perc\"]\n rxn_sum_sub_A <- colSums(rxn_clust_sub_A[, \"A_weighted\", drop=FALSE])\n rxn_sum_row <- data.frame(row.names=rxn_name, \"affinity\"=rxn_sum_sub_A, \"energy_supply\"=rxn_sum_sub_E, electrons=electrons, reaction=reaction)\n df_rxn_sum <- rbind(df_rxn_sum, rxn_sum_row)\n }\n \n # re-initialize vector for new reaction or reaction cluster\n rxn_name <- rxn\n rxn_list_sub <- c(rxn)\n \n }\n }\n }else{\n df_rxn_sum <- df_rxn\n }\n \n # append affinity and energy results to this sample's data\n sample_3o[[\"affinity_energy_raw\"]] <- df_rxn\n sample_3o[[\"affinity_energy\"]] <- df_rxn_sum\n } # end calculation of affinity and energy supply\n \n setwd(\"../\")\n\n return(sample_3o)\n\n}\n\n\n# function to melt aqueous contribution data from multiple samples into\n# a single dataframe and then return it.\nmelt_mass_contribution <- function(batch_3o, other=F, verbose=1){\n\n # initialize empty dataframe\n df_aq_cont <- data.frame(sample=character(0),\n basis=character(0),\n species=character(0),\n factor=character(0),\n molality=character(0),\n percent=character(0),\n stringsAsFactors=FALSE)\n\n # get all aqueous contribution data\n mass_contributions <- lapply(batch_3o[[\"sample_data\"]], `[[`, 'mass_contribution') \n\n # loop through each sample and basis species\n for(sample in names(mass_contributions)){\n if(verbose > 1){\n writeLines(paste0(\"Processing mass contribution of basis species in \", sample, \"...\"))\n }\n for(basis in names(mass_contributions[[sample]])){\n df <- mass_contributions[[sample]][[basis]]\n df[, \"basis\"] <- basis\n df[, \"sample\"] <- sample\n df[, \"species\"] <- rownames(df)\n rownames(df) <- NULL\n \n if(other){\n percent <- round(100-sum(as.numeric(df[, \"percent\"])), 2)\n df <- rbind(df, data.frame(sample=sample,\n basis=basis,\n species=\"Other\",\n factor=NA,\n molality=NA,\n percent=toString(percent),\n stringsAsFactors=FALSE))\n }\n \n df_aq_cont <- rbind(df_aq_cont, df)\n }\n }\n \n df_aq_cont <- df_aq_cont[, c(\"sample\", \"basis\", \"species\", \"factor\", \"molality\", \"percent\")]\n \n return(df_aq_cont)\n\n}\n\n\n# function to create report versions of data categories (aq distributions, etc.)\ncreate_report_df <- function(data, category, out_type){\n\n df_cat <- lapply(data, `[[`, category)\n \n all_species <- unique(unlist(lapply(lapply(df_cat, FUN=t), FUN=colnames)))\n \n df <- read.csv(text=paste(all_species, collapse=\"\\t\"), check.names=FALSE, sep=\"\\t\", stringsAsFactors=FALSE)\n\n for(i in 1:length(df_cat)){\n row <- as.data.frame(t(df_cat[[i]])[out_type, , drop=FALSE], stringsAsFactors=FALSE)\n df <- bind_rows(mutate_all(df, as.character), mutate_all(row, as.character))\n }\n df <- df[, order(colnames(df))]\n df_cat <- cbind.data.frame(sample=names(df_cat), df, stringsAsFactors = FALSE)\n \n return(df_cat)\n \n}\n\n# function to compile a report\ncompile_report <- function(data, csv_filename, aq_dist_type, mineral_sat_type,\n redox_type, get_aq_dist, get_mineral_sat, get_redox,\n get_charge_balance, get_ion_activity_ratios, get_fugacity,\n get_basis_totals, get_affinity_energy, input_processed_df,\n df_input_processed_names){\n \n report_list <- list()\n \n # open processed input file and initialize report with it\n report <- input_processed_df\n names(report) <- df_input_processed_names\n #report <- read.csv(csv_filename, check.names=FALSE, stringsAsFactors=FALSE)\n \n report_list[[\"divs\"]][[\"input\"]] <- names(report)[2:length(report)] # start at 2 to exclude \"sample\" column\n \n # create report versions of EQ3 output blocks\n if(get_aq_dist){\n aq_distribution <- create_report_df(data=data, category='aq_distribution', out_type=aq_dist_type)\n report_list[[\"divs\"]][[\"aq_distribution\"]] <- names(aq_distribution)[2:length(aq_distribution)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(aq_distribution, by=c(\"Sample\"=\"sample\"))\n }\n \n if(get_mineral_sat){\n mineral_sat <- create_report_df(data=data, category='mineral_sat', out_type=mineral_sat_type)\n report_list[[\"divs\"]][[\"mineral_sat\"]] <- names(mineral_sat)[2:length(mineral_sat)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(mineral_sat, by=c(\"Sample\"=\"sample\"))\n }\n \n if(get_redox){\n redox <- create_report_df(data=data, category='redox', out_type=redox_type)\n report_list[[\"divs\"]][[\"redox\"]] <- names(redox)[2:length(redox)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(redox, by=c(\"Sample\"=\"sample\"))\n }\n \n if(get_charge_balance){\n charge_balance <- create_report_df(data=data, category='charge_balance', out_type=1)\n report_list[[\"divs\"]][[\"charge_balance\"]] <- names(charge_balance)[2:length(charge_balance)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(charge_balance, by=c(\"Sample\"=\"sample\"))\n }\n\n if(get_ion_activity_ratios){\n if('ion_activity_ratios' %in% names(data)){\n ion_activity_ratios <- create_report_df(data=data, category='ion_activity_ratios', out_type=1)\n report_list[[\"divs\"]][[\"ion_activity_ratios\"]] <- names(ion_activity_ratios)[2:length(ion_activity_ratios)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(ion_activity_ratios, by=c(\"Sample\"=\"sample\"))\n }\n }\n\n if(get_fugacity){\n fugacities <- create_report_df(data=data, category='fugacity', out_type=1)\n report_list[[\"divs\"]][[\"fugacity\"]] <- names(fugacities)[2:length(fugacities)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(fugacities, by=c(\"Sample\"=\"sample\"))\n }\n\n if(get_basis_totals){\n sc <- create_report_df(data=data, category='basis_totals', out_type=4) # 4 is the molality column\n report_list[[\"divs\"]][[\"basis_totals\"]] <- names(sc)[2:length(sc)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(sc, by=c(\"Sample\"=\"sample\"))\n }\n\n if(get_affinity_energy){\n affinity <- create_report_df(data=data, category='affinity_energy', out_type=1)\n names(affinity)[2:length(names(affinity))] <- paste0(names(affinity)[2:length(names(affinity))], \"_affinity\")\n report_list[[\"divs\"]][[\"affinity\"]] <- names(affinity)[2:length(affinity)] # start at 2 to exclude \"sample\" column\n energy <- create_report_df(data=data, category='affinity_energy', out_type=2)\n names(energy)[2:length(names(energy))] <- paste0(names(energy)[2:length(names(energy))], \"_energy\")\n report_list[[\"divs\"]][[\"energy\"]] <- names(energy)[2:length(energy)] # start at 2 to exclude \"sample\" column\n report <- report %>%\n inner_join(affinity, by=c(\"Sample\"=\"sample\")) %>%\n inner_join(energy, by=c(\"Sample\"=\"sample\"))\n \n }\n\n rownames(report) <- report$Sample\n report$Sample <- NULL\n\n report_list[[\"report\"]] <- report\n \n return(report_list)\n\n}\n\n\n### main\nmain_3o_mine <- function(files_3o,\n rxn_filename,\n get_aq_dist,\n get_mass_contribution,\n get_mineral_sat,\n get_redox,\n get_charge_balance,\n get_ion_activity_ratios,\n get_fugacity,\n get_basis_totals,\n get_solid_solutions,\n get_affinity_energy,\n negative_energy_supplies,\n load_rxn_file,\n not_limiting,\n mass_contribution_other,\n csv_filename,\n aq_dist_type,\n mineral_sat_type,\n redox_type,\n input_filename,\n input_pressures,\n batch_3o_filename,\n df_input_processed,\n df_input_processed_names,\n custom_obigt,\n water_model,\n fixed_species,\n verbose){\n \n start_time <- Sys.time()\n\n water(water_model)\n\n # allow user to add their custom data as an OBIGT\n if(!is.null(custom_obigt)){\n custom_obigt <- read.csv(custom_obigt, stringsAsFactors=F)\n custom_obigt <- custom_obigt[, c(\"name\", \"abbrv\", \"formula\", \"state\", \"ref1\", \"ref2\", \"date\", \"E_units\", \"G\", \"H\", \"S\", \"Cp\", \"V\", \"a1.a\", \"a2.b\", \"a3.c\", \"a4.d\", \"c1.e\", \"c2.f\", \"omega.lambda\", \"z.T\")]\n suppressMessages({\n thermo(OBIGT=thermo()$OBIGT[unique(info(fixed_species)), ]) # replaces the default OBIGT database with user-supplied database\n mod.OBIGT(custom_obigt, replace=TRUE) # produces a message\n })\n }\n\n rxn_table <- NULL\n if(get_affinity_energy){\n if(load_rxn_file){\n # read table of reactions\n rxn_table <- readLines(rxn_filename)\n }else{\n rxn_table <- strsplit(rxn_filename, \"\\n\")[[1]]\n }\n }\n\n # instantiate an empty object to store data from all 3o files\n batch_3o <- list()\n \n if(verbose > 1){\n writeLines(\"Now processing EQ3 output files...\")\n }\n \n names(input_pressures) <- files_3o\n \n # process each .3o file\n for(file in files_3o){\n \n # add this sample's aqueous data to list of all sample data\n sample_3o <- mine_3o(file,\n this_pressure=input_pressures[file],\n rxn_table=rxn_table,\n get_aq_dist=get_aq_dist,\n get_mass_contribution=get_mass_contribution,\n get_mineral_sat=get_mineral_sat,\n get_redox=get_redox,\n get_charge_balance=get_charge_balance,\n get_ion_activity_ratios=get_ion_activity_ratios,\n get_fugacity=get_fugacity,\n get_basis_totals=get_basis_totals,\n get_solid_solutions=get_solid_solutions,\n get_affinity_energy=get_affinity_energy,\n negative_energy_supplies=negative_energy_supplies,\n not_limiting=not_limiting,\n mass_contribution_other=mass_contribution_other,\n verbose=verbose)\n \n # if this file could be processed, add its data to the batch_3o object\n if(length(sample_3o)>1){\n batch_3o[[\"sample_data\"]][[sample_3o[[\"name\"]]]] <- sample_3o\n }\n }\n \n if(verbose > 1){\n writeLines(\"Finished processing EQ3 output files...\")\n }\n \n # compile aqueous contribution data into a single melted dataframe and\n # append it to the batch_3o object.\n if(get_mass_contribution && length(batch_3o)>0){\n if(verbose > 1){\n writeLines(\"Now processing mass contribution data...\")\n }\n batch_3o[[\"mass_contribution\"]] <- melt_mass_contribution(batch_3o=batch_3o,\n other=mass_contribution_other,\n verbose=verbose)\n if(verbose > 1){\n writeLines(\"Finished processing mass contribution data...\")\n }\n }\n \n if(length(batch_3o)>0){\n # create a report summarizing 3o data from all samples\n report_list <- compile_report(data=batch_3o[[\"sample_data\"]],\n csv_filename=csv_filename,\n aq_dist_type,\n mineral_sat_type,\n redox_type,\n get_aq_dist,\n get_mineral_sat,\n get_redox,\n get_charge_balance,\n get_ion_activity_ratios,\n get_fugacity,\n get_basis_totals,\n get_affinity_energy,\n df_input_processed,\n df_input_processed_names)\n \n\n # add the report to the batch_3o object\n report <- report_list[[\"report\"]]\n batch_3o[[\"report\"]] <- report\n batch_3o[[\"report_divs\"]] <- report_list[[\"divs\"]]\n }else{\n return(list())\n }\n\n # store user input file data\n batch_3o[[\"input\"]] <- read.csv(input_filename, check.names=FALSE, stringsAsFactors=FALSE)\n\n # save the batch_3o object as an rds file\n if(!is.null(batch_3o_filename)){\n saveRDS(batch_3o, file=batch_3o_filename)\n }\n \n time_elapsed <- Sys.time() - start_time\n if(verbose > 1){\n writeLines(paste(\"Finished mining .3o files. Time elapsed:\", round(time_elapsed, 2), \"seconds\"))\n }\n\n return(batch_3o)\n}", "meta": {"hexsha": "567470c42da5e6fd98a4c0220a19058bedc4fe5f", "size": 44135, "ext": "r", "lang": "R", "max_stars_repo_path": "AqEquil/3o_mine.r", "max_stars_repo_name": "worm-portal/AqEquil", "max_stars_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-04T00:44:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T18:57:43.000Z", "max_issues_repo_path": "AqEquil/3o_mine.r", "max_issues_repo_name": "worm-portal/AqEquil", "max_issues_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqEquil/3o_mine.r", "max_forks_repo_name": "worm-portal/AqEquil", "max_forks_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9933396765, "max_line_length": 206, "alphanum_fraction": 0.5726067747, "num_tokens": 10784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3643827869818059}}
{"text": "NAME\tHF86\n\nMODE\tREDUCTION\n\nSORTS\tANY\n\nSIGNATURE\n\ta, b, c, d, e, f, g : ANY -> ANY\n sk : -> ANY\nORDERING KBO\n\ta = 5, b = 6, c = 6, d = 6, e = 1, f = 1, g = 1, sk = 1\n\tb > a > c > d > e > f > g > sk\n\nVARIABLES\n\tx : ANY\n\nEQUATIONS\n\t a (e (x)) = e (f (f (f (f (x)))))\n\t b (x) = e (f (f (f (x))))\n\t c (x) = e (f (f (x)))\n\t d (x) = e (f (x))\n\t g (e (x)) = x\n\nCONCLUSION\n% Loesung :\n% e (f (f (f (f (f (f (f (e (f (f (e (f (e (f (g (x)))))))))))))))) =\n% e (f (f (f (f (f (f (f (f (f (f (f (f (f (f (e (x))))))))))))))))\n\n a(b(c(d(e(f(g(sk))))))) = a(c(g(a(a(e(e(sk)))))))\n\n", "meta": {"hexsha": "b25bb366b0bc310349633ba9418a09efd633fe76", "size": 584, "ext": "rd", "lang": "R", "max_stars_repo_path": "src/main/resources/specs/hf86.rd", "max_stars_repo_name": "falsewasnottrue/forstmeister", "max_stars_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main/resources/specs/hf86.rd", "max_issues_repo_name": "falsewasnottrue/forstmeister", "max_issues_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/resources/specs/hf86.rd", "max_forks_repo_name": "falsewasnottrue/forstmeister", "max_forks_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8387096774, "max_line_length": 69, "alphanum_fraction": 0.3681506849, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3642787493341494}}
{"text": "# Install the required R packages\ninstall.packages(\"vegan\")\ninstall.packages(\"compiler\")\n\nlibrary(vegan) # Contains the function for biodiversity metrics \nlibrary(compiler) # Contains the functions to compile the R-commands to byte code to speed up processing \n\n\niterations <- 5 # Number of iterations (manuscript used 100 iterations)\nts.length <- 100 # Time series length (manuscript used 100,000 time-steps)\nrep.freq <- 10 # Reporting frequency (manuscript reported biodiversity metrics every 1000 time-steps.)\n\nSpec <- 0.0025 # Speciation rate, v (manuscript used these levels: 0.00075, 0.0025, 0.005, 0.01)\nDispersal <- 0.75 # Dispersal rate, m (manuscript used these levels: 0.25, 0.5, 0.75)\nDisp <- (Dispersal/(1-Spec))*1\n\n\n# Reporters for null counter-factual (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\nnull.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n#Reporters for development (dev) scenario (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\ndev.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n# Reporters for restoration (res) scenrio (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\nres.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n# Reporters for translocation (tran) scenario (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\ntran.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n################################################################################\n################################################################################\n\n\n# Function for the forward neutral simulation (death-immigration function)\n# Based on: Buschke, F.T. et al. (2016) Ecology and Evolution, doi:10.1002/ece3.2379\n\ndeath.imm.fun <- function (comm.t,new.K) {\nspecies <- 1:dim(comm.t)[1]\nif (runif(1) < Spec) {\n pres.ab <- ifelse(colSums(comm.t)== 0,0,1)\n N.id <- sample(samples,1,prob=(new.K*pres.ab))\n ind.k <- sample(species,1,prob=comm.t[,N.id])\n new.r <- rep(0,N)\n new.r[N.id] <- 1\n comm.t <- rbind(comm.t,new.r)\n if (sum(comm.t[,N.id]) == new.K[N.id]) {\n comm.t[ind.k,N.id] <- comm.t[ind.k,N.id]-1\n }\n} else{\n if (runif(1)>Disp) {\n pres.ab <- ifelse(colSums(comm.t)== 0,0,1)\n N.id <- sample(samples,1,prob=(new.K*pres.ab))\n ind.k <- sample(species,1,prob=comm.t[,N.id])\n if (sum(comm.t[,N.id]) == new.K[N.id]) {\n comm.t[ind.k,N.id] <- comm.t[ind.k,N.id]-1\n }\n ind.rep <- sample(species,1,prob=comm.t[,N.id])\n comm.t[ind.rep,N.id] <- comm.t[ind.rep,N.id]+1\n } else {\n pres.ab <- ifelse(colSums(comm.t)== 0,0,1)\n N.id <- sample(samples,1,prob=(new.K*pres.ab))\n ind.k <- sample(species,1,prob=comm.t[,N.id])\n if (sum(comm.t[,N.id]) == new.K[N.id]) {\n comm.t[ind.k,N.id] <- comm.t[ind.k,N.id]-1\n }\n \n imm.cell <- sample(samples,1,replace=TRUE, prob = (as.vector(imm.prob[N.id,])*pres.ab))\n \n ind.imm <- sample(species,1,prob=comm.t[,imm.cell])\n comm.t[ind.imm,N.id] <- comm.t[ind.imm,N.id]+1\n }\n}\ncomm.t\n}\n\ndeath.imm <- cmpfun(death.imm.fun)\n\n####################################################################################################\n# The follwing code sets up the landscape\n\nfor (k in 1:iterations) {\n M <- 179 # Number of patches\n Sites <- 1:M\n K <- rep(100,M) # Habitat capacity of each patch\n\n\n# Setting up the dispersal kernel based on inverse-quared distance \ndist.mat <- matrix(NA,nrow=M,ncol=M)\n for (i in 1:M) {\n for (j in 1:M) {\n if (abs(Sites[i] - Sites[j])<=89) {\n dist.mat[i,j] <- abs(Sites[i] - Sites[j])\n } else {\n dist.mat[i,j] <- 179 - (abs(Sites[i] - Sites[j]))\n }\n }\n }\n\ndisp.mat <- 1/(dist.mat^2)\ndiag(disp.mat) <- 0\n\n\n###############################################################################\n\n# Create a vector of the site identification for each species unit.\nsites <- rep(1:M,K)\n\nJ <- sum(K) # total number of species units\n\nsp.name <- 1:J # Start by assigning each species unit a unique ID\nind <- 1:J\n\n# This is a probability vector that determines whether a species unit has already coalesed.\nind.prob <- rep(1,J)\n\n# This is simply to set the counter to display the number of time-steps (starts at 1)\nx <- 1\n\n \n################################################################################\n# Algorithm for the coalescence process to set up the simulation\n# See: Rosindell, J., et al. (2008) Ecological Informatics, 3, 259-271. \n################################################################################\n\n# Start the loop and continue until the number of species in the simulation matches the observed species richness\nwhile(sum(ind.prob)> 0) {\n\n# Choose a species unit at random\nind.id <- sample(ind,1,prob=ind.prob)\n\n# First, Speciation\nif (runif(1)Disp) {\n # Identify the site location of selected species unit\n site.id <- sites[ind.id]\n # Identify a subset of species units that occur in the source patch\n migr.id <- ind[which(sites==site.id)]\n if(length(table(sp.name[migr.id]))>1) {\n # Select a subset of species units that DO NOT already share the same species ID\n imm.id <- migr.id[which(sp.name[migr.id]!=sp.name[ind.id])]\n # Select a parent/immigrant from the source quadrat\n sist.sp <- sample(imm.id,1)\n # Assign the same species ID as the parent species unit to the randomly selected focal species unit\n # AND all other species units that already share that species ID\n sp.name[which(sp.name==ind.id)] <- sp.name[sist.sp]\n }\n # Since the focal bird unit already has an assigned species ID, it is excluded from the model from now on.\n ind.prob[ind.id] <- 0\n } else {\n # Identify the site location of selected species unit\n site.id <- sites[ind.id]\n # Identify the source of selected species unit based on the dispersal kernel\n source.id <- sample(1:M,1,prob=(disp.mat[site.id,]*(K/100)))\n # Identify a subset of species units that occur in the source quadrat\n migr.id <- ind[which(sites==source.id)]\n if(length(table(sp.name[migr.id]))>1) {\n # Select a subset of species units that DO NOT already share the same species ID\n imm.id <- migr.id[which(sp.name[migr.id]!=sp.name[ind.id])]\n # Select a parent/immigrant from the source quadrat\n sist.sp <- sample(imm.id,1)\n # Assign the same species ID as the parent bird unit to the randomly selected focal bird unit\n # AND all other bird units that already share that species ID\n sp.name[which(sp.name==ind.id)] <- sp.name[sist.sp]\n }\n # Since the focal bird unit already has an assigned species ID, it is excluded from the model from now on.\n ind.prob[ind.id] <- 0\n }\n }\n}\n\n# Rearrange the new assemblage into a species-by site matrix\nPatches <- as.matrix(table(sp.name,sites))\n\n \n# Remove the diversity at the offset-receiving site (i.e. recent, but unrelated, degraded habitat)\nPatches[,81:100] <- 0\nK[81:100] <- 0\n\n \n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 1 (counterfactual)\n \nPatches.null <- Patches\nimm.prob <- disp.mat\n\nN <- dim(Patches.null)[2] \nS <- dim(Patches.null)[1]\n\nspecies <- seq(1:S) \nsamples <- seq(1:N) \n\nfor (i in 1:ts.length){\n Patches.null <- death.imm(Patches.null,K)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n null.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.null,\"pa\")))\n null.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.null,\"pa\"))>0))\n null.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.null)))/(log(colSums(decostand(Patches.null,\"pa\")))),na.rm=TRUE)\n null.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.null)))/(log(length(which(rowSums(decostand(Patches.null,\"pa\"))>0)))),na.rm=TRUE)\n null.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.null[,which(colSums(Patches.null)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.null)>0)))), type = \"centroid\")$distances)\n }\n }\n\n\n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 2 (No offsets)\n\nPatches.dev <- Patches\nPatches.dev[,c(1:10,170:179)] <- 0\nK.dev <- K\nK.dev[c(1:10,170:179)] <- 0 # Clear the development site\n\nfor (i in 1:ts.length){\n Patches.dev <- death.imm(Patches.dev,K.dev)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n dev.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.dev,\"pa\")))\n dev.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.dev,\"pa\"))>0))\n dev.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.dev)))/(log(colSums(decostand(Patches.dev,\"pa\")))),na.rm=TRUE)\n dev.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.dev)))/(log(length(which(rowSums(decostand(Patches.dev,\"pa\"))>0)))),na.rm=TRUE)\n dev.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.dev[,which(colSums(Patches.dev)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.dev)>0)))), type = \"centroid\")$distances)\n }\n }\n\n\n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 3 (passive restoration)\n\nPatches.res <- Patches\nPatches.res[,c(1:10,170:179)] <- 0\nK.res <- K\nK.res[c(1:10,170:179)] <- 0 # Clear the development site\nK.res[81:100] <- 100 # Increa the habitat capacity at the offset site\n\nfor (i in 1:ts.length){\n Patches.res <- death.imm(Patches.res,K.res)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n res.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.res,\"pa\")))\n res.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.res,\"pa\"))>0))\n res.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.res)))/(log(colSums(decostand(Patches.res,\"pa\")))),na.rm=TRUE)\n res.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.res)))/(log(length(which(rowSums(decostand(Patches.res,\"pa\"))>0)))),na.rm=TRUE)\n res.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.res[,which(colSums(Patches.res)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.res)>0)))), type = \"centroid\")$distances)\n }\n }\n\n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 4 (Translocation)\n\nPatches.tran <- Patches\nPatches.tran[,81:100] <- Patches.tran[,c(1:10,170:179)] # Translocate the communities\nPatches.tran[,c(1:10,170:179)] <- 0 # Clear the development site\nK.tran <- K\nK.tran[c(1:10,170:179)] <- 0\nK.tran[81:100] <- 100\n\nfor (i in 1:ts.length){\n Patches.tran <- death.imm(Patches.tran,K.tran)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n tran.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.tran,\"pa\")))\n tran.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.tran,\"pa\"))>0))\n tran.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.tran)))/(log(colSums(decostand(Patches.tran,\"pa\")))),na.rm=TRUE)\n tran.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.tran)))/(log(length(which(rowSums(decostand(Patches.tran,\"pa\"))>0)))),na.rm=TRUE)\n tran.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.tran[,which(colSums(Patches.tran)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.tran)>0)))), type = \"centroid\")$distances)\n }\n }\n\n print(k)\nflush.console()\n}\n\n\n\n#################################################################################\n# Average the biodiversity metric over the 100 iterations\n#################################################################################\n\nm.null.sr.a <- apply(null.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.null.sr.g <- apply(null.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.null.ev.a <- apply(null.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.null.ev.g <- apply(null.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.null.beta <- apply(null.beta,2,function(x){mean(x,na.rm=TRUE)})\n\nm.dev.sr.a <- apply(dev.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.sr.g <- apply(dev.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.ev.a <- apply(dev.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.ev.g <- apply(dev.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.beta <- apply(dev.beta,2,function(x){mean(x,na.rm=TRUE)})\n\nm.res.sr.a <- apply(res.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.res.sr.g <- apply(res.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.res.ev.a <- apply(res.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.res.ev.g <- apply(res.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.res.beta <- apply(res.beta,2,function(x){mean(x,na.rm=TRUE)})\n\nm.tran.sr.a <- apply(tran.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.sr.g <- apply(tran.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.ev.a <- apply(tran.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.ev.g <- apply(tran.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.beta <- apply(tran.beta,2,function(x){mean(x,na.rm=TRUE)})\n\n\n#################################################################################\n# This plots the outputs from the simulation\n# Each plot shows how the log response ratio between the offset scenario and the counterfactual varies through time.\n\npar(mfrow=c(2,3)) # Set up a multi-panel plot with 2 rows and three columns.\n\n# Top-left panel is for local species richness\nyval <- seq(rep.freq,ts.length,by=rep.freq)\nplot (log(m.dev.sr.a/m.null.sr.a)~yval,type=\"l\",col=\"red\",ylab=\"Alpha richness\",ylim=c(-.2,.2), xlab=\"Time steps\", main=\"Local species richness\")\nlines(log(m.res.sr.a/m.null.sr.a)~yval,col=\"blue\")\nlines(log(m.tran.sr.a/m.null.sr.a)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The top-middle panel is for regional species richness\nplot (log(m.dev.sr.g/m.null.sr.g)~yval,type=\"l\",col=\"red\",ylab=\"Gamma richness\",ylim=c(-.2,.2), xlab=\"Time steps\", main=\"Regional species richness\")\nlines(log(m.res.sr.g/m.null.sr.g)~yval,col=\"blue\")\nlines(log(m.tran.sr.g/m.null.sr.g)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The top-right panel is for local species evenness\nplot (log(m.dev.ev.a/m.null.ev.a)~yval,type=\"l\",col=\"red\",ylab=\"Alpha evenness\",ylim=c(-.5,.5), xlab=\"Time steps\", main=\"Local species evenness\")\nlines(log(m.res.ev.a/m.null.ev.a)~yval,col=\"blue\")\nlines(log(m.tran.ev.g/m.null.ev.g)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The bottom-left panel is for regional species evenness\nplot (log(m.dev.ev.g/m.null.ev.g)~yval,type=\"l\",col=\"red\",ylab=\"Gamma evennes\",ylim=c(-.2,.2), xlab=\"Time steps\", main=\"Regional species evenness\")\nlines(log(m.res.ev.g/m.null.ev.g)~yval,col=\"blue\")\nlines(log(m.tran.ev.g/m.null.ev.g)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The bottom-middle panel is for community dissimilarity\nplot (log(m.dev.beta/m.null.beta)~yval,type=\"l\",col=\"red\",ylab=\"Beta dispersion\",ylim=c(-.05,.05), xlab=\"Time steps\", main=\"Community dissimilarity\")\nlines(log(m.res.beta/m.null.beta)~yval,col=\"blue\")\nlines(log(m.tran.beta/m.null.beta)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# This plots a makeshift legen in the bottom right panel\nplot(0,0,type=\"n\",xlim=c(0,10),ylim=c(0,10),axes=F, xlab=\"\",ylab=\"\")\nlines (c(1,3),c(8,8),lty=2) \ntext(3.5,8,\"No Net loss\",pos=4)\nlines (c(1,3),c(6,6),col=\"red\") \ntext(3.5,6,\"Scenario 2 (No offset)\",pos=4)\nlines (c(1,3),c(4,4),col=\"blue\") \ntext(3.5,4,\"Scenario 3 (Passive restoration)\",pos=4)\nlines (c(1,3),c(2,2),col=\"green\") \ntext(3.5,2,\"Scenario 4 (Translocation)\",pos=4)\n\n########################################################################################\n########################################################################################\n\n# Write all the outputs to file (will be saved in your default working directory)\nwrite.table(null.sr.a,\"Null_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.sr.g,\"Null_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.ev.a,\"Null_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.ev.g,\"Null_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.beta,\"Null_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n\nwrite.table(dev.sr.a,\"Dev_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.sr.g,\"Dev_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.ev.a,\"Dev_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.ev.g,\"Dev_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.beta,\"Dev_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n\nwrite.table(res.sr.a,\"Res_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.sr.g,\"Res_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.ev.a,\"Res_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.ev.g,\"Res_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.beta,\"Res_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n\nwrite.table(tran.sr.a,\"Tran_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.sr.g,\"Tran_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.ev.a,\"Tran_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.ev.g,\"Tran_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.beta,\"Tran_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n", "meta": {"hexsha": "5e6a1f6a5356364fbadffdff3d1207e9c79dfe2f", "size": 19195, "ext": "r", "lang": "R", "max_stars_repo_path": "Neutral_simulations.r", "max_stars_repo_name": "falko-buschke/biodiversity-offsets-neutral-theory", "max_stars_repo_head_hexsha": "0d1cb3a7c767690146844d1d7efae504d8da7ed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Neutral_simulations.r", "max_issues_repo_name": "falko-buschke/biodiversity-offsets-neutral-theory", "max_issues_repo_head_hexsha": "0d1cb3a7c767690146844d1d7efae504d8da7ed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Neutral_simulations.r", "max_forks_repo_name": "falko-buschke/biodiversity-offsets-neutral-theory", "max_forks_repo_head_hexsha": "0d1cb3a7c767690146844d1d7efae504d8da7ed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-27T07:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:24:15.000Z", "avg_line_length": 46.5898058252, "max_line_length": 185, "alphanum_fraction": 0.6110966397, "num_tokens": 5538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36422578108397413}}
{"text": "# first make a a determenisti and stochastic forcast and save the results in for.det and for.sto\n# load('run/FORECAST.RData'); for.det<-forecast; summary(for.det); summary(for.det[[1]]);\n# load('run/FORECAST.RData'); for.sto<-forecast ; summary(for.sto); summary(for.sto[[1]]);\n\n# N2013\nN2013.sto<-lapply(for.sto,function(x){exp(apply(x$last.state.sim[,1:10],2,median))}) \nN2013.det<-lapply(for.det,function(x){exp(apply(x$last.state.sim[,1:10],2,median))}) \nN2013.det\nmatrix(unlist(N2013.sto),ncol=10,byrow=T)/matrix(unlist(N2013.det),ncol=10,byrow=T)\n\n\n\n# N2014\nN2014.sto<-lapply(for.sto,function(x){exp(apply(x$s1.state.sim[,1:10],2,median))}) \nN2014.det<-lapply(for.det,function(x){exp(apply(x$s1.state.sim[,1:10],2,median))}) \nN2014.det\nmatrix(unlist(N2014.sto),ncol=10,byrow=T)/matrix(unlist(N2014.det),ncol=10,byrow=T)\n\nSSB2014.sto<-lapply(for.sto,function(x){(apply(x$s1.ssb.sim,2,median))}) \nSSB2014.det<-lapply(for.det,function(x){(apply(x$s1.ssb.sim,2,median))}) \nunlist(SSB2014.sto)/unlist(SSB2014.det)\n\n\nfor.det[[1]]$s2.ssb.sim\n\n# N2015 \nN2015.sto<-lapply(for.sto,function(x){exp(apply(x$s2.state.sim[,1:10],2,median))}) \nN2015.det<-lapply(for.det,function(x){exp(apply(x$s2.state.sim[,1:10],2,median))}) \nN2015.det\nround(matrix(unlist(N2015.sto),ncol=10,byrow=T)/matrix(unlist(N2015.det),ncol=10,byrow=T),4)\n\n#WB herring\nSSB2015.sto<-lapply(for.sto,function(x){median(x$s2.ssb.sim,2)}) \nSSB2015.det<-lapply(for.det,function(x){median(x$s2.ssb.sim,2)}) \n\n\nSSB2015.sto<-lapply(for.sto,function(x){(apply(x$s2.ssb.sim,2,median))}) \nSSB2015.det<-lapply(for.det,function(x){(apply(x$s2.ssb.sim,2,median))}) \n\nunlist(SSB2015.sto)/unlist(SSB2015.det)\n\n\n\n# N2016 \nN2016.sto<-lapply(for.sto,function(x){exp(apply(x$s3.state.sim[,1:10],2,median))}) \nN2016.det<-lapply(for.det,function(x){exp(apply(x$s3.state.sim[,1:10],2,median))}) \nN2016.det\nround(matrix(unlist(N2016.sto),ncol=10,byrow=T)/matrix(unlist(N2016.det),ncol=10,byrow=T),4)\n\n\n\nSSB2016.sto<-lapply(for.sto,function(x){(apply(x$s3.ssb.sim,2,median))}) \nSSB2016.det<-lapply(for.det,function(x){(apply(x$s3.ssb.sim,2,median))}) \n \n#WB herring\nSSB2016.sto<-lapply(for.sto,function(x){median(x$s3.ssb.sim,2)}) \nSSB2016.det<-lapply(for.det,function(x){median(x$s3.ssb.sim,2)}) \n\nround(unlist(SSB2016.sto)/unlist(SSB2016.det),4)\n\nfor.det[[1]]$s2.catch.sim\nC2015.sto<-lapply(for.sto,function(x){(median(x$s2.catch.sim))}) \nC2015.det<-lapply(for.det,function(x){(median(x$s2.catch.sim))}) \nround(unlist(C2015.sto)/unlist(C2015.det),4)\n\n\n\n#WB herring\nSSB2015.sto<-lapply(for.sto,function(x){median(x$s2.ssb.sim,2)}) \nSSB2015.det<-lapply(for.det,function(x){median(x$s2.ssb.sim,2)}) \n\n\n# extract N 2015 from the first forecast option\nmatrix(unlist(N2015.sto),ncol=10,byrow=T)\nN<-matrix(unlist(N2015.sto),ncol=10,byrow=T)[1,]\nN\n\n# just checing they are the same\nfor.sto[[1]]$ave.sw\nfor.det[[1]]$ave.sw\n\nsum(for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm*N) # the simple way\nN %*% (for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm) # the Anders way\nSSB2015.sto[[1]]\nSSB2015.sto[[1]] / sum(for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm*N)\n\nsum(for.det[[1]]$ave.sw*for.sto[[1]]$ave.pm*N) # the simple way\nN %*% (for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm) # the Anders way\nSSB2015.det[[1]]\nSSB2015.det[[1]] /sum(for.det[[1]]$ave.sw*for.sto[[1]]$ave.pm*N) \n\n\n#The right way\nlapply(for.det,function(x){apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=2),1,sum)}) \nSSB2015.det<-lapply(for.det,function(x){median(apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=2),1,sum))}) \n\nlapply(for.sto,function(x){apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=1000),1,sum)})\nSSB2015.sto<-lapply(for.sto,function(x){median(apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=1000),1,sum))}) \n\nunlist(SSB2015.sto)/unlist(SSB2015.det)\n\n# ###########################################\n library(MASS)\n \nnoSim<-30000\nvar1<-0.8\nvar2<-var1*0.75\nvar12<-0.1 # co-var\nmu1<-4\nmu2<-mu1/2\nweight<-c(1,10)\nsigma<-matrix(c(var1,var12,var12,var2),ncol=2)\nlogN<-mvrnorm(noSim, mu=c(mu1,mu2), Sigma=sigma)\n\nplot(logN[,1],logN[,2])\nhist(logN[,1])\n\nN<-exp(logN)\nN.median<-apply(N,2,median)\n#N.median\nif (noSim<=10) log(N.median)\nif (noSim<=10) c(mu1,mu2) # there is no bias in N\nbio.deter<-exp(c(mu1,mu2))*weight\nif (noSim<=10) bio.deter\nbio.deter<-sum(bio.deter)\nif (noSim<=10) bio.deter\n\nif (noSim<=10) N\nbio<-N*rep(weight,each=noSim)\nif (noSim<=10) bio\n\nbio<-apply(bio,1,sum)\nif (noSim<=10) bio\nbio.sto<-median(bio)\n\nbio.sto/bio.deter\n#######\n\n# The same, but mu and variance and weight is the same for both of them\n\nnoSim<-1000000\nsd1<-0.8\nvar1<-sd1**2\nvar2<-var1\nvar12<-var1/4 # co-var\nmu1<-4\nmu2<-mu1*1\nweight<-c(1,1)\nsigma<-matrix(c(var1,var12,var12,var2),ncol=2)\nlogN<-mvrnorm(noSim, mu=c(mu1,mu2), Sigma=sigma)\n\npar(mfcol=c(2,2))\nhist(logN[,1],xlab='logN1',main=paste(\"age 1, logN, mean:\",round(mean(logN[,1]),4)))\nabline(v=mean(logN[,1]),col='red')\n\nhist(exp(logN[,1]),xlab='exp(logN1)',main=paste(\"age 1, exp(logN),median:\",round(median(exp(logN[,1])),4),'\\n exp(logN):',round(exp(mu1),4)))\nabline(v=median(exp(logN[,1])),col='red')\n\nhist(logN[,2],xlab='logN2',main=paste(\"age 2, logN, mean:\",round(mean(logN[,2]),4)))\nabline(v=mean(logN[,2]),col='red')\n\nhist(exp(logN[,2]),xlab='exp(logN1)',main=paste(\"age 2, exp(logN),median:\",round(median(exp(logN[,2])),4),'\\n exp(logN):',round(exp(mu1),4)))\nabline(v=median(exp(logN[,2])),col='red')\n\npar(mfcol=c(1,1))\n\nN<-exp(logN)\nbio.deter<-exp(c(mu1,mu2))*weight\nbio.deter<-sum(bio.deter)\nbio.deter\n\nbio<-N*rep(weight,each=noSim)\nbio<-apply(bio,1,sum)\nbio.sto<-median(bio)\nhist(bio,main=paste('median bio:',round(bio.sto,4),'\\n determ bio:',round(bio.deter,4),'\\n ratio stock:determ',round(bio.sto/bio.deter,4)))\nabline(v=bio.sto,col='red')\n\n#######\n\nneafc<-function(sd1=0.8,var2Fac=1,mu1=4,mu2Fac=1,noSim=100000,weight=c(1,10)){\n var1<-sd1*sd1\n var2<-var1*var2Fac\n var12<-var1/5 # co-var \n \n mu2<-mu1*mu2Fac\n sigma<-matrix(c(var1,var12,var12,var2),ncol=2)\n logN<-mvrnorm(noSim, mu=c(mu1,mu2), Sigma=sigma)\n N<-exp(logN)\n bio.sto<-N*rep(weight,each=noSim)\n bio.sto.corrected<-bio.sto # \"corrected\" later on\n\n bio.sto<-apply(bio.sto,1,sum)\n bio.sto<-median(bio.sto)\n\n #cat('\\nbefore adjustement')\n #print(bio.sto.corrected) \n \n cor.fac<-exp(rep(0.5*c(var1,var2),each=noSim))\n #print(cor.fac)\n \n bio.sto.corrected<-bio.sto.corrected/cor.fac\n \n #cat('\\nafter adjustement\\n')\n #print(bio.sto.corrected)\n bio.sto.corrected<-apply(bio.sto.corrected,1,sum)\n #cat('\\nsum after adjustement\\n')\n #print(bio.sto.corrected)\n bio.sto.corrected<-mean( bio.sto.corrected)\n # cat('\\nmean of sum after adjustement\\n')\n #print(bio.sto.corrected)\n \n bio.deter<-sum(exp(c(mu1,mu2))*weight)\n \n return(list(dterm=bio.deter,stoch=bio.sto,stoch.corr=bio.sto.corrected))\n}\n\n\nsd1<-seq(0.1,1.0,0.05)\ndo.it<-function(i){neafc(sd1=sd1[i],mu2Fac=1,var2Fac=1,weight=c(1,1)) }\nres<-lapply(1:length(sd1),do.it)\n\nres<-matrix(unlist(res),ncol=3,byrow=T)\nmatplot(sd1,res,ylab='Absolute values') #abs values\n\nmatplot(sd1,res/rep(res[,1],each=3),ylab='Relativ to deterministic') #relative to deterministic values\n\n\n", "meta": {"hexsha": "82733a4b2751728dbbd7ea9a2aed1ed9bd86e0e9", "size": 7136, "ext": "r", "lang": "R", "max_stars_repo_path": "SMS_R_prog/r_prog_less_frequently_used/neafc.r", "max_stars_repo_name": "ices-eg/wg_WGSAM", "max_stars_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-09-28T11:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:40:03.000Z", "max_issues_repo_path": "SMS_R_prog/r_prog_less_frequently_used/neafc.r", "max_issues_repo_name": "ices-eg/wg_WGSAM", "max_issues_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SMS_R_prog/r_prog_less_frequently_used/neafc.r", "max_forks_repo_name": "ices-eg/wg_WGSAM", "max_forks_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.298245614, "max_line_length": 141, "alphanum_fraction": 0.6748878924, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.36342745468541887}}
{"text": "# Benjamini-Hochberg procedure\n\nbh_apply <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n for (j in tws) { \n signi <- (p.adjust(dt[Timestamp >= j[1] & Timestamp <= j[2], ..i][[1]], method='fdr') < alpha)\n indi <- which(dt$Timestamp >= j[1] & dt$Timestamp <= j[2])\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_apply_bonf <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n for (j in tws) { \n signi <- (p.adjust(dt[Timestamp >= j[1] & Timestamp <= j[2], ..i][[1]], method='none') < alpha)\n indi <- which(dt$Timestamp >= j[1] & dt$Timestamp <= j[2])\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_apply_sepelec <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n elecs <- c(\"Fz\", \"Cz\", \"Pz\")\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n for (j in tws) {\n for (e in elecs) {\n signi <- (p.adjust(dt[Timestamp >= j[1] & Timestamp <= j[2] & Electrode == e, ..i][[1]], method='fdr') < alpha)\n indi <- which(dt$Timestamp >= j[1] & dt$Timestamp <= j[2] & dt$Electrode == e)\n dt[indi, paste0(\"sig_\", i) := signi]\n } \n }\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\n\nbh_apply_poolall <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n elecs <- c(\"Fz\", \"Cz\", \"Pz\")\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n signi <- (p.adjust(dt[(Timestamp >= 300 & Timestamp <= 500) | (Timestamp >= 600 & Timestamp <= 1000), ..i][[1]], method='fdr') < alpha)\n indi <- which((dt$Timestamp >= 300 & dt$Timestamp <= 500) | (dt$Timestamp >= 600 & dt$Timestamp <= 1000))\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_none <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n elecs <- c(\"Fz\", \"Cz\", \"Pz\")\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n signi <- dt[(dt$Timestamp >= 300 & dt$Timestamp <= 500) | (dt$Timestamp >= 600 & dt$Timestamp <= 1000),..i] < alpha\n indi <- which((dt$Timestamp >= 300 & dt$Timestamp <= 500) | (dt$Timestamp >= 600 & dt$Timestamp <= 1000))\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n\n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_identify_cutoff <- function(pvals, alpha = 0.05)\n{\n pvals <- sort(pvals) # sort ascending\n m <- length(pvals) # number of hypotheses\n k <- 1 # k iterator\n for (k in seq(1:m)){\n if (pvals[k] >= k/m * alpha) {\n break()\n } \n }\n # while (pvals[k] < (k / m) * alpha)\n # k <- k + 1\n return(pvals[k])\n}\n\nbh_plot <- function(pvals, alpha = 0.05)\n{\n pvals <- sort(pvals) # sort ascending\n m <- length(pvals) # number of hypothesis \n ks <- seq(1, length(pvals), 1)\n plot(pvals ~ ks)\n abline(0, alpha / m)\n}\n", "meta": {"hexsha": "1ad4de54ff45e36057e2fc66596796290c745ee0", "size": 5350, "ext": "r", "lang": "R", "max_stars_repo_path": "benjamini-hochberg.r", "max_stars_repo_name": "SFB1102/A1-PLOSONE21lmerERP", "max_stars_repo_head_hexsha": "63adf9c68d3d36a76b8d304648fdd07541c181eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benjamini-hochberg.r", "max_issues_repo_name": "SFB1102/A1-PLOSONE21lmerERP", "max_issues_repo_head_hexsha": "63adf9c68d3d36a76b8d304648fdd07541c181eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benjamini-hochberg.r", "max_forks_repo_name": "SFB1102/A1-PLOSONE21lmerERP", "max_forks_repo_head_hexsha": "63adf9c68d3d36a76b8d304648fdd07541c181eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.537037037, "max_line_length": 159, "alphanum_fraction": 0.4856074766, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3633007868865564}}
{"text": "################################################################################\n# \n# Simulation script\n# \n# Andrew Robinson 15-April-2015\n#\n################################################################################\n\n\nthe.seed <- 10000000\n\nreps <- 1000\ncores <- 25\n\nMAIL <- TRUE\n\nmail <- function(address, subject, message, attach = NULL) {\n if (MAIL)\n if (is.null(attach)) {\n system(paste(\"echo '\", message,\n \"' | mutt -s '\", subject,\n \"' \", address, sep=\"\"))\n } else {\n system(paste(\"echo '\", message,\n \"' | mutt -s '\", subject, \"'\",\n \" \", address,\n paste(\" -a \", attach, collapse=\" \"), sep=\"\"))\n }\n}\n\nmail.and.stop <- function() {\n mail(\"mensurationist@gmail.com\",\n \"Sims on server: ERROR.\",\n \"Stopped.\")\n stop()\n}\n\noptions(error = mail.and.stop)\n\n\nlibrary(lme4) # For mixed-effects models\n\nlibrary(Amelia) # For imputation\n\nlibrary(equivalence) # For data that I know\n\nlibrary(parallel) # Speed things up\n\ndata(ufc)\n\nstr(ufc)\n\nufc <- subset(ufc, !is.na(Dbh))\nufc$Species[ufc$Species %in% c(\"F\",\"FG\")] <- \"GF\"\nufc$Species <- factor(ufc$Species)\nufc$ht.measured <- is.na(ufc$Height)\n\nufc <- subset(ufc,\n Species %in% names(sort(-table(Species)))[1:6],\n select = c(\"ht.measured\",\"Plot\",\"Dbh.in\",\"Species\"))\n\n## Fit a pair of models to compare using LRT\n\nufc.whole <- ufc\n\nisna.1.w <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc.whole, family = binomial)\nisna.0.w <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc.whole, family = binomial)\n\nanova(isna.0.w, isna.1.w)\n\n################################################################################\n\nimputeLRT <- function(h0, h1, imputed.data.list) {\n m <- length(imputed.data.list)\n h0.models <- lapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset)\n })\n h0.dev.funs <- lapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.0 <-\n colMeans(do.call(rbind,\n lapply(h0.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n }))) \n h1.models <- lapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset)\n })\n h1.dev.funs <- lapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.1 <-\n colMeans(do.call(rbind,\n lapply(h1.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n d.prime.m.bar <- mean(unlist(lapply(1:m,\n function(i) {\n anova(h0.models[[i]],\n h1.models[[i]])$Chisq[2]\n })))\n d.L.bar <- mean(unlist(lapply(1:m,\n function(i) {\n h0.dev.funs[[i]](Q.bar.0) - \n h1.dev.funs[[i]](Q.bar.1) \n })))\n p0 <- length(Q.bar.0)\n p1 <- length(Q.bar.1)\n k <- p1 - p0\n rL <- (m + 1) / ((m - 1) * k) * (d.prime.m.bar - d.L.bar) # 3.8\n D.L <- d.L.bar / ((1 + rL) * k) # 3.7\n v <- k * (m - 1) \n w <- ifelse(v > 4, # 2.7 \n 4 + (v - 4) * (1 + (1 - v/2) / rL)^2,\n v / 2 * (1 + 1/k) * (1 + 1/rL)^2)\n Pval <- 1 - pf(D.L, k, w)\n return(list(\n D.L = D.L,\n Pval = Pval,\n rL = rL,\n d.L.bar = d.L.bar,\n d.prime.m.bar = d.prime.m.bar,\n Q.bar.0 = Q.bar.0,\n Q.bar.1 = Q.bar.1,\n k = k,\n w = w,\n p0 = p0,\n p1 = p1,\n m = m))\n}\n\n\nisna.1 <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc, family = binomial)\nisna.0 <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc, family = binomial) \n\nimputeLRT(isna.0, isna.1,\n list(ufc, ufc, ufc, ufc, ufc))\n\nanova(isna.0, isna.1)\n\n\n\nsimulate <- function(m = 5, n = 30) {\n make.missing <- sample(1:nrow(ufc), size = n * 3, replace = FALSE)\n is.na(ufc$Species[make.missing[1:n]]) <- TRUE\n is.na(ufc$Dbh.in[make.missing[(n+1):(2*n)]]) <- TRUE\n is.na(ufc$ht.measured[make.missing[(2*n+1):(3*n)]]) <- TRUE\n isna.1 <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc, family = binomial)\n isna.0 <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc, family = binomial) \n naive.p <- anova(isna.0, isna.1)[[\"Pr(>Chisq)\"]][2]\n ## Impute datasets using Amelia\n ufc.imputes <- amelia(ufc,\n m = m,\n cs = \"Plot\",\n noms = \"Species\",\n p2s = 0)\n imputed <- imputeLRT(isna.0, isna.1, ufc.imputes$imputations)\n return(list(naive.p = naive.p, imputed.p = imputed$Pval))\n}\n\nsimulate()\n\nframe <- expand.grid(ms = c(2, 5, 10, 20, 50, 100),\n ns = c(5, 10, 20, 30, 50, 100),\n reps = 1:reps)\n\nresults <- mclapply(1:nrow(frame),\n function(i) \n simulate(frame$ms[i], frame$ns[i]),\n mc.cores = cores)\n\nresults <- do.call(rbind, results)\n\nexperiment <- cbind(frame, results)\n\nsave(experiment, file = \"mi.RData\")\n\nmail(address = \"andrewpr\",\n subject = \"MI simulations\",\n message = \"All done.\",\n attach = \"mi.RData\")\n\n\n", "meta": {"hexsha": "423c949e9ff7d0f1b0c5971305c05154f3abae28", "size": 5936, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/experiment-sims.r", "max_stars_repo_name": "SteveLane/blistering-barnacles", "max_stars_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/experiment-sims.r", "max_issues_repo_name": "SteveLane/blistering-barnacles", "max_issues_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-09-12T05:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T22:37:45.000Z", "max_forks_repo_path": "scripts/experiment-sims.r", "max_forks_repo_name": "SteveLane/blistering-barnacles", "max_forks_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-08-28T04:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-28T04:09:34.000Z", "avg_line_length": 29.9797979798, "max_line_length": 80, "alphanum_fraction": 0.4290768194, "num_tokens": 1661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722127, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.36311054136073484}}
{"text": "subroutine locn(i,j,kj,nadj,madj,x,y,ntot,eps)\n\n# Find the appropriate location for j in the adjacency list\n# of i. This is the index which j ***will*** have when\n# it is inserted into the adjacency list of i in the\n# appropriate place. Called by insrt.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\nlogical before\n\nn = nadj(i,0)\n\n# If there is nothing already adjacent to i, then j will have place 1.\nif(n==0) {\n kj = 1\n return\n}\n\n# Run through i's list, checking if j should come before each element\n# of that list. (I.e. if i, j, and k are in anti-clockwise order.)\n# If j comes before the kj-th item, but not before the (kj-1)-st, then\n# j should have place kj.\ndo ks = 1,n {\n\tkj = ks\n k = nadj(i,kj)\n call acchk(i,j,k,before,x,y,ntot,eps)\n if(before) {\n km = kj-1\n if(km==0) km = n\n k = nadj(i,km)\n call acchk(i,j,k,before,x,y,ntot,eps)\n if(before) next\n # If j is before 1 and after n, then it should\n # have place n+1.\n if(kj==1) kj = n+1\n return\n }\n}\n\n# We've gone right through the list and haven't been before\n# the kj-th item ***and*** after the (kj-1)-st on any occasion.\n# Therefore j is before everything (==> place 1) or after\n# everything (==> place n+1).\nif(before) kj = 1\nelse kj = n+1\n\nreturn\nend\n", "meta": {"hexsha": "e2b581d8a5d3b5975a530b95a3784ac007c30851", "size": 1441, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/locn.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/locn.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/locn.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 28.82, "max_line_length": 70, "alphanum_fraction": 0.5850104094, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3618984898985668}}
{"text": "subroutine swap(j,k1,k2,shdswp,nadj,madj,x,y,ntot,eps,nerror)\n\n# The segment k1->k2 is a diagonal of a quadrilateral\n# with a vertex at j (the point being added to the\n# triangulation). If the LOP is not satisfied, swap\n# it for the other diagonal.\n# Called by addpt.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\ndimension ntadj(1000)\nlogical shdswp, anticl\n\n\n# If vertices k1 and k2 are not connected there is no diagonal to swap.\n# This could happen if vertices j, k1, and k2 were colinear, but shouldn't.\ncall adjchk(k1,k2,shdswp,nadj,madj,ntot,nerror)\nif(nerror > 0) {\n return\n}\nif(!shdswp) return\n\n# Get the other vertex of the quadrilateral.\ncall pred(k,k1,k2,nadj,madj,ntot,nerror) # If these aren't the same, then\nif(nerror > 0) return\ncall succ(kk,k2,k1,nadj,madj,ntot,nerror) # there is no other vertex.\nif(nerror > 0) return\nif(kk!=k) {\n# if(j==580) call intpr(\"no other vertex\",-1,1,0)\n shdswp = .false.\n return\n}\n\n# Check whether the LOP is satisified; i.e. whether\n# vertex k is outside the circumcircle of vertices j, k1, and k2\nif(k==580) {\n call intpr(\"From swap; point being added =\",-1,j,1)\n# Adj. list of k1 (\"now\").\n nk1 = nadj(k1,0)\n do jc = 1,nk1 {\n ntadj(jc) = nadj(k1,jc)\n }\n call intpr(\"now =\",-1,k1,1)\n call intpr(\"adjacency list of now:\",-1,ntadj,nk1)\n# Adj. list of k1 (\"now\").\n nk2 = nadj(k2,0)\n do jc = 1,nk2 {\n ntadj(jc) = nadj(k2,jc)\n }\n call intpr(\"nxt =\",-1,k2,1)\n call intpr(\"adjacency list of nxt:\",-1,ntadj,nk2)\n# Adj. list of j (\"point being added\").\n nj = nadj(j,0)\n do jc = 1,nj {\n ntadj(jc) = nadj(j,jc)\n }\n call intpr(\"point being added =\",-1,j,1)\n call intpr(\"adjacency list of point being added:\",-1,ntadj,nj)\n# j, now, nxt should be in anticlockwise order.\n call acchk(j,k1,k2,anticl,x,y,ntot,eps)\n if(anticl) {\n call intpr(\"anticlockwise\",-1,1,0)\n } else {\n call intpr(\"clockwise\",-1,1,0)\n }\n#\n# i = now = k1, k = nxt = k2, and j = other vertex = k:\n}\ncall qtest(j,k1,k,k2,shdswp,x,y,ntot,eps,nerror)\nif(nerror > 0) return\n\n# Do the actual swapping.\nif(shdswp) {\n call delet(k1,k2,nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n\tcall insrt(j,k,nadj,madj,x,y,ntot,nerror,eps)\n\tif(nerror > 0) return\n}\nreturn\nend\n", "meta": {"hexsha": "66489c9528f77b286abe93a169738f496e6891a0", "size": 2338, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/SavedRatfor/swap.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/SavedRatfor/swap.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/SavedRatfor/swap.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 28.8641975309, "max_line_length": 75, "alphanum_fraction": 0.6360136869, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.36079658646160623}}
{"text": "\\docType{data}\n\\name{paises}\n\\alias{paises}\n\\title{Datos de Gapminder}\n\\format{El cuadro de datos principal tiene 1704 filas y 6 columnas\n\\describe{\n\\item{pais}{países incluídos (factor con 142 niveles)}\n\\item{continente}{continentes (factor con 5 niveles)}\n\\item{anio}{desde 1952 a 2007, datos cada 5 años}\n\\item{esperanza_de_vida}{esperanza de vida al nacer, en años}\n\\item{poblacion}{población}\n\\item{pib_per_capita}{PIB per cápita (en dólares americanos, ajustados según inflación)}\n}}\n\\usage{paises}\n\\description{Extracto de datos de Gapminder sobre expectativa de vida, PIB per cápita y población, según país}\n\\source{http://www.gapminder.org/data/}\n\\keyword{datasets}\n", "meta": {"hexsha": "f69b237c771b9d09e6376fb42c87a3a7564d6b13", "size": 675, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/paises.rd", "max_stars_repo_name": "RubenMaier/datos", "max_stars_repo_head_hexsha": "c0606f7df0701d944cf0fe762cd29e821e53e75c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-15T08:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-15T08:12:23.000Z", "max_issues_repo_path": "man/paises.rd", "max_issues_repo_name": "RubenMaier/datos", "max_issues_repo_head_hexsha": "c0606f7df0701d944cf0fe762cd29e821e53e75c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "man/paises.rd", "max_forks_repo_name": "RubenMaier/datos", "max_forks_repo_head_hexsha": "c0606f7df0701d944cf0fe762cd29e821e53e75c", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 110, "alphanum_fraction": 0.7748148148, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.3602260580070423}}
{"text": "# 3. faza: Vizualizacija podatkov\n\n# Uvozimo zemljevid.\nzemljevid <- uvozi.zemljevid(\"http://baza.fmf.uni-lj.si/OB.zip\", \"OB\",\n pot.zemljevida=\"OB\", encoding=\"Windows-1250\")\nlevels(zemljevid$OB_UIME) <- levels(zemljevid$OB_UIME) %>%\n { gsub(\"Slovenskih\", \"Slov.\", .) } %>% { gsub(\"-\", \" - \", .) }\nzemljevid$OB_UIME <- factor(zemljevid$OB_UIME, levels=levels(obcine$obcina))\nzemljevid <- fortify(zemljevid)\n\n# Izračunamo povprečno velikost družine\npovprecja <- druzine %>% group_by(obcina) %>%\n summarise(povprecje=sum(velikost.druzine * stevilo.druzin) / sum(stevilo.druzin))\n\nstevilo.po.letih <- data %>% group_by(leto) %>% summarise(Stevilo=sum(stevilo, na.rm = TRUE))\n \n#Graf po stevilu priseljenih po letih \ngraf1 <- ggplot(stevilo.po.letih) + aes(x = leto, y = Stevilo) + \n geom_bar(stat = 'identity',position = 'dodge', fill = \"darkcyan\") + \n xlab(\"Leto\") + ylab(\"Število\") + ggtitle(\"Število priseljenih glede na leto\") \ngraf1\n\n#Graf po stevilu priseljenih po namenu\nstevilo.po.namenu <- data %>% group_by(namen) %>% summarise(Stevilo=sum(stevilo, na.rm = TRUE))\ngraf2 <- ggplot(stevilo.po.namenu) + aes(x = namen, y = Stevilo) + \n geom_bar(stat = 'identity',position = 'dodge', fill = \"darksalmon\") + \n xlab(\"Leto\") + ylab(\"Namen\") + ggtitle(\"Število priseljenih glede na namen\") \n#2021/22\n###################################################################################\n\n#mojzemljevid\n\n\nlibrary(tmap)\n\nzemljevid <- uvozi.zemljevid(\"http://biogeo.ucdavis.edu/data/gadm2.8/shp/SVN_adm_shp.zip\",\"SVN_adm1\", encoding = \"UTF-8\")\nzemljevid$NAME_1 <- c(\"Gorenjska\", \"Goriška\",\"Jugovzhodna Slovenija\", \"Koroška\", \"Primorsko-notranjska\", \"Obalno-kraška\", \n \"Osrednjeslovenska\", \"Podravska\", \"Pomurska\", \"Savinjska\", \"Posavska\", \"Zasavska\")\n\n\n# 1.zemljevid: priseljevanje prebivalstva po regijah\nregije_pri <- medregijske %>% group_by(regijapri) %>% summarise(skupaj = sum(stevilo, na.rm = TRUE ))\nregije_pri$regijapri = regije_pri$regijapri %>% trimws()\n\npodatki_pri = merge(zemljevid, regije_pri, by.x = \"NAME_1\", by.y = \"regijapri\" )\ntm_shape(podatki_pri) +\n tm_polygons(\"skupaj\") + \n tm_format(\"NLD\", title=\"Število prebivalstva, ki se je priselilo iz določene regije\", bg.color=\"white\")\n\n\n#2. zemljevid: izseljevanje prebivalstva po regijah\nregije_izs <- medregijske %>% group_by(regijaiz) %>% summarise(skupaj = sum(stevilo, na.rm = TRUE ))\nregije_izs$regijaiz = regije_izs$regijaiz %>% trimws()\n\npodatki_izs = merge(zemljevid, regije_izs, by.x = \"NAME_1\", by.y = \"regijaiz\" )\ntm_shape(podatki_izs) +\n tm_polygons(\"skupaj\") +\n tm_format(\"NLD\", title=\"Število prebivalstva, ki se je izselilo iz določene regije\", bg.color=\"white\")\n\n\n#ŠE LEGENDO UREDIT!\n\n#Graf 1: Povprečno število prebivalstva, ki se je selilo glede na statistične regije Slovenije\n\ngraf1 <- ggplot(data = povprecje_regije, aes(x=\" \" ,y=povprecje, fill = regijaiz)) +\n geom_bar(stat=\"identity\", position = 'dodge') +\n facet_wrap(~regijapri, ncol= 6) +\n xlab(\" \") + ylab(\"Povprečno število\") +\n ggtitle(\"Priseljevanje in odseljevanje po statističnih regijah Slovenije\") +\n theme(plot.title = element_text(family=\"Trebuchet MS\", face=\"bold\", size=20, hjust=0, color=\"black\")) +\n theme(axis.text.x = element_text(angle=90)) \n+ coord_flip() + theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n\n\n\n#Graf 2: Število priseljenih in izseljenih ljudi glede na drzavo selitve\n \ngraf2 <- ggplot(data=povprecje2, aes(x=drzava, y=povprecje, fill=`vrsta`)) +\n geom_col(position = 'dodge') +\n coord_flip() +\n labs(x = \"Država\", y = \"Povprečno število\", title = \"Povprečno število v priseljenega ali odseljenega prebivalstva glede na države\") +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\")\n\nodseljeni<- meddrzavne %>% filter( vrsta != \"Priseljeni iz tujine\") %>% select(- 'vrsta') %>% \n group_by (drzava, spol) %>% summarise(Stevio=sum(stevilo))\n\npriseljeni <- meddrzavne %>% filter( vrsta != \"Odseljeni iz tujino\") %>% select(- 'vrsta') %>% \n group_by (drzava, spol) %>% summarise(Stevilo=sum(stevilo)) #to bos potrebovala za pielibr\n\n\n# Graf 3: Graf, ki prikazuje število priseljenega prebivalstva glede na namen selitve in državo predhodnega bivališča.\n\ngraf3b <- ggplot(namen_priseljevanja, aes(x=leto,y=stevilo, group=1)) +\n geom_point(aes(col=drzava, size=stevilo)) +\n facet_grid(namen ~ .) + xlab(\"Leto\") + ylab(\"Število\") +\n ggtitle(\"Priseljeni prebivalci glede na namen selitve po letih\") +\n coord_flip() + theme_dark() +\n scale_fill_brewer(palette = \"BrBG\")\n\n\n#Graf 4: Graf, ki prikazuje število priseljenega prebivalstva glede na njihovo izobrazvo in državo predhodnega bivališča\n\npovprecje4 <- izobrazba_priseljeni %>% group_by(drzava, izobrazba) %>%\n summarise(povprecje=(sum(stevilo)/9))\n\ngraf4 <- ggplot(izobrazba_priseljeni, aes(x=leto,y=stevilo, group=1)) +\n geom_point(aes(col=drzava, size=stevilo)) +\n facet_grid(izobrazba ~ .) + \n labs(y=\"Število ljudi\", \n x=\"Vrsta izobrazbe\", \n title=\"Število priseljenega prebivalstva glede na stopnjo izobrazbe\") +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n\n#Graf 5: Graf, ki prikazuje število izseljenega prebivalstva glede na njihovo izobrazbo in starostno skupino\n\n#starost <- c(\"15-24\", \"25-54\", \"55-64\") zdruziii\n\npovprecje5 <- izobrazba_izseljeni %>% group_by(starost, izobrazba) %>%\n summarise(povprecje=(sum(stevilo)/9))\n\ngraf5 <- ggplot(povprecje5, aes(x=izobrazba, y=povprecje)) + \n geom_point(aes(col=starost, size=povprecje)) + \n geom_smooth(method=\"loess\", se=F) + \n labs(y=\"Število ljudi\", \n x=\"Vrsta izobrazbe\", \n title=\"Povprečno število izseljenega prebivalstva glede na starostno skupino in vrsto izobrazbe\") +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n\ngraf5a <- ggplot(data=izobrazba_izseljeni, aes(x=leto, y=stevilo, col=spol)) +\n geom_line(size=1) + facet_grid(~starost) +\n theme_bw() +\n scale_color_manual(values=c(\"darkgoldenrod3\", \"cadetblue\")) +\n xlab(\"Država\") + ylab(\"Povprečno število(/100)\") +\n ggtitle(\"Odseljeni prebivalci glede na status aktivnosti\") +\n coord_flip() +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") + \n scale_x_continuous(breaks=seq(2010, 2020, 4))\n \n\n\n \n\n#Graf 6: Graf, ki prikazuje število izeljenega prebivalstva glede na status aktivosti in državo pihodnjega bivališča\npovprecje6 <- izseljeni_status_akt %>% group_by(drzava, status) %>%\n summarise(povprecje=(sum(stevilo)/9)/100)\n\ngraf6 <- ggplot(data=povprecje6, aes(x = drzava, y = povprecje, fill = status)) +\n geom_bar(stat = 'identity', position = 'dodge') +\n xlab(\"Država\") + ylab(\"Povprečno število(/100)\") +\n ggtitle(\"Odseljeni prebivalci glede na status aktivnosti\") +\n coord_flip() +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n #dva grafa: celine pa evropa po drzavah\n\n#####################################################################\n\n\n\n\n", "meta": {"hexsha": "e88d7ae9facf0d017b3ad75dee4241d83af64dd0", "size": 6939, "ext": "r", "lang": "R", "max_stars_repo_path": "vizualizacija/vizualizacija.r", "max_stars_repo_name": "admira05/APPR-2019-20", "max_stars_repo_head_hexsha": "ecbcd44f0579229a5ff8906e3c8fdf44bcb8f81f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vizualizacija/vizualizacija.r", "max_issues_repo_name": "admira05/APPR-2019-20", "max_issues_repo_head_hexsha": "ecbcd44f0579229a5ff8906e3c8fdf44bcb8f81f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-19T12:45:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-17T18:36:40.000Z", "max_forks_repo_path": "vizualizacija/vizualizacija.r", "max_forks_repo_name": "admira05/APPR-2019-20", "max_forks_repo_head_hexsha": "ecbcd44f0579229a5ff8906e3c8fdf44bcb8f81f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8012048193, "max_line_length": 136, "alphanum_fraction": 0.6787721574, "num_tokens": 2608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3601504215316171}}
{"text": "#!/usr/bin/env Rscript\n#\n# Randomly draw distributions of fitness effects for variants and use those\n# to simulate S&R evolution.\n#\n# Can either specify \"all\" to draw fitness effects from an exponential\n# distribution, or a number to specify the number of SNPs that will have\n# an effect (all others set to zero).\n#\n\nlibrary(boot)\nlibrary(data.table)\nlibrary(dplyr)\nlibrary(dtplyr)\n\n## Program options:\ncargs = commandArgs(trailingOnly=TRUE)\ngenotype_file = cargs[1]\nn_snps = cargs[2]\nn_generations = as.numeric(cargs[3])\nmin_maf = as.numeric(cargs[4])\nmax_miss = as.numeric(cargs[5])\noutput_prefix = cargs[6]\n\n## Probability that the reference allele is more fit than the alternate\nref_allele_more_fit = 0.8\nif(length(cargs) > 6) {\n ref_allele_more_fit = as.numeric(cargs[7])\n}\n\n\n## Read in data\ngenotypes = fread(genotype_file, header=TRUE) %>%\n select(-pos, -contig, -rs) %>%\n as.matrix()\n\ngenotype_names = fread(genotype_file, header=TRUE) %>%\n select(pos, contig, rs)\n\ninitial_allele_freqs = apply(genotypes, 1, function(x) {\n ref = sum(!(is.na(x)) & x == 1)\n alt = sum(!(is.na(x)) & x == 0)\n ref / (ref + alt)\n})\n\n\n## Filter data\nmaf = ifelse(initial_allele_freqs < 0.5, initial_allele_freqs,\n 1 - initial_allele_freqs)\nmissingness = apply(genotypes, 1, function(x) sum(is.na(x)) / length(x))\n\nkeep = maf > min_maf & missingness < max_miss\ngenotypes = genotypes[keep, ]\ngenotype_names = genotype_names[keep, ]\ninitial_allele_freqs = initial_allele_freqs[keep]\nmaf = maf[keep]\nmissingness = missingness[keep]\n\n\n## Draw fitness effects\nif(!is.na(as.numeric(n_snps))) {\n ## Set a few SNPs to fitness effect of 1, all others = 0\n ns = as.numeric(n_snps)\n x = rep(0, nrow(genotypes))\n x[sample(1:nrow(genotypes), ns, FALSE)] = sample(c(1, -1), ns, TRUE,\n prob=c(1-ref_allele_more_fit, ref_allele_more_fit))\n snp_fitness_effects = x\n} else {\n ## Draw from exponential distribution for all SNPs\n snp_fitness_effects = rexp(nrow(genotypes)) * ifelse(sample(c(TRUE, FALSE), nrow(genotypes), TRUE,\n prob=c(1-ref_allele_more_fit, ref_allele_more_fit)),\n -1, 1)\n}\n\n\n## Simulate fitness of strains and calculate allele frequency and\n## allele frequency change. Takes fitness effects as Wrightian (average\n## number of offspring).\n\n## 1) Column-by-column, multiply the fitness_effect of the alternate\n## allele by whether the alternate allele is present. Do this in\n## a way that doesn't give any negative numbers (if alternate allele\n## effect is negative, make it a positive effect of the ref. allele).\n## 2) Row-by-row, set missing genotypes to have the average effect\n## 3) Add up all the fitness effects in a strain and divide by the\n## mean across strains.\n## Note that in the genotype input file 1 = reference, 0 = alternate\nsnp_effects =\n apply(genotypes, 2, function(x) {\n snp_fitness_effects * ifelse(snp_fitness_effects < 0, -x, 1-x)\n }) %>%\n apply(., 1, function(x) {\n mw = mean(x, na.rm=TRUE)\n ifelse(is.na(x), mw, x)\n }) %>%\n t()\nfitnesses = colSums(snp_effects) / mean(colSums(snp_effects))\n\n## Calculate final strain frequencies assuming equal starting frequencies.\n## Uses Wrightian fitness (fitness = average number of offspring).\ninitial_strain_freqs = rep(1/length(fitnesses), length(fitnesses))\nn_inds = (fitnesses^n_generations)\nstrain_freqs = n_inds / sum(n_inds)\nstopifnot(all(strain_freqs >= 0))\nrelative_fitnesses = log2(strain_freqs / initial_strain_freqs)\n## If fitness = 0, need to do a rough correction:\nrelative_fitnesses[is.na(relative_fitnesses) | is.infinite(relative_fitnesses)] =\n min(relative_fitnesses[!is.na(relative_fitnesses) & !(is.infinite(relative_fitnesses))]) - 2\n\n\n## Calculate final allele frequencies\nstopifnot(all(names(strain_freqs) == colnames(genotypes)))\nallele_freqs = apply(genotypes, 1, function(x) {\n ref = sum(strain_freqs[!(is.na(x)) & x == 1])\n alt = sum(strain_freqs[!(is.na(x)) & x == 0])\n ref / (ref + alt)\n })\nstopifnot(all(allele_freqs >= 0 & allele_freqs <= 1))\n\n\n## Calculate LD groups from final strain frequencies for the top 2000\n## snps (by allele frequency change); note groups with ties may not\n## be completely included in the top 5000. Order of ties is arbitrary.\nn_ld = 5000\naf_change = abs(allele_freqs - initial_allele_freqs)\naf_order = order(order(af_change, decreasing=TRUE))\nld_groups_95 = numeric(length(af_change)) * NaN\ngrp = -1\nfor(i in 1:(n_ld-1)) {\n ii = which(af_order == i)\n if(!is.na(ld_groups_95[ii])) next\n grp = grp + 1\n ld_groups_95[ii] = grp\n for(j in (i+1):n_ld) {\n jj = which(af_order == j)\n if(!is.na(ld_groups_95[jj])) next\n g = cbind(genotypes[ii, ], genotypes[jj, ])\n r2 = (corr(g[!(is.na(g[, 1])) & !(is.na(g[, 2])), ],\n w=strain_freqs[!(is.na(g[, 1])) & !(is.na(g[, 2]))]))^2\n if(is.na(r2)) {\n warning(paste('R^2 is NA at', genotype_names[['rs']][i],\n genotype_names[['rs']][j]))\n next\n }\n if(r2 >= 0.95) {\n ld_groups_95[jj] = grp\n }\n }\n}\ni = n_ld\nii = which(af_order == i)\nif(is.na(ld_groups_95[ii])) {\n grp = grp + 1\n ld_groups_95[ii] = grp\n}\n\nld_groups_80 = numeric(length(af_change)) * NaN\ngrp = -1\nfor(i in 1:(n_ld-1)) {\n ii = which(af_order == i)\n if(!is.na(ld_groups_80[ii])) next\n grp = grp + 1\n ld_groups_80[ii] = grp\n for(j in (i+1):n_ld) {\n jj = which(af_order == j)\n if(!is.na(ld_groups_80[jj])) next\n g = cbind(genotypes[ii, ], genotypes[jj, ])\n r2 = (corr(g[!(is.na(g[, 1])) & !(is.na(g[, 2])), ],\n w=strain_freqs[!(is.na(g[, 1])) & !(is.na(g[, 2]))]))^2\n if(is.na(r2)) {\n warning(paste('R^2 is NA at', genotype_names[['rs']][i],\n genotype_names[['rs']][j]))\n next\n }\n if(r2 >= 0.80) {\n ld_groups_80[jj] = grp\n }\n }\n}\ni = n_ld\nii = which(af_order == i)\nif(is.na(ld_groups_80[ii])) {\n grp = grp + 1\n ld_groups_80[ii] = grp\n}\n\n\n## Write output:\n\n## 1. Phenotype file for Plink with fitness of strains\n## (for external association testing)\nwrite.table(cbind(names(fitnesses), names(fitnesses), fitnesses),\n file=paste0(output_prefix, '.fitness.txt'),\n sep='\\t', col.names=FALSE, row.names=FALSE, quote=FALSE)\n\n## 2. Phenotype file with relative fitness\nwrite.table(cbind(names(relative_fitnesses), names(relative_fitnesses), relative_fitnesses),\n file=paste0(output_prefix, '.relative_fitness.txt'),\n sep='\\t', col.names=FALSE, row.names=FALSE, quote=FALSE)\n\n## 3. Table of fitness effects and allele frequency start and end for\n## each SNP\nwrite.table(data.frame(genotype_names, 'effect'=snp_fitness_effects,\n 'initial'=initial_allele_freqs,\n 'final'=allele_freqs,\n 'ld_95'=ld_groups_95,\n 'ld_80'=ld_groups_80),\n file=paste0(output_prefix, '.snp_effects.txt'),\n sep='\\t', col.names=TRUE, row.names=FALSE, quote=FALSE)\n\n## 4. Table of strain frequencies and fitnesses\nwrite.table(data.frame(strain=names(fitnesses), 'fitness'=fitnesses,\n 'relative_fitness'=relative_fitnesses,\n 'initial'=initial_strain_freqs,\n 'final'=strain_freqs),\n file=paste0(output_prefix, '.strain_frequencies.txt'),\n sep='\\t', col.names=TRUE, row.names=FALSE, quote=FALSE)\n\n## 5. Phenotype file with change in strain frequency\nwrite.table(cbind(names(strain_freqs), names(strain_freqs),\n strain_freqs - initial_strain_freqs),\n file=paste0(output_prefix, '.strain_freqs.txt'),\n sep='\\t', col.names=FALSE, row.names=FALSE, quote=FALSE)\n", "meta": {"hexsha": "4667898816e9da437aa86f098a7a817b048c0608", "size": 8151, "ext": "r", "lang": "R", "max_stars_repo_path": "simulate_strain_s_and_r_fitness.r", "max_stars_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_stars_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulate_strain_s_and_r_fitness.r", "max_issues_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_issues_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-17T11:14:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T11:14:13.000Z", "max_forks_repo_path": "simulate_strain_s_and_r_fitness.r", "max_forks_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_forks_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3883928571, "max_line_length": 116, "alphanum_fraction": 0.6162434057, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3599204338999551}}
{"text": "#' Markov Chain Monte Carlo\n#' \n#' A flexible implementation of the Metropolis-Hastings MCMC algorithm.\n#' \n#' @param fun A function. Returns the log-likelihood.\n#' @param initial Either a numeric matrix or vector, or an object of class [coda::mcmc]\n#' or [coda::mcmc.list] (see details).\n#' initial values of the parameters for each chain (See details).\n#' @param nsteps Integer scalar. Length of each chain.\n#' @param nchains Integer scalar. Number of chains to run (in parallel).\n#' @param cl A `cluster` object passed to [parallel::clusterApply].\n#' @param thin Integer scalar. Passed to [coda::mcmc].\n#' @param kernel An object of class [fmcmc_kernel].\n#' @param burnin Integer scalar. Length of burn-in. Passed to \n#' [coda::mcmc] as \\code{start}.\n#' @param multicore Logical. If `FALSE` then chains will be executed in serial.\n#' @param ... Further arguments passed to \\code{fun}.\n#' @param conv_checker A function that receives an object of class [coda::mcmc.list],\n#' and returns a logical value with `TRUE` indicating convergence.\n#' \n#' @details This function implements MCMC using the Metropolis-Hastings ratio with\n#' flexible transition kernels. Users can specify either one of the available\n#' transition kernels or define one of their own (see [kernels]). Furthermore,\n#' it allows easy parallel implementation running multiple chains in parallel. In\n#' addition, we incorporate a variety of convergence diagnostics, alternatively\n#' the user can specify their own (see [convergence-checker]).\n#' \n#' We now give details of the various options included in the function.\n#' \n#' @section Starting point:\n#' \n#' By default, if `initial` is of class `mcmc`, `MCMC` will take the last `nchains`\n#' points from the chain as starting point for the new sequence. If `initial` is\n#' of class `mcmc.list`, the number of chains in `initial` must match the `nchains`\n#' parameter. \n#' \n#' If `initial` is a vector, then it must be of length equal to the number of\n#' parameters used in the model. When using multiple chains, if `initial` is not\n#' an object of class `mcmc` or `mcmc.list`, then it must be a numeric matrix\n#' with as many rows as chains, and as many columns as parameters in the model.\n#' \n#' @section Multiple chains:\n#' \n#' When \\code{nchains > 1}, the function will run multiple chains. Furthermore,\n#' if \\code{cl} is not passed, \\code{MCMC} will create a \\code{PSOCK} cluster\n#' using [parallel::makePSOCKcluster] with\n#' [parallel::detectCores]\n#' clusters and attempt to execute using multiple cores. Internally, the function does\n#' the following:\n#' \n#' \\preformatted{\n#' # Creating the cluster\n#' ncores <- parallel::detectCores()\n#' ncores <- ifelse(nchains < ncores, nchains, ncores)\n#' cl <- parallel::makePSOCKcluster(ncores)\n#' \n#' # Loading the package and setting the seed using clusterRNGStream\n#' invisible(parallel::clusterEvalQ(cl, library(fmcmc)))\n#' parallel::clusterSetRNGStream(cl, .Random.seed)\n#' }\n#' \n#' When running in parallel, objects that are\n#' used within \\code{fun} must be passed through \\code{...}, otherwise the cluster\n#' will return with an error.\n#' \n#' The user controls the initial value of the parameters of the MCMC algorithm\n#' using the argument `initial`. When using multiple chains, i.e., `nchains > 1`,\n#' the user can specify multiple starting points, which is recommended. In such a\n#' case, each row of `initial` is use as a starting point for each of the\n#' chains. If `initial` is a vector and `nchains > 1`, the value is recycled, so\n#' all chains start from the same point (not recommended, the function throws a\n#' warning message).\n#' \n#' @section Automatic stop:\n#' \n#' By default, no automatic stop is implemented. If one of the functions in \n#' [convergence-checker] is used, then the MCMC is done by bulks as specified\n#' by the convergence checker function, and thus the algorithm will stop if,\n#' the `conv_checker` returns `TRUE`. For more information see [convergence-checker].\n#' \n#' @return An object of class [coda::mcmc] from the \\CRANpkg{coda}\n#' package. The \\code{mcmc} object is a matrix with one column per parameter,\n#' and \\code{nsteps} rows. If \\code{nchains > 1}, then it returns a [coda::mcmc.list].\n#' \n#' @export\n#' @examples \n#' # Univariate distributed data with multiple parameters ----------------------\n#' # Parameters\n#' set.seed(1231)\n#' n <- 1e3\n#' pars <- c(mean = 2.6, sd = 3)\n#' \n#' # Generating data and writing the log likelihood function\n#' D <- rnorm(n, pars[1], pars[2])\n#' fun <- function(x) {\n#' x <- log(dnorm(D, x[1], x[2]))\n#' sum(x)\n#' }\n#' \n#' # Calling MCMC, but first, loading the coda R package for\n#' # diagnostics\n#' library(coda)\n#' ans <- MCMC(\n#' fun, initial = c(mu=1, sigma=1), nsteps = 2e3,\n#' kernel = kernel_reflective(scale = .1, ub = 10, lb = 0)\n#' )\n#' \n#' # Ploting the output\n#' oldpar <- par(no.readonly = TRUE)\n#' par(mfrow = c(1,2))\n#' boxplot(as.matrix(ans), \n#' main = expression(\"Posterior distribution of\"~mu~and~sigma),\n#' names = expression(mu, sigma), horizontal = TRUE,\n#' col = blues9[c(4,9)],\n#' sub = bquote(mu == .(pars[1])~\", and\"~sigma == .(pars[2]))\n#' )\n#' abline(v = pars, col = blues9[c(4,9)], lwd = 2, lty = 2)\n#' \n#' plot(apply(as.matrix(ans), 1, fun), type = \"l\",\n#' main = \"LogLikelihood\",\n#' ylab = expression(L(\"{\"~mu,sigma~\"}\"~\"|\"~D)) \n#' )\n#' par(oldpar)\n#' \n#' \\dontrun{\n#' # In this example we estimate the parameter for a dataset with ----------------\n#' # With 5,000 draws from a MVN() with parameters M and S.\n#' \n#' # Loading the required packages\n#' library(mvtnorm)\n#' library(coda)\n#' \n#' # Parameters and data simulation\n#' S <- cbind(c(.8, .2), c(.2, 1))\n#' M <- c(0, 1)\n#' \n#' set.seed(123)\n#' D <- rmvnorm(5e3, mean = M, sigma = S)\n#' \n#' # Function to pass to MCMC\n#' fun <- function(pars) {\n#' # Putting the parameters in a sensible way\n#' m <- pars[1:2]\n#' s <- cbind( c(pars[3], pars[4]), c(pars[4], pars[5]) )\n#' \n#' # Computing the unnormalized log likelihood\n#' sum(log(dmvnorm(D, m, s)))\n#' }\n#' \n#' # Calling MCMC\n#' ans <- MCMC(\n#' initial = c(mu0=5, mu1=5, s0=5, s01=0, s2=5), \n#' fun,\n#' kernel = kernel_reflective(\n#' lb = c(-10, -10, .01, -5, .01),\n#' ub = 5\n#' scale = 0.01\n#' ),\n#' nsteps = 1e5,\n#' thin = 20,\n#' burnin = 5e3\n#' )\n#' \n#' # Checking out the outcomes\n#' plot(ans)\n#' summary(ans)\n#' \n#' # Multiple chains -----------------------------------------------------------\n#' \n#' # As we want to run -fun- in multiple cores, we have to\n#' # pass -D- explicitly (unless using Fork Clusters)\n#' # just like specifying that we are calling a function from the\n#' # -mvtnorm- package.\n#' \n#' fun <- function(pars, D) {\n#' # Putting the parameters in a sensible way\n#' m <- pars[1:2]\n#' s <- cbind( c(pars[3], pars[4]), c(pars[4], pars[5]) )\n#' \n#' # Computing the unnormalized log likelihood\n#' sum(log(mvtnorm::dmvnorm(D, m, s)))\n#' }\n#' \n#' # Two chains\n#' ans <- MCMC(\n#' initial = c(mu0=5, mu1=5, s0=5, s01=0, s2=5), \n#' fun,\n#' nchains = 2,\n#' kernel = kernel_reflective(\n#' lb = c(-10, -10, .01, -5, .01),\n#' ub = 5\n#' scale = 0.01\n#' ),\n#' nsteps = 1e5,\n#' thin = 20,\n#' burnin = 5e3,\n#' D = D\n#' )\n#' \n#' summary(ans)\n#' }\n#' \n#' @aliases Metropolis-Hastings\nMCMC <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n) UseMethod(\"MCMC\")\n\n#' @export\n#' @rdname MCMC\nMCMC.mcmc <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n) {\n \n MCMC.default(\n initial = utils::tail(initial, nchains - 1L),\n fun = fun,\n nsteps = nsteps,\n ..., \n nchains = nchains,\n burnin = burnin,\n thin = thin,\n kernel = kernel,\n multicore = multicore,\n conv_checker = conv_checker,\n cl = cl\n )\n \n}\n\n#' @export\n#' @rdname MCMC\nMCMC.mcmc.list <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n) {\n \n if (nchains != length(initial))\n stop(\n \"The parameter `nchains` must equal the number of chains passed by \",\n \"`initial`.\", call. = FALSE\n )\n \n MCMC.default(\n initial = do.call(rbind, utils::tail(initial, 0)),\n fun = fun,\n nsteps = nsteps,\n ..., \n nchains = nchains,\n burnin = burnin,\n thin = thin,\n kernel = kernel,\n multicore = multicore,\n conv_checker = conv_checker,\n cl = cl\n )\n \n}\n\n\n\n#' @export\n#' @rdname MCMC\nMCMC.default <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n ) {\n \n # # if the coda package hasn't been loaded, then return a warning\n # if (!(\"package:coda\" %in% search()))\n # warning(\"The -coda- package has not been loaded.\", call. = FALSE, )\n\n # Checking initial argument\n initial <- check_initial(initial, nchains)\n \n if (multicore && nchains == 1L) \n stop(\"When `multicore = TRUE`, `nchains` should be greater than 1.\",\n call. = FALSE)\n \n if (nchains < 1L)\n stop(\"`nchains` must be an integer greater than 1.\", call. = FALSE)\n \n # Checkihg burnins\n if (burnin >= nsteps)\n stop(\"-burnin- (\",burnin,\") cannot be >= than -nsteps- (\",nsteps,\").\", call. = FALSE)\n \n # Checking thin\n if (thin >= nsteps)\n stop(\"-thin- (\",thin,\") cannot be > than -nsteps- (\",nsteps,\").\", call. = FALSE)\n \n if (thin < 1L)\n stop(\"-thin- should be >= 1.\", call. = FALSE)\n \n # Filling the gap on parallel\n if (multicore && !length(cl)) {\n \n # Creating the cluster\n ncores <- parallel::detectCores()\n ncores <- ifelse(nchains < ncores, nchains, ncores)\n cl <- parallel::makePSOCKcluster(ncores)\n \n # Loading the package and setting the seed using clusterRNGStream\n invisible(parallel::clusterEvalQ(cl, library(fmcmc)))\n parallel::clusterSetRNGStream(cl, .Random.seed)\n \n on.exit(parallel::stopCluster(cl))\n }\n \n if (nchains > 1L) {\n \n # Preparing the call for multicore\n fmcmc_call <- as.call(\n c(\n if (multicore) \n list(quote(parallel::clusterApply), cl=quote(cl), x = quote(1L:nchains)) \n else \n list(quote(lapply), X = quote(1L:nchains)),\n list(\n FUN = quote(function(\n i, fun., initial., nsteps., thin., kernel., burnin., ...) {\n \n MCMC(\n fun = fun.,\n ...,\n initial = initial.[i, , drop = FALSE],\n nsteps = nsteps.,\n burnin = burnin.,\n thin = thin.,\n kernel = kernel.,\n nchains = 1L,\n multicore = FALSE,\n cl = NULL,\n conv_checker = NULL\n )\n \n }),\n fun. = quote(fun),\n initial. = quote(initial),\n nsteps. = quote(nsteps),\n burnin. = quote(burnin),\n thin. = quote(thin),\n kernel. = quote(kernel),\n quote(...)\n )\n )\n )\n \n # updating names\n if (multicore)\n names(fmcmc_call)[names(fmcmc_call) == \"FUN\"] <- \"fun\"\n \n fmcmc_call <- as.call(list(quote(do.call),quote(coda::mcmc.list), fmcmc_call))\n \n } else if (!is.null(conv_checker)) {\n \n # If not multicore, still we need to make sure that we are passing some\n # variables as symbols and not as constants. As in the convergence checker\n # function we modify the current environment in order to adapt the algorithm.\n fmcmc_call <- match.call()\n fmcmc_call$fun <- quote(fun)\n fmcmc_call$nsteps <- quote(nsteps)\n fmcmc_call$thin <- quote(thin)\n fmcmc_call$burnin <- quote(burnin)\n fmcmc_call$conv_checker <- enquote(NULL)\n \n }\n \n # If conv_checker, we run it with the conv checker and return. Notice that\n # we already adapted the code for the case in which we are runing multiple\n # chains\n if (!is.null(conv_checker)) {\n \n fmcmc_call <- call(\n \"with_autostop\",\n fmcmc_call,\n conv_checker = quote(conv_checker)\n )\n \n ans <- eval(fmcmc_call)\n return(ans)\n \n # If we are not using conv_checker, but still have multiple chains, then\n # we still have to run this somewhat recursively.\n } else if (nchains > 1L) {\n ans <- eval(fmcmc_call)\n return(ans)\n }\n \n # Adding names\n initial <- initial[1,,drop=TRUE]\n cnames <- names(initial)\n \n # Wrapping function. If ellipsis is there, it will wrap it\n # so that the MCMC call only uses a single argument\n passedargs <- names(list(...))\n # print(match.call())\n funargs <- methods::formalArgs(eval(fun))\n \n # Compiling\n # cfun <- compiler::cmpfun(fun)\n \n # ... has extra args\n if (length(passedargs)) {\n # ... has stuff that fun doesnt\n if (any(!(passedargs %in% funargs))) {\n \n stop(\"The following arguments passed via -...- are not present in -fun-:\\n - \",\n paste(setdiff(passedargs, funargs), collapse=\",\\n - \"),\".\\nThe function\",\n \"was expecting:\\n - \", paste0(funargs, collapse=\",\\n - \"), \".\", call. = FALSE)\n \n # fun has stuff that ... doesnt\n } else if (length(funargs) > 1 && any(!(funargs[-1] %in% passedargs))) {\n \n stop(\"-fun- requires more arguments to be passed via -...-.\", call. = FALSE)\n \n # Everything OK\n } else {\n \n f <- function(z) {\n fun(z, ...)\n }\n \n }\n # ... doesnt have extra args, but funargs does!\n } else if (length(funargs) > 1) {\n \n stop(\"-fun- has extra arguments not passed by -...-.\", call. = FALSE)\n \n # Everything OK\n } else {\n \n f <- function(z) fun(z)\n \n }\n \n # MCMC algorithm -----------------------------------------------------------\n \n theta0 <- initial\n theta1 <- theta0\n f0 <- f(theta0)\n f1 <- f(theta1)\n \n # The updates can be done jointly or sequentially\n klogratio <- kernel$logratio(environment())\n if (length(klogratio) > 1L) {\n joint_rate <- FALSE\n R <- matrix(stats::runif(nsteps * length(initial)), nrow = nsteps)\n R[] <- log(R)\n } else {\n joint_rate <- TRUE\n R <- matrix(log(stats::runif(nsteps)), nrow = nsteps)\n }\n \n ans <- matrix(ncol = length(initial), nrow = nsteps,\n dimnames = list(1:nsteps, cnames))\n \n for (i in 1L:nsteps) {\n # Step 1. Propose\n theta1[] <- kernel$proposal(environment())\n f1 <- f(theta1)\n \n # Checking f(theta1) (it must be a number, can be Inf)\n if (is.nan(f1) | is.na(f1) | is.null(f1)) \n stop(\n \"fun(par) is undefined (\", f1, \")\",\n \"Check either -fun- or the -lb- and -ub- parameters.\",\n call. = FALSE\n )\n \n # Step 2. Hastings ratio\n klogratio <- kernel$logratio(environment())\n if (joint_rate) {\n \n if (R[i] < klogratio) {\n theta0 <- theta1\n f0 <- f1\n }\n \n } else {\n \n klogratio <- (R[i, ] < klogratio)\n theta0[klogratio] <- theta1[klogratio]\n \n }\n \n \n # Step 3. Saving the state\n ans[i,] <- theta0\n \n }\n \n # Thinning the data\n if (burnin) ans <- ans[-c(1:burnin), , drop = FALSE]\n if (thin) ans <- ans[(1:nrow(ans) %% thin) == 0, , drop = FALSE]\n \n # Returning an mcmc object from the coda package\n return(\n coda::mcmc(\n ans,\n start = as.integer(rownames(ans)[1]),\n end = as.integer(rownames(ans)[nrow(ans)]),\n thin = thin\n )\n )\n \n}\n", "meta": {"hexsha": "46404063c892a1f1aa47edf1c5a528e0ad70c402", "size": 16043, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mcmc.r", "max_stars_repo_name": "arokem/fmcmc", "max_stars_repo_head_hexsha": "2b897e6978d1b23107d3e88d39abb68f4ad3ab97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-20T17:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-20T17:37:05.000Z", "max_issues_repo_path": "R/mcmc.r", "max_issues_repo_name": "arokem/fmcmc", "max_issues_repo_head_hexsha": "2b897e6978d1b23107d3e88d39abb68f4ad3ab97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/mcmc.r", "max_forks_repo_name": "arokem/fmcmc", "max_forks_repo_head_hexsha": "2b897e6978d1b23107d3e88d39abb68f4ad3ab97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4908088235, "max_line_length": 89, "alphanum_fraction": 0.5796297451, "num_tokens": 4657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.35988861419884083}}
{"text": "\n# Function to fit continous heavy tail functions\n# Mostly using poweRlaw package\n#\nfit_con_heavy_tail <- function (data_set,xmins,options.output)\n{\n\tn <- length(unique(data_set))\n\tn_models <- 4\n\tn_sets <- 1 # delete set 3\n\t# List of models\n\tmodel_list = list(list(model=vector(\"list\", length=0), \n\t\t\t\t\t\t \t\t\t\t\t\tGOF=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t xmin_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t uncert_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t k=0,\n\t\t\t\t\t\t\t\t\t\t\t\t LL=0,\n\t\t\t\t\t\t\t\t\t\t\t\t n=n,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t delta_AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=0,\n\t\t\t\t\t\t model_name=character(0),\n\t\t\t\t\t\t model_set=character(0))) \n\tfit_ht <- rep(model_list,n_models*n_sets)\n\tdim(fit_ht) <- c(n_models,n_sets)\n\t# Two sets: power law with and without cut-off\n\t# Declare models\n\tfor (i_set in 1:(n_sets)){\n\t\t# Continuous power law\n\t\tfit_ht[[1,i_set]]$model <- conpl$new(data_set)\n\t\tfit_ht[[1,i_set]]$k <- 1\n\t\t# Continuous log-normal\n\t\tfit_ht[[2,i_set]]$model <- conlnorm$new(data_set)\n\t\tfit_ht[[2,i_set]]$k <- 2\n\t\t# Continuous exponential\n\t\tfit_ht[[3,i_set]]$model <- conexp$new(data_set)\n\t\tfit_ht[[3,i_set]]$k <- 1\n\t\t# power law with exponential cutoff\n\t\tfit_ht[[4,i_set]]$model <- \"\" \n\t\tfit_ht[[4,i_set]]$k <- 2\n\t}\n\t\n\t# Set xmin for set 1\n\t#fit_ht[[1,1]]$model$xmin <- 9\n\t\n\t# Estimate Xmin with complete data_set for power law model\n\tfit_ht[[1,1]]$xmin_estimation <- estimate_xmin(fit_ht[[1,1]]$model,\n\t\txmins = xmins, \n\t\tpars = NULL, \n\t\txmax = max(data_set))\n\n\tfit_ht[[1,1]]$model$setXmin(fit_ht[[1,1]]$xmin_estimation)\n\n\n\tmodel_names <- c(\"Power\", \"LogNorm\",\"Exp\",\"PowerExp\")\n\tlabels_set <- c(\"Estimated Xmin\")\n\n\tAICc_weight <- matrix( nrow = n_models, ncol = n_sets,\n\t\t\t\t\t\t\tdimnames = list(model_names,labels_set))\n\n\tdelta_AICc <- AICc_weight\n\tGOF <- delta_AICc\n\tif(n>8) {\n\t\tfor (i_set in 1:n_sets){\n\t\taic_min=Inf\n\t\tnorm_aic_weight=0\n\t\tfor (i in 1:(n_models)){\n\t\t\t# Set cut-off (x_min)\n\t\t\tfit_ht[[i,i_set]]$model$xmin <- fit_ht[[1,i_set]]$model$xmin\n\t\t\t\n\t\t\t# Correct n with xmin\n\t\t\tfit_ht[[i,i_set]]$n <-length(data_set[data_set>=fit_ht[[1,i_set]]$model$xmin])\n\n\t\t\t# Fit models\n\t\t\t#\n\t\t\tif(i!=n_models){\n\t\t\t\tfit_ht[[i,i_set]]$model$setPars(estimate_pars(fit_ht[[i,i_set]]$model))\n\t\t\t\t# \n\t\t\t\t# Get Loglikelihood\n\t\t\t\tfit_ht[[i,i_set]]$LL <- dist_ll(fit_ht[[i,i_set]]$model)\n\t\t\t} else {\n\t\t\t\t# Fit Power Exponential (not poweRlaw package)\n\t\t\t\t#\n\t\t\t\tfit_ht[[i,i_set]]$model<- powerexp.fit(data_set,fit_ht[[1,i_set]]$model$xmin)\n\t\t\t\t# \n\t\t\t\t# Get Loglikelihood\n\t\t\t\tfit_ht[[i,i_set]]$LL <- fit_ht[[i,i_set]]$model$loglike \t\t\t\n\t\t\t}\n\t\t\tLL <- fit_ht[[i,i_set]]$LL\n\t\t\tk <- fit_ht[[i,i_set]]$k\n\t\t\t# Compute AICc\n\t\t\t#\n\t\t\tfit_ht[[i,i_set]]$AICc <- (2*k-2*LL)+2*k*(k+1)/(n-k-1)\n\t\t\taic_min <- min(aic_min,fit_ht[[i,i_set]]$AICc)\n\t\t\tif (i==1 & options.output$GOF){\n\t\t\t\t#\n\t\t\t\t# Goodness of fit via boostrap\n\t\t\t\t#\n\t\t\t\t# xmins is fixed at estimated value\n\t\t\t\tfit_ht[[i,i_set]]$GOF <- bootstrap_p(fit_ht[[i,i_set]]$model,\n\t\t\t\t\t\t\t\t\t\t\t xmins=fit_ht[[i,i_set]]$model$xmin,\n\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n\t\t\t\t\t\t\t\t\t\t\t no_of_sims = 1000,\n\t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores())\n\t\t\t\t#\n\t\t\t\t# Uncertainty in parms estimation via bootstrap\n\t\t\t\t#\n\t\t\t\t# Range of xmins to make bootstrap\n\t\t\t\tl_xmin <- round(fit_ht[[i,i_set]]$model$xmin * 0.8)\n\t\t\t\tu_xmin <- round(fit_ht[[i,i_set]]$model$xmin * 1.2)\n\t\t\t\t\n\t\t\t\tfit_ht[[i,i_set]]$uncert_estimation <- bootstrap(fit_ht[[i,i_set]]$model,\n\t\t\t\t\t\t\t\t\t\t\t xmins=l_xmin:u_xmin,\n\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n\t\t\t\t\t\t\t\t\t\t\t no_of_sims = 1000,\n\t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores())\n\t\t\t}\n\t\t\tfit_ht[[i,i_set]]$model_set <- labels_set[i_set]\n\t\t\tfit_ht[[i,i_set]]$model_name <- model_names[i]\n\t\t}\n\n\t\tfor (i in 1:n_models){\n\t\t\tdelta_AICc[i,i_set] <- fit_ht[[i,i_set]]$AICc - aic_min\n\t\t\tfit_ht[[i,i_set]]$delta_AICc <- delta_AICc[i,i_set]\n\t\t\tnorm_aic_weight <- norm_aic_weight + exp(-0.5*fit_ht[[i,i_set]]$delta_AICc) \n\t\t}\n\t\t# Akaike weigths\n\t\tfor (i in 1:n_models){\n\t\t\tAICc_weight[i,i_set] <- exp(-0.5*fit_ht[[i,i_set]]$delta_AICc)/norm_aic_weight \n\t\t\tfit_ht[[i,i_set]]$AICc_weight <- AICc_weight[i,i_set]\n\t\t}\n\t\t# Plots\n\t\tif (options.output$ploting){\n\t\t\t#setwd(options.output$resultsDir)\n\t\t\tfnam <-paste0(strsplit(options.output$data_set_name[i_im],\".tif\"),\"_\",labels_set[i_set], \".png\")\n\t\t\tpng(filename=fnam, res=300,units = \"mm\", height=200, width=200,bg=\"white\")\n\n\t\t\tpo <-plot(fit_ht[[1,i_set]]$model,xlab=\"Area\",ylab=\"CCDF\",main=labels_set[i_set])\n\t\t\tfor (i in 1:n_models){\n\t\t\t\tif(i!=n_models) {\n\t\t\t\t\tlines(fit_ht[[i,i_set]]$model, col=i+1)\n\t\t\t\t} else {\n\t\t\t\t\test1 <- fit_ht[[i,i_set]]$model\n\t\t\t\t\tx <- sort(unique(data_set))\n\t\t\t\t\tx <- x[x>=est1$xmin]\n\t\t\t\t\tshift <- max(po[po$x>=est1$xmin,]$y)\n\t\t\t\t\ty <- ppowerexp(x,est1$xmin,est1$exponent,est1$rate,lower.tail=F)*shift\n\t\t\t\t\tlines(x,y,col=i+1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlegend(\"topright\",model_names,bty=\"n\",col=seq(2,5),lty=c(1,1,1,1),cex=0.5)\n\t\t\tdev.off()\n\t\t}\n\t}\n\t}\n\treturn(list(fitted_models=fit_ht,delta_AICc=delta_AICc,AICc_weight=AICc_weight)) \n}\n\n# Function to extract a data frame from output generated by fit_con_heavy_tail\n#\n#\nextract_fit_ht <-function(e)\n{\n\tee <- e$model\n\tgg <- e$GOF\n\tuu <- e$uncert_estimation\n\tbootXmin <-list(quantile(uu$bootstraps[,2],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\tbootPar1 <-list(quantile(uu$bootstraps[,3],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\t\n\tif(grepl(\"con\",class(ee),fixed = T))\n\t{\n# \t\tif(class(ee)==\"conlnorm\") { \n# \t\t\tpa<-ee$getPars()\n# \t\t\tif(length(pa)!=2) stop(\"conlnorm must have 2 parameters\")\n# \t\t} else {\n# \t\t\tpa<-double(2)\n# \t\t\tpa[1]<- ee$getPars()\n# \t\t\tpa[2]<- 0\n# \t\t}\n\t\tdata_frame(model_name=e$model_name,model_set=e$model_set,\n\t\t\t\t par1=ifelse(is.null(ee$pars[1]),NA,ee$pars[1]),\n\t\t\t\t par2=ifelse(is.null(ee$pars[2]),NA,ee$pars[2]),\n\t\t\t\t xmin=ee$getXmin(),n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,GOFp=ifelse(is.null(gg$p),NA,gg$p),bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t\t\n\t} else {\n\t\tdata_frame(model_name=e$model_name,model_set=e$model_set,par1=ee$exponent,par2=ee$rate,\n\t\t\t\t xmin=ee$xmin,n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,GOFp=ifelse(is.null(gg$p),NA,gg$p),bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t}\n\t\n}\n\n# Read data to call fit_con_heavy_tail and format output in a data.frame\n#\n#\ncall_fit_con_heavy_tail <-function(options,i){\n\t\n\t# Read binary data\n\tconnection_file <- file(options$original_bin_files[i], \"rb\")\n\tdata_set <- readBin(connection_file, \"double\", n = 10^6)\n\t\n\tta<-sum(data_set)*233*233/1000000\n\t\n\tcat(options$original_bin_files[i],ta,\"\\n\")\n\t\n\tfit_ht_df<-data_frame()\n\t\n\tif(ta>100000){# Set folder with results for the region \n\n\t\t#\n\t\t# Sample data for testing\n\t\tif(options$sample_data>0) data_set<- sample(data_set,options$sample_data) ### TESTING\n\t\t\n\t\t# Fit distribution models\n\t\tfit_ht <- fit_con_heavy_tail(data_set,options$xmins,options)\n\t\t\n\t\t# List to data.frame\n\t\tfit_ht_df <- ldply(fit_ht$fitted_models,extract_fit_ht)\n\t\tfit_ht_df$data_set_name <- strsplit(options$data_set_name[i],\".tif\")[[1]][1]\n\t\tss <- strsplit(options$data_set_name[i],\"_\")\n\t\tfit_ht_df$region <- ss[[1]][2]\n\t\tfit_ht_df$subregion <- ss[[1]][3]\n\t\tfit_ht_df$threshold <- ss[[1]][4]\n\t\tfit_ht_df$year <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options$data_set_name[i])\n\t}\n\t\n\tclose(connection_file)\n\t\n\treturn(fit_ht_df)\n\t\n}\n\n# Returns a data.frame with: number of patches, max patch, and total patch area\n#\ndata_con_heavy_tail <-function(options,i){\n\t\n\t# Read binary data\n\tconnection_file <- file(options$original_bin_files[i], \"rb\")\n\tdata_set <- readBin(connection_file, \"double\",n = 10^7)\n\tif(length(data_set)==10^7)\n\t\t\twarning(\"Data set\",options$original_bin_files[i], \" may be bigger than 10^7\")\n\tnl<-length(data_set)\n\tmx<-max(data_set)*233*233/1000000 # Convert to km2\n\tta<-sum(data_set)*233*233/1000000\n\tmx2 <- (sort(data_set,partial=nl-1)[nl-1])*233*233/1000000\n\tcat(options$original_bin_files[i],\"\\tNo.patches\",nl,\"\\tMax.PatchKm2\",mx,\"\\t2nd.Max.PatchKm2\",mx2,\"\\tTotalKm2\",ta,\"\\n\")\n\t\n\tfit_ht_df <- data_frame(number_of_patches=nl,max_patch=mx,second_max=mx2,total_patch_area=ta)\n\tfit_ht_df$data_set_name <- strsplit(options$data_set_name[i],\".tif\")[[1]][1]\n\tss <- strsplit(options$data_set_name[i],\"_\")\n\tfit_ht_df$region <- ss[[1]][2]\n\tfit_ht_df$subregion <- ss[[1]][3]\n\tfit_ht_df$threshold <- ss[[1]][4]\n\tfit_ht_df$year <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options$data_set_name[i])\n\n\tclose(connection_file)\n\t\n\treturn(fit_ht_df)\n\t\n}\n\n\n\n# Fit all the images patch sizes for a region with maybe different areas \n#\n#\nregion_fit_con_heavy_tail <-function(options,region,year=0){\n\n\t# Change to results folder \n\t#\n\tsetwd(options$resultsDir)\n\t\n\t# Get files with patch sizes (*.bin) and image file names *.tif (data_set_name)\n\t#\n\toptions$original_bin_files <- list.files(pattern=paste0(\"^.*\",region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\toptions$data_set_name <- unlist(strsplit(options$original_bin_files,\".bin\")) \n\t\n\tif( year > 0)\n\t\toptions$data_set_name <- options$data_set_name[gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options$data_set_name)==year]\n\t\n\t\n\tfit <- data_frame()\n\n\n\tfor(i in 1:length(options$data_set_name))\n\t{ \n\t\tif(options$fit)\n\t\t{\n\t\t \tfit <- rbind(fit,call_fit_con_heavy_tail(options,i))\t# Fit models\n\t\t} else {\n\t\t \tfit <- rbind(fit,data_con_heavy_tail(options,i)) \t\t# calculate patch stats\n\t\t}\n\t}\n\tif(region!=fit$region[1]) warning(\"Regions don't match \",region, fit$region)\n\t\n\t# Change to base folder \n\t#\n\tsetwd(oldcd)\n\t\n\treturn(fit)\n}\n\n\n# Plot of frequencies of patch sizes with fitted continuous heavy tail functions\n# x: data\n# fit_ht_df : dataframe with fitted parameters\n#\nfreq_plot_con_ht <- function(x,fit_ht,tit=\"\") # PLOT ALL FROM X=1 ?????????????????\n{\n\trequire(dplyr)\n\trequire(ggplot2)\n\txx <-as.data.frame(table(x))\n\txx$x <- as.numeric(as.character(xx$x))\n\tff <- filter(fit_ht,model_name==\"PowerExp\")\n\txmin <- ff$xmin\n\txx$pexp <-dpowerexp(xx$x,1,ff$par1,ff$par2)\n\t\n\tff <- filter(fit_ht,model_name==\"Power\")\n\txx$pow <-dpareto(xx$x,xmin,ff$par1)\n\n\tff <- filter(fit_ht,model_name==\"Exp\")\n\txx$exp <-dexp(xx$x,ff$par1)\t\n\n\txx <-mutate(xx,pexp=ifelse(x= min(tP$Rank))\n\t#tP1 <-filter(tP1, powl>= min(tP$Rank))\n\t\n\t#mc <- c(\"#E69F00\", \"#56B4E9\", \"#009E73\",\"#F0E442\", \"#0072B2\",\"#D55E00\", \"#CC79A7\")\n\t# Brewer\n\t#mc <- c(\"#d7191c\",\"#fdae61\",\"#abd9e9\",\"#2c7bb6\")\n\t\n\tg <- ggplot(tP, aes(x=x,y=y)) + theme_bw() + geom_point(alpha=0.3) + \n\t\tcoord_cartesian(ylim=c(1,min(tP$y)))+\n\t\tscale_y_log10() +scale_x_log10() + ylab(\"log[P(X > x)]\") + xlab(\"Patch size\") #+ggtitle(tit)\n\tif(xmax>0) {\n\t\tg<-g + xlim(0,xmax+1) + scale_x_log10()\n\t}\n\tbrk<-unique(tP1$model)\n\tg <- g + geom_line(data=tP1,aes(y=powl,x=psize,colour=model)) + \n\t\t#scale_colour_discrete(name=\"\",breaks=brk)\n\t\t#scale_colour_manual(values=mc,name=\"\",breaks=brk) \n\t\tscale_colour_brewer(type=\"div\",palette=7,name=\"\",breaks=brk)\n\n\t\n\t\n# \tif(!is.null(fit_ht1))\n# \t{\t\n# \t\t#tP <-filter(tP,x x)]\") + xlab(\"Patch size\") #+ggtitle(tit)\n# \t\t\n# \n# \t\t#xmin <- fit_ht1$xmin \n# \t\ttP2 <- cdfplot_conpl_exp_helper(x,tP,fit_ht1,xmin,\"lt\")\n# \t\tbrk<-unique(tP2$model)\n# \t\t\n# \t\tg <- g + geom_line(data=tP2,aes(y=powl,x=psize,colour=model)) + \n# \t\t\t#scale_colour_discrete(name=\"\",breaks=brk)\n# \t\t\t#scale_colour_manual(values=mc,name=\"\",breaks=brk) \n# \t\t\tscale_colour_brewer(type=\"div\",palette=7,name=\"\",breaks=brk)\n# \t\t\n# \t\tfil <- gsub(\" \", \"\", tit, fixed = TRUE)\n# \t\tfil <- paste0(fil,\"_1.png\")\n# \t\tif(tit==\"\")\n# \t\t\tprint(g)\n# \t\telse\n# \t\t\tggsave(fil,plot=g,width=6,height=4,units=\"in\",dpi=600)\n# \t\t\n# \n# \t}\n\tfil <- gsub(\" \", \"\", tit, fixed = TRUE)\n\tfil <- paste0(fil,\".png\")\n\tif(tit==\"\")\n\t\tprint(g)\n\telse\n\t\tggsave(fil,plot=g,width=6,height=4,units=\"in\",dpi=600)\n\t\n}\n\ncdfplot_conpl_exp_helper <- function(x,tP,fit_ht,xmin,mode=\"gt\")\n{\n\tx1 <- unique(x)\n\n\t# Select model and generate a data frame \n\t#\n\tff <- filter(fit_ht,model_name==\"PowerExp\")\n\n\tif(mode==\"gt\") {\n\t\tx1 <- x1[x1>=xmin]\n\t\tshift <- max(filter(tP,x>=xmin)$y)\n\t} else {\n\t\tx1 <- x1[x1=xmin)$y)\n\t}\n\n\ttP2 <- data.frame(psize=x1, powl=ppowerexp(x1,xmin,ff$par1,ff$par2,lower.tail=F)*shift,model=\"PowerExp\")\n\n\tff <- filter(fit_ht,model_name==\"Power\")\n\n\ttP1 <-data.frame(psize=x1, powl=ppareto(x1,xmin,ff$par1,lower.tail=F)*shift,model=\"Power\")\n\n\tff <- filter(fit_ht,model_name==\"Exp\")\n\tm <- conexp$new(x)\n\tm$setPars(ff$par1)\n\tm$setXmin(xmin)\n\ttP3 <- data.frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model=\"Exp\")\n\t\n\tff <- filter(fit_ht,model_name==\"LogNorm\")\n\tm <- conlnorm$new(x)\n\tm$setPars(c(ff$par1,ff$par2))\n\tm$setXmin(xmin)\n\ttP4 <- data.frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model=\"LogNorm\")\n\ttP1 <- bind_rows(tP1,tP2,tP3,tP4)\n}\n\n\n# Function to plot CCDF of heavy tailed distributions using base graphics\n# x: data set\n# fit_ht: a data frame with the fitted parameters\n#\ncdfplot_con_ht <- function(x,fit_ht,fnam=\"\")\n{\n\trequire(dplyr)\n\tif(fnam!=\"\"){\n\t\t\tfnam <-paste0(fnam,\".png\")\n\t\t\tpng(filename=fnam, res=300,units = \"mm\", height=200, width=200,bg=\"white\")\n\t}\n\n\t#fil <- gsub(\" \", \"\", tit, fixed = TRUE)\n\t#fil <- paste0(fil,\".png\")\n\n\tmc <- c(\"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#CC79A7\")\n\n\trequire(poweRlaw)\n\tm <- conpl$new(x)\n\tpo <- plot(m,xlab=\"Area\",ylab=\"CCDF\")\n\t#x <- x[x>=xmin]\n\n\t\t\n\t#x <- unique(x)\n\t# Plot with base plot and poweRlaw package\n\t#\n\tff <- filter(fit_ht,model_name==\"Power\")\n\txmin <- ff$xmin\n\tm$setPars(ff$par1)\n\tm$setXmin(xmin)\n\tlines(m, col=mc[1])\n\n\tshift <- max(filter(po,x>=xmin)$y)\n\tff <- filter(fit_ht,model_name==\"PowerExp\")\n\tx1 <- sort(unique(x))\n\t#x1 <- sort(x)\n\tx1 <- x1[x1>=xmin]\n\ty1 <- ppowerexp(x1,xmin,ff$par1,ff$par2,lower.tail=F)*shift\n\tlines(x1,y1,col=mc[2])\n\n\t\n\tff <- filter(fit_ht,model_name==\"Exp\")\n\tm <- conexp$new(x)\n\tm$setPars(ff$par1)\n\tm$setXmin(xmin)\n\tlines(m, col=mc[3])\n\n\tff <- filter(fit_ht,model_name==\"LogNorm\")\n\tm <- conlnorm$new(x)\n\tm$setPars(c(ff$par1,ff$par2))\n\tm$setXmin(xmin)\n\tlines(m, col=mc[4])\n\t\n\tmodel_names <- c(\"Power\",\"PowerExp\",\"Exp\",\"LogNorm\")\n\tlegend(\"topright\",model_names,bty=\"n\",col=mc[1:4],lty=c(1,1,1,1),cex=0.5)\n\n\tif(fnam!=\"\")\n\t\tdev.off()\n\n}\n\n# Function to plot distributions fits from the complete dataset Xmin=9\n# and the dataset from the estimated Xmin \n# calls the function cdfplot_con_ht and use global variables\n#\n# reg: geographic region {SA,CA,NA,EU, etc}\n#\nccdfPlots_one_region <- function(options,region)\n{\n\tfor( i_im in 1:length(options$data_set_name)) \n\t{\n\t\tconnection_file <- file(options$original_bin_files[i_im], \"rb\")\n\t\tdata_set <- readBin(connection_file, \"double\", n = 10^6)\n\t\tif(options$sample_data>0) data_set<- sample(data_set,options$sample_data) \n\t\tta<-sum(data_set)*233*233/1000000\n\t\tif(ta>100000){\n\t\t\tss <- strsplit(options$data_set_name[i_im],\"_\")[[1]][2]\n\t\t\tif( region != ss) warning(\"Region extracted from file names: \",ss, \" Different from parameter: \",region)\n\t\t\t\n\t\n\t\t\tnn <- strsplit(options$original_bin_files[i_im],\".tif\")[[1]][1]\n\t\t\t\n\t\t\t# Complete data set (Xmin=1)\n\t\t\t#\n\t\t\tff <- filter(all_fit,grepl(nn,data_set_name,ignore.case = T),model_set==\"Xmin=9\",region==region)\n\t\t\tna<-paste0(ff$region[1],\"_\", ff$subregion[1],\"_\",ff$year[1],\"_\",ff$model_set[1])\n\t\t\tcdfplot_conpl_exp(data_set,ff,na)\n\t\t\t\n\t\t\t# data set< Estimated Xmin (=hmin & h<=hmax) \n\t} else {\n\t dn1 <- dn\n\t}\n\tstr_sub(dn1$V1,28,40) <- \"*\"\n\t\n\twrite.table(str_c(dn1$V1,\"*\"),file=\"MOD44BFiles\",row.names = F,col.names = F,quote = F)\n\t\n\tsystem(\"modis_download_from_list.py -U lsaravia -P Octa2004 -p MOD44B.051 -f MOD44BFiles hdf \")\n\t\n\tsetwd(oldcd)\n\t\n\treturn(dn1)\n\t}\n\n\n# Make mosaic of hdf files downloaded with down_modis\n# in a folder \"hdf\" with base dataDir, it uses a file called\n# \"Download.txt\" to read the files to compose and the Python PyModis package\n#\n# dataDir: base folder to output mosaic geotif files\n# \n#\nmosaic_modis <- function(dataDir,hmin,hmax) {\n\t\n\tsetwd(dataDir)\n\tdn <- read.table(\"Download.txt\",stringsAsFactors = F)\n\trequire(stringr)\n\tdn$h=as.numeric(str_sub(dn[,1],18,19))\n\tdn$v=as.numeric(str_sub(dn[,1],21,22))\n\tdn$year=str_sub(dn[,1],9,12)\n\n\trequire(dplyr)\n\tdn1 <- filter(dn,h>=hmin & h<=hmax) \n\tsetwd(\"hdf\")\n\tgroup_by(dn1,year) %>% do( s=mosaic_by_year(.))\n\n\tsetwd(oldcd)\n}\n\n# helper function for mosaic_modis\n#\nmosaic_by_year <-function(x) {\n \n # write list of file names to use in the mosaic\n #\n\twrite.table(x$fname,file=\"listfileMOD44B.051.txt\",quote=F,col.names = F,row.names = F)\n \n # Output file name \n #\n gname <- paste0('MOD44B.MRTWEB.A',x$year[1],'065.051.Percent_Tree_Cover.tif')\n \n\ts <- paste0('modis_mosaic.py -s \"1 0 0 0 0 0 0\" listfileMOD44B.051.txt -o ', gname)\n\tsystem(s)\n\t\n\treturn(gname)\n}\n\n# Read the h and v limits for modis hdf files to make composite images by continent \n#\n#\nget_modis_limits <-function(region,hmin,hmax){\n \n setwd(\"MODIS_tools\")\n fn <- paste0(\"Download_\",region,\".txt\")\n dn <- read.table(fn,stringsAsFactors = F)\n setwd(oldcd)\n \n require(stringr)\n \n # regexpr(\"h[0-9]\",dn[1,1])\n \n dn$h=as.numeric(str_sub(dn[,1],18,19))\n dn$v=as.numeric(str_sub(dn[,1],21,22))\n dn$year=str_sub(dn[,1],9,12)\n \n # Generate a DF with only the h v needed for a region\n #\n require(dplyr)\n dn <- filter(dn,h>=hmin & h<=hmax) \n m <- matrix(0,nrow=max(dn$v),ncol=max(dn$h))\n m[dn$v,dn$h]<-1\n print(m) \n mod_limits <- dn %>% filter(year==2000) %>% arrange(v,h) %>% select(h,v) %>% mutate( Region=region) \n \n}\n\n\n#' Make geotiff mosaic of hdf files for a region defined as h & v modis granules\n#' in a folder \"hdf\" within base dataDir\n#'\n#' @param dataDir Folder where the geotiff file will be generated and where there is \n#' a subfolder hdf with granules \n#' \n#' @param destDir Destination folder for the generated geotiff files\n#' \n#' @param granules Data frame with h & v columns identifying granules to be mosaicked, with\n#' fields h,v,region \n#' @param region region defined in the data frame to generate the geotiff\n#' \n#' @param year year of the modis granules to generate the geotiff \n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' \nmosaic_modis_region <- function(dataDir,destDir,granules,region,year) {\n oldcd <-getwd() \n setwd(dataDir)\n \n # read the files in dir 'hdf'\n #\n dn <- list.files(\"hdf\",pattern = \"^.*\\\\.hdf$\")\n if(length(dn)==0) stop(\"The folder hdf is empty\")\n require(dplyr)\n dn <- tibble(dn)\n names(dn) <- \"fname\"\n \n require(stringr)\n dn$h <- as.numeric(str_match(dn$fname, \"h(\\\\d{2})\")[,2])\n dn$v <- as.numeric(str_match(dn$fname, \"v(\\\\d{2})\")[,2])\n dn$year <- str_match(dn$fname, \"A(\\\\d{4})\")[,2]\n \n\n dn1 <- granules %>% filter(Region==region) %>% inner_join(dn) \n setwd(\"hdf\")\n \n dn2 <- group_by(dn1,year) %>% do( gname=mosaic_by_year(.))\n dn2$gname <-unlist(dn2$gname)\n \n dn2$toname <- paste0(destDir,\"/\",dn2$gname)\n \n # dn2 <- data.frame(gname=\"MOD44B.MRTWEB.A2015065.051.Percent_Tree_Cover.tif\",stringsAsFactors = F)\n file.rename(dn2$gname,dn2$toname)\n \n setwd(oldcd)\n}\n\n\n\n# Read data to call fit_con_heavy_tail and format output in a data.frame\n#\n#\nmax_patch_size <-function(im_names,opts.out){\n\t\n\tmax_s_df <- data_frame()\n\t\n\tfor(i in 1:length(im_names))\n\t{ \n\t\t# Read binary data\n\t\tconnection_file <- file(original_bin_files[i], \"rb\")\n\t\tdata_set <- readBin(connection_file, \"double\", n = 10^6)\n\t\tif(options.output$sample_data>0) data_set<- sample(data_set,options.output$sample_data) ### TESTING\n\t\tmax_s_df <- rbind(max_s_df,data_frame( maxS=max(data_set), data_set_name=strsplit(options.output$data_set_name[i],\".tif\")[[1]][1],\n\t\t\t\t\t\t\t\tyear=substr(data_set_name,16,19),region=opts.out$region))\n\t\t\n\t}\n\n\treturn(max_s_df)\n}\n\n\nread_random_percolation <-function(region) {\n\t\n\tpercolation_R_files <- list.files(pattern=\"^.*_randomized_p_sweep\\\\.R$\")\n\tdf <- data.frame()\n\t\n\tfor(i in 1:length(percolation_R_files)){\n\t\tss <- strsplit(percolation_R_files[i],\"_\")\n\t\t#df$region <- ss[[1]][2]\n\t\t#df$subregion <- ss[[1]][3]\n\t\tif(ss[[1]][2]!=region) warning(\"Regions don't match \",region, ss[[1]][2])\n\n\t\tsource(percolation_R_files[i])\n\t\tll <- length(p_set)\n\t\tdf1 <- data.frame(region=rep(ss[[1]][2],ll),subregion=rep(ss[[1]][3],ll),correlation_length_km=t(correlation_length_km_set),p_set=t(p_set))\n\t\tdf1$equivalent_diameter_km <- equivalent_diameter_km\n\t\tdf1$maximum_length_km <- maximum_length_km\n\t\tdf1$total_area_km2 <- total_area_km2\n\t\tdf <- rbind(df,df1)\n\t\t\n\t}\n\treturn(df)\n}\n\n\nread_region_correlation<-function(region) {\n\n\tr_files <- list.files(pattern=\"^.*_Tree_Cover.tif_Correlation_analisys\\\\.R$\")\n\tdf <- data.frame()\n\t\n\tfor(i in 1:length(r_files)){\n\n\t\tss <- strsplit(r_files[i],\"_\")\n\t\t#df$region <- ss[[1]][2]\n\t\t#df$subregion <- ss[[1]][3]\n\t\tif(ss[[1]][2]!=region) warning(\"Regions don't match \",region, ss[[1]][2])\n\n\t\tsource(r_files[i])\n\t\tdf1 <- data.frame(region=ss[[1]][2],subregion=ss[[1]][3],year=gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",r_files[i]),\n\t\t\tcorrelation_length_km,maximum_length_km,total_area_km2,equivalent_diameter_km)\n\n\t\tdf <- rbind(df,df1)\n\t}\n\treturn(df)\n}\n\n# Estimation of the correlation exponent epsilon ~ (p-pc)^-nu\n# based in the potential relationship near the critical point\n#\n# range: range of p to estimate exponent\n# cp: critical point\n# df: data frame with data\n#\nest_correlation_exponent <- function(range,cp,df)\n{\n\trequire(ggplot2)\n\t\n\tf_df <- df %>% group_by(region,subregion) %>% filter(p_set>=range[1] & p_set<=range[2]) %>% mutate(p_dif=abs(p_set-cp))\n\t\n\tg <- ggplot(f_df,aes(p_dif,correlation_length_km,colour=subregion))+theme_bw() + geom_point() + scale_y_log10() +scale_x_log10() \n\tprint(g + geom_smooth(method=lm, se=FALSE)) # Don't add shaded confidence region\n\t\n\tmods <- do(f_df,mod=lm(log(correlation_length_km) ~ log(p_dif),data=.),max_corr_length=max(.$correlation_length_km),min_corr_length=min(.$correlation_length_km))\n\tslop <- mods %>% mutate(log_inter=coef(summary(mod))[1],correl_exp=coef(summary(mod))[2],\n\t\t\t\t\t\tR2 = summary(mod)$r.squared,pvalue_exp=coef(summary(mod))[2,4], #full_coef=coef(summary(.$mod)),\n\t\t\t\t\t\tmax_corr_length=max_corr_length,min_corr_length=min_corr_length) %>% select(-mod)\n\t\n\t#slop <- mods %>% do(data.frame(region=.$region, subregion=.$subregion, var = names(coef(.$mod)), coef(summary(.$mod)))) %>% filter(var==\"log(p_dif)\")\n\t#R2s <- mods %>% summarise(region=region, subregion=subregion,R2 = summary(mod)$r.squared)\n\t#slop$R2 <- R2s$R2\n\t\n\treturn(slop) # %>% select(-var,-t.value) %>% rename(correl_exp=Estimate,SE=Std..Error,pvalue=Pr...t..))\n}\n\n# Calculates critical probability from correlation length based on the estimated exponents using \n# function est_correlation_exponent\n#\n# range: range of p to estimate exponent (not used)\n# cp: critical point\n# corexp: data frame ouput of the function est_correlation_exponent\n# regcor: data frame with data \n#\ncalc_critical_probability <- function(range,cp,corexp,regcor)\n{\n\tallcor <- regcor %>% inner_join(corexp) %>% mutate(p=cp-(correlation_length_km/exp(log_inter))^(1/correl_exp),\n\t\t\t\t\t\t\t\t\t\t\t\t\t p=ifelse(p<0,0,ifelse(p>1,1,p)))\n#\tincor <- allcor %>% filter(correlation_length_km>=min_corr_length,correlation_length_km<=max_corr_length) %>%\n#\t\tmutate(pdist=exp((log_inter-log(correlation_length_km))/correl_exp))\n#\t\tmutate(p=cp-(correlation_length_km/exp(log_inter))^(1/correl_exp))\n#\tltcor <- allcor %>% filter(correlation_length_km% mutate(p=0.1)\n#\tgtcor <- allcor %>% filter(correlation_length_km>max_corr_length) %>% mutate(p=0.9)\n\t\n\treturn(select(allcor, -(max_corr_length:pvalue_exp)))\n}\n\n# Estimation of the critical point using logistic regression \n#\n#\nest_critical_point <- function(rndper)\n{\n # Estimate the probability of percolation as correlation_length/equivalent_diameter\n #\n\trp <-rndper %>% group_by(region,subregion) \t%>% mutate(p_correlation_length=correlation_length_km/equivalent_diameter_km) %>% mutate(p_correlation_length=ifelse(p_correlation_length>1,1,p_correlation_length))\n\t\n # Fit a binomial model to estimate the critical point\n\t#\n\trfit <- rp %>% do(lfit= glm(.$p_correlation_length ~ .$p_set, family=binomial(logit), data = .))\n\t# slop <- rfit %>% mutate(beta0 = coef(lfit)[1],\n\t# \t\t\t\t\t\tbeta1 = coef(lfit)[2],\n\t# \t\t\t\t\t\tpcrit = - beta0 / beta1) \n\t\n\t# Estimate the critical point using a regression of the values around the probability of percolation =0.50\n\t# p_correlation_length = 0.5\n\t#\n\tslop <- rp %>% do(pcrit = est_critical_point_helper(.)) %>% mutate(pcrit=unlist(pcrit))\n\n\t# Calculate the predicted values of the binomial regression to plot\n\t#\n\trfit <-rfit %>% inner_join(rp %>% slice(1) %>% transmute(max_cl=equivalent_diameter_km))\n\trp1 <-rfit %>% do(data.frame(fit = .$lfit$fitted*.$max_cl))\n\trp <- bind_cols(rp, rp1)\n\t\n\tgt <- slop %>% mutate(label = sprintf(\"p == %.3f\", pcrit),x=0.9,y=0.1)\n\tg <-ggplot(rp,aes(p_set,correlation_length_km))+theme_bw() + geom_point(shape=21) + \t\t\n\t\tgeom_line(aes(x = p_set, y = fit), linetype = 2) +\n\t\tgeom_vline(aes(xintercept = pcrit),data = slop, color = \"blue\") +\n\t\tgeom_text(aes(x,y,label = label) ,data=gt,parse = TRUE ) +\n\t\tfacet_wrap(region ~ subregion,scales=\"free_y\") \n\tprint(g)\n\n\treturn(slop)\n}\n\nest_critical_point_helper<- function(x)\n{\n # lf <-glm(p_correlation_length ~ p_set, family=binomial(logit), data = x)\n # pcrit=- (lf$coefficients[1] / lf$coefficients[2])\n # x$p <-predict(lf,x,type=\"resp\")\n x1 <- x %>% filter(p_correlation_length>0.50) %>% arrange(p_correlation_length) %>% slice(1:10) \n x1 <- bind_rows(x1, x %>% filter(p_correlation_length<=0.50) %>% arrange(desc(p_correlation_length)) %>% slice(1:10))\n pcrit <- approx(x1$p_correlation_length,x1$p_set,xout=0.5)[[\"y\"]]\n \n}\n\n\n\n#' Plot estimated correlations lenght with ramdomized correlation lengths \n#'\n#' @param cpoint Data frame with critical points\n#' @param rndcor Data frame with randomized correlation lengths\n#' @param corlen Data frame with correlation lengths\n#'\nplot_corr_length <- function(cpoint,rndcor,corlen)\n{\n gt <- cpoint %>% mutate(label = sprintf(\"p == %.3f\", pcrit),x=0.9,y=0.1)\n g <-ggplot(rndcor,aes(p_set,correlation_length_km))+theme_bw() + geom_point(shape=21) + \t\t\n geom_vline(aes(xintercept = pcrit),data = cpoint, color = \"blue\") +\n geom_text(aes(x,y,label = label) ,data=gt,parse = TRUE ) +\n geom_point(aes(),data=corlen)\n facet_wrap(region ~ subregion,scales=\"free_y\") \n print(g)\n} \n\n# Calculates the percolation probability using logistic equation parms from est_critical_point\n#\n# cripoi: critical point and logistic parameters \n# regcor: data frame with data \n#\ncalc_critical_probability_logis <- function(cripoi,regcor)\n{\n\tallcor <- regcor %>% inner_join(cripoi) %>% mutate( pl = (-log((max_cl-correlation_length_km)/correlation_length_km) -beta0) / beta1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t \n\treturn(select(allcor,-(lfit:max_cl)))\t\n\t\n}\n\n\n# Plot inverse cumulative size distributions fits by region\n#\n# region\n# odir: folder with the size distribution files\n#\nplot_size_dist_by_region <-function(region,odir,Thres=0,Year=0)\n{\n\trequire(ggplot2)\n\n\toptions.glo$resultsDir <- odir\n\toptions.glo$sample_data <- 0 # Set >0 For testing\n\t\n\tsetwd(options.glo$resultsDir)\n\toptions.glo$original_bin_files <- list.files(pattern=paste0(\"^.*\",region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\t\n\toptions.glo$data_set_name <- unlist(strsplit(options.glo$original_bin_files,\".bin\")) \n\tyear <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options.glo$data_set_name)\n\tthreshold <- sub(\"^(?:[^_]*_){3}([^_]+).*\",\"\\\\1\",options.glo$data_set_name)\n\n\tif(Thres>0)\n\t\toptions.glo$data_set_name <- options.glo$data_set_name[threshold==thres] \n\n\tif(Year>0)\n\t\toptions.glo$data_set_name <- options.glo$data_set_name[year==Year] \n\t\n\t# Read binary data\n\tset.seed(seed=0)\n\t\n\tccdfPlots_one_region(options.glo,region)\n\t\n\tsetwd(oldcd)\n}\n\n\n# Fit continuos heavy tail models (used for small data sets not patch size distributions)\n# \n#\nfit_cont_heavy_tail_mdls <- function (data_set,xmins,ploting=TRUE,gof=FALSE)\n{\n\tn <- length(unique(data_set))\n\tn_models <- 3\n\t# List of models\n\tmodel_list = list(list(model=vector(\"list\", length=0), \n\t\t\t\t\t\t \t\t\t\t\t\tGOF=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t xmin_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t uncert_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t k=0,\n\t\t\t\t\t\t\t\t\t\t\t\t LL=0,\n\t\t\t\t\t\t\t\t\t\t\t\t n=n,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t delta_AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=0,\n\t\t\t\t\t\t model_name=character(0),\n\t\t\t\t\t\t modelfit_cont_heavy_tail_mdls_set=character(0))) \n\tfit_ht <- rep(model_list,n_models)\n\tdim(fit_ht) <- c(n_models)\n\n\t# Declare models\n\t# Continuous power law\n\tfit_ht[[1]]$model <- conpl$new(data_set)\n\tfit_ht[[1]]$k <- 1\n\t# Continuous log-normal\n\tfit_ht[[2]]$model <- conlnorm$new(data_set)\n\tfit_ht[[2]]$k <- 2\n\t# Continuous exponential\n\tfit_ht[[3]]$model <- conexp$new(data_set)\n\tfit_ht[[3]]$k <- 1\n\n\t# Set xmin for set 1\n\tfit_ht[[1]]$model$xmin <- xmins\n\tif(length(xmins)>1){\n\t\t# Estimate Xmin with complete data_set for power law model\n\t\tfit_ht[[1]]$xmin_estimation <- estimate_xmin(fit_ht[[1]]$model,\n\t\t\txmins = xmins, \n\t\t\tpars = NULL, \n\t\t\txmax = max(data_set))\n\t\tfit_ht[[1]]$model$setXmin(fit_ht[[1]]$xmin_estimation)\n\t} else if(xmins-1){\n\t\tfit_ht[[1]]$xmin_estimation <- estimate_xmin(fit_ht[[1]]$model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set))\n\t\tfit_ht[[1]]$model$setXmin(fit_ht[[1]]$xmin_estimation)\n\t} else {\t\t\n\t\tfit_ht[[1]]$model$setXmin(xmins)\n\t}\n\t\n\t\n\tmodel_names <- c(\"Power\", \"LogNorm\",\"Exp\")\n\n\tAICc_weight <- matrix( nrow = n_models, ncol = 1,\n\t\t\t\t\t\t\tdimnames = list(model_names))\n\n\tdelta_AICc <- AICc_weight\n\tGOF <- delta_AICc\n\tif(n>8) {\n\t\taic_min=Inf\n\t\tnorm_aic_weight=0\n\t\tfor (i in 1:(n_models)){\n\t\t\t# Set cut-off (x_min)\n\t\t\tfit_ht[[i]]$model$xmin <- fit_ht[[1]]$model$xmin\n\t\t\t\n\t\t\t# Correct n with xmin\n\t\t\tfit_ht[[i]]$n <-length(data_set[data_set>=fit_ht[[1]]$model$xmin])\n\n\t\t\t# Fit models\n\t\t\t#\n\t\t\tfit_ht[[i]]$model$setPars(estimate_pars(fit_ht[[i]]$model))\n\t\t\t# \n\t\t\t# Get Loglikelihood\n\t\t\tfit_ht[[i]]$LL <- dist_ll(fit_ht[[i]]$model)\n\n\t\t\tLL <- fit_ht[[i]]$LL\n\t\t\tk <- fit_ht[[i]]$k\n\t\t\t# Compute AICc\n\t\t\t#\n\t\t\tfit_ht[[i]]$AICc <- (2*k-2*LL)+2*k*(k+1)/(n-k-1)\n\t\t\taic_min <- min(aic_min,fit_ht[[i]]$AICc)\n\t\t\tif (gof && fit_ht[[i]]$n>4){\n\t\t\t\t#\n\t\t\t\t# Goodness of fit via boostrap\n\t\t\t\t#\n\t\t\t\t# xmins is fixed at estimated value (or 9)\n\t\t\t\tfit_ht[[i]]$GOF <- try(bootstrap_p(fit_ht[[i]]$model,\n\t\t\t\t\t\t\t\t\t\t\t #xmins=fit_ht[[i]]$model$xmin,\n\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n\t\t\t\t\t\t\t\t\t\t\t no_of_sims = 999,\n\t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores()))\n\t\t\t\tGOF <- fit_ht[[i]]$GOF\n\t\t\t\tif(class(GOF)!=\"bs_p_xmin\"){\n\t\t\t\t\tfit_ht[[i]]$GOF <-NULL\n\t\t\t\t} else {\n\t\t\t\t\tfit_ht[[i]]$GOF$p <- sum(GOF$gof >= GOF$bootstraps$gof,na.rm = TRUE)/999\n\t\t\t\t}\n\t\t\t\t#\n\t\t\t\t# Uncertainty in parms estimation via bootstrap\n\t\t\t\t#\n\t\t\t\t# Range of xmins to make bootstrap\n# \t\t\t\tl_xmin <- fit_ht[[i]]$model$xmin * 0.8\n# \t\t\t\tu_xmin <- fit_ht[[i]]$model$xmin * 1.2\n# \t\t\t\tfit_ht[[i]]$uncert_estimation <- bootstrap(fit_ht[[i]]$model,\n# \t\t\t\t\t\t\t\t\t\t\t xmins=l_xmin:u_xmin,\n# \t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n# \t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n# \t\t\t\t\t\t\t\t\t\t\t no_of_sims = 1000,\n# \t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores())\n\t\t\t}\n\t\t\tfit_ht[[i]]$model_name <- model_names[i]\n\t\t}\n\n\t\tfor (i in 1:n_models){\n\t\t\tdelta_AICc[i] <- fit_ht[[i]]$AICc - aic_min\n\t\t\tfit_ht[[i]]$delta_AICc <- delta_AICc[i]\n\t\t\tnorm_aic_weight <- norm_aic_weight + exp(-0.5*fit_ht[[i]]$delta_AICc) \n\t\t}\n\t\t# Akaike weigths\n\t\tfor (i in 1:n_models){\n\t\t\tAICc_weight[i] <- exp(-0.5*fit_ht[[i]]$delta_AICc)/norm_aic_weight \n\t\t\tfit_ht[[i]]$AICc_weight <- AICc_weight[i]\n\t\t}\n\t\t# Plots\n\t\tif (ploting){\n\t\t\t#setwd(options.output$resultsDir)\n\t\t\t#fnam <-paste0(strsplit(options.output$data_set_name[i_im],\".tif\"),\"_\",labels_set[i_set], \".png\")\n\t\t\t#png(filename=fnam, res=300,units = \"mm\", height=200, width=200,bg=\"white\")\n\n\t\t\tpo <-plot(fit_ht[[1]]$model,xlab=\"Area\",ylab=\"CCDF\")\n\t\t\tfor (i in 1:n_models){\n\t\t\t\tif(model_names[i]!=\"PowerExp\") \n\t\t\t\t{\n\t\t\t\t\tlines(fit_ht[[i]]$model, col=i+1)\n\t\t\t\t} else {\n\t\t\t\t\test1 <- fit_ht[[i]]$model\n\t\t\t\t\tx <- sort(unique(data_set))\n\t\t\t\t\tx <- x[x>=est1$xmin]\n\t\t\t\t\tshift <- max(po[po$x>=est1$xmin,]$y)\n\t\t\t\t\ty <- ppowerexp(x,est1$xmin,est1$exponent,est1$rate,lower.tail=F)*shift\n\t\t\t\t\tlines(x,y,col=i+1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlegend(\"topright\",model_names,bty=\"n\",col=seq(2,5),lty=c(1,1,1,1),cex=0.5)\n\t\t\t#dev.off()\n\t\t}\n\t}\n\tfit_ht_df <- ldply(fit_ht,extract_fit_ht_mdls)\n\n\treturn(fit_ht_df) \n}\n\n# Function to extract a data frame from output generated by fit_con_heavy_tail\n#\n#\nextract_fit_ht_mdls <-function(e)\n{\n\tee <- e$model\n\tgg <- e$GOF\n\tuu <- e$uncert_estimation\n\tbootXmin <-list(quantile(uu$bootstraps[,2],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\tbootPar1 <-list(quantile(uu$bootstraps[,3],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\t\n\tif(grepl(\"con\",class(ee),fixed = T))\n\t{\n\t\tdata_frame(model_name=e$model_name,\n\t\t\t\t par1=ifelse(is.null(ee$pars[1]),NA,ee$pars[1]),\n\t\t\t\t par2=ifelse(is.null(ee$pars[2]),NA,ee$pars[2]),\n\t\t\t\t xmin=ee$getXmin(),n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,\n\t\t\t\t GOFp=ifelse(is.null(gg$p),NA,\n\t\t\t\t \t\tifelse(is.na(gg$p),sum(gg$bootstraps$KS>gg$gof,na.rm=TRUE)/nrow(gg$bootstraps),gg$p)),\n\t\t\t\t \n\t\t\t\t bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t\t\n\t} else {\n\t\tdata_frame(model_name=e$model_name,model_set=e$model_set,par1=ee$exponent,par2=ee$rate,\n\t\t\t\t xmin=ee$xmin,n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,GOFp=ifelse(is.null(gg$p),NA,gg$p),bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t}\n\t\n}\n\n\n# Fit all the images patch sizes for a region with maybe different areas \n#\n#\nmerge2_region_fit_con_heavy_tail <-function(options,region,new_region){\n\n\t# Change to results folder \n\t#\n\tsetwd(options$resultsDir)\n\n\t# If new_region files already exist don't merge\n\t#\n\tif(list.files(pattern=paste0(\"^.*\",new_region,\".*\\\\.bin$\"))==\"\") {\n\t\t\n\t\t# Get the original files nameswith patch sizes (*.bin) and image file names *.tif (data_set_name)\n\t\t#\n\t\toptions$original_bin_files <- list.files(pattern=paste0(\"^.*\",region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\t\n\t\toptions$data_set_name <- unlist(strsplit(options$original_bin_files,\".bin\")) \n\t\t\n\t\t# Merge the two largest patches\n\t\t#\n\t\tfor(i in 1:length(options$data_set_name))\n\t\t{ \n\t\t\tconnection_file <- file(options$original_bin_files[i], \"rb\")\n\t\t\tdata_set <- sort(readBin(connection_file, \"double\", n = 10^6),decreasing=TRUE)\n\t\t\tdata_set[2] <- data_set[1]+data_set[2]\n\t\t\tdata_set <- data_set[2:length(data_set)]\n\t\t\tclose(connection_file)\n\t\n\t\t\t# Change the name of the file to new_region\n\t\t\t#\n\t\t\toptions$original_bin_files[i] <- sub(region,new_region,options$original_bin_files[i])\n\t\t\tconnection_file <- file(options$original_bin_files[i], \"wb\")\n\t\t\twriteBin(data_set,connection_file)\n\t\t\tclose(connection_file)\n\t\t}\t\t\n\t}\n\t\n\t# Get the new files names with merged patches\n\t#\n\t\n\toptions$original_bin_files <- list.files(pattern=paste0(\"^.*\",new_region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\t\n\toptions$data_set_name <- unlist(strsplit(options$original_bin_files,\".bin\")) \n\n\tfit <- data_frame()\n\t\n\tfor(i in 1:length(options$data_set_name))\n\t{ \n\t\tif(options$fit)\n\t\t{\n\t\t \tfit <- rbind(fit,call_fit_con_heavy_tail(options,i))\t# Fit models\n\t\t} else {\n\t\t \tfit <- rbind(fit,data_con_heavy_tail(options,i)) \t\t# calculate patch stats\n\t\t}\n\t}\n\n\t# Change to base folder \n\t#\n\tsetwd(oldcd)\n\t\n\treturn(fit)\n}\n\n\n# Plot of RSmax by year and threshold\n#\n# pst: pstat_threshold data frame\n# regions: vector of regions to include\nplot_RSmax_yearThreshold <- function(pst,regions){\n\n\tff1 <- filter(pst,regsub %in% regions) \n\tff2<- group_by(ff1,regsub,threshold) %>% summarise(mprop=mean(prop_max_patch))\n\t\n\tif(length(unique(ff1$regsub))==1)\n\t{\n\t\trequire(viridis)\n\t\tg <- ggplot(ff1, aes(y=prop_max_patch,x=year,colour=regsub)) + theme_bw() +\n\t\tgeom_point(shape=19) + geom_line() + facet_wrap(~threshold) + scale_colour_viridis(discrete = T,guide=F) + \n\t\t\tggtitle(unique(ff1$regsub)) + theme(plot.title = element_text(hjust = 0.5)) +\n\t\t\tgeom_hline(aes(yintercept=mprop,colour=regsub),ff2,linetype = 2)\n\t\t\n\t} else {\n\t\tpd <-position_dodge(.3)\n\t\tg <- ggplot(ff1, aes(y=prop_max_patch,x=year,colour=regsub)) + theme_bw() +\n\t\tgeom_point(shape=19,position=pd) + facet_wrap(~threshold) + scale_colour_brewer(palette=\"Set1\",name=\"Region\") +\n\t\tgeom_hline(aes(yintercept=mprop,colour=regsub),ff2,linetype = 2)\n\t}\n\n\tprint(g + ylab(expression(RS[max])) +\n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0)) \n\t\t)\n\n\n}\n\n# Plot fluctuations of RSmax by year and faceted by threshold\n#\n# pst: pstat_threshold data frame\n# regions: vector of regions to include\nplot_RSmax_Fluctuations_yearThreshold <- function(pst,regions,isSignif,numcol=3){\n\trequire(viridis)\n\tff1 <- filter(pst,regsub %in% regions) \n\tff1 <- filter(ff1,threshold %in% isSignif) %>% mutate(is_signif=TRUE) %>% bind_rows( filter(ff1,!(threshold %in% isSignif)) %>% mutate(is_signif=FALSE) )\n\t#\n\t# Fluctuations around the mean Smax - /TotArea\n\t#\n\tg <- ggplot(ff1, aes(y=delta_prop_max_patch,x=year,colour=is_signif)) + theme_bw() +\n\t\tgeom_point(shape=19,size=1) + facet_wrap(~threshold,ncol=numcol) + \n\t\tylab(expression(Delta~RS[max])) + scale_colour_viridis(discrete = T,guide=F,direction = -1) + \n\t\tggtitle(unique(ff1$regsub)) +\n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0),plot.title = element_text(hjust = 0.5,size=12)) +\n\t\tstat_quantile(quantiles=c(.10,.90),linetype=2)\n\n\tprint(g)\n\treturn(g)\n}\n\n\nplot_RSmax_Fluctuations_yearThreshold_regions <- function(pst,regions,isSignif,numcol=3){\n\trequire(viridis)\n\tff1 <- filter(pst,regsub %in% regions) \n\tff2 <- inner_join(ff1,isSignif) %>% mutate(is_signif=TRUE) \n\tff3 <- anti_join(ff1 %>% ungroup(),isSignif) %>% mutate(is_signif=FALSE) \n\tff1 <- bind_rows(ff2,ff3)\n\t#%>% bind_rows( filter(ff1,!(threshold %in% isSignif)) %>% mutate(is_signif=FALSE) )\n\t#\n\t# Fluctuations around the mean Smax - /TotArea\n\t#\n\tg <- ggplot(ff1, aes(y=delta_prop_max_patch,x=year,colour=is_signif)) + theme_bw() +\n\t\tgeom_point(shape=19) + facet_grid(threshold~regsub) + \n\t\tylab(expression(Delta~RS[max])) + scale_colour_viridis(discrete = T,guide=F,direction = -1) + \n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0),plot.title = element_text(hjust = 0.5)) +\n\t\tstat_quantile(quantiles=c(.10,.90),linetype=2)\n\t\n\tprint(g)\n}\n\n# Plot fluctuations of Absolute max patch Smax by year and faceted by threshold\n#\n# pst: pstat_threshold data frame\n# regions: vector of regions to include\nplot_Smax_Fluctuations_yearThreshold <- function(pst,regions){\n\t\n\tff1 <- filter(pst,regsub %in% regions) \n\t#\n\t# Fluctuations around the mean Smax - /TotArea\n\t#\n\tg <- ggplot(ff1, aes(y=delta_max_patch,x=year,colour=region)) + theme_bw() +\n\t\tgeom_point(shape=19) + facet_wrap(~threshold) +\n\t\tylab(expression(Delta~S[max]~~~(km^2))) + scale_colour_brewer(palette=\"Set1\",name=\"Sub-Region\",guide=F) +\n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0)) +\n\t\tstat_quantile(quantiles=c(.10,.50,.90),linetype=2)\n\t\n\tprint(g)\n}\n\n\n#\n#' Call python routine to estimate distributions and likelihood ratio tests \n#'\n#' @param binDir folder with bin files with patch sizes\n#'\n#' @return data frame with results\n#'\ncall_python_powlawfit <- function(binDir,fit=TRUE){\n\t\n\tps <- paste0(\"python \", oldcd,\"/Code/powlawfit.py 1\")\n\n\tsetwd(binDir)\n\tif(fit){\n\t\tfile.remove(\"fittedDistributions.txt\")\n\t\t\n\t\tsystem(ps)\n\t}\n\tpyfit <- read.table(\"fittedDistributions.txt\", header=TRUE,sep=\"\\t\",stringsAsFactors=FALSE)\n\t#names(pyfit)\n\n\tpyfit1 <- pyfit %>% group_by(model_name,file_name) %>% do( {\n\t\tss <- strsplit(.$file_name,\"_\")\n\t\tregion <- ss[[1]][2]\n\t\tsubregion <- ss[[1]][3]\n\t\tthreshold <- ss[[1]][4]\n\t\tyear <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",.$file_name)\n\t\tdata.frame(region=region,subregion=subregion,threshold=threshold,year=year)})\n\t\n\tpyfit <- pyfit %>% inner_join(pyfit1) %>% arrange(region,subregion,threshold)\n\t\n\t# Lognormal without restriction has mu negative which results in a 99.7% probability is outside the range of patch data\n\t#\n\t\n\tlNorm <- pyfit %>% ungroup() %>% filter(grepl(\"Log.*\",model_name)) %>% select(model_name:xmin) %>% mutate(mu=exp(par1),si=exp(par2),lowd=mu/si^3,hid=mu*si^3)\n\n\tprint(lNorm %>% mutate(higher= hid>.01) %>% group_by(model_name,higher) %>% summarize(n=n(), mlow=mean(lowd),mhi=mean(hid)) %>% mutate(modFreq= n/sum(n)))\n\t#\n\t#\n\tpyfit <- filter(pyfit, model_name!=\"LogNorm\")\n\t\n\tpyfit <- pyfit %>% group_by(file_name) %>% mutate(delta_AICc= AICc - min(AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t norm_AICc_w = exp(-0.5*delta_AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=exp(-0.5*delta_AICc)/sum(norm_AICc_w))\n\t\n\tsetwd(oldcd)\n\t\n\treturn(list(pyfit=pyfit,lNorm=lNorm))\n\t}\n\n\n#\n#' Call python routine to estimate distributions and likelihood ratio tests \n#' for delta_Smax and delta_RSmax\n#'\n#' @param binDir folder with bin files with patch sizes\n#'\n#' @return data frame with results\n#'\ncall_python_powlawfit_delta_threshold <- function(ff,binDir,fit=TRUE){\n\t\n\tsetwd(binDir)\n\n\tgroup_by(ff, regsub,threshold) %>% do( nothing={ \t\n\t\tzz <- file(paste0(\"delta_\", .$regsub,\"_\",.$threshold,\"_.bin\")[1], \"wb\")\n\t\twriteBin(.$delta_max_patch,zz) \n\t\tclose(zz)\n\t\treturn(.$regsub)\n\t })\n\n\n\n\tps <- paste0(\"python \", oldcd,\"/Code/powlawfit.py 0\")\n\n\tif(fit){\n\t\tfile.remove(\"fittedDistributions.txt\")\n\t\t\n\t\tsystem(ps)\n\t}\n\tpyfit <- read.table(\"fittedDistributions.txt\", header=TRUE,sep=\"\\t\",stringsAsFactors=FALSE)\n\t#names(pyfit)\n\n\tpyfit1 <- pyfit %>% group_by(model_name,file_name) %>% do( {\n\t\tss <- strsplit(.$file_name,\"_\")\n\t\tregsub <- ss[[1]][2]\n\t\tthreshold <- ss[[1]][3]\n\t\tdata.frame(regsub=regsub,threshold=threshold)})\n\t\n\tpyfit <- pyfit %>% inner_join(pyfit1) %>% arrange(regsub,threshold)\n\t\n\t#\n\t#\n\tpyfit <- filter(pyfit, model_name!=\"LogNormPos\")\n\tpyfit <- filter(pyfit, model_name!=\"PowerExp\")\n\t\n\tpyfit <- pyfit %>% group_by(file_name) %>% mutate(delta_AICc= AICc - min(AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t norm_AICc_w = exp(-0.5*delta_AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=exp(-0.5*delta_AICc)/sum(norm_AICc_w)) %>% \n\t\tungroup() %>% select( -file_name )\n\t\n\tunlink(\"*.bin\")\n\tsetwd(oldcd)\n\t\n\treturn(pyfit=pyfit)\n\t}", "meta": {"hexsha": "7b43388f1e739c248a804389a764f61485919f6d", "size": 44971, "ext": "r", "lang": "R", "max_stars_repo_path": "R/power_fun.r", "max_stars_repo_name": "lsaravia/CriticalGlobalForest", "max_stars_repo_head_hexsha": "36d5be4ee16706708923bbcff3ace5c0a31576c7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/power_fun.r", "max_issues_repo_name": "lsaravia/CriticalGlobalForest", "max_issues_repo_head_hexsha": "36d5be4ee16706708923bbcff3ace5c0a31576c7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-12-01T15:29:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-30T13:05:54.000Z", "max_forks_repo_path": "R/power_fun.r", "max_forks_repo_name": "lsaravia/CriticalGlobalForest", "max_forks_repo_head_hexsha": "36d5be4ee16706708923bbcff3ace5c0a31576c7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-05T21:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T21:48:21.000Z", "avg_line_length": 31.1649341649, "max_line_length": 209, "alphanum_fraction": 0.6623601877, "num_tokens": 15188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3588787298227148}}
{"text": "#Generacion de la Linea de Muerte para la UBA año 2020\n#Solo necesita 32GB de memoria RAM , 8 vCPU y una hora para correr\n\n#limpio la memoria\nrm( list=ls() ) #remove all objects\ngc() #garbage collection\n\nrequire(\"data.table\")\nrequire(\"lightgbm\")\nrequire(\"DiceKriging\")\nrequire(\"mlrMBO\")\n\n#en estos archivos queda el resultado\nkbayesiana <- paste0(\"~/buckets/b2/opt_bayesiana_lgbm/linea_de_muerte.RDATA\")\n\nkBO_iter <- 10 #cantidad de iteraciones de la Optimizacion Bayesiana\n\n#------------------------------------------------------------------------------\n#esta es la funcion de ganancia, que se busca optimizar\n#se usa internamente a LightGBM\n#se calcula internamente la mejor ganancia para todos los puntos de corte posibles\n\nfganancia_logistic_lightgbm <- function(probs, data) \n{\n vlabels <- getinfo(data, \"label\")\n\n tbl <- as.data.table( list( \"prob\"=probs, \"gan\"= ifelse( vlabels==1, 29250, -750 ) ) )\n\n setorder( tbl, -prob )\n tbl[ , gan_acum := cumsum( gan ) ]\n gan <- max( tbl$gan_acum )\n\n return( list( name= \"ganancia\", value= gan, higher_better= TRUE ) )\n}\n#------------------------------------------------------------------------------\n#funcion que va a optimizar la Bayesian Optimization\n\nestimar_lightgbm <- function( x )\n{\n modelo <- lgb.train(data= dBO_train,\n objective= \"binary\", #la clase es binaria\n eval= fganancia_logistic_lightgbm, #esta es la fuciona optimizar\n valids= list( valid1= dBO_test1 ),\n first_metric_only= TRUE,\n metric= \"custom\", #ATENCION tremendamente importante\n num_iterations= 999999, #un numero muy grande\n early_stopping_rounds= 200,\n min_data_in_leaf= as.integer( x$pmin_data_in_leaf ),\n feature_fraction= 0.25,\n learning_rate= 0.02,\n feature_pre_filter= FALSE,\n verbose= -1,\n seed= 102191\n )\n\n ganancia1 <- unlist(modelo$record_evals$valid1$ganancia$eval)[ modelo$best_iter ] \n\n #esta es la forma de devolver un parametro extra\n attr(ganancia1 ,\"extras\" ) <- list(\"pnum_iterations\"= modelo$best_iter )\n\n cat( modelo$best_iter, ganancia1, \"\\n\" )\n\n return( ganancia1 )\n}\n#------------------------------------------------------------------------------\n#Aqui comienza el programa\ndataset <- fread(\"~/buckets/b1/datasets/fe_exthist.txt.gz\")\n\ncampos_lags <- setdiff( colnames(dataset) , c(\"clase_ternaria\",\"clase01\", \"numero_de_cliente\",\"foto_mes\") )\n\n#agreglo los lags de orden 1\nsetorderv( dataset, c(\"numero_de_cliente\",\"foto_mes\") )\ndataset[, paste0( campos_lags, \"_lag1\") :=shift(.SD, 1, NA, \"lag\"), by=numero_de_cliente, .SDcols= campos_lags]\n\n#agrego los deltas de los lags, de una forma nada elegante\nfor( vcol in campos_lags )\n{\n dataset[, paste0(vcol, \"_delta1\") := get( vcol) - get(paste0( vcol, \"_lag1\"))]\n}\n \n#paso la clase a binaria que tome valores {0,1} enteros\ndataset[ , clase01 := ifelse( clase_ternaria==\"BAJA+2\", 1L, 0L) ]\n\n\n#los campos que se van a utilizar, intencionalmente no uso numero_de_cliente\ncampos_buenos <- setdiff( colnames(dataset) , c(\"clase_ternaria\",\"clase01\",\"numero_de_cliente\") )\n\n#hago undersampling de los negativos\n#me quedo con TODOS los positivos, pero con solo el 5% de los negativos\nset.seed(102191)\ndataset[ , azar:= runif( nrow(dataset) ) ]\n\ndataset[ ( foto_mes>=201701 & foto_mes<=202003 & foto_mes!=201912 & ( clase01==1 | azar<=0.05) ), BO_train := 1L]\n\n#Testeo en 201902, el mismo mes pero un año antes\ndataset[ foto_mes==201912, BO_test1 := 1L]\n\n#dejo los datos en el formato que necesita LightGBM\ndBO_train <- lgb.Dataset( data = data.matrix( dataset[ BO_train==1, campos_buenos, with=FALSE]),\n label = dataset[ BO_train==1, clase01],\n free_raw_data = TRUE\n )\n\ndBO_test1 <- lgb.Dataset( data = data.matrix( dataset[ BO_test1==1, campos_buenos, with=FALSE]),\n label = dataset[ BO_test1==1, clase01],\n free_raw_data = TRUE\n )\n\ndataset_aplicacion <- copy( dataset[ foto_mes==202005, ] )\n\n#libero la memoria borrando el dataset\nrm(dataset)\ngc()\n\n#Aqui comienza la configuracion de la Bayesian Optimization\nconfigureMlr(show.learner.output = FALSE)\n\n#configuro la busqueda bayesiana, los hiperparametros que se van a optimizar\n#por favor, no desesperarse por lo complejo\nobj.fun <- makeSingleObjectiveFunction(\n name = \"OptimBayesiana\", #un nombre que no tiene importancia\n fn = estimar_lightgbm, #aqui va la funcion que quiero optimizar\n minimize= FALSE, #quiero maximizar la ganancia \n par.set = makeParamSet(\n makeNumericParam(\"pmin_data_in_leaf\", lower= 10, upper= 30000 )\n ),\n has.simple.signature = FALSE, #porque le pase los parametros con makeParamSet\n noisy= TRUE\n )\n\nctrl <- makeMBOControl( save.on.disk.at.time = 600, save.file.path = kbayesiana )\nctrl <- setMBOControlTermination(ctrl, iters = kBO_iter )\nctrl <- setMBOControlInfill(ctrl, crit = makeMBOInfillCritEI())\n\nsurr.km <- makeLearner(\"regr.km\", predict.type= \"se\", covtype= \"matern3_2\", control = list(trace = FALSE))\n\nif(!file.exists(kbayesiana))\n{\n #lanzo la busqueda bayesiana\n run <- mbo(obj.fun, learner = surr.km, control = ctrl)\n} else {\n #retoma el procesamiento en donde lo dejo\n run <- mboContinue( kbayesiana ) \n}\n\n#En run$x$pmin_data_in_leaf ha quedo el optimo\n#------------------------------------------------------------------------------\n\n#calculo el modelo final\nmodelo_final <- lgb.train(data= dBO_train,\n objective= \"binary\",\n eval= fganancia_logistic_lightgbm,\n valids= list( valid1= dBO_test1 ),\n first_metric_only= TRUE,\n metric= \"custom\",\n num_iterations= 999999,\n early_stopping_rounds= 200,\n learning_rate= 0.02, #ATENCION, este es el valor que se cambia\n min_data_in_leaf= as.integer( run$x$pmin_data_in_leaf ),\n feature_pre_filter= FALSE,\n feature_fraction= 0.25,\n verbose= -1,\n seed= 102191\n )\n\n#Genero los archivos que voy a probar contra el Leaderboard Publico y quedarme con el mejor\nprediccion_202005 <- predict( modelo_final, data.matrix( dataset_aplicacion[ , campos_buenos, with=FALSE]))\n\n#Genero posibles probabilidades de corte, tener en \nfor( vprob_corte in (25:25)/100 ) #de 0.15 a 0.35\n{\n entrega <- as.data.table( list( \"numero_de_cliente\"= dataset_aplicacion[ , numero_de_cliente], \n \"estimulo\"= (prediccion_202005> vprob_corte) ) )\n\n #genero el archivo de salida\n fwrite( entrega, logical01=TRUE, sep=\",\", file= paste0(\"~/buckets/b1/work/BORRADOR_lineademuerte_04_\", vprob_corte*100, \".csv\") )\n \n data = data.table('numero_de_cliente' = dataset_aplicacion[, numero_de_cliente], 'prob' = prediccion_202005)\n fwrite(data, sep = ',', file = paste0(\"~/buckets/b1/work/BORRADOR_lineademuerte_04.probs\"))\n}\n\n#Se deben probar con el metodo de busqueda binaria contra el leaderboard publico las salidas, y quedarse con el mejor\n\n ", "meta": {"hexsha": "409183875a6811d8f62be8931ac1a03143c2d3b0", "size": 7561, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/lineademuerte.r", "max_stars_repo_name": "miglesias91/dmeyf", "max_stars_repo_head_hexsha": "6b73adacd2f23644b8a14efd784d038c5ec79157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/lineademuerte.r", "max_issues_repo_name": "miglesias91/dmeyf", "max_issues_repo_head_hexsha": "6b73adacd2f23644b8a14efd784d038c5ec79157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lineademuerte.r", "max_forks_repo_name": "miglesias91/dmeyf", "max_forks_repo_head_hexsha": "6b73adacd2f23644b8a14efd784d038c5ec79157", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0923913043, "max_line_length": 132, "alphanum_fraction": 0.6078561037, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3585257198641219}}
{"text": "model_cumulttfrom <- function (calendarMoments_t1 = c('Sowing'),\n calendarCumuls_t1 = c(0.0),\n cumulTT = 8.0){\n #'- Name: CumulTTFrom -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: CumulTTFrom Model\n #' * Author: Pierre Martre\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA Montpellier\n #' * Abstract: Calculate CumulTT \n #'- inputs:\n #' * name: calendarMoments_t1\n #' ** description : List containing appearance of each stage at previous day\n #' ** variablecategory : state\n #' ** datatype : STRINGLIST\n #' ** default : ['Sowing']\n #' ** unit : \n #' ** inputtype : variable\n #' * name: calendarCumuls_t1\n #' ** description : list containing for each stage occured its cumulated thermal times at previous day\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** default : [0.0]\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: cumulTT\n #' ** description : cumul TT at current date\n #' ** datatype : DOUBLE\n #' ** variablecategory : auxiliary\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 8.0\n #' ** unit : °C d\n #' ** inputtype : variable\n #'- outputs:\n #' * name: cumulTTFromZC_65\n #' ** description : cumul TT from Anthesis to current date \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : °C d\n #' * name: cumulTTFromZC_39\n #' ** description : cumul TT from FlagLeafLiguleJustVisible to current date \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : °C d\n #' * name: cumulTTFromZC_91\n #' ** description : cumul TT from EndGrainFilling to current date \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : °C d\n cumulTTFromZC_65 <- 0.0\n cumulTTFromZC_39 <- 0.0\n cumulTTFromZC_91 <- 0.0\n if ('Anthesis' %in% calendarMoments_t1)\n {\n cumulTTFromZC_65 <- cumulTT - calendarCumuls_t1[which(calendarMoments_t1 %in% 'Anthesis')]\n }\n if ('FlagLeafLiguleJustVisible' %in% calendarMoments_t1)\n {\n cumulTTFromZC_39 <- cumulTT - calendarCumuls_t1[which(calendarMoments_t1 %in% 'FlagLeafLiguleJustVisible')]\n }\n if ('EndGrainFilling' %in% calendarMoments_t1)\n {\n cumulTTFromZC_91 <- cumulTT - calendarCumuls_t1[which(calendarMoments_t1 %in% 'EndGrainFilling')]\n }\n return (list (\"cumulTTFromZC_65\" = cumulTTFromZC_65,\"cumulTTFromZC_39\" = cumulTTFromZC_39,\"cumulTTFromZC_91\" = cumulTTFromZC_91))\n}", "meta": {"hexsha": "a86e13953e066fcf3a691778ec2353d565fdecf6", "size": 3901, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Cumulttfrom.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Cumulttfrom.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Cumulttfrom.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 52.0133333333, "max_line_length": 133, "alphanum_fraction": 0.4386054858, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3581421435540733}}
{"text": "## This script replicates Shiller 1981 using a slightly different data set\n## The replication code was written by Caraiani and Anghel (forthcoming)\n\nbehavioral_equity_market <- function(data_vintage, path_fig) {\n path_data <- here(\"data/vintages\", data_vintage)\n \n ## First specify the packages of interest\n packages <- c(\"ggplot2\", \"readxl\", \"dplyr\", \"tidyr\", \"dplyr\", \"purrr\", \"stringr\",\n \"Quandl\", \"viridis\", \"ggpmisc\", \"readstata13\", \"imfr\", \"writexl\", \"fredr\")\n \n source(here(\"src/check_packages.r\"))\n check_packages(packages) # Check whether packages are installed already and load them \n \n ## Collect data on S&P 500 prices and dividends from QUANDL\n ## Note: Quandl does not requires an API unless user exceeds 50 calls a day.\n \n curr_year <- as.double(format(Sys.Date(), \"%Y\")) # don't change this\n \n first_years <- c(1871, 1947, 1960, 1980)\n # first_years <- c(1871)\n last_years <- c(1947, 1979, 2009, as.double(format(Sys.Date(), \"%Y\")))\n # last_years <- c(1979)\n \n reg_results <- data.frame(matrix(ncol = 5, nrow = 0))\n reg_columns <- c(\"first year\", \"last year\", \"specification\", \"b\", \"r2\")\n colnames(reg_results) <- reg_columns\n \n for (f in first_years) {\n first_year <- f\n \n for (t in last_years) {\n last_year <- t # can be different from current year\n if (last_year <= first_year) next # skip iteration if last year is smaller than first year\n \n #######################################\n ########### DATA PREP #################\n #######################################\n # Read data first\n div <- readRDS(file = here(path_data, \"sp500_dividends.rds\")) \n price <- readRDS(file = here(path_data, \"sp500_prices.rds\"))\n\n # Prep data: Dividends\n div$month <- as.double(format(div$Date, \"%m\"))\n div$year <- as.double(format(div$Date, \"%Y\"))\n div <- subset(div, (year <= last_year & year >= first_year))\n div <- div[order(div$Date), ]\n div <- div %>% # There may be multiple observations per year - we will choose the first observation of every year \n group_by(year) %>%\n filter(row_number() == 1)\n div$Date <- format(div$Date,\"%Y\")\n div <- div %>% rename(div = Value) %>% select(-c(\"month\", \"year\"))\n\n # Prep data: Prices\n price$month <- as.double(format(price$Date, \"%m\"))\n price$year <- as.double(format(price$Date, \"%Y\"))\n price$day <- as.double(format(price$Date, \"%d\"))\n price <- subset(price, (year <= last_year & year >= first_year))\n price <- price[order(price$Date), ]\n price <- price %>% # There may be multiple observations per year so we need to choose the last observation of every year \n group_by(year) %>%\n filter(row_number() == 1)\n \n price$Date <- format(price$Date,\"%Y\")\n price <- price %>% rename(price = Value)\n price <- price %>% select(-c(\"day\", \"month\", \"year\"))\n\n ## Add interest rates from JST database\n rawdata <- read.dta13(here(path_data, \"JSTdatasetR5.dta\"))\n myvars <- c(\"year\", \"country\", \"cpi\", \n \"stir\", # short-term gov bills\n \"ltrate\" # long-term gov bonds\n )\n rates <- rawdata[rawdata$country == \"USA\", myvars]\n rates <- rates %>% \n rename(Date = year) %>% \n mutate(Date = as.character(Date),\n stir = stir/100,\n ltrate = ltrate/100)\n\n ## Merging and indexing\n df <- left_join(div, price, by = \"Date\")\n df <- left_join(df, rates, by = \"Date\")\n\n df$Date <- as.Date(df$Date, format = \"%Y\")\n df$year <- as.double(format(df$Date, \"%Y\"))\n df <- df[order(df$year), ] # Note: the data must be ordered in increasing order of time for the Shiller algo to work \n\n df <- df %>%\n mutate(div_index = div/div[year == first_year]*100) %>%\n mutate(price_index = price/price[year == first_year]*100) %>%\n mutate(infl = (cpi/lag(cpi, 1) - 1)) %>% # inflation defined as growth in yearly CPI inflation \n mutate(stir_real = (1 + stir) / (1 + infl) - 1) %>% # deflate nominal shot-term interest rates\n mutate(ltrate_real = (1 + ltrate) / (1 + infl) - 1) %>% # deflate nominal long-term interest rates\n mutate(price_div_ratio = price / div,\n div_price_ratio = div / price) %>%\n mutate(price_lead5 = lead(price, n = 5),\n annual_return_5yr = (price_lead5/price)^(1/5) - 1, # real annual returns\n annual_return_5yr_minus_stir = annual_return_5yr - stir_real, \n annual_return_5yr_minus_ltrate = annual_return_5yr - ltrate_real, \n year = as.double(format(Date, \"%Y\")),\n ) %>%\n mutate(return_5yr = (1 + annual_return_5yr)^5 - 1, # real returns over the whole period\n return_5yr_minus_stir = (1 + annual_return_5yr_minus_stir)^5 - 1,\n return_5yr_minus_ltrate = (1 + annual_return_5yr_minus_ltrate)^5 - 1)\n\n \n ## Shiller method of detrending data and constructing PV of dividends\n \n # Compute long run exponential growth rate (last observation - first observation)\n g <- (df[df$year==last_year, \"price\"] / df[df$year==first_year, \"price\"]) ^ (1/(nrow(df)-1)) - 1\n\n # Detrend prices\n df$price_detrended <- df$price\n for (i in 1:nrow(df)) {\n df[i, \"price_detrended\"] <- df[i, \"price_detrended\"] / (1+g)^(i-nrow(df))\n }\n\n # Detrend dividends\n df$div_detrended <- df$div\n for (i in 1:nrow(df)) {\n df[i, \"div_detrended\"] <- df[i, \"div_detrended\"] / (1+g)^(i-nrow(df))\n }\n\n # Compute constant discount rate as the mean yield of stocks over chosen period\n r <- mean(df$div_detrended) / mean(df$price_detrended)\n\n # Set terminal price \n tp <- mean(df$price_detrended)\n\n # Compute fundamental values\n df$p_star <- df$price_detrended\n df[nrow(df),\"p_star\"] <- tp\n for (i in (nrow(df)-1):1) { \n df[i,\"p_star\"] = (df[i+1,\"p_star\"] + df[i,\"div_detrended\"]) / (1 + r)\n }\n \n #######################################\n ########### PLOTTING ##################\n #######################################\n \n ## PLOTTING Shiller graph\n # load the formatting and saving settings from another script\n source(here(\"src/format_plots.r\"))\n source(here(\"src/save_plots.r\"))\n \n if (last_year - first_year <= 60) {\n xticks = 10\n } else {\n xticks = 20\n }\n xlimits <- c(as.double(first_year), as.double(format(Sys.Date(), \"%Y\")))\n \n # Wide to long format (better for ggplot)\n df_tmp <- df %>%\n select(c(\"price_detrended\", \"p_star\", \"year\")) %>%\n pivot_longer(c(\"price_detrended\", \"p_star\"), names_to = \"series\", values_to = \"value\") \n df_tmp$series <- gsub(\"price_detrended\", \"Actual\", df_tmp$series, fixed = TRUE)\n df_tmp$series <- gsub(\"p_star\", \"Expected\", df_tmp$series, fixed = TRUE)\n \n ggplot(data = df_tmp, aes(x = year, y = value)) +\n geom_line(aes(color = series, linetype = series), size = 2) +\n scale_x_continuous(breaks=seq(xlimits[1], xlimits[2], xticks)) +\n labs(y = \"\", x = \"\", title = \"\") + \n format +\n scale_linetype_manual(values = c(\"solid\", \"dotdash\")) +\n scale_color_manual(values = c(purple, green))\n \n # Save\n savefolder <- here(path_fig, \"behavioral_finance\")\n filename <- paste(\"equity_market_\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n ## PLOTTING price to dividend against subsequent 7-year return\n df_tmp <- na.omit(df)\n nth_year <- 5 # Label every nth year\n df_tmp <- df_tmp %>% mutate(year = as.character(year))\n df_tmp$year[seq(1, nrow(df_tmp), nth_year)] <- NA\n formula = y ~ x\n xlimits <- c(0, NA)\n \n ggplot(data = df_tmp, aes(x = div_price_ratio, y = annual_return_5yr)) +\n geom_smooth(method = lm, formula = formula, se = FALSE, color = purple, size = 2) +\n geom_text(aes(label = year), fontface = \"bold\", size = 5, color = green,\n hjust = 0, nudge_x = 0, check_overlap = TRUE) +\n stat_poly_eq(formula = formula,\n aes(label = paste(stat(rr.label), sep = \", \")),\n label.x = \"right\", label.y = \"top\", size = 6, geom = \"label_npc\"\n ) +\n xlim(xlimits) +\n labs(\n x = \"Dividend-to-price ratio\",\n y = \"5-year annual return\",\n ) + \n format \n \n filename <- paste(\"equity_market_pd_return_\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n ggplot(data = df_tmp, aes(x = div_price_ratio, y = annual_return_5yr_minus_stir)) +\n geom_smooth(method = lm, formula = formula, se = FALSE, color = purple, size = 2) +\n geom_text(aes(label = year), fontface = \"bold\", size = 5, color = green,\n hjust = 0, nudge_x = 0, check_overlap = TRUE) +\n stat_poly_eq(formula = formula,\n aes(label = paste(stat(rr.label), sep = \", \")),\n label.x = \"right\", label.y = \"top\", size = 6, geom = \"label_npc\"\n ) +\n xlim(xlimits) +\n labs(\n x = \"Dividend-to-price ratio\",\n y = \"5-year annual return - 3-month Bill yield\",\n ) + \n format \n \n filename <- paste(\"equity_market_pd_return_stir\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n ggplot(data = df_tmp, aes(x = div_price_ratio, y = annual_return_5yr_minus_ltrate)) +\n geom_smooth(method = lm, formula = formula, se = FALSE, color = purple, size = 2) +\n geom_text(aes(label = year), fontface = \"bold\", size = 5, color = green,\n hjust = 0, nudge_x = 0, check_overlap = TRUE) +\n stat_poly_eq(formula = formula,\n aes(label = paste(stat(rr.label), sep = \", \")),\n label.x = \"right\", label.y = \"top\", size = 6, geom = \"label_npc\"\n ) +\n xlim(xlimits) +\n labs(\n x = \"Dividend-to-price ratio\",\n y = \"5-year annual return - 10-year Bond yield\",\n ) + \n format \n \n filename <- paste(\"equity_market_pd_return_ltrate\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n # caption <- paste(\"Data provider: Quandl. Original data source: Standard & Poor's and Robert Shiller. \n # Period: \", as.character(first_year), \" - \", as.character(last_year), \" Note: \n # The 7-year return is calculated as the 7-year growth in prices.\", sep =\"\") \n \n #################################\n ########## REGRESSIONS ##########\n #################################\n \n # model<- lm(annual_return_5yr ~ price_div_ratio, data = df_tmp)\n # r1 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_stir ~ price_div_ratio, data = df_tmp)\n # r2 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_ltrate ~ price_div_ratio, data = df_tmp)\n # r3 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr ~ div_price_ratio, data = df_tmp)\n # r4 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_stir ~ div_price_ratio, data = df_tmp)\n # r5 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_ltrate ~ div_price_ratio, data = df_tmp)\n # r6 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(return_5yr ~ div_price_ratio, data = df_tmp)\n # r7 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(return_5yr_minus_stir ~ div_price_ratio, data = df_tmp)\n # r8 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(return_5yr_minus_ltrate ~ div_price_ratio, data = df_tmp)\n # r9 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # reg_results <- do.call(rbind, list(reg_results, r1, r2, r3, r4, r5, r6, r7, r8, r9)) \n # colnames(reg_results) <- reg_columns\n }\n \n }\n\n # write_xlsx(reg_results, \"table/reg_results_cochrane_2011.xlsx\")\n}", "meta": {"hexsha": "074a418190244435db4fb37f01522b6815a998bf", "size": 14871, "ext": "r", "lang": "R", "max_stars_repo_path": "code/lec1/shiller_graph.r", "max_stars_repo_name": "tudorschlanger/macro-finance-lectures", "max_stars_repo_head_hexsha": "fa658fefce90362c0e5db671be39009e14ce6e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/lec1/shiller_graph.r", "max_issues_repo_name": "tudorschlanger/macro-finance-lectures", "max_issues_repo_head_hexsha": "fa658fefce90362c0e5db671be39009e14ce6e31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/lec1/shiller_graph.r", "max_forks_repo_name": "tudorschlanger/macro-finance-lectures", "max_forks_repo_head_hexsha": "fa658fefce90362c0e5db671be39009e14ce6e31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6859205776, "max_line_length": 142, "alphanum_fraction": 0.5148947616, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.3570914909196419}}
{"text": "## Assorted routines for manipulation of\r\n## Zernike polynomials, interferogram analysis,\r\n## and other forms of optical testing\r\n\r\n## Author: M.L. Peck (mlpeck54@gmail.com)\r\n## Language: R (http://www.r-project.org/)\r\n## Copyright (c) 2004-2021, M.L. Peck\r\n\r\n\r\n\r\n\r\n## greyscale\r\n\r\ngrey256 <- gray(seq(0,1,length=256))\r\ngray256 <- grey256\r\n\r\n## A rainbow that may be better than R's rainbow() color palette\r\n\r\nrygcb <- colorRampPalette(c(\"red\", \"yellow\", \"green\", \"cyan\", \"blue\"), space = \"Lab\",\r\n interpolate=\"spline\")\r\n \r\n## Yet another rainbow made up of additive and subtractive primaries\r\n\r\nrygcbm <- colorRampPalette(c(\"red\", \"yellow\", \"green\", \"cyan\", \"blue\", \"magenta\"),\r\n\t\t\tspace=\"Lab\", interpolate=\"spline\")\r\n\r\n\r\n## comparison plot of n wavefront estimates\r\n\r\nplotn <- function(...,\r\n labels=NULL, addContours=FALSE,\r\n wftype=\"net\", col=rygcb(400), qt=c(.01, .99)) {\r\n\tfits <- list(...)\r\n\tnwf <- length(fits)\r\n\twfget <- paste(\"wf\",wftype,sep=\".\")\r\n\twfi <- get(wfget, pos=fits[[1]])\r\n\tnr <- nrow(wfi)\r\n\tnc <- ncol(wfi)\r\n\twfs <- array(0, dim=c(nr,nc,nwf))\r\n\twfs[,,1] <- wfi\r\n\tfor (i in 2:nwf) wfs[,,i] <- get(wfget,pos=fits[[i]])\r\n\trm(fits)\r\n\tif(is.null(labels)) labels=1:nwf\r\n\r\n\trdiff <- matrix(0,nwf*(nwf-1)/2,2)\r\n\tk <- 1\r\n\tfor (i in 1:(nwf-1)) {\r\n\t\tfor (j in (i+1):nwf) {\r\n\t\t\trdiff[k,] <- quantile(wfs[,,i]-wfs[,,j], probs=qt, na.rm=TRUE)\r\n\t\t\tk <- k+1\r\n\t\t}\r\n\t}\r\n\tzlim <- range(rdiff)\r\n\tif (tolower(.Platform$OS.type)==\"windows\") {\r\n windows(width = 5*nwf, height = 5*nwf)\r\n } else {\r\n X11(width = 5*nwf,height = 5*nwf)\r\n }\r\n\tpar(mar=c(0,0,2,0))\r\n\tsplit.screen(figs=c(nwf,nwf))\r\n\tfor (i in 1:nwf) {\r\n\t screen(i)\r\n\t wfi <- wfs[,,i]\r\n\t class(wfi) <- \"pupil\"\r\n\t plot(wfi, col=col, addContours=addContours, eqa=(wftype==\"net\"), axes=FALSE)\r\n\t title(main=paste(labels[i],\"rms=\",format(pupilrms(wfi),digits=3)))\r\n\t}\r\n\tscr <- nwf+1\r\n\tfor (row in 1:(nwf-1)) {\r\n\t screen(scr)\r\n\t plot(0:1,0:1,type=\"n\",axes=FALSE)\r\n\t text(0.5,0.5,labels[row])\r\n\t scr <- scr+row\r\n\t for (i in (row+1):nwf) {\r\n\t\tscreen(scr)\r\n\t\timage(1:nr,1:nc,wfs[,,row]-wfs[,,i],col=grey256,asp=1,axes=FALSE,zlim=zlim,useRaster=TRUE)\r\n\t\ttitle(main=paste(\"rms diff =\",format(pupilrms(wfs[,,row]-wfs[,,i]), digits=3)))\r\n\t\tscr <- scr+1\r\n\t }\r\n\t}\r\n\tclose.screen(all.screens=T)\r\n}\r\n\r\n## plot cross sections through a wavefront map\r\n\r\nplotxs <- function(wf, cp, theta0=0, ylim=NULL, N=4, n=101,\r\n\tcol0=\"black\", col=\"gray\", lty=2) {\r\n theta0 <- theta0*pi/180\r\n ixy <- seq(-1,1,length=n)\r\n theta <- (0:(N-1))*pi/N\r\n ix <- cp$rx*ixy\r\n iy <- cp$ry*ixy\r\n if (is.null(ylim)) ylim <- range(wf, na.rm=TRUE)\r\n plot(range(ixy),ylim, type=\"n\", xlab=\"rho\", ylab=\"Height\")\r\n for (i in 1:N) {\r\n\tiix <- round(cp$xc+cos(theta[i])*ix)\r\n\tiiy <- round(cp$yc+sin(theta[i])*iy)\r\n\tpoints(ixy, diag(wf[iix,iiy]), type=\"l\", col=col, lty=lty)\r\n }\r\n iix <- round(cp$xc+cos(theta0)*ix)\r\n iiy <- round(cp$yc+sin(theta0)*iy)\r\n points(ixy, diag(wf[iix,iiy]), type=\"l\", col=col0, lty=lty)\r\n}\r\n\r\n\r\n\r\n###########\r\n## Various fun stuff\r\n###########\r\n\r\n\r\n## Star test simulator & support routines\r\n\r\n## calculate phase values for wavefront at wavelength lambda\r\n## replaces NA values with 0\r\n\r\nwftophase <- function(X, lambda = 1) {\r\n phi <- exp(2i*pi*X/lambda)\r\n phi[is.na(phi)] <- 0\r\n phi\r\n}\r\n\r\n## puts matrix X into corner of npadded x npadded matrix\r\n## padded with zeroes\r\n\r\npadmatrix <- function(X, npad, fill=0) {\r\n nr <- nrow(X)\r\n nc <- ncol(X)\r\n xpad <- matrix(fill, npad, npad)\r\n xpad[1:nr,1:nc] <- X\r\n xpad\r\n}\r\n\r\n\r\n## extract a matrix from the center of a larger matrix\r\n\r\n\r\nsubmatrix <- function(X,size=255) {\r\n nr <- nrow(X)\r\n X[((nr-size)/2+1):((nr+size)/2),((nr-size)/2+1):((nr+size)/2)]\r\n}\r\n\r\n## shuffle quadrants of a 2d fft around to display as an image\r\n\r\n\r\nfftshift <- function(X) {\r\n nr <- nrow(X)\r\n XS <- matrix(0,nr,nr)\r\n XS[1:(nr/2),1:(nr/2)] <- X[(nr/2+1):nr,(nr/2+1):nr]\r\n XS[(nr/2+1):nr,(nr/2+1):nr] <- X[1:(nr/2),1:(nr/2)]\r\n XS[(nr/2+1):nr,1:(nr/2)] <- X[1:(nr/2),(nr/2+1):nr]\r\n XS[1:(nr/2),(nr/2+1):nr] <- X[(nr/2+1):nr,1:(nr/2)]\r\n XS\r\n}\r\n\r\n## computes & displays fraunhofer diffraction pattern\r\n## & mtf for wavefront described in zernike coefficients zcoef\r\n\r\nstartest <- function(wf=NULL, zcoef=NULL, maxorder=14L, phi=0,\r\n\tlambda = 1, defocus=5, cp=NULL,\r\n\tobstruct=NULL, \r\n\tnpad = 4, \r\n\tgamma=2, psfmag=2, displaymtf=TRUE, displaywf=FALSE) {\r\n\r\n if (tolower(.Platform$OS.type) == \"windows\") {\r\n windows(width=15, height=5) \r\n } else {\r\n x11(width=15,height=5)\r\n }\r\n screens<- split.screen(c(1,3))\r\n\r\n if (is.null(wf)) {\r\n wf <- pupil(zcoef=zcoef, maxorder=maxorder, phi=phi, piston=0)\r\n cp <- cp.default\r\n } else {\r\n if (is.null(cp)) {\r\n stop(\"must specify cp if wf is non-null\")\r\n }\r\n }\r\n nrow <- nrow(wf)\r\n ncol <- ncol(wf)\r\n wf.df <- pupil(zcoef=c(0, 0, 0, 1), maxorder=2, nrow=nrow, ncol=ncol, cp=cp)\r\n if (!is.null(obstruct)) {\r\n wf[is.na(wf.df)] <- NA\r\n }\r\n lx <- round(2*cp$rx)+1\r\n ly <- round(2*cp$ry)+1\r\n npad <- npad * .up2(lx,ly)\r\n\r\n phase <- wftophase(wf,lambda)\r\n up <- Mod(fft(padmatrix(phase,npad)))\r\n up <- up*up\r\n\r\n otf <- fft(up, inverse=TRUE)/npad^2\r\n otf <- otf[1:lx,1:ly]\r\n mtf <- Re(otf)\r\n mtf <- mtf/max(mtf)\r\n freqx <- seq(0,1,length=lx)\r\n freqy <- seq(0,1,length=ly)\r\n mtfideal <- 2/pi*(acos(freqx)-freqx*sqrt(1-freqx^2))\r\n\r\n nrpsf <- max(lx,ly)\r\n psf <- submatrix(fftshift(up),floor(nrpsf/psfmag))\r\n screen(screens[2])\r\n image(psf^(1/gamma),col=grey256,asp=1,bty='n', axes=FALSE, useRaster=TRUE)\r\n mtext(\"0\")\r\n\r\n\r\n if (defocus >5) nrpsf <- 2*nrpsf\r\n if (defocus >15) nrpsf <- npad\r\n\r\n phase <- wftophase(wf - defocus/3.46*lambda*wf.df, lambda)\r\n up <- Mod(fft(padmatrix(phase,npad)))\r\n up <- up*up\r\n psf2 <- submatrix(fftshift(up),nrpsf)\r\n screen(screens[1])\r\n image(psf2^(1/gamma),col=grey256, asp=1,bty='n', axes=FALSE, useRaster=TRUE)\r\n mtext(-defocus)\r\n\r\n phase <- wftophase(wf + defocus/3.46*lambda*wf.df, lambda)\r\n up <- Mod(fft(padmatrix(phase,npad)))\r\n up <- up*up\r\n psf2 <- submatrix(fftshift(up),nrpsf)\r\n screen(screens[3])\r\n image(psf2^(1/gamma),col=grey256,asp=1,bty='n',axes=FALSE, useRaster=TRUE)\r\n mtext(defocus)\r\n close.screen(all.screens=TRUE)\r\n\r\n\r\n if (displaywf) {\r\n if (tolower(.Platform$OS.type) == \"windows\") windows() else x11()\r\n plot(wf/lambda)\r\n }\r\n\r\n if (displaymtf) {\r\n if (tolower(.Platform$OS.type) == \"windows\") windows() else x11()\r\n plot(freqx,mtf[1,],type=\"l\",ylab=\"mtf\",xlab=\"relative frequency\")\r\n title(main='MTF vs. ideal')\r\n lines(freqy,mtf[,1])\r\n lines(freqx,mtfideal, lty=5)\r\n grid()\r\n }\r\n list(psf=psf, otf=otf, mtf=mtf)\r\n}\r\n\r\n## Kolmogorov turbulence\r\n\r\nturbwf <- function(friedratio=1, zlist=makezlist(2,40), reps=1) {\r\n require(mvtnorm)\r\n dimz <- length(zlist$n)\r\n cova <- matrix(0, nrow=dimz, ncol=dimz)\r\n c0 <- friedratio^(5/3)*gamma(14/3)*(4.8*gamma(1.2))^(5/6)*(gamma(11/6))^2/(2^(8/3)*pi)\r\n for (i in 1:dimz) {\r\n for (j in i:dimz) {\r\n if ((zlist$m[i] == zlist$m[j]) && (zlist$t[i] == zlist$t[j])) {\r\n n <- zlist$n[i]\r\n np <- zlist$n[j]\r\n cova[i,j] <- (-1)^((n+np-2*zlist$m[i])/2) * sqrt((n+1)*(np+1)) *\r\n gamma((n+np-5/3)/2)/(gamma((np-n+17/3)/2)*gamma((n-np+17/3)/2)*\r\n gamma((n+np+23/3)/2))\r\n cova[j,i] <- cova[i,j]\r\n }\r\n }\r\n }\r\n cova <- cova * c0/(4*pi^2)\r\n zcoef.turb <- rmvnorm(reps, mean=rep(0,dimz), sigma=cova)\r\n if (reps==1) zcoef.turb <- as.vector(zcoef.turb)\r\n list(zcoef.turb=zcoef.turb, V=cova)\r\n}\r\n\r\n\r\n\r\n## Foucault test simulator\r\n\r\nfoucogram <- function(wf, edgex = 0, phradius = 0, slit=FALSE, pad=4, gamma=1, \r\n map =FALSE, lev=0.5) {\r\n\r\n nr <- nrow(wf)\r\n nc <- ncol(wf)\r\n npad <- pad*nextn(max(nr,nc))\r\n phi<-padmatrix(wftophase(wf),npad)\r\n ca<-fftshift(fft(phi))\r\n u <- npad/2 + 1 + edgex\r\n ca[1:(u-phradius-1),]<-0\r\n ca[u,] <- .5*ca[u,]\r\n if (phradius>0) {\r\n if (slit) {\r\n for (i in 1:phradius) {\r\n f <- .5*(1+i/phradius)\r\n ca[(u+i),] <- f*ca[(u+i),]\r\n ca[(u-i),] <- (1-f)*ca[(u-i),]\r\n }\r\n } else {\r\n for (i in 1:phradius) {\r\n f <- .5 + i*sqrt(phradius^2-i^2)/(pi*phradius^2) + asin(i/phradius)/pi\r\n ca[(u+i),] <- f*ca[(u+i),]\r\n ca[(u-i),] <- (1-f)*ca[(u-i),]\r\n }\r\n }\r\n }\r\n ike <- Mod(fft(ca,inverse=T)[1:nr,1:nc])^2\r\n image(ike^(1/gamma),col=grey256,asp=nc/nr,axes=FALSE, useRaster=TRUE)\r\n if (map) {\r\n zmin <- floor(min(wf, na.rm=TRUE))\r\n zmax <- ceiling(max(wf, na.rm=TRUE))\r\n contour(wf,add=TRUE,levels=seq(zmin,zmax,by=lev),\r\n axes=FALSE,frame.plot=FALSE,col=\"red\")\r\n }\r\n ike/max(ike)\r\n}\r\n\r\n## Synthetic interferogram\r\n\r\n## notes: must have either non-null wf or zcoef. If wf is NULL\r\n## and cp is null make a new wavefront with current defaults\r\n## for matrix size and cp in pupil(), otherwise use the values\r\n## passed here. If wf is non-null zcoef is ignored\r\n## and the correct cp must be passed.\r\n\r\nsynth.interferogram <- function(wf=NULL, zcoef=NULL, maxorder=NULL, \r\n nr=nrow(wf), nc=ncol(wf), cp=NULL, \r\n phi=0, addzc=rep(0,4), fringescale=1, \r\n plots=TRUE) {\r\n if (is.null(wf)) {\r\n if (is.null(cp)) {\r\n wf <- pupil(zcoef=zcoef, maxorder=maxorder, phi=phi, piston=0)+\r\n pupil(zcoef=addzc, maxorder=2)\r\n nr <- nrow(wf)\r\n nc <- ncol(wf)\r\n cp <- cp.default\r\n } else {\r\n wf <- pupil(zcoef=zcoef, maxorder=maxorder, phi=phi, piston=0,\r\n nrow=nr, ncol=nc, cp=cp) +\r\n pupil(zcoef=addzc, maxorder=2, nrow=nr, ncol=nc, cp=cp)\r\n }\r\n } else {\r\n if (is.null(cp)) {\r\n stop(\"must specify a value for cp if wf is non-null\")\r\n }\r\n wf <- wf + pupil(zcoef=addzc, maxorder=2, nrow=nr, ncol=nc, cp=cp)\r\n }\r\n igram <- cos(2*pi*wf/fringescale)\r\n igram[is.na(igram)] <- 0\r\n class(igram) <- c(\"pupil\", class(igram))\r\n if (plots) plot(igram, col=grey256, addContours=FALSE)\r\n igram\r\n}\r\n \r\n \r\n#########\r\n## general utilities\r\n#########\r\n\r\n## crop an array\r\n\r\ncrop <- function(img, cp, npad=20) {\r\n nr <- dim(img)[1]\r\n nc <- dim(img)[2]\r\n xmin <- max(1, round(cp$xc-cp$rx-npad))\r\n xmax <- min(nr, round(cp$xc+cp$rx+npad))\r\n ymin <- max(1, round(cp$yc-cp$ry-npad))\r\n ymax <- min(nc, round(cp$yc+cp$rx+npad))\r\n cp.new <- cp\r\n cp.new$xc <- cp$xc-xmin+1\r\n cp.new$yc <- cp$yc-ymin+1\r\n if (length(dim(img)) > 2) img <- img[xmin:xmax,ymin:ymax,]\r\n else img <- img[xmin:xmax,ymin:ymax]\r\n list(im=img, cp=cp.new)\r\n}\r\n\r\n## general purpose 2D convolution using FFT's.\r\n\r\n## kern is the convolution kernel\r\n\r\nconvolve2d <- function(im, kern) {\r\n\tnr <- nrow(im)\r\n\tnc <- ncol(im)\r\n\tnrp <- nr + nrow(kern) - 1\r\n\tncp <- nc + ncol(kern) - 1\r\n\txs <- nrow(kern) %/% 2 + nrow(kern) %% 2\r\n\tys <- ncol(kern) %/% 2 + ncol(kern) %% 2\r\n\tnpad <- nextn(max(nrp, ncp))\r\n\tkern <- padmatrix(kern, npad=npad)\r\n\tim <- padmatrix(im, npad=npad)\r\n\tim.f <- Re(fft(fft(kern)*fft(im), inv=T))\r\n\tim.f <- im.f[xs:(nr+xs-1),ys:(nc+ys-1)]/(npad^2)\r\n\treturn(im.f)\r\n}\r\n\r\n\r\n## Gaussian blur. fw is the standard deviation\r\n## of the gaussian convolution kernel, in pixels.\r\n\r\ngblur <- function(X, fw = 0, details=FALSE) {\r\n if (fw == 0) return(X)\r\n XP <- X\r\n XP[is.na(XP)] <- 0\r\n nr <- nrow(X)\r\n nc <- ncol(X)\r\n ksize <- max(ceiling(4 * fw), 3)\r\n if ((ksize %% 2) == 0) ksize <- ksize+1\r\n xc <- (ksize %/% 2) + 1\r\n xs <- ((1:ksize)-xc)/fw\r\n gkern <- outer(xs, xs, function(x,y) (x^2+y^2))\r\n gkern <- exp(-gkern/2)\r\n gkern <- round(gkern/min(gkern))\r\n npad <- nextn(max(nr,nc)+ksize-1)\r\n XP <- padmatrix(XP, npad)\r\n kernp <- padmatrix(gkern, npad)\r\n XP <- Re(fft(fft(XP)*fft(kernp), inv=TRUE))/(npad^2)/sum(gkern)\r\n XP <- XP[xc:(nr+xc-1), xc:(nc+xc-1)]\r\n XP[is.na(X)] <- NA\r\n if (details) \r\n\t return(list(gkern=gkern, X=XP))\r\n else return(XP)\r\n}\r\n \r\n\r\n\r\n## Plot a complex matrix. \r\n## Maybe make cmat a class, so this becomes default plot routine?\r\n\r\nplot.cmat <- function(X, fn=\"Mod\", col=grey256, cp=NULL, zoom=1, gamma=1, ...) {\r\n\t ## define some possibly useful functions. Note Mod2 produces power spectrum\r\n\t \r\n\tlogMod <- function(X) log(1+Mod(X))\r\n\tMod2 <- function(X) Mod(X)^2\r\n\tlogMod2 <- function(X) log(Mod2(X))\r\n\tnr <- nrow(X)\r\n\tnc <- ncol(X)\r\n\txs <- seq(-nr/2,nr/2-1,length=nr)\r\n\tys <- seq(-nc/2,nc/2-1,length=nc)\r\n\tif (!is.null(cp)) {\r\n\t\txs <- (cp$rx/nr)*xs\r\n\t\tys <- (cp$ry/nc)*ys\r\n\t}\r\n\txsub <- max(1, floor(1+nr/2*(1-1/zoom))) : min(nr, ceiling(nr/2*(1+1/zoom)))\r\n\tysub <- max(1, floor(1+nc/2*(1-1/zoom))) : min(nc, ceiling(nc/2*(1+1/zoom)))\r\n\timage(xs[xsub], ys[ysub], (eval(call(fn, X))[xsub,ysub])^(1/gamma), \r\n\t col=col, asp=1, xlab=\"k_x\", ylab=\"k_y\", useRaster=TRUE, ...)\r\n}\r\n\r\n\r\npick.sidelobe <- function(imagedata, logm=FALSE, gamma=3) {\r\n\timagedata <- imagedata - mean(imagedata)\r\n\tnpad <- nextn(max(nrow(imagedata), ncol(imagedata)))\r\n\tim <- padmatrix(imagedata, npad=npad, fill=0)\r\n\tif (logm) fn <- \"logMod2\" else fn <- \"Mod\"\r\n\tim.fft <- fftshift(fft(im))\r\n\tplot.cmat(im.fft, fn=fn, gamma=gamma)\r\n\tcat(\"Click on the desired sidelobe peak\\n\")\r\n\tpeak <- locator(n=1, type=\"p\", col=\"red\")\r\n\tcat(\"Click on background filter size\\n\")\r\n\tedge <- locator(n=1, type=\"n\")\r\n\thw <- round(sqrt((edge$x)^2+(edge$y)^2))\r\n\tsymbols(0, 0, circles=hw, inches=FALSE, add=TRUE, fg=\"red\")\r\n\treturn(list(sl=c(round(peak$x), round(peak$y)), filter=hw))\r\n}\r\n\r\n\r\n## simple utility returns Euclidean length of a vector\r\n\r\nhypot <- function(x) sqrt(crossprod(x))\r\n\r\n## Zernike moments\r\n\r\nzmoments <- function(zcoef, maxorder=14) {\r\n zcoef <- zcoef[-(1:3)]\r\n zlist <- makezlist(4, maxorder)\r\n nz <- length(zlist$n)\r\n sumstats <- NULL\r\n i <- 1\r\n repeat {\r\n if (i > nz) break\r\n if (zlist$m[i] == 0) {\r\n sumstats <- rbind(sumstats, c(zlist$n[i], zlist$m[i], zcoef[i]))\r\n i <- i+1\r\n }\r\n else {\r\n sumstats <- rbind(sumstats, c(zlist$n[i], zlist$m[i], hypot(zcoef[i:(i+1)])))\r\n i <- i+2\r\n }\r\n }\r\n sumstats <- data.frame(sumstats)\r\n names(sumstats) <- c(\"n\", \"m\", \"value\")\r\n return(sumstats)\r\n}\r\n\r\n## these two functions provide rudimentary project management. The first adds\r\n## Zernike coefficients and rotation angles from one or more fits to a matrix.\r\n## The second separates polished in from instrumental aberrations (if possible)\r\n\r\naddfit <- function(..., th=0, zcm=NULL, theta=numeric(0)) {\r\n fits <- list(...)\r\n nt <- length(fits)\r\n if (length(th)==1 && nt>1) th=rep(th, nt)\r\n theta <- c(theta, th*pi/180)\r\n nz <- length(fits[[1]]$zcoef.net)\r\n for (i in 1:nt) {\r\n zcm <- cbind(zcm, fits[[i]]$zcoef.net[4:nz])\r\n }\r\n list(zcm=zcm, theta=theta)\r\n}\r\n\r\nseparate.wf <- function(zcm, theta, maxorder=14) {\r\n \r\n nt <- length(theta)\r\n zlist <- makezlist(4, maxorder)\r\n nz <- length(zlist$n)\r\n zcb <- matrix(0, nz, 4)\r\n sumstats <- NULL\r\n cx <- c(rep(1,nt),rep(0,nt))\r\n cy <- c(rep(0,nt),rep(1,nt))\r\n i <- 1\r\n repeat {\r\n if (i > nz) break\r\n if (zlist$m[i] == 0) {\r\n zcb[i,1] <- mean(zcm[i,])\r\n zcb[i,3] <- sd(zcm[i,])/sqrt(nt)\r\n sumstats <- rbind(sumstats, c(zlist$n[i], zlist$m[i], zcb[i,1],\r\n NA, zcb[i, 3], rep(NA, 4)))\r\n i <- i+1\r\n } else {\r\n y <- c(zcm[i,],zcm[i+1,])\r\n rx <- c(cos(zlist$m[i]*theta),sin(zlist$m[i]*theta))\r\n ry <- c(-sin(zlist$m[i]*theta),cos(zlist$m[i]*theta))\r\n lsm <- lm(y ~ -1+rx+ry+cx+cy)\r\n cc <- coef(summary(lsm))[,1:2]\r\n zcb[i:(i+1),1] <- cc[1:2,1]\r\n zcb[i:(i+1),3] <- cc[1:2,2]\r\n if (nrow(cc)==4) {\r\n zcb[i:(i+1),2] <- cc[3:4,1]\r\n zcb[i:(i+1),4] <- cc[3:4,2]\r\n }\r\n lsm <- summary(lsm)\r\n sumstats <- rbind(sumstats,c(zlist$n[i],zlist$m[i],\r\n hypot(zcb[i:(i+1),1]), hypot(zcb[i:(i+1),2]),\r\n lsm$sigma, lsm$r.squared,lsm$fstatistic))\r\n i <- i+2\r\n }\r\n }\r\n zcb[is.na(zcb)] <- 0\r\n colnames(zcb) <- c(\"zc_mirror\", \"zc_inst\", \"se_zc_mirror\", \"se_zc_inst\")\r\n colnames(sumstats)[1:7] <- c(\"n\",\"m\",\"rms_mirror\", \"rms_inst\", \"sigma\",\"R2\", \"F\")\r\n wf.mirror <- pupil.arb(zcoef=zcb[,1],zlist=zlist)\r\n wf.inst <- pupil.arb(zcoef=zcb[,2], zlist=zlist)\r\n list(zcb=data.frame(zcb),sumstats=data.frame(sumstats),\r\n wf.mirror=wf.mirror, wf.inst=wf.inst)\r\n}\r\n", "meta": {"hexsha": "8f28f5e4e6559d23e79af0c9433e50ead6b02374", "size": 17104, "ext": "r", "lang": "R", "max_stars_repo_path": "R/zernike_misc.r", "max_stars_repo_name": "mlpeck/zernike", "max_stars_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/zernike_misc.r", "max_issues_repo_name": "mlpeck/zernike", "max_issues_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/zernike_misc.r", "max_forks_repo_name": "mlpeck/zernike", "max_forks_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 31.0981818182, "max_line_length": 96, "alphanum_fraction": 0.5323316183, "num_tokens": 5944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.3567653198779008}}
{"text": "################################################################################################\r\n# This code uses myExchangeFileH1 from ReadExchangeFileExample_WKRDBEST2 (Author:David Currie) ###\r\n## This data is dummy data for H1 VS, FT, FO, SS, SA, FM and BV.\r\n## This code does not present anything new. It was an opportunity for me to get to use RDBES format and play around with ratio and inclusion probabilities estimation.\r\n## Ana Ribeiro Santos\r\n########################################################################################\r\n\r\nlibrary(dplyr)\r\n\r\n#load the data\r\nsource (\"ReadExchangeFileExample_WKRDBEST2.r\")\r\n#lst(myExchangeFileH1)\r\n\r\n# Because the data did not have sampled weight or total sample weight I had to estimated.\r\n#add species name to FM table\r\nmyExchangeFileH1$FM$Species <- myExchangeFileH1$SA$SAspeciesCode[match(myExchangeFileH1$FM$SAid,myExchangeFileH1$SA$SAid)]\r\n#head(myExchangeFileH1$FM)\r\n\r\n#dim(myExchangeFileH1$FM)\r\n#For this example we are goin to select just one species = 1015724 = Leuciscus aspius.\r\nmyExchangeFileH1$FM <- myExchangeFileH1$FM [myExchangeFileH1$FM$Species ==\"1015724\",]\r\n\r\n#calculate the weight per length. a and b paramters from Fisbase\r\na <- 0.01389\r\nb <- 3\r\n\r\nmyExchangeFileH1$FM$Wt.at.len_g <- with (myExchangeFileH1$FM, ((as.numeric(FMclass)/10)^ b) * a) # this gives in grams, equation expected CM not MM hence divide by 10\r\n\r\n#calculate the weight for each SAid (Sample ID)\r\nsample_wght_SAid <- myExchangeFileH1$FM %>%\r\n group_by(SAid) %>%\r\n summarise (., SAsampleWeightLive_est = round (sum (Wt.at.len_g), 0)) %>% as.data.frame()\r\n\r\n# merge it with SA table\r\nmyExchangeFileH1$SA <- merge (myExchangeFileH1$SA, sample_wght_SAid)\r\n#head(myExchangeFileH1$SA)\r\n\r\n#Calculate the totalweightlive based on the ratio_SA\r\nmyExchangeFileH1$SA$ratio_SA <- ifelse (is.na (myExchangeFileH1$SA$SAsampleWeightLive), with (myExchangeFileH1$SA, as.numeric (SAnumberTotal) / as.numeric (SAnumberSampled)),\r\n with (myExchangeFileH1$SA, as.numeric (SAtotalWeightLive) / as.numeric (SAsampleWeightLive)))\r\n\r\nmyExchangeFileH1$SA$SAtotalWeightLive_est <- with (myExchangeFileH1$SA, SAsampleWeightLive_est * ratio_SA)\r\n\r\n##########################################################################################################################################################\r\n# uses myExchnageFileH1 data and assumes simple random sampling within stages\r\n# trips within domains (quarter, area and gear) and ages within lengths.\r\n# In the code below, the hierarchy is as follows in order: VS, FT, \"FO\",\"SS\",\"SA\",\"FM\",\"BV\"\r\n\r\n\r\n# set up the population totals\r\npopDat <- as.data.frame(matrix(c(16,39,86,54, 32, 29, 1464760,3937180,6831707, 2876490, 3487500, 2345431),byrow=F,nrow=6,ncol=2))\r\nnames(popDat) <- c(\"tripNum\",\"liveWt\")\r\nrownames(popDat) <- c(\"Q2 27 GND\", \"Q3 27 DRB\", \"Q3 27 FPO\", \"Q4 27 FPO\", \"Q4 27 FYK\", \"Q4 27 GNS\")\r\n\r\n# calculate inclusion probabilities assuming SRS within strata\r\nmyExchangeFileH1$VS$VSincProb <- as.numeric (myExchangeFileH1$VS$VSnumberSampled)/ as.numeric (myExchangeFileH1$VS$VSnumberTotal)\r\nmyExchangeFileH1$BV$BVincProb <- as.numeric (myExchangeFileH1$BV$BVnumberSampled)/ as.numeric (myExchangeFileH1$BV$BVnumberTotal)\r\nmyExchangeFileH1$FM$FMincProb <- 1\r\nmyExchangeFileH1$SA$SAincProb <- as.numeric (myExchangeFileH1$SA$SAnumberSampled)/as.numeric (myExchangeFileH1$SA$SAnumberTotal) \r\nmyExchangeFileH1$SS$SSincProb <- as.numeric (myExchangeFileH1$SS$SSnumberSampled)/as.numeric (myExchangeFileH1$SS$SSnumberTotal) \r\nmyExchangeFileH1$FO$FOincProb <- as.numeric (myExchangeFileH1$FO$FOnumberSampled)/as.numeric (myExchangeFileH1$FO$FOnumberTotal) \r\nmyExchangeFileH1$FT$FTincProb <- as.numeric (myExchangeFileH1$FT$FTnumberSampled)/as.numeric (myExchangeFileH1$FT$FTnumberTotal) \r\n\r\n# caclulate quarter from date, and then make a domain of quarter combined with area\r\n# allocate domains to FM & BV as well\r\nmyExchangeFileH1$SA$FTid <- myExchangeFileH1$SS$FTid[match(myExchangeFileH1$SA$SSid,myExchangeFileH1$SS$SSid)]\r\nmyExchangeFileH1$SS$date <- myExchangeFileH1$FO$FOendDate[match(myExchangeFileH1$SS$FOid,myExchangeFileH1$FO$FOid)]\r\nmyExchangeFileH1$SA$date <- myExchangeFileH1$SS$date[match(myExchangeFileH1$SA$SSid,myExchangeFileH1$SS$SSid)]\r\nmyExchangeFileH1$SA$quarter <- paste(\"Q\",(as.numeric(substr(myExchangeFileH1$SA$date,6,7))-1) %/% 3 + 1,sep=\"\")\r\nmyExchangeFileH1$SA$domain <- paste(myExchangeFileH1$SA$quarter,myExchangeFileH1$SA$SAarea, myExchangeFileH1$SA$SAgear)\r\nmyExchangeFileH1$FM$domain <- myExchangeFileH1$SA$domain[match(myExchangeFileH1$FM$SAid,myExchangeFileH1$SA$SAid)]\r\nmyExchangeFileH1$BV$domain <- myExchangeFileH1$FM$domain[match(myExchangeFileH1$BV$FMid,myExchangeFileH1$FM$FMid)]\r\nmyExchangeFileH1$BV$numAtUnit <- 1\r\n\r\n# add spp to FM\r\nmyExchangeFileH1$FM$spp <- myExchangeFileH1$SA$SAspeciesCode[match(myExchangeFileH1$FM$SAid,myExchangeFileH1$SA$SAid)]\r\n\r\n# -----------------------------------------------------------------------\r\n# a function to calculate inclusion probabilities for the units at the final stage\r\n# of sampling given all the inclusion probabilities for the other stages\r\n# -----------------------------------------------------------------------\r\ngetIncProb <- function(RDB,stages){\r\n nStages <- length(stages)\r\n if (any(stages %in% c(\"FM\"))) {\r\n RDB[[\"FM\"]][[\"FMincProb\"]] <- 1\r\n }\r\n RDB[[stages[[1]]]][[\"incProb\"]] <- RDB[[stages[[1]]]][[paste(stages[[1]],\"incProb\",sep=\"\")]]\r\n for (i in 2:(nStages)) {\r\n indx <- RDB[[stages[[i]]]][[paste(stages[[i-1]],\"id\",sep=\"\")]]\r\n indxPrev <- RDB[[stages[[i-1]]]][[paste(stages[[i-1]],\"id\",sep=\"\")]]\r\n RDB[[stages[[i]]]][[\"incProbPrev\"]] <- RDB[[stages[[i-1]]]][[paste(\"incProb\",sep=\"\")]][match(indx,indxPrev)]\r\n RDB[[stages[[i]]]][[\"incProb\"]] <- RDB[[stages[[i]]]][[\"incProbPrev\"]]*RDB[[stages[[i]]]][[paste(stages[[i]],\"incProb\",sep=\"\")]]\r\n }\r\n return(RDB)\r\n}\r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# Number-at-Length\r\n# -----------------------------------------------------------------------\r\n# set up the stages in the sampling design used in the estimation\r\n#stages <- list(\"FT\",\"FO\", \"SS\",\"SA\",\"FM\")\r\nstages <- list(\"VS\", \"FT\",\"FO\", \"SS\",\"SA\",\"FM\")\r\n#stages <- list(\"LE\",\"SS\",\"SA\",\"FM\")\r\n\r\n# calculate the inclusion probabilities by length class given the other inclusion probabilities \r\n# in the higher stages\r\ntest <- getIncProb(myExchangeFileH1,stages)\r\n\r\n# calculate a Horvitz Thompson estimate for total numbers at length by domain\r\n# assuming srs within the domain - this is valid for the RDBshare data\r\nestL <- tapply(as.numeric(test$FM$FMnumberAtUnit)/test$FM$incProb,list(test$FM$FMclass,test$FM$domain),sum)\r\n\r\n#estL <- test$FM %>%\r\n# group_by(FMclass, domain, spp) %>%\r\n# summarise (., est.L = sum (as.numeric (FMnumberAtUnit)/incProb))\r\n\r\n# calculate a HT estimate for total landed weight using the sampled landed weights\r\n# assuming srs etc as before\r\nestX <- tapply(test$SA$SAtotalWeightLive_est/test$SA$incProbPrev,list(test$SA$domain),sum)/1e3\r\n\r\n# get the relevant population totals\r\npopX <- popDat[match(names(estX),rownames(popDat)),\"liveWt\"]\r\n\r\n# calculate the ratio estimates for numbers at length\r\nestLR <- estL*matrix(rep(popX/estX,dim(estL)[1]),byrow=T,ncol=dim(estL)[2])\r\n\r\n\r\n# compare the estLR with the ratio estimation using the ratio between the sum total sampled weight and the landings in the domain\r\ntest <- myExchangeFileH1\r\nsumX <- tapply(myExchangeFileH1$SA$SAtotalWeightLive_est,list(myExchangeFileH1$SA$domain),sum) # sum te total sampled weight for each domain\r\ntestLR <- estL*matrix(rep(popX/sumX,dim(estL)[1]),byrow=T,ncol=dim(estL)[2]) # multiply the number at length by the ratio between landings and sampled weight\r\n\r\ntestLR\r\nestLR\r\n## They are super different!!! So im wondering if Im doing something wrong here!! The fact that Im working with made up data does not help at all!!\r\n\r\n########################################################################################################################################\r\n# JUST to test if using a different approach from Liz's code and function we would get the same number at length up to Vessel selection'\r\n#############################################################################################################################################\r\nVSinfo <- myExchangeFileH1$VS %>% transmute(VSid,SDid,\r\n VSincProb)%>%distinct()\r\n\r\nFTinfo <-myExchangeFileH1$FT%>%transmute(FTid, VSid, FTincProb )%>%distinct()\r\n\r\n\r\nFOinfo<-myExchangeFileH1$FO%>%transmute(FOid,FTid, time=paste(\"Q\",(as.numeric(substr(myExchangeFileH1$FO$FOendDate,6,7))-1) %/% 3 + 1,sep=\"\"), \r\n metier=FOgear, space=FOarea, FOincProb)%>%distinct()\r\nFOinfo$domain <- paste (FOinfo$time, FOinfo$space, FOinfo$metier) \r\n\r\nSSinfo<-myExchangeFileH1$SS%>%transmute(SSid, FOid, SSincProb)%>%distinct()\r\n#SAinfo<-myExchangeFileH1$SA%>%transmute(SAid,SSid,spp=SAspeciesCode,\r\n# wsamp=SAsampleWeightMeasured,wsamptot=SAtotalWeightMeasured)%>%distinct()\r\n\r\nSAinfo<- myExchangeFileH1$SA%>%transmute(SAid,SSid,spp=SAspeciesCode,SAincProb)%>%distinct()\r\n\r\n\r\nFMinfo<-myExchangeFileH1$FM%>%transmute(FMid,SAid,len=FMclass,n=as.numeric(FMnumberAtUnit), FMincProb)\r\n\r\nsamp_est_stratum_incPro <-FMinfo%>% left_join (SAinfo)%>%left_join(SSinfo)%>%left_join(FOinfo)%>%left_join(FTinfo)%>% left_join(VSinfo) %>%\r\n group_by(domain, spp, len, n) %>%\r\n summarise (., final_prob = FMincProb * SAincProb * SSincProb * FOincProb * FTincProb * VSincProb) %>% \r\n ungroup() %>%\r\n group_by(domain, spp, len) %>%\r\n summarise (., est.n = sum(n / final_prob))\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7b1fe3e71557dcc5c041a164f18de1bfc69e8f6c", "size": 9706, "ext": "r", "lang": "R", "max_stars_repo_path": "Subgroup1/code/RDBES_EST_IncPRob&Ratio_ARibeiroSantos.r", "max_stars_repo_name": "AnaRibeiroSantos/WKRATIO", "max_stars_repo_head_hexsha": "bc84a8d70f1712cc74fdda3f0b94d7275f11289f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Subgroup1/code/RDBES_EST_IncPRob&Ratio_ARibeiroSantos.r", "max_issues_repo_name": "AnaRibeiroSantos/WKRATIO", "max_issues_repo_head_hexsha": "bc84a8d70f1712cc74fdda3f0b94d7275f11289f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Subgroup1/code/RDBES_EST_IncPRob&Ratio_ARibeiroSantos.r", "max_forks_repo_name": "AnaRibeiroSantos/WKRATIO", "max_forks_repo_head_hexsha": "bc84a8d70f1712cc74fdda3f0b94d7275f11289f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.0941176471, "max_line_length": 175, "alphanum_fraction": 0.6551617556, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3560883656595589}}
{"text": "\n######################\n############FRAILTY INDEX CALCULATION\n\nsetwd(\"P:/2019 0970 151 000/User Data/Faraz-Export IDAVE folders\")\nlibrary(tidyverse)\nlibrary(icd)\ndf <- read.csv(\"./datasets/New/NACRASCIHI_2_dupRemoved.csv\")\n\ntabna <- function(x){table(x, useNA = \"ifany\")}\n\n\nic <- df %>% select(ID, days_to_lefteddate, dx10code1:dx10code10, alc_status)%>%\nmutate(IDm = paste(ID, days_to_lefteddate, sep=\"_\"))\n\ncodes <- read.csv(\"./ICD10 codes/frailty_score2.csv\")\n\n# codes <- c(\"F00\", \"G81\",\"G30\", \"I69\", \"R29\", \"N39\", \"F05\", \"W19\",\"S00\",\n# \"R31\", \"B96\", \"R41\", \"R26\", \"I67\", \"R56\", \"R40\", \"T83\", \"S06\",\n# \"S42\", \"E87\", \"M25\", \"E86\", \"R54\", \"Z50\", \"F03\", \"W18\", \"Z75\", \"F01\",\n# \"S80\", \"L03\", \"H54\", \"E53\", \"Z60\", \"G20\", \"R55\", \"S22\", \"K59\", \"N17\",\n# \"L89\", \"Z22\", \"B95\", \"L97\", \"R44\", \"K26\", \"I95\", \"N19\", \"A41\", \"Z87\", \n# \"J96\", \"X59\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",\n# \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\")\n\n# points <- c(7.1, 4.4, 4, 3.7, 3.6, 3.2, 3.2, 3.2, 3.2, \n# 3.0, 2.9, 2.7, 2.6, 2.6, 2.6, 2.5, 2.4, 2.4,\n# 2.3,2.3,2.3,2.3, 2.2, 2.1, 2.1, 2.1, 2.0, 2.0,\n# 2.0,2.0,1.9,1.9,1.8,1.8,1.8,1.8,1.8,1.8,\n# rep(1.7,3), rep(1.6, 6), 1.5,\n# rep(1.5, 4), rep(1.4, 6),\n\n# ) \n\nfor (i in 1:nrow(codes)){\n\tid_ls <- ic %>% filter_at(vars(dx10code1:dx10code10),\n\t any_vars(substr(.,1,3) == codes$ICD.Code[i])) %>%\n\tselect(IDm , dx10code1:dx10code10) %>% .$IDm \n\t\n\tvar_name <- paste0(\"frail_\",as.character(codes$ICD.Code[i])) #dynamic name in mutate\n\t\n\tic <- ic %>% mutate(!!var_name := ifelse(IDm %in% id_ls, 1, 0))\n}\n\n\n# for (i in 1:nrow(codes)){\n\t# var_name <- paste0(\"frail_\",as.character(codes$ICD.Code[i])) #dynamic name in mutate\n\n\t# ic2 <- ic %>%\n\t# mutate_at(vars(dx10code1:dx10coSde10), ~substr(.,1,3)) %>%\n\t# mutate(!!var_name := ifelse(any(vars(dx10code1:dx10code10) %in% codes$ICD.Code[i]), 1, 0))\n\t\n# }\n##Occurences are low usually\nic %>% select(frail_F00:frail_R50) %>% colSums / nrow(ic) * 100 %>% round(digits=2)\n\nmat <- as.matrix(ic %>% select(frail_F00:frail_R50))\n\nscores <- mat %*% codes$coef \n####Check Safety\nscores[1:5]\nic[1,] %>% select(frail_F00:frail_R50) %>% select_if(.==1)\n############\nic$frailty_score <- scores\nsummary(ic$frailty_score)\n\nic %>% select(IDm, frailty_score) %>% write.csv(\"./ICD10 codes/frailty_index.csv\", row.names = F)", "meta": {"hexsha": "9a7d27c1419ae96abcfbba7dc49fde6c6025a8df", "size": 2260, "ext": "r", "lang": "R", "max_stars_repo_path": "ICD10 codes/Frailty_IndexCalculation.r", "max_stars_repo_name": "farazahmadi/machine-learning-prediction-of-alternate-level-of-care", "max_stars_repo_head_hexsha": "7957364c0f263d2e80325643d1118e9b47ef3754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICD10 codes/Frailty_IndexCalculation.r", "max_issues_repo_name": "farazahmadi/machine-learning-prediction-of-alternate-level-of-care", "max_issues_repo_head_hexsha": "7957364c0f263d2e80325643d1118e9b47ef3754", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICD10 codes/Frailty_IndexCalculation.r", "max_forks_repo_name": "farazahmadi/machine-learning-prediction-of-alternate-level-of-care", "max_forks_repo_head_hexsha": "7957364c0f263d2e80325643d1118e9b47ef3754", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7313432836, "max_line_length": 97, "alphanum_fraction": 0.5646017699, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.35551830274017754}}
{"text": "\n#required packages\nlibrary(\"openxlsx\")\nlibrary(\"stringr\")\nlibrary(ComplexHeatmap)\nlibrary(circlize)\nlibrary(colorspace)\nlibrary(GetoptLong)\nlibrary(ggplot2)\nlibrary(gplots)\nlibrary(survival)\nrequire(\"survival\")\n# install.packages(\"svglite\")\nlibrary(survminer)\nlibrary(reticulate)\n\n\n#set the project path\nproject_path = \"./project/\"\n\n#load patient data (include survival info)\nstudy_cohort = read.xlsx(paste(project_path, \"data/tcga/study_cohort.xlsx\",sep=\"\"), sheet = 1, colNames = TRUE)\nentire_cohort = read.xlsx(paste(project_path, \"data/tcga/entire_cohort.xlsx\",sep=\"\"), sheet = 1, colNames = TRUE)\n\nlength(rownames(study_cohort))\n\nlength(rownames(entire_cohort))\n\nmedian(entire_cohort$ENSG00000206567.8)\n\n#To build a risk score system based on lncRNA signature, we first estimate the coef of the signature\nfit = coxph(Surv(OS, Censor) ~ \n\nENSG00000187185.4+\nENSG00000259641.4+\nENSG00000218510.5 + \nENSG00000257989.1+\nENSG00000206567.8\n, data=study_cohort)\n\n# summary(fit)\n\nHR <- exp(coef(fit))\nCI <- exp(confint(fit))\nP <- round(coef(summary(fit))[,5],8)\nCOEF <- coef(fit)\n\ncolnames(CI) <- c(\"Lower\", \"Higher\")\n\ntable2 <- as.data.frame(cbind(HR, CI,COEF, P))\ntable2\n\n#calculate the risk score based on expression and coef of the signature\n#use coef (estimated in the study cohort) in above table\nentire_cohort$risk_lnc = (\n entire_cohort$ENSG00000187185.4 * table2[1,4] +\n entire_cohort$ENSG00000259641.4 * table2[2,4]+\n entire_cohort$ENSG00000218510.5 * table2[3,4] +\n entire_cohort$ENSG00000257989.1 * table2[4,4] +\n entire_cohort$ENSG00000206567.8 * table2[5,4] )\n\n#calculate hazard ratio\nfit1 = coxph(Surv(OS, Censor) ~ \n\nrisk_lnc\n, data=entire_cohort)\n\n# summary(fit)\n\nHR <- exp(coef(fit1))\nCI <- exp(confint(fit1))\nP <- coef(summary(fit1))[,5]\nCOEF <- coef(fit1)\n\ncolnames(CI) <- c(\"Lower\", \"Higher\")\n\ntable22 <- as.data.frame(cbind(HR, CI,COEF, P))\ntable22\n\n#calculate the time-dependent roc (lncrna signature on entire tcga cohort)\nlibrary(timeROC)\nROC<-timeROC(T=entire_cohort$OS,# survival time\n\ndelta=entire_cohort$Censor,# results, alive or death\n\nmarker=entire_cohort$risk_lnc,# variables\n\ncause=1,\n\nweighting=\"marginal\",\n\ntimes=c(365*3, 365*5, 365*10),# time, survival 3,5,10 years\n\nROC = TRUE,\n\niid = TRUE)\nROC\n\n#the time-dependent roc/auc shown above result and confidence interval shown below\n#the lncrna signature performance on entire TCGA dataset\nconfint(ROC)$CB_AUC\n\n#To build a risk score system based on lncRNA signature + 3 clinical factors, \n#we first estimate the coef of the signature and 3 clinical factors\n\nfit = coxph(Surv(OS, Censor) ~ stage + gender + age_at_diagnosis +\n\nENSG00000187185.4+\nENSG00000259641.4+\nENSG00000218510.5 + \nENSG00000257989.1+\nENSG00000206567.8\n, data=study_cohort)\n\n\n# summary(fit)\n\nHR <- exp(coef(fit))\nCI <- exp(confint(fit))\nP <- round(coef(summary(fit))[,5],8)\nCOEF <- coef(fit)\n\ncolnames(CI) <- c(\"Lower\", \"Higher\")\n\ntable2 <- as.data.frame(cbind(HR, CI,COEF, P))\ntable2\n\n#calculate the risk score based on expression and coef of the signature and 3 clinical factors\n#use coef (estimated in the study cohort) in above table\nentire_cohort$risk_lncClinical = (\n entire_cohort$stage * table2[1,4]+\n entire_cohort$gender * table2[2,4]+\n entire_cohort$age_at_diagnosis * table2[3,4] +\n entire_cohort$ENSG00000187185.4 * table2[4,4] +\n entire_cohort$ENSG00000259641.4 * table2[5,4]+\n entire_cohort$ENSG00000218510.5 * table2[6,4] +\n entire_cohort$ENSG00000257989.1 * table2[7,4] +\n entire_cohort$ENSG00000206567.8 * table2[8,4] )\n\n#calculate the time-dependent roc (lncrna signature + 3 clinical factors on entire cohort)\nlibrary(timeROC)\nROCAll<-timeROC(T=entire_cohort$OS,# survival time\n\ndelta=entire_cohort$Censor,# results, alive or death\n\nmarker=entire_cohort$risk_lncClinical,\n\ncause=1,# positive results\n\nweighting=\"marginal\",\n\ntimes=c(365*3, 365*5, 365*10),# time, survival 3,5,10 years\n\nROC = TRUE,\n\niid = TRUE)\nROCAll\n\n#the time-dependent roc/auc is shown above and confidence interval shown below\n#the lncrna signature + 3 clinical factors performance on entire dataset\nconfint(ROCAll)$CB_AUC\n\ntitle = paste(project_path,\"results/tcga_time-dependent-roc\", \".pdf\", sep=\"\")\n\n# pdf(title)\n\n#(95% CI: 0.6328-0.6835), lncrna, 5 years\n#(95% CI: 0.6771-0.7596), lncrna + 3 clinical factors, 10 years\n\n#plot the time-dependent roc\nplot(ROC,time=365*3,col = \"red\", lty=2,add =FALSE, title=\"\")\nplot(ROC,time=365*5,col = \"red\",lwd=2, add =TRUE)\nplot(ROC,time=365*10,col = \"red\",lty=3, add =TRUE)\n\nplot(ROCAll,time=365*3,col = \"blue\",lty=2,add =TRUE)\nplot(ROCAll,time=365*5,col = \"blue\",lty=3,add =TRUE)\nplot(ROCAll,time=365*10,col = \"blue\",lwd=2,add =TRUE)\nlegend(\"bottomright\", c(\"5-lncRNA at 3 years (AUC = 0.64)\",\"5-lncRNA at 5 years (AUC = 0.66)\",\"5-lncRNA at 10 years (AUC = 0.63)\", \"5-lncRNA + 3 clinical factors at 3 years (AUC= 0.68)\",\"5-lncRNA + 3 clinical factors at 5 years (AUC= 0.67)\", \"5-lncRNA + 3 clinical factors 10 years (AUC= 0.72)\"), lty=c(2,1,3,2,3,1), lwd=c(1,2,1,1,1,2), col = c(\"red\",\"red\",\"red\",\"blue\",\"blue\", \"blue\"), bty=\"n\")\n\n# dev.off()\n\n#calculate the median risk score (lncrna signature)\nmediam_risk_score = median(as.numeric(as.vector(entire_cohort$risk_lnc)))\nentire_cohort$risk_cluster <- 1\nentire_cohort$risk_cluster[which(entire_cohort$risk_lnc <= mediam_risk_score)] <- 0 \nmediam_risk_score\n\n#calculate the surviva different of the high- and low-risk score groups (lncrna signature)\nsurvdiff(Surv(OS, Censor) ~risk_cluster, data = entire_cohort)\n\n#plot the survival difference\nlibrary(survival)\nrequire(\"survival\")\n# install.packages(\"svglite\")\nlibrary(survminer)\n\ndif = survdiff(Surv(OS, Censor) ~risk_cluster, data = entire_cohort)\npv = pchisq(dif$chisq, length(dif$n)-1, lower.tail = FALSE)\npv = formatC(pv, format = \"e\", digits = 2) \nret = c(\"Log-rank\\r\\np = \",pv)\npvalue=paste(ret[1],ret[2], sep=\"\")\n\nfit<- survfit(Surv(OS, Censor) ~ risk_cluster, data = entire_cohort)\n\np <- ggsurvplot(fit, data=entire_cohort,risk.table = TRUE,tables.theme = theme_cleantable(),palette = c(\"#E7B890\", \"#2E9FCF\"), ggtheme = theme_bw(),surv.median.line = \"hv\",legend.title = \"Risk Score\", legend.labs = c(\"Low\", \"High\"), xlab='Time (days)', conf.int = TRUE,pval = pvalue,pval.method=TRUE,conf.int.style='ribbon', conf.int.alpha=0.1)\n \np = p + theme_survminer( font.main = c(16, \"bold\", \"darkblue\"), font.submain = c(15, \"bold\", \"purple\"), font.caption = c(14, \"plain\", \"orange\"), font.x = c(14, \"bold\"), font.y = c(14, \"bold\"), font.tickslab = c(12, \"plain\") )\n\np\n\n#save the results\ntitle = paste(project_path, \"results/RiskScore-Survival-TCGA.tiff\", sep=\"\")\ntiff(title, width=480*7, height=480*7, units=\"px\", res=96*6, compression = \"lzw\")\nprint(p, newpage = FALSE)\ndev.off()\n\n# let's see the median survival time between high- and low-risk groups\n# risk_cluster=0, low-risk score group (low risk), longer survival time\n#risk_cluster=1, high-risk score group (high risk), shorter survival time\nprint(fit)\n\n#we need to drop patients without age_at_diagnosis or OS info\nvalidPatients = entire_cohort[!is.na(entire_cohort$OS),]\nvalidPatients = validPatients[!is.na(validPatients$age_at_diagnosis),]\nmediam_risk_score_lncClinical = median(as.numeric(as.vector(validPatients$risk_lncClinical)))\n#stratified into two groups based on median risk score\nvalidPatients$risk_cluster1 <- 1\nvalidPatients$risk_cluster1[which(validPatients$risk_lncClinical <= mediam_risk_score_lncClinical)] <- 0 \nmediam_risk_score_lncClinical\n\n#calculate the survival difference\n#risk_cluster1=0, low-risk score group (low risk), longer survival time\n#risk_cluster1=1, high-risk score group (high risk), shorter survival time\nfit<- survfit(Surv(OS, Censor) ~ risk_cluster1, data = validPatients)\nfit\n\ndif = survdiff(Surv(OS, Censor) ~risk_cluster1, data = validPatients)\npv = pchisq(dif$chisq, length(dif$n)-1, lower.tail = FALSE)\npv = formatC(pv, format = \"e\", digits = 2) \npv # p-value\n", "meta": {"hexsha": "1369dcbe9c05e84a56317dcf5d096525ed6f7df0", "size": 7911, "ext": "r", "lang": "R", "max_stars_repo_path": "LncRNASurivival-TCGA.r", "max_stars_repo_name": "guoqingbao/PanCancerLncRNA", "max_stars_repo_head_hexsha": "297eca20d1d3e9f97f7df1811f009c8942e1bc0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-25T09:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T02:12:33.000Z", "max_issues_repo_path": "LncRNASurivival-TCGA.r", "max_issues_repo_name": "guoqingbao/PanCancerLncRNA", "max_issues_repo_head_hexsha": "297eca20d1d3e9f97f7df1811f009c8942e1bc0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LncRNASurivival-TCGA.r", "max_forks_repo_name": "guoqingbao/PanCancerLncRNA", "max_forks_repo_head_hexsha": "297eca20d1d3e9f97f7df1811f009c8942e1bc0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-14T04:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T04:42:00.000Z", "avg_line_length": 32.8257261411, "max_line_length": 395, "alphanum_fraction": 0.7272152699, "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.35531546397375835}}
{"text": "#!/usr/bin/env Rscript\n#\tBuilding a statistical model for predicting sediment reworking from fraction of preserved bar structures.\n#\tEric Barefoot\n#\tOct 2019\n\n# load packages\n\nlibrary(tidyverse)\nlibrary(here)\nlibrary(broom)\nlibrary(lme4)\nif (interactive()) {\n require(colorout)\n}\n\n# load data\n\nchamb_data = readRDS(file = here('data','derived_data', 'chamberlin_model_data.rds'))\n\n# for helpfulness later - plot up the data with factors, etc\n# factors are that the model results were generated by either:\n # (1) compensational avulsions or\n # (2) random avulsions.\n# The other factors shown are sets of experiments with the same input overbank/channel material ratio (\"input ratio\")\n# This is a strong controlling factor, and is also mapped to a frac_input continuous variable. \n\n# chamb_data %>%\n# ggplot(., aes(x = frac_elems, y = frac_supply)) + \n# geom_point(aes(color = exp_set, shape = model)) \n\n# We are interested in finding the best predictive model for these data. \n# Let's try out some. \n\n# null\n# fixed-effects model with\n# fixed effects on % fully preserved structures\n\nfixed_model_null = lm(frac_supply ~ frac_elems, data = chamb_data)\n\n# fixed-effects model with\n# fixed effects on % fully preserved structures\n# fixed effects on input ratio\n\nfixed_model_input = lm(frac_supply ~ frac_elems + frac_input, data = chamb_data)\n\n# fixed-effects model with\n# fixed effects on % fully preserved structures\n# fixed effects on input ratio\n# also interactions between two predictors.\n\nfixed_model_input_interactions = lm(frac_supply ~ frac_elems*frac_input, data = chamb_data)\n\n# AIC(fixed_model_null, fixed_model_input, fixed_model_input_interactions)\n\n# mixed-effects model with\n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean\n\nmixed_model_int_expSet = lmer(frac_supply ~ frac_elems + (1|exp_set), data = chamb_data)\n\n# mixed-effects model with\n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean\n# random effects on avulsion type mean\n\nmixed_model_int_expSet_avulType = lmer(frac_supply ~ frac_elems + (1|exp_set) + (1|model), data = chamb_data)\n\n# mixed-effects model with \n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean and slope\n\nmixed_model_slp_expSet = lmer(frac_supply ~ frac_elems + (1 + frac_elems|exp_set), data = chamb_data, REML = FALSE, control = lmerControl(optimizer = 'Nelder_Mead'))\n\n# mixed-effects model with\n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean and slope\n# random effects on avulsion type mean and slope\n\nmixed_model_slp_expSet_avulType = lmer(frac_supply ~ frac_elems + (1+frac_elems|exp_set) + (1+frac_elems|model), data = chamb_data, REML = FALSE)\n\n# mixed-effects model with \n# fixed effects on % fully preserved structures\n# fixed effects on input ratio\n# random effects on experiment set (proxy for input ratio) mean and slope\n# random effects on avulsion type mean and slope\n\nmixed_model_input_slp_expSet_avulType = lmer(frac_supply ~ frac_elems + frac_input + (1+frac_elems|model), data = chamb_data, REML = FALSE)\n\n# So after doing all of those models, we need to evaluate them. \n\nmodels_aic = AIC(fixed_model_null, fixed_model_input, mixed_model_int_expSet, mixed_model_int_expSet_avulType, mixed_model_slp_expSet, mixed_model_slp_expSet_avulType, mixed_model_input_slp_expSet_avulType)\n\n# based on this, it looks like the best model is really the simplest fixed-effects model with the input ratio included. \n# That effect seems to be pretty important! Since we have NO way of constraining that in the ancient, the best route forward is determine the sensitivity of the analysis to overbank vs channel deposition and work that in somehow.\n\n# for fun, plot this model on the data.\n\n# chamb_data_pred = chamb_data %>% mutate(pred_supply = predict(fixed_model_input_interactions))\n# \n# ggplot(data = chamb_data_pred) + \n# geom_point(aes(x = frac_elems, y = frac_supply, color = frac_input, shape = model)) + \n# geom_point(aes(x = frac_elems, y = pred_supply), color = 'red3')\n\n# export the best model as a derived data product. \n\nsaveRDS(fixed_model_input_interactions, file = here('data','derived_data', 'chamberlin_stat_model.rds'))\n", "meta": {"hexsha": "47d3c0939480e16e48f3b710427d3d802a2e2124", "size": 4339, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/analyzing_reworking/make_stat_model_chamberlin.r", "max_stars_repo_name": "ericbarefoot/barefoot_fluvial_reworking_manuscript_2020", "max_stars_repo_head_hexsha": "379d70bafcdc624064b052b8b7e86dd05ffff076", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/analyzing_reworking/make_stat_model_chamberlin.r", "max_issues_repo_name": "ericbarefoot/barefoot_fluvial_reworking_manuscript_2020", "max_issues_repo_head_hexsha": "379d70bafcdc624064b052b8b7e86dd05ffff076", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/analyzing_reworking/make_stat_model_chamberlin.r", "max_forks_repo_name": "ericbarefoot/barefoot_fluvial_reworking_manuscript_2020", "max_forks_repo_head_hexsha": "379d70bafcdc624064b052b8b7e86dd05ffff076", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5514018692, "max_line_length": 229, "alphanum_fraction": 0.7734501037, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3548759777846301}}
{"text": "#' Choose initial parameters for direct effects on X and Y\n#'\n#' @param nsnp_x nsnp_x\n#' @param var_gx.x var_gx.x\n#' @param var_x.y var_x.y\n#' @param var_gx.y var_gx.y=0\n#' @param nsnp_y nsnp_y=0\n#' @param var_gy.y var_gy.y=0\n#' @param mu_gx.y mu_gx.y=0\n#' @param var_gy.x var_gy.x=0\n#' @param mu_gy.x mu_gy.x=0\n#' @param prop_gy.x prop_gy.x=1\n#' @param prop_gx.y prop_gx.y=1\n#'\n#' @export\n#' @return List of model parameters\ninit_parameters <- function(nsnp_x, var_gx.x, var_x.y, var_gx.y=0, nsnp_y=0, var_gy.y=0, mu_gx.y=0, var_gy.x=0, mu_gy.x=0, prop_gy.x=1, prop_gx.y=1)\n{\n\tparameters <- list(\n\t\t# Causal effect\n\t\tvar_x.y = var_x.y,\n\n\t\t# Direct effects on x\n\t\tnsnp_x = nsnp_x,\n\t\tvar_gx.x = var_gx.x,\n\t\tvar_gx.y = var_gx.y,\n\t\tmu_gx.y = mu_gx.y,\n\t\tprop_gx.y = prop_gx.y,\n\n\t\tnsnp_y = nsnp_y,\n\t\tvar_gy.y = var_gy.y,\n\t\tvar_gy.x = var_gy.x,\n\t\tmu_gy.x = mu_gy.x,\n\t\tprop_gy.x = prop_gy.x,\n\t\tu = list()\n\t)\n\treturn(parameters)\n}\n\n#' Add confounder variables and their instruments\n#'\n#' @param parameters Output from \\code{init_parameters}\n#' @param nsnp_u nsnp_u\n#' @param var_u.x var_u.x\n#' @param var_u.y var_u.y\n#' @param var_gu.u var_gu.u\n#'\n#' @export\n#' @return List of model parameters\nadd_u <- function(parameters, nsnp_u, var_u.x, var_u.y, var_gu.u)\n{\n\tnom <- \"u\"\n\tif(var_u.x == 0 & var_u.y != 0) nom <- \"b\"\n\tif(var_u.x != 0 & var_u.y == 0) nom <- \"a\"\n\ti <- length(parameters$u) + 1\n\tparameters$u[[i]] <- list(\n\t\tnsnp_u = nsnp_u,\n\t\tvar_u.x = var_u.x,\n\t\tvar_u.y = var_u.y,\n\t\tvar_gu.u = var_gu.u,\n\t\tname_u = nom\n\t)\n\treturn(parameters)\n}\n\n#' Sample the actual effects based on initial parameters\n#'\n#' @param parameters Output from \\code{init_parameters} or \\code{add_u}\n#'\n#' @export\n#' @return List of effect parameters\nsample_system_effects <- function(parameters)\n{\n\tnu <- length(parameters$u)\n\tif(nu > 0)\n\t{\n\t\tfor(i in 1:nu)\n\t\t{\n\t\t\tparameters$u[[i]]$eff_gu.u <- choose_effects(parameters$u[[i]]$nsnp_u, parameters$u[[i]]$var_gu.u)\n\t\t\tparameters$u[[i]]$eff_u.x <- choose_effects(1, parameters$u[[i]]$var_u.x)\n\t\t\tparameters$u[[i]]$eff_u.y <- choose_effects(1, parameters$u[[i]]$var_u.y)\n\t\t}\n\t}\n\n\t# Make genetic effects for x instruments\n\tparameters$eff_gx.x <- choose_effects(parameters$nsnp_x, parameters$var_gx.x)\n\n\t# Make genetic effects for y instruments\n\tparameters$eff_gy.y <- choose_effects(parameters$nsnp_y, parameters$var_gy.y)\n\n\n\t# Create pleiotropic effects for some proportion of the effects\n\t# X-Y\n\tnchoose <- round(parameters$nsnp_x * parameters$prop_gx.y)\n\tind <- sample(1:parameters$nsnp_x, nchoose, replace=FALSE)\n\tparameters$eff_gx.y <- rep(0, parameters$nsnp_x)\n\tif(nchoose > 0)\n\t{\n\t\tparameters$eff_gx.y[ind] <- choose_effects(nchoose, parameters$var_gx.y, mua=parameters$mu_gx.y)\n\t}\n\n\t# Create pleiotropic effects for some proportion of the effects\n\t# Y-X\n\tnchoose <- round(parameters$nsnp_y * parameters$prop_gy.x)\n\tind <- sample(1:parameters$nsnp_y, nchoose, replace=FALSE)\n\tparameters$eff_gy.x <- rep(0, parameters$nsnp_y)\n\tif(nchoose > 0)\n\t{\n\t\tparameters$eff_gy.x[ind] <- choose_effects(nchoose, parameters$var_gy.x, mua=parameters$mu_gy.x)\n\t}\n\n\tparameters$eff_u.x <- sapply(parameters$u, function(x) choose_effects(1, x$var_u.x))\n\tparameters$eff_u.y <- sapply(parameters$u, function(x) choose_effects(1, x$var_u.y))\n\tparameters$eff_x.y <- sqrt(parameters$var_x.y)\n\n\treturn(parameters)\n}\n\n\n#' Simulate individual level data from initial parameters\n#'\n#' @param parameters Output from \\code{init_parameters} or \\code{add_u}\n#' @param nid Sample size to generate\n#'\n#' @export\n#' @return List of matrices and vectors that represent individual level data\nsimulate_population <- function(parameters, nid)\n{\n\tGx <- matrix(rbinom(parameters$nsnp_x * nid, 2, 0.5), nid, parameters$nsnp_x)\n\n\tGy <- matrix(rbinom(parameters$nsnp_y * nid, 2, 0.5), nid, parameters$nsnp_y)\n\n\tU <- lapply(parameters$u, function(param)\n\t{\n\t\tG <- matrix(rbinom(param$nsnp_u * nid, 2, 0.5), nid, param$nsnp_u)\n\t\tu <- make_phen(param$eff_gu.u, G)\n\t\treturn(list(p=u, G=G, nom=param$name_u))\n\t})\n\n\n\tbx <- parameters$eff_gx.x\n\tby <- parameters$eff_gx.y\n\n\tGt <- Gx\n\tif(parameters$nsnp_y > 0)\n\t{\n\t\tbx <- c(bx, parameters$eff_gy.x)\n\t\tby <- c(by, parameters$eff_gy.y)\n\t\tGt <- cbind(Gt, Gy)\n\t}\n\n\tif(length(parameters$u) > 0)\n\t{\n\t\tbx <- c(bx, sapply(parameters$u, function(x) x$eff_u.x))\n\t\tby <- c(by, sapply(parameters$u, function(x) x$eff_u.y))\n\t\tGt <- cbind(Gt, do.call(cbind, lapply(U, function(x) x$p)))\n\t}\n\tby <- c(by, parameters$eff_x.y)\n\n\tx <- make_phen(bx, Gt)\n\ty <- make_phen(by, cbind(Gt, x))\n\n\treturn(list(\n\t\ty=y,\n\t\tx=x,\n\t\tGx=Gx,\n\t\tGy=Gy,\n\t\tU=U\n\t))\n\n}\n\n\n#' Estimate the effects of all SNPs on all phenotypes\n#'\n#' @param sim Output from \\code{simulate_population}\n#'\n#' @export\n#' @return Lists of SNP-trait effect estimates\nestimate_system_effects <- function(sim)\n{\n\t# Get effects of all X SNPs\n\n\tl <- list()\n\n\tgx.x <- gwas(sim$x, sim$Gx)\n\tgx.x$inst <- \"x\"\n\tgx.x$snp <- paste0(1:nrow(gx.x), \"x\")\n\t\n\tgx.y <- gwas(sim$y, sim$Gx)\n\tgx.y$inst <- \"x\"\n\tgx.y$snp <- paste0(1:nrow(gx.y), \"x\")\n\n\tgx <- gx.x\n\tgy <- gx.y\n\n\t# Get effects of all SNPs on Y\n\n\tif(ncol(sim$Gy) > 0)\n\t{\n\t\tgy.x <- gwas(sim$x, sim$Gy)\n\t\tgy.x$inst <- \"y\"\n\t\tgy.x$snp <- paste0(1:nrow(gy.x), \"y\")\n\t\tgx <- rbind(gx, gy.x)\n\n\t\tgy.y <- gwas(sim$y, sim$Gy)\n\t\tgy.y$inst <- \"y\"\n\t\tgy.y$snp <- paste0(1:nrow(gy.y), \"y\")\n\t\tgy <- rbind(gy, gy.y)\n\t}\n\n\tnconf <- length(sim$U)\n\tif(nconf > 0)\n\t{\n\t\tgu.x <- list()\n\t\tgu.y <- list()\n\t\tgx.u <- list()\n\t\tgy.u <- list()\n\t\tgu.u <- list()\n\t\tfor(i in 1:nconf)\n\t\t{\n\t\t\tgu.u[[i]] <- gwas(sim$U[[i]]$p, sim$U[[i]]$G)\n\t\t\tgu.u[[i]]$inst <- paste0(\"u\", i)\n\t\t\tgu.u[[i]]$snp <- paste0(1:nrow(gu.u[[i]]), gu.u[[i]]$inst)\n\n\t\t\tgu.x[[i]] <- gwas(sim$x, sim$U[[i]]$G)\n\t\t\tgu.x[[i]]$inst <- paste0(\"u\", i)\n\t\t\tgu.x[[i]]$snp <- paste0(1:nrow(gu.x[[i]]), gu.x[[i]]$inst)\n\n\t\t\tgx.u[[i]] <- gwas(sim$U[[i]]$p, sim$Gx)\n\t\t\tgx.u[[i]]$inst <- \"x\"\n\t\t\tgx.u[[i]]$snp <- paste0(1:nrow(gx.u[[i]]), gx.u[[i]]$inst)\n\n\t\t\tgu.y[[i]] <- gwas(sim$y, sim$U[[i]]$G)\n\t\t\tgu.y[[i]]$inst <- paste0(\"u\", i)\n\t\t\tgu.y[[i]]$snp <- paste0(1:nrow(gu.y[[i]]), gu.y[[i]]$inst)\n\n\t\t\tif(ncol(sim$Gy) > 0)\n\t\t\t{\n\t\t\t\tgy.u[[i]] <- gwas(sim$U[[i]]$p, sim$Gy)\n\t\t\t\tgy.u[[i]]$inst <- \"y\"\n\t\t\t\tgy.u[[i]]$snp <- paste0(1:nrow(gy.u[[i]]), gy.u[[i]]$inst)\n\t\t\t}\n\t\t}\n\t\tgx <- rbind(gx, dplyr::bind_rows(gu.x))\n\t\tgy <- rbind(gy, dplyr::bind_rows(gu.y))\n\t\tgu <- list()\n\t\tfor(i in 1:nconf)\n\t\t{\n\t\t\tif(ncol(sim$Gy) > 0)\n\t\t\t{\n\t\t\t\tgu[[i]] <- rbind(gx.u[[i]], gy.u[[i]], gu.u[[i]])\n\t\t\t} else {\n\t\t\t\tgu[[i]] <- rbind(gx.u[[i]], gu.u[[i]])\n\t\t\t}\n\t\t}\n\t\tnames(gu) <- paste0(\"u\", 1:nconf)\n\t\tl <- gu\n\t}\n\tl$x <- gx\n\tl$y <- gy\n\treturn(l)\n}\n\n\n\n\n#' Wrapper for simulation pipeline\n#'\n#' Based on the parameters specified this function will call \\code{init_parameters}, \\code{add_u}, \\code{sample_system_effects}, \\code{simulate_population} and \\code{estimate_system_effects}. A separate population is generated for each phenotype (x, y and each of u) to allow 2SMR and PRS analyses\n#'\n#' @param nidx number of individuals for x\n#' @param nidy number of individuals for y\n#' @param nidu Default=0 If 0 then don't simulate separate populations for the u variables\n#' @param nu Default=0 Number of confounders influencing x and y\n#' @param na Default=0 Number of traits upstream of x\n#' @param nb Default=0 Number of traits upstream of y\n#' @param var_x.y var in y explained by x\n#' @param nsnp_x nsnp influencing x\n#' @param var_gx.x variance in x explained by instruments for x\n#' @param var_gx.y Default=0 \n#' @param mu_gx.y Default=0 \n#' @param prop_gx.y Default=1 \n#' @param nsnp_y Default=0 \n#' @param var_gy.y Default=0 \n#' @param var_gy.x Default=0 \n#' @param mu_gy.x Default=0 \n#' @param prop_gy.x Default=1 \n#'\n#' @export\n#' @return List of effects across system\ncreate_system <- function(nidx, nidy, nidu=0, nu=0, na=0, nb=0, var_x.y, nsnp_x, var_gx.x, var_gx.y=0, mu_gx.y=0, prop_gx.y=1, nsnp_y=0, var_gy.y=0, var_gy.x=0, mu_gy.x=0, prop_gy.x=1)\n{\n\tparameters <- init_parameters(nsnp_x=nsnp_x, nsnp_y=nsnp_y, var_gx.x=var_gx.x, var_gy.y=var_gy.y, var_x.y=var_x.y, var_gx.y=var_gx.y, mu_gx.y=mu_gx.y, prop_gx.y=prop_gx.y, var_gy.x=var_gy.x, mu_gy.x=mu_gy.x, prop_gy.x=prop_gy.x)\n\tif(nu > 0)\n\t{\n\t\tfor(i in 1:nu)\n\t\t{\n\t\t\tparameters <- add_u(\n\t\t\t\tparameters, \n\t\t\t\tnsnp_u=sample(5:30, 1), \n\t\t\t\tvar_u.x=stats::runif(1, min=0.01, max=0.1), \n\t\t\t\tvar_u.y=stats::runif(1, min=0.01, max=0.1), \n\t\t\t\tvar_gu.u=stats::runif(1, min=0.02, 0.2)\n\t\t\t)\n\t\t}\n\t}\n\tif(na > 0)\n\t{\n\t\tfor(i in 1:na)\n\t\t{\n\t\t\tparameters <- add_u(\n\t\t\t\tparameters, \n\t\t\t\tnsnp_u=sample(5:30, 1), \n\t\t\t\tvar_u.x=stats::runif(1, min=0.01, max=0.1), \n\t\t\t\tvar_u.y=0,\n\t\t\t\tvar_gu.u=stats::runif(1, min=0.02, 0.2)\n\t\t\t)\n\t\t}\n\t}\n\tif(nb > 0)\n\t{\n\t\tfor(i in 1:nb)\n\t\t{\n\t\t\tparameters <- add_u(\n\t\t\t\tparameters, \n\t\t\t\tnsnp_u=sample(5:30, 1), \n\t\t\t\tvar_u.x=0,\n\t\t\t\tvar_u.y=stats::runif(1, min=0.01, max=0.1),\n\t\t\t\tvar_gu.u=stats::runif(1, min=0.02, 0.2)\n\t\t\t)\n\t\t}\n\t}\n\n\tparameters <- sample_system_effects(parameters)\n\n\tmessage(\"X\")\n\tpop <- simulate_population(parameters, nidx)\n\tx <- estimate_system_effects(pop)\n\n\tmessage(\"Y\")\n\tpop <- simulate_population(parameters, nidy)\n\ty <- estimate_system_effects(pop)\n\n\tout <- list(x=x, y=y, parameters=parameters)\n\n\tif(nidu > 0)\n\t{\n\t\tu <- list()\n\t\tif(nu > 0)\n\t\t{\n\t\t\tfor(i in 1:nu)\n\t\t\t{\n\t\t\t\tmessage(\"U: \", i, \" of \", nu)\n\t\t\t\tpop <- simulate_population(parameters, nidu)\n\t\t\t\tu[[i]] <- estimate_system_effects(pop)\n\t\t\t}\n\t\t}\n\n\t\ta <- list()\n\t\tif(na > 0)\n\t\t{\n\t\t\tfor(i in 1:na)\n\t\t\t{\n\t\t\t\tmessage(\"A: \", i, \" of \", na)\n\t\t\t\tpop <- simulate_population(parameters, nidu)\n\t\t\t\ta[[i]] <- estimate_system_effects(pop)\n\t\t\t}\n\t\t}\n\n\t\tb <- list()\n\t\tif(nb > 0)\n\t\t{\n\t\t\tfor(i in 1:nb)\n\t\t\t{\n\t\t\t\tmessage(\"B: \", i, \" of \", nb)\n\t\t\t\tpop <- simulate_population(parameters, nidu)\n\t\t\t\tb[[i]] <- estimate_system_effects(pop)\n\t\t\t}\n\t\t}\n\t\tu <- c(u, a, b)\n\t\tnames(u) <- paste0(\"u\", 1:length(u))\n\t\tout$u <- u\n\t}\n\treturn(out)\n}\n\n\n#' Apply MR tests to system\n#'\n#'\n#' @param ss Output from create_syste,\n#' @param id string denoting simulation ID\n#'\n#' @export\n#' @return List\ntest_system <- function(ss, id=\"test\")\n{\n\tout <- list()\n\n\tdx <- merge_exp_out(ss$x$x, ss$y$y)\n\tdx$exposure <- paste0(\"X:\", id)\n\tdx$outcome <- paste0(\"Y:\", id)\n\tdx$id.exposure <- paste0(\"X:\", id)\n\tdx$id.outcome <- paste0(\"Y:\", id)\n\n\tdy <- merge_exp_out(ss$y$y, ss$x$x)\n\tdy$exposure <- paste0(\"Y:\", id)\n\tdy$outcome <- paste0(\"X:\", id)\n\tdy$id.exposure <- paste0(\"Y:\", id)\n\tdy$id.outcome <- paste0(\"X:\", id)\n\n\t# Oracle\n\tox <- subset(dx, grepl(\"x\", SNP))\n\tout$ox <- try(TwoSampleMR::mr_wrapper(ox)[[1]])\n\toy <- subset(dy, grepl(\"y\", SNP))\n\tout$oy <- try(TwoSampleMR::mr_wrapper(oy)[[1]])\n\n\t# Empirical\n\tex <- subset(dx, pval.exposure < 5e-8)\n\tout$ex <- try(TwoSampleMR::mr_wrapper(ex)[[1]])\n\tey <- subset(dy, pval.exposure < 5e-8)\n\tout$ey <- try(TwoSampleMR::mr_wrapper(ey)[[1]])\n\n\tparam <- expand.grid(\n\t\thypothesis = c(\"x\", \"y\"), \n\t\tselection = c(\"e\", \"o\"),\n\t\ttype = c(\"valid\", \"reverse\", \"confounder\")\n\t)\n\to <- list()\n\tfor(i in 1:nrow(param))\n\t{\n\t\to[[i]] <- dplyr::tibble(\n\t\t\thypothesis = param$hypothesis[i],\n\t\t\tselection = param$selection[i],\n\t\t\ttype = param$type[i],\n\t\t\tmeasure = c(\"nofilter\", \"outlier\", \"steiger\", \"both\"),\n\t\t\tcounts = get_counts(\n\t\t\t\tparam$type[i], \n\t\t\t\tparam$hypothesis[i],\n\t\t\t\tget(paste0(param$selection[i], param$hypothesis[i])), \n\t\t\t\tout[[paste0(param$selection[i], param$hypothesis[i])]]\n\t\t\t)\n\t\t)\n\t}\n\n\tout$instrument_validity <- dplyr::bind_rows(o) %>% dplyr::group_by(hypothesis, selection, type) %>% dplyr::mutate(n=dplyr::first(counts), pcounts=counts/n)\n\tout$instrument_validity$id <- id\n\n\t# Best model\n\tout$ex$estimates <- best_model(out$ex$estimates, ss$parameters$eff_x.y)\n\tout$ox$estimates <- best_model(out$ox$estimates, 0)\n\n\treturn(out)\n}\n\nget_counts <- function(type, hyp, dat, res)\n{\n\tif(type == \"valid\")\n\t{\n\t\tnode = hyp\n\t} else if(type == \"reverse\") {\n\t\tnode = ifelse(hyp==\"x\", \"y\", \"x\")\n\t} else {\n\t\tnode = \"u\"\n\t}\n\tc(\n\t\tnrow(res$snps_retained %>% subset(grepl(node, SNP))),\n\t\tnrow(subset(res$snps_retained, outlier) %>% subset(grepl(node, SNP))),\n\t\tnrow(subset(res$snps_retained, steiger) %>% subset(grepl(node, SNP))),\n\t\tnrow(subset(res$snps_retained, both) %>% subset(grepl(node, SNP)))\n\t)\n}\n\nbest_model <- function(res, bxy)\n{\n\tres$beta_correct <- res$ci_low <= bxy & res$ci_upp >= bxy\n\tres$beta_best <- FALSE\n\tres$beta_best[which.min(abs(res$b - bxy))] <- TRUE\n\tres$pval_sig <- res$pval < 0.05\n\tres$pval_lowest <- FALSE\n\tres$pval_lowest[which.min(res$pval)] <- TRUE\n\tres$pval_highest <- FALSE\n\tres$pval_highest[which.max(res$pval)] <- TRUE\n\treturn(res)\n}\n", "meta": {"hexsha": "4470721bdf9c798f6e731b0ecf000c627d1bbadf", "size": 12401, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mr_system.r", "max_stars_repo_name": "explodecomputer/simulateGP", "max_stars_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-05T16:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T16:58:46.000Z", "max_issues_repo_path": "R/mr_system.r", "max_issues_repo_name": "aeaswar81/simulateGP", "max_issues_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T16:14:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T16:14:15.000Z", "max_forks_repo_path": "R/mr_system.r", "max_forks_repo_name": "aeaswar81/simulateGP", "max_forks_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-10T19:27:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T16:59:02.000Z", "avg_line_length": 25.4640657084, "max_line_length": 297, "alphanum_fraction": 0.6285783405, "num_tokens": 4583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.35453162109329645}}
{"text": "###########################################################################################\n### Table 3 simulation (linear)\n###########################################################################################\neachCase <- function(case,eff=0)\n sapply(c('sh','ik','cft'),\n function(method) c(bias=case[paste0(method,'.est')]-eff,\n cover=case[paste0(method,'.CIl')]<=eff &\n case[paste0(method,'.CIh')]>=eff,\n width=case[paste0(method,'.CIh')]-\n case[paste0(method,'.CIl')])\n )\n\nlevTabCI <- function(res,eff=0){\n out <- NULL\n for(n in c(50,250,2500))\n for(err in c('norm','t')){\n run <- res[[paste(n,eff,err,sep='_')]]\n row <- NULL\n for(meth in c('cft','sh','ik'))\n row <- c(row,\n if(is.list(run))\n mean(sapply(run,function(x) x[paste0(meth,'.p')])<0.05,na.rm=TRUE)\n else mean(run[paste0(meth,'.p'),]<0.05))\n\n out <- rbind(out,row)\n rownames(out)[nrow(out)] <- paste(err,n)\n }\n colnames(out) <- c('cft','sh','ik')\n out\n}\n\ndisplayCIsimHet <- function(res,tau=0,caption='',label=''){\n ## omit cases where one of the methods (ours?) didn't converge, gave NA\n res <- lapply(res,function(x) t(x[,apply(x,2,function(cc) !any(is.na(cc)))]))\n\n res <- res[grep(paste0('_tau',tau,'W'),names(res),fixed=TRUE)]\n res <- res[grepl('Wnone|Wt',names(res))]\n\n\n tab0 <- lapply(res,function(x)\n apply(sapply(1:nrow(x),function(i) eachCase(x[i,],eff=tau),simplify='array'),\n 1:2,mean))\n\n tab0 <- lapply(tab0,function(xx){\n out <- rbind(sprintf(\"%.2f\",round(xx[1,],2)),sprintf(\"%i\",as.integer(round(xx[2,]*100))),sprintf(\"%.2f\",round(xx[3,],2)))\n dimnames(out) <- dimnames(xx)\n out})\n\n cat('\n\\\\begin{table}\n\\\\footnotesize\n\\\\begin{tabular}{ccc|ccc|ccc|ccc}\n\\\\hline\n\n&&& \\\\multicolumn{ 3 }{c}{Permutation}&\\\\multicolumn{ 3 }{c}{\\`\\`Limitless\\'\\'}&\\\\multicolumn{ 3 }{c}{Local OLS}\\\\\\\\\n$n$& Effect& Error &', paste(rep(c('Bias','Cover.','Width'),3),collapse='&'),'\\\\\\\\\n\\\\hline \\n')\n for(n in c(50,250,2500))\n# for(err in c('norm','t')){\n for(rr in c('n0','t0','tt')){\n row <- NULL\n err <- ifelse(rr=='n0','norm','t')\n eff <- ifelse(rr=='tt','$t_3$',0)\n for(meth in c('cft','sh','ik'))\n row <- c(row,tab0[[paste0(n,'_err',err,'_tau',tau,'W',ifelse(rr=='tt','t','none'))]][,meth])\n if(err=='norm'){\n cat('\\\\hline \\n')\n cat('\\\\multirow{3}{*}{',n,'} &0& $\\\\mathcal{N}(0,1)$ &')\n } else cat(' & ',eff,'& $t_3$ &')\n cat(paste(row,collapse='&'),'\\\\\\\\ \\n')\n }\n cat('\\\\hline\n\\\\end{tabular}\n \\\\caption{',caption,'}\n \\\\label{',label,'}\\n',sep='')\n cat('\\\\end{table}\\n')\n}\n\ndispAllSimp <- function(res){\n res <- sapply(res,function(x) t(x[,apply(x,2,function(cc) !any(is.na(cc)))]),simplify=FALSE)\n tab0 <- lapply(names(res),function(nn){\n x <- res[[nn]]\n tau <- ifelse(grepl('tau0.2',nn,fixed=TRUE),0.2,0)\n apply(sapply(1:nrow(x),function(i) eachCase(x[i,],eff=tau),simplify='array'),\n 1:2,mean)\n })\n\n cond <- strsplit(names(res),'_')\n cond <- lapply(cond,function(x) gsub('err|tau','',x))\n cond <- lapply(cond,function(x) c(x[1],x[2],strsplit(x[3],'W')[[1]]))\n cond <- do.call('rbind',cond)\n out <- data.frame(tab0[[1]],stringsAsFactors=FALSE)\n out <- cbind(cond[rep(1,3),],c('Bias','Coverage','Width'),out)\n\n for(i in 2:length(tab0))\n out <- rbind(out,cbind(cond[rep(i,3),],\n c('Bias','Coverage','Width'),\n data.frame(tab0[[i]],stringsAsFactors=FALSE)))\n\n\n names(out) <- c('n','error','ATE','TE randomness','meas','Limitless','Local-OLS','Permutation')\n\n out\n}\n\n\n###########################################################################################\n### Table 4 simulation (polynomial)\n###########################################################################################\n\n\n#' @export\n## dgms <- function(tp){\n\n## ### the DGMs\n## curve(0.5*x,from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='Linear')\n## abline(v=0,lty=2)\n## curve(ifelse(abs(x)>0.5, 3*x+sign(x)*(0.5-3)*0.5,0.5*x),from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='Anti-Symmetric')\n## abline(v=0,lty=2)\n## #curve(ifelse(x>0.5,3*x+(0.5-3)*0.5,0.5*x),from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='One-Sided')\n## curve(mu4,from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='One-Sided')\n## abline(v=0,lty=2)\n## }\n\ndgms <- function(){\n lin <- function(x) 0.5*x\n as <- function(x) ifelse(abs(x)>0.5,3*x+sign(x)*(0.5-3)*0.5,lin(x))\n mu4 <- function(x) sin(3*x)\n p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))+xlim(-1,1)+\n theme(axis.line=element_blank(),\n axis.text.x=element_blank(),\n axis.text.y=element_blank(),\n axis.ticks=element_blank(),\n #axis.title.x='$r$',\n #axis.title.y='$\\\\EE[Y|R=r]$',\n legend.position=\"none\",\n ## panel.background=element_blank(),\n ## panel.border=element_blank(),\n ## panel.grid.major=element_blank(),\n ## panel.grid.minor=element_blank(),\n ## plot.background=element_blank()\n )+xlab('$r$')+ylab('$\\\\EE[Y|R=r]$')\n\n gridExtra::grid.arrange(p+stat_function(fun=lin)+ggtitle('Linear'),\n p+stat_function(fun=as)+ggtitle('Anti-Symmetric'),\n p+stat_function(fun=mu4)+ggtitle('Sine'),nrow=1)\n}\n\nresTab <- function(run,full=FALSE){\n llr <- run[c(nrow(run)-1,nrow(run)),]\n run <- run[-c(nrow(run)-1,nrow(run)),]\n\n pvals <- run[seq(1,nrow(run)-1,2),]\n ests <- run[seq(2,nrow(run),2),]\n\n runPsh <- pvals[seq(1,nrow(pvals),2),]\n runPik <- pvals[seq(2,nrow(pvals),2),]\n\n runEstsh <- ests[seq(1,nrow(ests),2),]\n runEstik <- ests[seq(2,nrow(ests),2),]\n\n\n tabFun <- function(runP,runEst,full){\n tab <- rbind(\n level=apply(runP,1,function(x) mean(x<0.05,na.rm=TRUE)),\n RMSE=apply(runEst,1,function(x) sqrt(mean(x^2,na.rm=TRUE))))\n if(full) tab <- rbind(tab,\n bias=rowMeans(runEst,na.rm=TRUE),\n sd=apply(runEst,1,sd,na.rm=TRUE))\n tab\n }\n list(tabSH=tabFun(runPsh,runEstsh,full=full),\n tabIK=tabFun(runPik,runEstik,full=full),\n tabLLR=tabFun(rbind(llr[1,]),rbind(llr[2,]),full=full))\n}\n\n\nresTab <- function(run,full=FALSE){\n run <- run[,apply(run,2,function(x) !any(is.na(x)))]\n tabFun <- function(ests)\n rbind(\n bias=rowMeans(rbind(ests)),\n RMSE=sqrt(rowMeans(rbind(ests^2))))\n\n tabFunP <- function(ps)\n apply(rbind(ps),1,function(x) mean(x<0.05,na.rm=TRUE))\n\n\n out <- sapply(c('sh','ik','ll'),function(mm) tabFun(run[grep(paste0(mm,'.est'),rownames(run)),]),\n simplify=FALSE)\n\n if(full) out <- sapply(c('sh','ik','ll'),\n function(mm) rbind(out[[mm]],level= tabFunP(run[grep(paste0(mm,'.p'),rownames(run)),])),\n simplify=FALSE)\n\n out\n}\n\n#' @export\nprntTab <- function(totalPoly,maxDeg=4,full=TRUE,md=FALSE){\n tab <- NULL\n\n if(maxDeg>(nrow(totalPoly[[1]])-2)/4){\n maxDeg <- (nrow(totalPoly[[1]])-2)/4\n if(!full)\n warning(paste('There don\\'t seem to be that many degrees in the simulation.\\n Setting maxDeg=',maxDeg))\n }\n\n ctab <- function(runname,full){\n run <- totalPoly[[runname]]\n res <- resTab(run,full=full)\n\n cbind(res[['sh']][,1:maxDeg],\n res[['ik']][,1:maxDeg],\n res[['ll']])\n }\n for(dgm in c('lin','antiSym','wass')){\n tab <- rbind(tab,ctab(paste0(dgm,'_t'),full))\n if(full) if(paste0(dgm,'_norm')%in%names(totalPoly)) tab <- rbind(tab,ctab(paste0(dgm,'_norm'),full))\n }\n if(md){\n colnames(tab) <- c(paste('LRD, deg=',1:maxDeg),paste('OLS, deg=',1:maxDeg),'Loc.Lin')\n rownames(tab) <- paste(rep(c('lin','antiSym','sine'),\n each=nrow(tab)/sum(rownames(tab)=='bias')),#,times=2),\n #rep(c('t err','norm err'),each=nrow(tab)/2),\n rownames(tab))\n }\n return(tab)\n}\n\n#' @export\npolyLatex <- function(tab,full,caption='',label='tab:poly'){\n if(NCOL(tab)!=9) stop('This only works with polynomial degree=1,...,4')\n cat('\n \\\\begin{table}[ht]\n\\\\centering\n\\\\begin{tabular}{cr|llll|llll|l',ifelse(full,'|llll|llll|l}','}'),'\n \\\\hline \\n')\n if(full) cat('&&\\\\multicolumn{9}{c|}{$t_3$ Errors} &\\\\multicolumn{9}{c|}{$\\\\mathcal{N}(0,1)$ Errors} \\\\\\\\ \\n')\n\n cat('&& \\\\multicolumn{4}{c|}{Limitless} & \\\\multicolumn{4}{c|}{OLS} &\\\\makecell[c]{Local\\\\\\\\Linear}',\n ifelse(full,'\\\\multicolumn{4}{c|}{Limitless} & \\\\multicolumn{4}{c|}{OLS} &\\\\makecell[c]{Local\\\\\\\\Linear}',''),'\\\\\\\\\n \\\\multicolumn{2}{r|}{\\\\makecell[r]{Polynomial\\\\\\\\Degree}}&1&2&3&4&1&2&3&4&',ifelse(full,'&1&2&3&4&1&2&3&4&n/a','n/a'),' \\\\\\\\\n')\n for(rr in 1:nrow(tab)){\n if(rr==1) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Linear\\\\end{sideways}','Linear'),'}')\n if(rr==3) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Anti-Sym\\\\end{sideways}','Anti-Sym'),'}')\n if(rr==5) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}One-Side\\\\end{sideways}','One-Side'),'}')\n cat('&',rownames(tab)[rr],'&')\n cat(paste(sprintf(\"%.1f\", round(tab[rr,],1)),collapse='&'))\n cat('\\\\\\\\ \\n')\n }\n cat('\n \\\\hline\n\\\\end{tabular}\n\\\\caption{',caption,'}\n\\\\label{',label,'}\n\\\\end{table}\\n',sep='')\n\n}\n\n#' @export\npolyLatex5 <- function(tab,full,caption='',label='tab:poly'){\n if(NCOL(tab)!=11) stop('This only works with polynomial degree=1,...,5')\n tab2 <- tab\n for(i in 1:nrow(tab)) for(j in 1:ncol(tab))\n tab2[i,j] <- ifelse(tab[i,j]>10,\n sprintf(\"%i\",as.integer(round(tab[i,j]))),\n sprintf(\"%.1f\",round(tab[i,j],1)))\n\n cat('\n \\\\begin{table}[ht]\n\\\\centering\n\\\\begin{tabular}{ll|ccccc|ccccc|c',ifelse(full,'|llll|llll|l}','}'),'\n \\\\hline \\n')\n if(full) cat('&&\\\\multicolumn{11}{c|}{$t_3$ Errors} &\\\\multicolumn{11}{c|}{$\\\\mathcal{N}(0,1)$ Errors} \\\\\\\\ \\n')\n\n cat('&& \\\\multicolumn{5}{c|}{Limitless} & \\\\multicolumn{5}{c|}{OLS} &Local',\n ifelse(full,'\\\\multicolumn{5}{c|}{Limitless} & \\\\multicolumn{5}{c|}{OLS} &Local',''),'\\\\\\\\\n && \\\\multicolumn{5}{c|}{Polynomial Degree}&\\\\multicolumn{5}{c|}{Polynomial Degree}&Linear',\n ifelse(full,'\\\\multicolumn{5}{c|}{Polynomial Degree}&\\\\multicolumn{5}{c|}{Polynomial Degree}&Linear',''),'\\\\\\\\\n DGM&Measure&1&2&3&4&5&1&2&3&4&5&',ifelse(full,'&1&2&3&4&1&2&3&4&5&',''),' \\\\\\\\\n')\n for(rr in 1:nrow(tab)){\n if(rr==1) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Linear\\\\end{sideways}','Linear'),'}',sep='')\n if(rr==3) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Anti-Sym\\\\end{sideways}','\\\\makecell[c]{Anti-\\\\\\\\Sym}'),'}',sep='')\n if(rr==5) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}One-Side\\\\end{sideways}','Sine'),'}',sep='')\n cat('&',rownames(tab)[rr],'&')\n cat(paste(tab2[rr,],collapse='&'))\n cat('\\\\\\\\ \\n')\n }\n cat('\n \\\\hline\n\\\\end{tabular}\n\\\\caption{',caption,'}\n\\\\label{',label,'}\n\\\\end{table}\\n',sep='')\n\n}\n\n\n", "meta": {"hexsha": "955d5051ad4ebe5a74ae4fb58d70ffb03de2f3b3", "size": 11404, "ext": "r", "lang": "R", "max_stars_repo_path": "R/displaySim.r", "max_stars_repo_name": "adamSales/lrd", "max_stars_repo_head_hexsha": "dcf9637cce7afe241a35f118718533be55c3bd26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/displaySim.r", "max_issues_repo_name": "adamSales/lrd", "max_issues_repo_head_hexsha": "dcf9637cce7afe241a35f118718533be55c3bd26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/displaySim.r", "max_forks_repo_name": "adamSales/lrd", "max_forks_repo_head_hexsha": "dcf9637cce7afe241a35f118718533be55c3bd26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-05-07T15:07:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-30T19:06:03.000Z", "avg_line_length": 37.761589404, "max_line_length": 176, "alphanum_fraction": 0.5268326903, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.35348600489656395}}
{"text": "=begin\n= Changes\n== 0.71(2005.07.26)\n* MPolynomial#derivate\n* MPolynomial#map_to\n\n== 0.70(2005.02.02)\n* id => object_id\n\n== 0.69(2004.10.15)\n* MRationalFunctionField\n* MPolynomial#gcd\n* SquareMatrix#inverse depends on ufd?\n\n== 0.68(2004.07.28)\n* fix Mpolynomial#to_s (for tex)\n\n== 0.67(2004.06.10)\n* need_paren_in_coeff?\n* Matrix: entries are regulated.\n* Matrix: type*type is due to wedge.\n* AlgebraicSystem: wedge, superior?\n* Polynomial#sub, MPolynomial#sub\n* SquareMatrix.determinant\n* fix MPolynomial#to_s\n* fix Factors#normalize!\n* (Co)Vector#norm2, inner_product\n\n== 0.66(2004.06.05)\n* fix _hensel_lift (add param 'where')\n* sample-geometry01.rb\n* title of docs\n\n== 0.65(2004.06.04)\n* Polynomial#factor over Polynomial\n* reverse var's order in value_on & convert_to in polynomial-convert.rb\n\n== 0.64(2004.03.01)\n* return value of SquareMatrix#diagonalize is Strut\n\n== 0.63(2004.01.08)\n* fix matrix[i, j] = x\n\n== 0.62(2003.11.13)\n* allow f.gcd_coeff_all()\n\n== 0.61(2003.11.06)\n* corrected Enumerable#any? in finite-set.rb\n\n== 0.60(2003.07.28)\n* AlgebraMatrix(cofactor, cofactor_matrix, adjoint)\n\n== 0.59(2003.07.28)\n* adapted to the version 1.8.0(preview 4)\n* include installer\n\n== 0.58(2002.04.00)\n* AlgebraicExtensionField#[n] is lift[n]\n* abolish the field of 'poly_exps' of the splitting field' and add 'proots'\n* MatrixAlgebra#rank\n* Raise Exception for the inverse of the non invertible square matrix\n* Use \"import-module\" for monomial order (0.57.18.01)\n\n== 0.57 (2002.03.16)\n* New class\n * Set\n * Map\n * Group\n * PermuationGroup\n * AlgebraicExtensionField\n* New methods\n * Galois#group\n * Polynomial#splitting_field\n* Rename MinimalDecompositionField to decompose\n* Move *.rb to lib/\n* Define Polynomial.to_ary and MPolynomial.to_ary\n\n== 0.56 (2002.02.06)\n* MPolynomial#with_ord\n* Orderings belong to MPolynomial.\n* MIndex is not a subclass of Array, now.\n* \"Integer < Numeric\" ==> \"Integer\"\n\n== 0.55 (2001.11.15)\n* Improve Algorithm of Factorization over algebraic fields\n\n== 0.54 (2001.11.05)\n* Elementary Divisor\n* Jordan Form\n* Minimal Decomposition Field\n\n== 0.53 (2001.10.03)\n\n* move \"MatrixAlgebra\" to \"Algebra::MatrixAlgebra\"\n* move \"MatrixAlgebra::Vector\" to \"Algebra::Vector\"\n* move \"MatrixAlgebra::Covector\" to \"Algebra::Covector\",\n* move \"MatrixAlgebra::SquareMatrix\" to \"Algebra::SquareMatrix\"\n\n== 0.52 (2001.09.22)\n\n* One-variate polynomial\n * Fundamental operations (addition, multiplication, quotient/remainder, ...)\n * factorization\n* Multi-variate polynomial\n * Fundamental operations (addition, multiplication, ...)\n * factorization\n * Creating Groebner-basis, quotient/remainder by Groebner-basis.\n* Algebraic systems\n * Creating quotient fields\n * Creating residue class fields\n * Operating matrices.\n* Linear Algebra\n * Diagonalization of Symmetrix Matrix\n\n== 0.40 (2001.03.03)\n\n* Initial Version\n\n=end\n", "meta": {"hexsha": "7976612379a332892c2ba0478a446099d0b20674", "size": 2855, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/changes.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/changes.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/changes.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7916666667, "max_line_length": 78, "alphanum_fraction": 0.7243432574, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3532147701894888}}
{"text": "#' ---\n#' title: \"Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions\"\n#' author: \"Judith Degen\"\n#' date: \"January 26, 2014\"\n#' ---\n\nlibrary(ggplot2)\ntheme_set(theme_bw(18))\nsetwd(\"/Users/titlis/cogsci/conferences_talks/_2015/5_berkeley/\")\nsource(\"rscripts/helpers.r\")\n\n# get prior expectations\npriorexpectations = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorexpectations) = paste(priorexpectations$effect, priorexpectations$object)\n\n# histogram of expectations\nexps = ggplot(priorexpectations, aes(x=expectation_corr)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\",breaks=seq(0,8, by=2))\nggsave(\"priorexpectations-histogram.pdf\",width=5,height=3.7)\n\n\n# get prior allstate-probs\npriorprobs = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorprobs) = priorprobs$Item\nhead(priorprobs)\n\n# histogram of allstate-probs\nallprobs = ggplot(priorprobs, aes(x=X15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Prior all-state probability\") +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"priorallprobs-histogram.pdf\")\n\npdf(\"priordistributions.pdf\",width=10,height=4)\ngrid.arrange(exps, allprobs, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\")))\ndev.off()\n\n#####################################\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n\nlibrary(dplyr)\nlibrary(plyr)\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\npexpectations = ddply(toplot, .(Item), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = some\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\n\n\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5 & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData\")\nsummary(mp)\ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_r = toplot\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\",wes_palette(\"Darjeeling\")[1])) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior mean all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior all-state probability\") \np_probs\nggsave(\"pred_probs.pdf\")\n\np_probs = ggplot(toplot_r, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Posterior all-state probability\") \np_probs\nggsave(\"pred_prob_rsa.pdf\")\n\n\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\n\npexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot_w = toplot\n\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData\")\ntoplot_r = toplot\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_r$PriorExpectation = toplot_r$PriorExpectation_smoothed*15\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\n\np_exps = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\",wes_palette(\"Darjeeling\")[1])) +#values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior mean number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Predicted posterior number of objects\") \np_exps\nggsave(\"pred_exps.pdf\")\n\np_exps = ggplot(toplot_r, aes(x=PriorExpectation, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\")) +#values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior expectation\") \np_exps\nggsave(\"pred_exps_rsa.pdf\")\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_exps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_exps_nolegend = p_exps + theme(legend.position=\"none\")\np_probs_nolegend = p_probs + theme(legend.position=\"none\")\n\npdf(\"rsa-predictions.pdf\",width=12,height=4.9)\ngrid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData\")\n\nagr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nagr$Quantifier = factor(x=agr$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \np_eexps\nggsave(file=\"empirical_exps.pdf\")#,width=5,height=3.7)\n\n\n# allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData\")\n\n# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)\ntmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)\nub = subset(agrr, Proportion == \"100\")\nub = droplevels(ub)\nub$Quantifier = factor(x=ub$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(limits=c(0,1),name=\"Posterior probability of all-state \") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(limits=c(0,1),name=\"Prior probability of all-state\") \np_eprobs\nggsave(file=\"empirical-allprobs.pdf\")#,width=5,height=3.7)\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_eexps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_eexps_nolegend = p_eexps + theme(legend.position=\"none\")\np_eprobs_nolegend = p_eprobs + theme(legend.position=\"none\")\n\npdf(\"empirical-results.pdf\",width=12,height=4.9)\ngrid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(wr, WonkyWorldPrior == .5 & Wonky == \"true\"))\nnrow(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n#toplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$Quantifier, levels=c(\"some\",\"all\",\"none\"))\n\np_wmodel = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier,shape=Quantifier)) +\n geom_point() + \n geom_smooth() + \n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n #scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Predicted posterior wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wmodel\nggsave(\"model-wonkiness-uniform.pdf\",width=6.8,height=5)#,width=30,height=10)\n\n############\n# empirical wonkiness posteriors\n############\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData\")\nhead(r)\nnrow(r)\n\ntoplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN=\"mean\", data=r)\ntoplot = droplevels(subset(toplot, quantifier %in% c(\"All\",\"Some\",\"None\")))\ntoplot$Quantifier = factor(tolower(toplot$quantifier), levels=c(\"all\", \"none\",\"some\"))\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\ntoplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$quantifier, levels=c(\"Some\",\"All\",\"None\"))\n\np_wempirical = ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier,shape=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wempirical\nggsave(file=\"empirical-wonkiness.pdf\",width=6.8,height=5)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_wmodel + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_wmodel_nolegend = p_wmodel + theme(legend.position=\"none\")\np_wempirical_nolegend = p_wempirical + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"wonkiness-fullplot.pdf\",width=12,height=5)\ngrid.arrange(p_wmodel_nolegend, p_wempirical_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n", "meta": {"hexsha": "239d4e0eac89e72803fe0b7a9f25bcba261fb745", "size": 13812, "ext": "r", "lang": "R", "max_stars_repo_path": "writing/_2015/cogsci_2015/talk/rscripts/plots.r", "max_stars_repo_name": "thegricean/sinking-marbles", "max_stars_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/_2015/cogsci_2015/talk/rscripts/plots.r", "max_issues_repo_name": "thegricean/sinking-marbles", "max_issues_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/_2015/cogsci_2015/talk/rscripts/plots.r", "max_forks_repo_name": "thegricean/sinking-marbles", "max_forks_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5050505051, "max_line_length": 234, "alphanum_fraction": 0.7430495222, "num_tokens": 4249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.35321476845132627}}
{"text": "# Xiaofeng Xu created this file in May 2020, and updated in Sep 2020, and finalized with 14C on Nov 11 2020\nlibrary(\"RNetCDF\")\nlibrary(\"akima\")\nrm(list=ls())\nsetwd(\"/Users/xxuadmin/BUSINESS/PUBLICATIONS/WorkingOn_Xu_Isotope/SPRUCE_2020Sep\")\n# 13C is based on the PD standard Pee Dee Belemnite (PDB). 13C:12C = 0.0112372.\n# 13C/12C(sample) / 13C/12C(standard - 1)\n# 13C = (delta / 1000 + 1) * 0.0112372 * 12C\n\n# for the spruce site, the 14C = 12C * ((1 + delta14C / 1000) * (1.176e-12/((1+delta13C)*(1+delta13C)/(1-0.025)/(1-0.025)))\n# the 13Cdealta is -25 per mil for standard sample; this is for SPRUCE site based on the data from Erik Hobbie at UNH\n\ndata <- read.csv(\"Peat_Characteristics_T0_20180425_plot.csv\", header=TRUE)\nO13C <- data[1:16,3:4]\nO14C <- data[1:16,5]\n#depth 25, 15, 5, -5, -25, -35, -45, -55, -65, -85, -113, -163, -188, -225, -255\n#CLM depth 0.71, 2.8, 6.2, 11.9, 21.2, 36.6, 61.97, 103.8, 172.8, 286.5, 473.9, 782.97, 1292.5, 2132.6, 3517.8 \n\ndepth <- c(0.0071, 0.0028, 0.0623, 0.1189, 0.2122, 0.366, 0.6197, 1.038, 1.72, 2.86)\n\n#Hommock\n#25 for layer 1, 2, 3\n#15 for layer 4\n# 5 for layer 5, \n#-5 for layer 6,\n#-25, -35, -45 for layer 7\n#-55, -65, and -85 for layer 8\n# -113, -163, and -188 for layer 9\n# -255 for layer 10 2.86\n\n#Hollow\n#-5 for layer 1, 2, 3\n# -15 for layer 4, \n#-25 for layer 5,\n#-35 for layer 6\n#-45 -55, and -65 for layer 7 0.6197\n#-85 and -133 for layer 8 1.038\n# -163 and -188 for layer 9 1.72\n# -225 and -275 for layer 10 2.86\nSO13C = array(0, dim=c(15,2))\n#L13C = O13C[3,1]\nSO13C[1,1] = O13C[1,1]\nSO13C[2,1] = O13C[1,1]\nSO13C[3,1] = O13C[1,1]\nSO13C[4,1] = O13C[2,1]\nSO13C[5,1] = O13C[3,1]\nSO13C[6,1] = O13C[4,1]\nSO13C[7,1] = mean(O13C[5:7,1])\nSO13C[8,1] = mean(O13C[8:10,1])\nSO13C[9,1] = mean(O13C[11:13,1])\nSO13C[10,1] = mean(O13C[14:15,1])\n\nSO13C[1,2] = mean(O13C[3:4,1])\nSO13C[2,2] = mean(O13C[3:4,1])\nSO13C[3,2] = mean(O13C[3:4,1])\nSO13C[4,2] = mean(O13C[4:5,1])\nSO13C[5,2] = mean(O13C[6:7,1])\nSO13C[6,2] = mean(O13C[8:9,1])\nSO13C[7,2] = mean(O13C[8:9,1])\nSO13C[8,2] = mean(O13C[10:11,1])\nSO13C[9,2] = mean(O13C[12:13,1])\nSO13C[10,2] = mean(O13C[14:16,1])\n\n#plot(SO13C[1:10,1],-depth,type=\"l\",xlab=\"soil 13CH4 (mmol/L)\", ylab=\"soil depth (m)\",cex=1,las=1, cex.lab = 1.5, cex.axis = 1.5,lwd=2)\n\nSO14C = array(0, dim=c(15,2))\nSO14C[1,1] = O14C[1]\nSO14C[2,1] = O14C[1]\nSO14C[3,1] = O14C[1]\nSO14C[4,1] = O14C[2]\nSO14C[5,1] = O14C[3]\nSO14C[6,1] = O14C[4]\nSO14C[7,1] = mean(O14C[5:7])\nSO14C[8,1] = mean(O14C[8:10])\nSO14C[9,1] = mean(O14C[11:13])\nSO14C[10,1] = mean(O14C[14:15])\n\nSO14C[1,2] = O14C[4]\nSO14C[2,2] = O14C[4]\nSO14C[3,2] = O14C[4]\nSO14C[4,2] = O14C[5]\nSO14C[5,2] = O14C[6]\nSO14C[6,2] = mean(O14C[7:9])\nSO14C[7,2] = mean(O14C[7:9])\nSO14C[8,2] = mean(O14C[10:11])\nSO14C[9,2] = mean(O14C[12:13])\nSO14C[10,2] = mean(O14C[14:16])\n\n#13C_ave\tDepth_ave\n#-29.058\t25\n#-28.34\t15\n#-28.1075\t5\n#-28.77631579\t-5\n#-27.79684211\t-15\n#-27.006\t-25\n#-26.72888889\t-35\n#-26.45055556\t-45\n#-26.60555556\t-55\n#-26.36611111\t-65\n#-26.05333333\t-85\n#-25.93\t-113\n#-26.39176471\t-163\n#-26.27\t-188\n#-26.63857143\t-225\n#-25.75\t-275\n\n#depth\t14C_mean\t14Cto12C\n#25\t40.65714286\t1.23406E-12\n#15\t54.37692308\t1.24849E-12\n#5\t112.4714286\t1.31665E-12\n#-5\t68.17647059\t1.26596E-12\n#-15\t140.0176471\t1.34839E-12\n#-25\t114.2\t 1.31571E-12\n#-35\t-99.17647059\t1.06314E-12\n#-45\t-180.2058824\t9.66953E-13\n#-55\t-199.9941176\t9.43913E-13\n#-65\t-286.2058824\t8.41779E-13\n#-85\t-358.8117647\t7.55669E-13\n#-113\t-392.4058824\t7.15896E-13\n#-163\t-486.13125\t6.06039E-13\n#-188\t-350.8\t 7.65452E-13\n#-225\t-571.1\t 5.06086E-13\n#-275\t-703.75\t 3.48927E-13\n\ncomputC13 <- function(C12, deltaC)\n{\n (deltaC / 1000.0 + 1.0) * 0.0112372 * C12\n}\n\ncomputC14 <- function(C12, deltaC13, deltaC14)\n{\n C12 * ((1.0 + deltaC14 / 1000) * (1.176e-12/((1+deltaC13)*(1+deltaC13)/(1-0.000025)/(1-0.000025))))\n}\n \n#14C = 12C * ((1 + delta14C / 1000) * (1.176e-12/((1+delta13C)*(1+delta13C)/(1-0.025)/(1-0.025)))\n \n#notice: please copy a file with the name of fileoutput in the following code for variable to be incorporated\nfileinput <- open.nc(\"SPRUCE-finalspinup-peatland-carbon-initial.nc\") # 2012 year climate data\n#filerestart <- open.nc(\"SPR_I20TRCLM45CN_adspinup.clm2.r.1201-01-01-00000.nc\")\nfileoutput <- open.nc(\"SPRUCE-finalspinup-peatland-ISOcarbon-initial.nc\",write=TRUE)\n\n#depth <- c(0.0071, 0.0028, 0.0623, 0.1189, 0.2122, 0.366, 0.6197, 1.038, 1.72, 2.86)\n#thick <- c(0.0175128179, 0.0275789693, 0.0454700332, 0.0749674110, 0.1236003651, 0.2037825510, 0.3359806264, 0.5539384054, 0.9132900316, 1.5057607014)\n#realcarbondensity = c(22385, 22385, 22385, 30294, 43978, 95584, 92983, 83658, 83799, 90616)\n\ncwdc_vr <- var.get.nc(fileinput, \"cwdc_vr\")\nlitr1c_vr <- var.get.nc(fileinput, \"litr1c_vr\")\nlitr2c_vr <- var.get.nc(fileinput, \"litr2c_vr\")\nlitr3c_vr <- var.get.nc(fileinput, \"litr3c_vr\")\nsoil1c_vr <- var.get.nc(fileinput, \"soil1c_vr\")\nsoil2c_vr <- var.get.nc(fileinput, \"soil2c_vr\")\nsoil3c_vr <- var.get.nc(fileinput, \"soil3c_vr\")\nsoil4c_vr <- var.get.nc(fileinput, \"soil4c_vr\")\n\ncwdn_vr <- var.get.nc(fileinput, \"cwdn_vr\")\nlitr1n_vr <- var.get.nc(fileinput, \"litr1c_vr\")\nlitr2n_vr <- var.get.nc(fileinput, \"litr2n_vr\")\nlitr3n_vr <- var.get.nc(fileinput, \"litr3n_vr\")\nsoil1n_vr <- var.get.nc(fileinput, \"soil1n_vr\")\nsoil2n_vr <- var.get.nc(fileinput, \"soil2n_vr\")\nsoil3n_vr <- var.get.nc(fileinput, \"soil3n_vr\")\nsoil4n_vr <- var.get.nc(fileinput, \"soil4n_vr\")\n\n#rc13_canair <- var.get.nc(filerestart, \"rc13_canair\")\n#rc13_psnsun <- var.get.nc(filerestart, \"rc13_psnsun\")\n#rc13_psnsha <- var.get.nc(filerestart, \"rc13_psnsha\")\n#leafc_13 <- var.get.nc(filerestart, \"leafc_13\")\n#leafc_storage_13 <- var.get.nc(filerestart, \"leafc_storage_13\")\n#leafc_xfer_13 <- var.get.nc(filerestart, \"leafc_xfer_13\")\n#frootc_13 <- var.get.nc(filerestart, \"frootc_13\")\n#frootc_storage_13 <- var.get.nc(filerestart, \"frootc_storage_13\")\n#frootc_xfer_13 <- var.get.nc(filerestart, \"frootc_xfer_13\")\n#livestemc_13 <- var.get.nc(filerestart, \"livestemc_13\")\n#livestemc_storage_13 <- var.get.nc(filerestart, \"livestemc_storage_13\")\n#livestemc_xfer_13 <- var.get.nc(filerestart, \"livestemc_xfer_13\")\n#deadstemc_13 <- var.get.nc(filerestart, \"deadstemc_13\")\n#deadstemc_storage_13 <- var.get.nc(filerestart, \"deadstemc_storage_13\")\n#deadstemc_xfer_13 <- var.get.nc(filerestart, \"deadstemc_xfer_13\")\n#livecrootc_13 <- var.get.nc(filerestart, \"livecrootc_13\")\n#deadstemc_13 <- var.get.nc(filerestart, \"deadstemc_13\")\n\ncwdc_13_vr = cwdc_vr\nlitr1c_13_vr = litr1c_vr\nlitr2c_13_vr = litr2c_vr\nlitr3c_13_vr = litr3c_vr\nsoil1c_13_vr = soil1c_vr\nsoil2c_13_vr = soil2c_vr\nsoil3c_13_vr = soil3c_vr\nsoil4c_13_vr = soil4c_vr\n\n# C14 \ncwdc_14_vr = cwdc_vr\nlitr1c_14_vr = litr1c_vr\nlitr2c_14_vr = litr2c_vr\nlitr3c_14_vr = litr3c_vr\nsoil1c_14_vr = soil1c_vr\nsoil2c_14_vr = soil2c_vr\nsoil3c_14_vr = soil3c_vr\nsoil4c_14_vr = soil4c_vr\n\nbacteriac_vr = litr1c_vr\nfungic_vr = litr1c_vr\ndomc_vr = litr1c_vr\nseedc = litr1c_vr\ncol_ctrunc_vr = litr1c_vr\n\ntotlitc = litr1c_vr\ntotcolc = litr1c_vr\nprod10c = litr1c_vr\nprod100c = litr1c_vr\n\nbacteriac_13_vr = bacteriac_vr\nfungic_13_vr = fungic_vr\ndomc_13_vr = domc_vr\nseedc_13 = seedc\ncol_ctrunc_13_vr = col_ctrunc_vr\n\ntotlitc_13 = totlitc\ntotcolc_13 = totcolc\nprod10c_13 = prod10c\nprod100c_13 = prod100c\n\n#C14\nbacteriac_14_vr = bacteriac_vr\nfungic_14_vr = fungic_vr\ndomc_14_vr = domc_vr\nseedc_14 = seedc\ncol_ctrunc_14_vr = col_ctrunc_vr\n\ntotlitc_14 = totlitc\ntotcolc_14 = totcolc\nprod10c_14 = prod10c\nprod100c_14 = prod100c\n\nfor(i in 1:10)\n{\ncwdc_13_vr[i,1] = computC13(cwdc_vr[i,1], SO13C[i])\nlitr1c_13_vr[i,1] = computC13(litr1c_vr[i,1], SO13C[i])\nlitr2c_13_vr[i,1] = computC13(litr2c_vr[i,1], SO13C[i])\nlitr3c_13_vr[i,1] = computC13(litr3c_vr[i,1], SO13C[i])\nsoil1c_13_vr[i,1] = computC13(soil1c_vr[i,1], SO13C[i])\nsoil2c_13_vr[i,1] = computC13(soil2c_vr[i,1], SO13C[i])\nsoil3c_13_vr[i,1] = computC13(soil3c_vr[i,1], SO13C[i])\nsoil4c_13_vr[i,1] = computC13(soil4c_vr[i,1], SO13C[i])\n\nbacteriac_13_vr[i,1] = computC13(bacteriac_vr[i,1], SO13C[i])\nfungic_13_vr[i,1] = computC13(fungic_vr[i,1], SO13C[i])\ndomc_13_vr[i,1] = computC13(domc_vr[i,1], SO13C[i])\nseedc_13[i,1] = computC13(seedc[i,1], SO13C[i])\ncol_ctrunc_13_vr[i,1] = computC13(col_ctrunc_vr[i,1], SO13C[i])\ntotlitc_13[i,1] = computC13(totlitc[i,1], SO13C[i])\ntotcolc_13[i,1] = computC13(totcolc[i,1], SO13C[i])\nprod10c_13[i,1] = computC13(prod10c[i,1], SO13C[i])\nprod100c_13[i,1] = computC13(prod100c[i,1], SO13C[i])\n\ncwdc_13_vr[i,2] = computC13(cwdc_vr[i,2], SO13C[i])\nlitr1c_13_vr[i,2] = computC13(litr1c_vr[i,2], SO13C[i])\nlitr2c_13_vr[i,2] = computC13(litr2c_vr[i,2], SO13C[i])\nlitr3c_13_vr[i,2] = computC13(litr3c_vr[i,2], SO13C[i])\nsoil1c_13_vr[i,2] = computC13(soil1c_vr[i,2], SO13C[i])\nsoil2c_13_vr[i,2] = computC13(soil2c_vr[i,2], SO13C[i])\nsoil3c_13_vr[i,2] = computC13(soil3c_vr[i,2], SO13C[i])\nsoil4c_13_vr[i,2] = computC13(soil4c_vr[i,2], SO13C[i])\n\nbacteriac_13_vr[i,2] = computC13(bacteriac_vr[i,2], SO13C[i])\nfungic_13_vr[i,2] = computC13(fungic_vr[i,2], SO13C[i])\ndomc_13_vr[i,2] = computC13(domc_vr[i,2], SO13C[i])\nseedc_13[i,2] = computC13(seedc[i,2], SO13C[i])\ncol_ctrunc_13_vr[i,2] = computC13(col_ctrunc_vr[i,2], SO13C[i])\ntotlitc_13[i,2] = computC13(totlitc[i,2], SO13C[i])\ntotcolc_13[i,2] = computC13(totcolc[i,2], SO13C[i])\nprod10c_13[i,2] = computC13(prod10c[i,2], SO13C[i])\nprod100c_13[i,2] = computC13(prod100c[i,2], SO13C[i])\n}\n\nfor(i in 11:15)\n{\ncwdc_13_vr[i,1] = 0.0\nlitr1c_13_vr[i,1] = 0.0\nlitr2c_13_vr[i,1] = 0.0\nlitr3c_13_vr[i,1] = 0.0\nsoil1c_13_vr[i,1] = 0.0\nsoil2c_13_vr[i,1] = 0.0\nsoil3c_13_vr[i,1] = 0.0\nsoil4c_13_vr[i,1] = 0.0\n \nbacteriac_13_vr[i,1] = 0.0\nfungic_13_vr[i,1] = 0.0\ndomc_13_vr[i,1] = 0.0\nseedc_13[i,1] = 0.0\ncol_ctrunc_13_vr[i,1] = 0.0\n\ntotlitc_13[i,1] = 0.0\ntotcolc_13[i,1] = 0.0\nprod10c_13[i,1] = 0.0\nprod100c_13[i,1] = 0.0\n \ncwdc_13_vr[i,2] = 0.0\nlitr1c_13_vr[i,2] = 0.0\nlitr2c_13_vr[i,2] = 0.0\nlitr3c_13_vr[i,2] = 0.0\nsoil1c_13_vr[i,2] = 0.0\nsoil2c_13_vr[i,2] = 0.0\nsoil3c_13_vr[i,2] = 0.0\nsoil4c_13_vr[i,2] = 0.0\n \nbacteriac_13_vr[i,2] = 0.0\nfungic_13_vr[i,2] = 0.0\ndomc_13_vr[i,2] = 0.0\nseedc_13[i,2] = 0.0\ncol_ctrunc_13_vr[i,2] = 0.0\n \ntotlitc_13[i,2] = 0.0\ntotcolc_13[i,2] = 0.0\nprod10c_13[i,2] = 0.0\nprod100c_13[i,2] = 0.0\n}\n\nfor(i in 1:10)\n{\n cwdc_14_vr[i,1] = computC14(cwdc_vr[i,1], cwdc_13_vr[i,1], SO14C[i])\n litr1c_14_vr[i,1] = computC14(litr1c_vr[i,1], litr1c_13_vr[i,1], SO14C[i])\n litr2c_14_vr[i,1] = computC14(litr2c_vr[i,1], litr2c_13_vr[i,1], SO14C[i])\n litr3c_14_vr[i,1] = computC14(litr3c_vr[i,1], litr3c_13_vr[i,1], SO14C[i])\n soil1c_14_vr[i,1] = computC14(soil1c_vr[i,1], soil1c_13_vr[i,1], SO14C[i])\n soil2c_14_vr[i,1] = computC14(soil2c_vr[i,1], soil2c_13_vr[i,1], SO14C[i])\n soil3c_14_vr[i,1] = computC14(soil3c_vr[i,1], soil3c_13_vr[i,1], SO14C[i])\n soil4c_14_vr[i,1] = computC14(soil4c_vr[i,1], soil4c_13_vr[i,1], SO14C[i])\n \n bacteriac_14_vr[i,1] = computC14(bacteriac_vr[i,1], bacteriac_13_vr[i,1], SO14C[i])\n fungic_14_vr[i,1] = computC14(fungic_vr[i,1], fungic_13_vr[i,1], SO14C[i])\n domc_14_vr[i,1] = computC14(domc_vr[i,1], domc_13_vr[i,1], SO14C[i])\n seedc_14[i,1] = computC14(seedc[i,1], seedc_13[i,1], SO14C[i])\n col_ctrunc_14_vr[i,1] = computC14(col_ctrunc_vr[i,1], col_ctrunc_13_vr[i,1], SO14C[i])\n totlitc_14[i,1] = computC14(totlitc[i,1], totlitc_13[i,1], SO14C[i])\n totcolc_14[i,1] = computC14(totcolc[i,1], totcolc_13[i,1], SO14C[i])\n prod10c_14[i,1] = computC14(prod10c[i,1], prod10c_13[i,1], SO14C[i])\n prod100c_14[i,1] = computC14(prod100c[i,1], prod100c_13[i,1], SO14C[i])\n \n cwdc_14_vr[i,2] = computC14(cwdc_vr[i,2], cwdc_13_vr[i,2], SO14C[i])\n litr1c_14_vr[i,2] = computC14(litr1c_vr[i,2], litr1c_13_vr[i,2], SO14C[i])\n litr2c_14_vr[i,2] = computC14(litr2c_vr[i,2], litr2c_13_vr[i,2], SO14C[i])\n litr3c_14_vr[i,2] = computC14(litr3c_vr[i,2], litr3c_13_vr[i,2], SO14C[i])\n soil1c_14_vr[i,2] = computC14(soil1c_vr[i,2], soil1c_13_vr[i,2], SO14C[i])\n soil2c_14_vr[i,2] = computC14(soil2c_vr[i,2], soil2c_13_vr[i,2], SO14C[i])\n soil3c_14_vr[i,2] = computC14(soil3c_vr[i,2], soil3c_13_vr[i,2], SO14C[i])\n soil4c_14_vr[i,2] = computC14(soil4c_vr[i,2], soil4c_13_vr[i,2], SO14C[i])\n \n bacteriac_14_vr[i,2] = computC14(bacteriac_vr[i,2], bacteriac_13_vr[i,2], SO14C[i])\n fungic_14_vr[i,2] = computC14(fungic_vr[i,2], fungic_13_vr[i,2], SO14C[i])\n domc_14_vr[i,2] = computC14(domc_vr[i,2], domc_13_vr[i,2], SO14C[i])\n seedc_14[i,2] = computC14(seedc[i,2], seedc_13[i,2], SO14C[i])\n col_ctrunc_14_vr[i,2] = computC14(col_ctrunc_vr[i,2], col_ctrunc_13_vr[i,2], SO14C[i])\n totlitc_14[i,2] = computC14(totlitc[i,2], totlitc_13[i,2], SO14C[i])\n totcolc_14[i,2] = computC14(totcolc[i,2], totcolc_13[i,2], SO14C[i])\n prod10c_14[i,2] = computC14(prod10c[i,2], prod10c_13[i,2], SO14C[i])\n prod100c_14[i,2] = computC14(prod100c[i,2], prod100c_13[i,2], SO14C[i])\n}\n\nfor(i in 11:15)\n{\n cwdc_14_vr[i,1] = 0.0\n litr1c_14_vr[i,1] = 0.0\n litr2c_14_vr[i,1] = 0.0\n litr3c_14_vr[i,1] = 0.0\n soil1c_14_vr[i,1] = 0.0\n soil2c_14_vr[i,1] = 0.0\n soil3c_14_vr[i,1] = 0.0\n soil4c_14_vr[i,1] = 0.0\n \n bacteriac_14_vr[i,1] = 0.0\n fungic_14_vr[i,1] = 0.0\n domc_14_vr[i,1] = 0.0\n seedc_14[i,1] = 0.0\n col_ctrunc_14_vr[i,1] = 0.0\n \n totlitc_14[i,1] = 0.0\n totcolc_14[i,1] = 0.0\n prod10c_14[i,1] = 0.0\n prod100c_14[i,1] = 0.0\n \n cwdc_14_vr[i,2] = 0.0\n litr1c_14_vr[i,2] = 0.0\n litr2c_14_vr[i,2] = 0.0\n litr3c_14_vr[i,2] = 0.0\n soil1c_14_vr[i,2] = 0.0\n soil2c_14_vr[i,2] = 0.0\n soil3c_14_vr[i,2] = 0.0\n soil4c_14_vr[i,2] = 0.0\n \n bacteriac_14_vr[i,2] = 0.0\n fungic_14_vr[i,2] = 0.0\n domc_14_vr[i,2] = 0.0\n seedc_14[i,2] = 0.0\n col_ctrunc_14_vr[i,2] = 0.0\n \n totlitc_14[i,2] = 0.0\n totcolc_14[i,2] = 0.0\n prod10c_14[i,2] = 0.0\n prod100c_14[i,2] = 0.0\n}\n\n\n# \n#rc13_canair = c(0.005582864, 0.002791432)\n#rc13_psnsha = c(0.005544063, 0.002771556)\n#rc13_psnsun = c(0.0055442, 0.002771556)\n#\n\n#levgrnd = 15\n#column = 2\n#var.def.nc(fileoutput,\"levgrnd\",\"NC_FLOAT\",\"levgrnd\")\n#var.def.nc(fileoutput,\"column\",\"NC_FLOAT\",\"column\")\n\nvar.def.nc(fileoutput,\"cwdc_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr1c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr2c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr3c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil1c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil2c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil3c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil4c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"bacteriac_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"fungic_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"domc_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"seedc_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"col_ctrunc_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totlitc_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totcolc_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod10c_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod100c_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\n\nvar.def.nc(fileoutput,\"cwdc_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr1c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr2c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr3c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil1c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil2c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil3c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil4c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"bacteriac_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"fungic_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"domc_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"seedc_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"col_ctrunc_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totlitc_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totcolc_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod10c_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod100c_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\n\nvar.put.nc(fileoutput, \"cwdc_vr\",cwdc_vr)\nvar.put.nc(fileoutput, \"litr1c_vr\",litr1c_vr)\nvar.put.nc(fileoutput, \"litr2c_vr\",litr2c_vr)\nvar.put.nc(fileoutput, \"litr3c_vr\",litr3c_vr)\nvar.put.nc(fileoutput, \"soil1c_vr\",soil1c_vr)\nvar.put.nc(fileoutput, \"soil2c_vr\",soil2c_vr)\nvar.put.nc(fileoutput, \"soil3c_vr\",soil3c_vr)\nvar.put.nc(fileoutput, \"soil4c_vr\",soil4c_vr)\n\nvar.put.nc(fileoutput, \"cwdn_vr\",cwdn_vr)\nvar.put.nc(fileoutput, \"litr1n_vr\",litr1n_vr)\nvar.put.nc(fileoutput, \"litr2n_vr\",litr2n_vr)\nvar.put.nc(fileoutput, \"litr3n_vr\",litr3n_vr)\nvar.put.nc(fileoutput, \"soil1n_vr\",soil1n_vr)\nvar.put.nc(fileoutput, \"soil2n_vr\",soil2n_vr)\nvar.put.nc(fileoutput, \"soil3n_vr\",soil3n_vr)\nvar.put.nc(fileoutput, \"soil4n_vr\",soil4n_vr)\n\natt.put.nc(fileoutput, \"cwdc_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"cwdc_13_vr\",cwdc_13_vr)\n\natt.put.nc(fileoutput, \"litr1c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr1c_13_vr\",litr1c_13_vr)\n\natt.put.nc(fileoutput, \"litr2c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr2c_13_vr\",litr2c_13_vr)\n\natt.put.nc(fileoutput, \"litr3c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr3c_13_vr\",litr3c_13_vr)\n\natt.put.nc(fileoutput, \"soil1c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil1c_13_vr\",soil1c_13_vr)\n\natt.put.nc(fileoutput, \"soil2c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil2c_13_vr\",soil2c_13_vr)\n\natt.put.nc(fileoutput, \"soil3c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil3c_13_vr\",soil3c_13_vr)\n\natt.put.nc(fileoutput, \"soil4c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil4c_13_vr\",soil4c_13_vr)\n\natt.put.nc(fileoutput, \"bacteriac_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"bacteriac_13_vr\",bacteriac_13_vr)\n\natt.put.nc(fileoutput, \"fungic_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"fungic_13_vr\",fungic_13_vr)\n\natt.put.nc(fileoutput, \"domc_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"domc_13_vr\",domc_13_vr)\n\natt.put.nc(fileoutput, \"seedc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"seedc_13\",seedc_13)\n\natt.put.nc(fileoutput, \"col_ctrunc_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"col_ctrunc_13_vr\",col_ctrunc_13_vr)\n\natt.put.nc(fileoutput, \"totlitc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totlitc_13\",totlitc_13)\n\natt.put.nc(fileoutput, \"totcolc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totcolc_13\",totcolc_13)\n\natt.put.nc(fileoutput, \"prod10c_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod10c_13\",prod10c_13)\n\natt.put.nc(fileoutput, \"prod100c_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod100c_13\",prod100c_13)\n\n# 14C\natt.put.nc(fileoutput, \"cwdc_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"cwdc_14_vr\",cwdc_14_vr)\n\natt.put.nc(fileoutput, \"litr1c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr1c_14_vr\",litr1c_14_vr)\n\natt.put.nc(fileoutput, \"litr2c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr2c_14_vr\",litr2c_14_vr)\n\natt.put.nc(fileoutput, \"litr3c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr3c_14_vr\",litr3c_14_vr)\n\natt.put.nc(fileoutput, \"soil1c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil1c_14_vr\",soil1c_14_vr)\n\natt.put.nc(fileoutput, \"soil2c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil2c_14_vr\",soil2c_14_vr)\n\natt.put.nc(fileoutput, \"soil3c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil3c_14_vr\",soil3c_14_vr)\n\natt.put.nc(fileoutput, \"soil4c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil4c_14_vr\",soil4c_14_vr)\n\natt.put.nc(fileoutput, \"bacteriac_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"bacteriac_14_vr\",bacteriac_14_vr)\n\natt.put.nc(fileoutput, \"fungic_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"fungic_14_vr\",fungic_14_vr)\n\natt.put.nc(fileoutput, \"domc_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"domc_14_vr\",domc_14_vr)\n\natt.put.nc(fileoutput, \"seedc_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"seedc_14\",seedc_14)\n\natt.put.nc(fileoutput, \"col_ctrunc_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"col_ctrunc_14_vr\",col_ctrunc_14_vr)\n\natt.put.nc(fileoutput, \"totlitc_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totlitc_14\",totlitc_14)\n\natt.put.nc(fileoutput, \"totcolc_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totcolc_14\",totcolc_14)\n\natt.put.nc(fileoutput, \"prod10c_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod10c_14\",prod10c_14)\n\natt.put.nc(fileoutput, \"prod100c_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod100c_14\",prod100c_14)\n\n# new file\n#var.def.nc(fileoutput,\"rc13_canair\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"rc13_canair\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"rc13_canair\",rc13_canair)\n\n#var.def.nc(fileoutput,\"rc13_psnsun\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"rc13_psnsun\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"rc13_psnsun\",rc13_psnsun)\n\n#var.def.nc(fileoutput,\"rc13_psnsha\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"rc13_psnsha\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"rc13_psnsha\",rc13_psnsha)\n\n#var.def.nc(fileoutput,\"leafc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"leafc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"leafc_13\",leafc_13)\n\n#var.def.nc(fileoutput,\"leafc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"leafc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"leafc_storage_13\",leafc_storage_13)\n\n#var.def.nc(fileoutput,\"leafc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"leafc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"leafc_xfer_13\",leafc_xfer_13)\n\n#var.def.nc(fileoutput,\"frootc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"frootc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"frootc_13\",frootc_13)\n\n#var.def.nc(fileoutput,\"frootc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"frootc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"frootc_storage_13\",frootc_storage_13)\n\n#var.def.nc(fileoutput,\"frootc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"frootc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"frootc_xfer_13\",frootc_xfer_13)\n\n#var.def.nc(fileoutput,\"livestemc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livestemc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livestemc_13\",livestemc_13)\n\n#var.def.nc(fileoutput,\"livestemc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livestemc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livestemc_storage_13\",livestemc_storage_13)\n\n#var.def.nc(fileoutput,\"livestemc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livestemc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livestemc_xfer_13\",livestemc_xfer_13)\n\n#var.def.nc(fileoutput,\"deadstemc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_13\",deadstemc_13)\n\n#var.def.nc(fileoutput,\"deadstemc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_storage_13\",deadstemc_storage_13)\n\n#var.def.nc(fileoutput,\"deadstemc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_xfer_13\",deadstemc_xfer_13)\n\n#var.def.nc(fileoutput,\"livecrootc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livecrootc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livecrootc_13\",livecrootc_13)\n\n#var.def.nc(fileoutput,\"deadstemc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_13\",deadstemc_13)\n\natt.put.nc(fileoutput,\"NC_GLOBAL\",\"title\",\"NC_CHAR\",\"isotopic 13 carbon pools and 14 carbon pools\")\n\nclose.nc(fileinput)\nclose.nc(fileoutput)\n\n", "meta": {"hexsha": "5174f6a3a2d002d743150d8d4465cbbc9616ab01", "size": 25306, "ext": "r", "lang": "R", "max_stars_repo_path": "inputdata/lnd/clm2/inidata/2020Sep/SPRUCE-initial20200923.r", "max_stars_repo_name": "email-clm/clm-microbe", "max_stars_repo_head_hexsha": "3470e673957e4e3c3d730c5979a89d1448e9e4e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-03-12T01:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T03:08:25.000Z", "max_issues_repo_path": "inputdata/lnd/clm2/inidata/2020Sep/SPRUCE-initial20200923.r", "max_issues_repo_name": "email-clm/clm-microbe", "max_issues_repo_head_hexsha": "3470e673957e4e3c3d730c5979a89d1448e9e4e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-21T01:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T01:51:13.000Z", "max_forks_repo_path": "inputdata/lnd/clm2/inidata/2020Sep/SPRUCE-initial20200923.r", "max_forks_repo_name": "email-clm/CLM-Microbe", "max_forks_repo_head_hexsha": "711c87faec2c1bfe2cea1a7ebd07e4373e82a184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-03-08T21:04:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T03:29:35.000Z", "avg_line_length": 39.173374613, "max_line_length": 151, "alphanum_fraction": 0.6999525804, "num_tokens": 11365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3527520337238278}}
{"text": "#' ---\n#' title: \"Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions\"\n#' author: \"Judith Degen\"\n#' date: \"January 26, 2014\"\n#' ---\n\nlibrary(ggplot2)\ntheme_set(theme_bw(18))\nsetwd(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/_journal_cognition/pics/\")\nsource(\"../rscripts/helpers.r\")\n\n# get prior modes\npriormodes = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/modes.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priormodes) = paste(priormodes$Item)\n\n# get prior expectations\npriorexpectations = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/24_sinking-marbles-prior-fourstep/results/data/expectations.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorexpectations) = priorexpectations$Item\n\n# histogram of expectations\nexps = ggplot(priorexpectations, aes(x=expectation_corr)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\",breaks=seq(0,8, by=2))\nggsave(\"priorexpectations-histogram.pdf\",width=5,height=3.7)\n\n\n# get prior allstate-probs\npriorprobs = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/24_sinking-marbles-prior-fourstep/results/data/smoothed_15marbles_priors_withnames.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorprobs) = priorprobs$Item\nhead(priorprobs)\n\n# histogram of allstate-probs\nallprobs = ggplot(priorprobs, aes(x=X15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Prior all-state probability\") +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"priorallprobs-histogram.pdf\")\n\nlibrary(gridExtra)\npdf(\"priordistributions.pdf\",width=10,height=4)\ngrid.arrange(exps, allprobs, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\")))\ndev.off()\n\n#####################################\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n# plot expectations for unreliable speaker model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\"))\nnrow(toplot)\nhead(toplot)\nsummary(toplot)\nub = droplevels(subset(toplot, State == 15))\n\nggplot(ub, aes(x=PriorProbability, y=PosteriorProbability, color=as.factor(SpeakerOptimality))) +\n geom_point() +#color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() +#color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior all-state probability\") +\n facet_wrap(~WonkyWorldPrior)\nggsave(\"speakerreliability-ieoptimality.pdf\",height=8,width=11)\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\npexpectations = ddply(toplot, .(Item), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\n\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\n\npexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n# geom_text(data=cors, aes(label=r)) +\n\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \nggsave(\"model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nsave(toplot, file=\"../data/toplot-expectations.RData\")\n\n# plot by prior mode instead\nggplot(toplot, aes(x=Mode, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), name=\"Prior mode\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData\")\ntoplot_r = toplot\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot regular rsa predictions\nggplot(toplot_r, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15)) +\n geom_point(color=\"#007fb1\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#007fb1\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expected number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior predicted number of objects\")\n# geom_text(data=cors, aes(label=r)) +\n\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \nggsave(\"model-expectations-rrsa.pdf\",width=6.5,height=4.5)#,width=30,height=10)\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_exps = ggplot(toplot, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expected number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior predicted number of objects\")\n# geom_text(data=cors, aes(label=r)) +\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \n#ggsave(\"graphs/model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-expectations-binomial-regular.pdf\",width=6.5,height=4.5)\nggsave(\"model-expectations-uniform-regular.pdf\",width=6.5,height=4.5)\n\n\n# plot model predictions: allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & Quantifier == \"some\" & WonkyWorldPrior == .5 & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\nggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior probability of all-state\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior probability of all-state\")\n# geom_text(data=cors, aes(label=r)) +\n\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \nggsave(\"model-allprobs.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-uniform-allprobs.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nsave(toplot, file=\"../data/toplot-allprobs.RData\")\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData\")\nsummary(mp)\ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_r = toplot\n\n# plot only rrsa\nggplot(toplot_r, aes(x=PriorProbability, y=PosteriorProbability)) +\n geom_point(color=\"#007fb1\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#007fb1\") + #color=\"#00B0F6\") +\n #scale_color_manual(values=c(\"#007fb1\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior probability of all-state\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior probability of all-state\")\n# geom_text(data=cors, aes(label=r)) +\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \n#ggsave(\"graphs/model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-allprobs-rrsa.pdf\",width=6.5,height=4.5)\n\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior probability of all-state\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior probability of all-state\")\n# geom_text(data=cors, aes(label=r)) +\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \n#ggsave(\"graphs/model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-allprobs-binomial-regular.pdf\",width=6.5,height=4.5)\nggsave(\"model-allprobs-uniform-regular.pdf\",width=6.5,height=4.5)\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_exps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_exps_nolegend = p_exps + theme(legend.position=\"none\")\np_probs_nolegend = p_probs + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"rsa-predictions.pdf\",width=10,height=4)\ngrid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\ns = subset(r, quantifier==\"Some\" & Proportion == \"100\")\nnrow(s)\n\nlibrary(lmerTest)\nm=lmer(normresponse ~ AllPriorProbability + (1+AllPriorProbability|workerid) + (1|Item), data=s)\nsummary(m)\n\n\n\n#####################################\n# plot model predictions: wonkiness\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData\")\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-binomial.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(wr, WonkyWorldPrior == .5 & Wonky == \"true\"))\nnrow(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nmod = toplot\nnrow(toplot)\nhead(toplot)\n\np_wmodel = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Model predicted wonkiness probability\")\n\nggsave(\"model-wonkiness-uniform.pdf\",width=5.5,height=4)#,width=30,height=10)\nggsave(\"model-wonkiness-binomial.pdf\",width=5.5,height=4)#,width=30,height=10)\n\n# plot by mode\nggplot(toplot, aes(x=Mode, y=PosteriorProbability,color=Quantifier)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Model predicted wonkiness probability\")\n\n############\n# empirical wonkiness posteriors\n############\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData\")\nhead(r)\nnrow(r)\n\nggplot(r, aes(x=response, fill=quantifier)) +\n geom_histogram() +\n facet_grid(workerid~quantifier)\nggsave(\"subject-variability-wonkiness.pdf\",width=7,height=25)\n\ntoplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN=\"mean\", data=r)\ntoplot = droplevels(subset(toplot, quantifier %in% c(\"All\",\"Some\",\"None\")))\ntoplot$Quantifier = factor(tolower(toplot$quantifier), levels=c(\"all\", \"none\",\"some\"))\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\np_wempirical = ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") \nggsave(file=\"empirical-wonkiness.pdf\",width=5.5,height=4)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_wmodel + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_wmodel_nolegend = p_wmodel + theme(legend.position=\"none\")\np_wempirical_nolegend = p_wempirical + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"wonkiness-fullplot.pdf\",width=12,height=5)\ngrid.arrange(p_wmodel_nolegend, p_wempirical_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# scatterplot of mdoel vs empirical\nhead(toplot)\ntoplot$PosteriorProbability = toplot$response\nhead(mod)\ntoplot$Type = \"empirical\"\nmod$Type = \"model\"\n\npl = merge(mod, toplot, all=T)\nsummary(pl)\npl$Type = as.factor(as.character(pl$Type))\ntopl = pl %>% select(Item, Quantifier,PosteriorProbability,Type) %>%\n spread(Type,PosteriorProbability)\nsummary(topl)\n\nggplot(topl, aes(x=model,y=empirical,color=Quantifier,group=1)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\"))\ncor(topl$model,topl$empirical,use=\"pairwise.complete.obs\") # cor=.69\n\nlibrary(hydroGOF)\ngof(topl$model,topl$empirical,na.rm=T,do.spearman=T)\n\n#plot by mode\nggplot(toplot, aes(x=Mode, y=response, color=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") \n\n\n\n###############\n## EMPIRICAL PLOTS\n###############\n\n# expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData\")\n\nagr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)\n#agr$CILow = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r, FUN=ci.low)$ProportionResponse\n#agr$CIHigh = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=ci.high)$ProportionResponse\n#agr$YMin = agr$ProportionResponse - agr$CILow\n#agr$YMax = agr$ProportionResponse + agr$CIHigh\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \nggsave(file=\"meanresponses.pdf\",width=5,height=3.7)\n\n\n# allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData\")\n\n# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)\ntmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)\nub = subset(agrr, Proportion == \"100\")\nub = droplevels(ub)\n\np_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=quantifier)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agrr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(limits=c(0,1),name=\"Posterior probability of all-state \") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(limits=c(0,1),name=\"Prior probability of all-state\") \nggsave(file=\"empirical-allprobs.pdf\",width=5,height=3.7)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_eexps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_eexps_nolegend = p_eexps + theme(legend.position=\"none\")\np_eprobs_nolegend = p_eprobs + theme(legend.position=\"none\")\n\npdf(\"empirical-results.pdf\",width=10,height=4)\ngrid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# plot subejct variability for exclusion\nggplot(r[r$Proportion == \"0\",], aes(x=normresponse,fill=quantifier)) +\n geom_histogram() +\n facet_grid(workerid~quantifier) \nggsave(\"subject-variability.pdf\",width=5.5,height=4)\n\n\n\n\n\n\n\n######################\n### NOAH'S MODEL PREDICTIONS\nrsa_allstate = read.csv(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-allstate.csv\",header=F)\nhead(rsa_allstate)\ncolnames(rsa_allstate) = c(\"BinomialCW\",\"PosteriorAllProbability\")\nggplot(rsa_allstate, aes(x=BinomialCW,y=PosteriorAllProbability)) +\n geom_point(color=\"#00B0F6\") +\n scale_x_continuous(limits=c(0,1), name=\"Binomial coin weight\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior probability of all-state\") \nggsave(\"noahs-allstate-predictions.pdf\",width=4.5,height=3.5) \n\nrsa_expectation = read.csv(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectation.csv\",header=F)\nhead(rsa_expectation)\ncolnames(rsa_expectation) = c(\"PriorExpectation\",\"PosteriorExpectation\")\nggplot(rsa_expectation, aes(x=PriorExpectation/15,y=PosteriorExpectation/15)) +\n geom_point(color=\"#00B0F6\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior expectation\") \nggsave(\"noahs-expectation-predictions.pdf\",width=4.5,height=3.5) \n\nrsa_expall = read.csv(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectedVsallstate.csv\",header=F)\nhead(rsa_expall)\ncolnames(rsa_expall) = c(\"PriorExpectation\",\"PosteriorExpectation\")\nggplot(rsa_expall, aes(x=PriorExpectation/15,y=PosteriorExpectation)) +\n geom_point(color=\"#00B0F6\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior probability of all-state\") \nggsave(\"noahs-allstate-predictions-bypriorexp.pdf\",width=4.5,height=3.5) \n\n\n", "meta": {"hexsha": "1e83b1f2eda02c5f87df4cdafdeabd2ede72310a", "size": 21567, "ext": "r", "lang": "R", "max_stars_repo_path": "writing/_2015/_journal_cognition/rscripts/plots.r", "max_stars_repo_name": "thegricean/sinking-marbles", "max_stars_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/_2015/_journal_cognition/rscripts/plots.r", "max_issues_repo_name": "thegricean/sinking-marbles", "max_issues_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/_2015/_journal_cognition/rscripts/plots.r", "max_forks_repo_name": "thegricean/sinking-marbles", "max_forks_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3806451613, "max_line_length": 222, "alphanum_fraction": 0.7403440441, "num_tokens": 6696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3526136708121351}}
{"text": "subroutine inddup(x,y,n,rw,frac,dup)\nimplicit double precision(a-h,o-z)\nlogical dup(n)\ndimension x(n), y(n), rw(4)\n\nxtol = frac*(rw(2)-rw(1))\nytol = frac*(rw(4)-rw(3))\n\ndup(1) = .false.\ndo i = 2,n {\n\tdup(i) = .false.\n\tdo j = 1,i-1 {\n\t\tdx = abs(x(i)-x(j))\n\t\tdy = abs(y(i)-y(j))\n\t\tif(dx < xtol & dy < ytol) {\n\t\t\tdup(i) = .true.\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nreturn\nend\n", "meta": {"hexsha": "a01a2080b4f6a5b87dccc88d934eb9a0b5f21714", "size": 356, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/inddup.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/inddup.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/inddup.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 14.8333333333, "max_line_length": 36, "alphanum_fraction": 0.5421348315, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3523235188660187}}
{"text": "#' barefootr: A package for holding useful functions for Eric\n#'\n#' I use this package to hold some functions that are useful to me.\n#' \n#' @section barefootr functions:\n#' \n#' The functions here make up a mix of tools to calculate and estimate modern suficial processes and back-calculate those processes in ancient rivers. \n#' \n#' \\code{settle} calculates the settling velocity of particles following the formulation by Dietrich (1982).\n#' \n#' \\code{lynds_one} estimates ancient river slope using the first method described by Lynds et al. (2014)\n#' \n#' \\code{lynds_two} estimates ancient river slope using the second method described by Lynds et al. (2014)\n#' \n#' \\code{lynds_three} estimates ancient river slope using the third method described by Lynds et al. (2014)\n#'\n#' \\code{xset2H} estimates ancient river dune heights based on cross-set thicknesses. Methods from Leclair and Paola.\n#' \n#' \\code{H2h} estimates ancient river depths based on dune heights. Methods from Bradley and Venditti.\n#' \n#' \\code{xset2depthSimple} estimates ancient river depths directly from cross-set thicknesses using the simplest assumptions. Methods from Leclair, Paola, and Bradley and Venditti.\n#'\n#' \\code{azStringConvert} Azimuth conversion for 'quadrant' based strike/trend measurements.\n#' \n#' \n#' \n#' \n#' \n#' \n#' \n#' @docType package\n#' @name barefootr\nNULL", "meta": {"hexsha": "54545afef5aa510a15139677ae1858cc2f95d241", "size": 1352, "ext": "r", "lang": "R", "max_stars_repo_path": "R/barefootr.r", "max_stars_repo_name": "ericbarefoot/barefootr", "max_stars_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/barefootr.r", "max_issues_repo_name": "ericbarefoot/barefootr", "max_issues_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/barefootr.r", "max_forks_repo_name": "ericbarefoot/barefootr", "max_forks_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9696969697, "max_line_length": 180, "alphanum_fraction": 0.75, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3516196361020301}}
{"text": "# The MIT License (MIT)\n# Copyright (c) 2017 Louise AC Millard, MRC Integrative Epidemiology Unit, University of Bristol\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without\n# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions\n# of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n# splits the pheno into 3 bins with the cut points between values rather at the exact value for the quantile\nequalSizedBins <- function(phenoAvg) {\n\n\t## equal sized bins \n q = quantile(phenoAvg, probs=c(1/3,2/3), na.rm=TRUE)\n\n\tminX = min(phenoAvg, na.rm=TRUE)\n\tmaxX = max(phenoAvg, na.rm=TRUE)\n\n\tphenoBinned = phenoAvg;\n\tif (q[1]==minX) {\n\t\t# edge case - quantile value is lowest value\n\n\t\t# assign min value as cat1\n\t\tidx1 = which(phenoAvg==q[1]);\n\t\tphenoBinned[idx1] = 0;\n\n\t\t# divide remaining values into cat2 and cat3\n\t\tphenoAvgRemaining = phenoAvg[which(phenoAvg!=q[1])];\n\t\tqx = quantile(phenoAvgRemaining, probs=c(0.5), na.rm=TRUE)\n\t\tminXX = min(phenoAvgRemaining, na.rm=TRUE)\n\t\tmaxXX =\tmax(phenoAvgRemaining, na.rm=TRUE)\n\n\t\tif (qx[1]==minXX) {\n\t\t\t# edge case again - quantile value is lowest value\n\t\t\tidx2 = which(phenoAvg==qx[1]);\n\t\t\tidx3 = which(phenoAvg>qx[1]);\n\t\t\tcat(\"Bin 1: ==\", q[1],\", bin 2: ==\",qx[1], \"bin 3: >\", qx[1], \" || \", sep=\"\")\n\t\t}\n\t\telse if (qx[1]==maxXX) {\n\t\t\t# edge case again - quantile value is max value\n\t\t\tidx2 = which(phenoAvgq[1]);\n\t\t\tidx3 = which(phenoAvg==qx[1]);\n\t\t\tcat(\"Bin 1: ==\", q[1],\", bin 2: > \",q[1], \" AND <\", qx[1] , \"bin 3: ==\", qx[1], \" || \", sep=\"\")\n\t\t}\n\t\telse {\n\t\t\tidx2 = which(phenoAvgq[1]);\n\t\t\tidx3 = which(phenoAvg>=qx[1]);\n\t\t\tcat(\"Bin 1: ==\", q[1],\", bin 2: > \",q[1], \" AND <\", qx[1] , \"bin 3: >=\", qx[1], \" || \", sep=\"\")\n\t\t}\n\t\tphenoBinned[idx2] = 1;\n phenoBinned[idx3] = 2;\n\t}\n\telse if (q[2]==maxX) {\n\t\t# edge case - quantile value is highest value\n\n\t\t# assign max value as cat3\n\t\tidx3 = which(phenoAvg==q[2]);\n\t\tphenoBinned[idx3] = 2;\n\n\t\t# divide remaining values into cat1 and cat2\n\t\tphenoAvgRemaining = phenoAvg[which(phenoAvg!=q[2])];\n qx = quantile(phenoAvgRemaining, probs=c(0.5), na.rm=TRUE)\n\t\tminXX = min(phenoAvgRemaining, na.rm=TRUE)\n maxXX = max(phenoAvgRemaining, na.rm=TRUE)\n\n\t\tif (qx[1]==minXX) {\n\t\t\t# edge case again - quantile value is lowest value\n idx1 = which(phenoAvg==qx[1]);\n idx2 = which(phenoAvg>qx[1] & phenoAvg\", qx[1], \" AND < \", q[2], \", bin 3: ==\", q[2], \" || \", sep=\"\")\n }\n else if\t(qx[1]==maxXX) {\n\t\t\t# edge case again - quantile value is max value\n idx1 = which(phenoAvg=qx[1] & phenoAvg=\", qx[1], \" AND < \", q[2], \", bin 3: ==\", q[2], \" || \", sep=\"\")\n\t\t}\n\n phenoBinned[idx1] = 0;\n phenoBinned[idx2] = 1;\n\t}\n else if (q[1] == q[2]) {\n\t\t# both quantiles correspond to the same value so set \n\t\t# cat1 as < this value, cat2 as exactly this value and\n\t\t# cat3 as > this value\n \tphenoBinned = phenoAvg;\n \tidx1 = which(phenoAvgq[2]);\n phenoBinned[idx1] = 0;\n phenoBinned[idx2] = 1;\n phenoBinned[idx3] = 2;\n\n\t\tcat(\"Bin 1: <\", q[1], \", bin 2: ==\", q[2], \", bin 3: >\", q[2], \" || \", sep=\"\")\n \t}\n else {\n\t\t# standard case - split the data into three roughly equal parts where\n\t\t# cat1=q2\n \tphenoBinned = phenoAvg;\n idx1 = which(phenoAvg=q[1] & phenoAvg=q[2]);\n phenoBinned[idx1] = 0;\n phenoBinned[idx2] = 1;\n phenoBinned[idx3] = 2;\n\n\t\tcat(\"Bin 1: <\", q[1], \", bin 2: >=\", q[1], \"AND < \", q[2] ,\", bin 3: >=\", q[2], \" || \", sep=\"\")\n\t}\n\n\tcat(\"cat N: \", length(idx1),\", \",length(idx2),\", \",length(idx3), \" || \", sep=\"\");\n\t\n\treturn(phenoBinned);\n}\n\n", "meta": {"hexsha": "fe4624ec6b78174dc81f2fba1e1f36d9cd7a4e3c", "size": 5240, "ext": "r", "lang": "R", "max_stars_repo_path": "WAS/equalSizedBins.r", "max_stars_repo_name": "kevmanderson/PHESANT", "max_stars_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2017-02-27T00:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T15:42:01.000Z", "max_issues_repo_path": "WAS/equalSizedBins.r", "max_issues_repo_name": "kevmanderson/PHESANT", "max_issues_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-05-07T13:39:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:23:55.000Z", "max_forks_repo_path": "WAS/equalSizedBins.r", "max_forks_repo_name": "kevmanderson/PHESANT", "max_forks_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2017-02-27T12:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T22:03:16.000Z", "avg_line_length": 40.6201550388, "max_line_length": 111, "alphanum_fraction": 0.575, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.35101171954492155}}
{"text": "#R Vignere Functions Document\r\n\r\nalphabet <- c(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\",\r\n\"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\",\r\n\"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\")\r\n\r\nenglish_frequencies <- data.frame(\r\n letters = alphabet,\r\n frequencies = c(8.4966, 2.0720, 4.5388, 3.3844, 11.1607, 1.8121, 2.4705,\r\n 3.0034, 7.5448, 0.1965, 1.1016, 5.4893, 3.0129, 6.6544, 7.1635, 3.1671,\r\n 0.1962, 7.5809, 5.7351, 6.9509, 3.6308, 1.0074, 1.2899, 0.2902, 1.7779,\r\n 0.2722) / 100\r\n)\r\n\r\n#Removes all punctuation, upper case letters and spaces from a string\r\nformat_func <- function(string) {\r\n string <- gsub(\"[[:punct:][:blank:]]\", \"\", string)\r\n string <- gsub(\"[0-9]\", \"\", string)\r\n string <- tolower(string)\r\n return(string)\r\n}\r\n\r\n#Function returns the encrypted text by applying the vigenere cipher\r\n#Function requires a key, and a string, returns the ciphertext\r\nencrypt_func <- function(text, key) {\r\n encrypted <- c()\r\n #loop to get alphabetical indexes of the characters in the text\r\n split_text <- strsplit(text, \"\")[[1]] #creates a character class\r\n for (i in 1:nchar(text)) {\r\n letter_index <- which(alphabet %in% split_text[i])\r\n j <- i %% nchar(key)\r\n if (j == 0) {\r\n j <- nchar(key)\r\n }\r\n key_index <- which(alphabet %in% substring(key, j, j))\r\n #applying the relevant shift to the letters, using the vigenere cipher\r\n alphabet_index <- (letter_index + key_index - 2) %% length(alphabet) + 1\r\n encrypted <- paste(encrypted, alphabet[alphabet_index], sep = \"\")\r\n }\r\n return(encrypted)\r\n}\r\n\r\ndecrypt <- function(ciphertext, key) {\r\n decrypted <- c()\r\n for (i in 1:nchar(ciphertext)) {\r\n j <- i %% nchar(key)\r\n if (j == 0) {\r\n j <- nchar(key)\r\n }\r\n key_index <- which(alphabet %in% substring(key, j, j))\r\n cipher_index <- which(alphabet %in% substring(ciphertext, i, i))\r\n alphabet_index <- (cipher_index - key_index) %% 26 + 1\r\n decrypted <- paste(decrypted, alphabet[alphabet_index], sep = \"\")\r\n }\r\n return(decrypted)\r\n}\r\n\r\n#Kasiski Algorithm Functions to find the key length\r\n\r\n\r\n#Repeats function, finds all n letter repeats within the ciphertext\r\n# then counts their frequency, finds the spacing between repeats,\r\n# then finds the most comming factor of all the spacings (kas_mode)\r\nrepeats <- function(ciphertext, n) {\r\n elements <- c()\r\n indexes <- list()\r\n spacings <- list()\r\n for (i in 1:nchar(ciphertext)) {\r\n if (i <= nchar(ciphertext) - n + 1) {\r\n substr <- substring(ciphertext, i, i + n - 1)\r\n if (substr %in% elements == FALSE) {\r\n elements <- c(elements, substr)\r\n data <- gregexpr(substr, ciphertext)\r\n data2 <- list(\"attributes<-\" (data[[1]], NULL))\r\n indexes <- append(indexes, data2)\r\n if (length(data2[[1]]) > 1) {\r\n diff <- c()\r\n for (j in 1:(length(data2[[1]]) - 1)) {\r\n for (k in 1:(length(data2[[1]]) - j)) {\r\n diff <- c(diff, data2[[1]][j + k] - data2[[1]][j])\r\n }\r\n }\r\n spacings <- append(spacings, diff)\r\n }\r\n }\r\n }\r\n }\r\n factors_matrix <- c()\r\n for (i in 2:nchar(ciphertext)) {\r\n counts <- 0\r\n for (d in spacings) {\r\n if ((d %% i) == 0) {\r\n counts <- counts + 1\r\n }\r\n }\r\n if (counts != 0) {\r\n factors_matrix <- rbind(factors_matrix, c(i, counts))\r\n }\r\n }\r\n kas_mode <- 0\r\n mode_val <- 0 \r\n for (r in 1:nrow(factors_matrix)) {\r\n if (factors_matrix[r, 2] >= mode_val) {\r\n kas_mode <- factors_matrix[r, 1]\r\n mode_val <- factors_matrix[r, 2]\r\n }\r\n }\r\n return(kas_mode)\r\n}\r\n\r\n\r\n#Function takes every nth letter starting from index m,\r\n#where m is in range 0:n-1\r\nstr_subset <- function(junk, n, m) {\r\n ifelse(n == 1, junk,\r\npaste(strsplit(junk, split = NULL)[[1]][(1:nchar(junk)) %% n == m],\r\ncollapse = \"\"))\r\n}\r\n\r\n\r\n#Function below returns a list of the ciphertext split into n=key_length\r\n#subsections, so that letter frequency analysis can be used\r\nnth_letter <- function(key_length, ciphertext) {\r\n list_of_substrings <- c()\r\n sub_indexes <- 1:(key_length - 1)\r\n sub_indexes <- append(sub_indexes, 0)\r\n if (key_length == 1) {\r\n sub_indexes <- c(1)\r\n }\r\n for (i in sub_indexes) {\r\n list_of_substrings <- append(list_of_substrings,\r\n str_subset(ciphertext, key_length, i))\r\n }\r\n return(list_of_substrings)\r\n}\r\n\r\nsub_letter_totals <- function(key_length, ciphertext) {\r\n sorted_frequencies <- c()\r\n list_of_substrings <- nth_letter(key_length, ciphertext)\r\n index <- 1\r\n for (sub in list_of_substrings) {\r\n letter_freqs <- c()\r\n sub_split <- strsplit(sub, \"\")[[1]]\r\n for (letter in alphabet) {\r\n count <- length(grep(letter, sub_split))\r\n letter_freqs <- append(letter_freqs, count)\r\n }\r\n sorted_frequencies[[index]] <- letter_freqs\r\n index <- index + 1\r\n }\r\n return(sorted_frequencies)\r\n}\r\n\r\npercentages <- function(vec_of_vecs) {\r\n int <- 1\r\n s_percs <- c()\r\n for (i in vec_of_vecs) {\r\n j <- i / sum(i)\r\n s_percs[[int]] <- j\r\n int <- int + 1\r\n }\r\n return(s_percs)\r\n}\r\n\r\nchi_squared <- function(eng_freqs, sub_percs) {\r\n chis <- c()\r\n ind <- 1\r\n for (sublist in sub_percs) {\r\n chi_stats <- c()\r\n for (i in 1:length(alphabet)) {\r\n chi <- 0\r\n if (i == 1) {\r\n series <- i:26\r\n }\r\n else {\r\n series <- (28 - i):26\r\n series <- c(series, 1:(27 - i))\r\n }\r\n for (j in seq_along(sublist)) {\r\n value <- ((sublist[j] - eng_freqs[[2]][series[j]]) ^ 2) / (eng_freqs[[2]][series[j]])\r\n chi <- chi + value\r\n }\r\n chi_stats <- c(chi_stats, chi)\r\n }\r\n chis[[ind]] <- chi_stats\r\n ind <- ind + 1\r\n }\r\n return(chis)\r\n}\r\n\r\n#Function which returns the n most likely letters for every key letter.\r\n#It takes in two arguments, the vector list of chi squared values, and n.\r\n#It returns a vector, of length == key length.\r\nlikely_letters <- function(chi_vector, n) {\r\n n_likely <- c()\r\n step <- 1\r\n for (chis in chi_vector) {\r\n letters <- c()\r\n sorted_freqs <- chis[order(chis)]\r\n for (int in 1:n) {\r\n letters <- c(letters, alphabet[match(sorted_freqs[int], chis)])\r\n }\r\n n_likely[[step]] <- letters\r\n step <- step + 1\r\n }\r\n return(n_likely)\r\n}\r\n\r\n### Twist Algorithm Implementation, used to find the key length\r\n\r\ntwist_subsets_func <- function(key_limit, text) {\r\n all_key_lengths <- c()\r\n for (m in 1:(key_limit + 1)) {\r\n nth_sub <- sub_letter_totals(m, text)\r\n perc <- percentages(nth_sub)\r\n all_key_lengths[[m]] <- perc\r\n }\r\n return(all_key_lengths)\r\n}\r\n\r\ntwists <- function(twist_subsets) {\r\n twists <- c()\r\n for (c in 1:length(twist_subsets)) {\r\n twist <- 0\r\n for (r in 1:length(twist_subsets[[c]])) {\r\n list_of_percs <- sort(twist_subsets[[c]][r][[1]], decreasing = TRUE)\r\n twist <- twist + sum(list_of_percs[1:13]) - sum(list_of_percs[14:26])\r\n }\r\n twist <- twist * (100 / c)\r\n twists <- c(twists, twist)\r\n }\r\n return(twists)\r\n}\r\n\r\ntwistplus <- function(twists) {\r\n twistplus <- c()\r\n for (i in seq_along(twists)) {\r\n subtract <- 0\r\n if (i != length(twists)) {\r\n for (j in 1:i) {\r\n subtract <- subtract + (twists[j]/(i))\r\n }\r\n number <- twists[i + 1] - subtract\r\n twistplus <- c(twistplus, number, i + 1)\r\n }\r\n }\r\n mode_value <- 0\r\n sequence <- seq_along(twistplus)\r\n integers <- which(sequence %% 2 == 1)\r\n for (j in integers) {\r\n if(twistplus[j] > mode_value) {\r\n mode <- twistplus[j + 1]\r\n mode_value <- twistplus[j]\r\n }\r\n }\r\n return (mode)\r\n}\r\n\r\n############################\r\n#Testing\r\n############################\r\n\r\n#Code below demonstrates how the Vigenere Cipher is solved with the twistplus algorithm\r\n#to identify the key length.\r\n\r\nnormal_text <- \"there are various kinds of certainty. a belief is psychologically certain when the subject who has it is supremely convinced of its truth. certainty in this sense is similar to incorrigibility, which is the property a belief has of being such that the subject is incapable of giving it up.but psychological certainty is not the same thing as incorrigibility. a belief can be certain in this sense without being incorrigible; this may happen, for example, when the subject receives a very compelling bit of counterevidence to the (previously) certain belief and gives it up for that reason.\"\r\nkeyword <- \"notebook\"\r\n\r\nc_text <- encrypt_func(format_func(normal_text), keyword)\r\ntwists_a <- twists(twist_subsets_func(8, c_text))\r\nmode <- twistplus(twists_a)\r\nprint(mode)\r\n\r\noutput <- sub_letter_totals(mode, c_text)\r\npercs <- percentages(output)\r\nchi_vals <- chi_squared(english_frequencies, percs)\r\nlikely <- likely_letters(chi_vals, 3)\r\nprint(likely)\r\n\r\ndecryp <- decrypt(c_text, \"notebook\")\r\nprint(decryp)\r\n\r\n\r\n#######################\r\n#Testing the Kasiski Algorithm\r\n#######################\r\n\r\n#Try different length ciphertexts and keys to determine the effectiveness of the Kasiski Algorithm\r\n#compared to the Twistplus algorithm. You may find different results for the function repeats(text, n), when\r\n#changing 'n' the length of the repeated fragment of text.\r\nrepeats(c_text, 5)\r\n", "meta": {"hexsha": "afe057a59f2f8adbc32d6303a8e4f4ad83684982", "size": 9884, "ext": "r", "lang": "R", "max_stars_repo_path": "Vignere_Functions.r", "max_stars_repo_name": "MFarchive/Vigenere-Cipher", "max_stars_repo_head_hexsha": "914849d47a37e95bb24bcd488b01bd82fb7be56f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vignere_Functions.r", "max_issues_repo_name": "MFarchive/Vigenere-Cipher", "max_issues_repo_head_hexsha": "914849d47a37e95bb24bcd488b01bd82fb7be56f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vignere_Functions.r", "max_forks_repo_name": "MFarchive/Vigenere-Cipher", "max_forks_repo_head_hexsha": "914849d47a37e95bb24bcd488b01bd82fb7be56f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8493150685, "max_line_length": 607, "alphanum_fraction": 0.556353703, "num_tokens": 2627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3509226641726137}}
{"text": "\\name{psm_analysis_weighted}\r\n\\alias{psm_analysis_weighted}\r\n\r\n\\title{\r\nWeighted van Westendorp Price Sensitivity Meter Analysis (PSM)\r\n}\r\n\r\n\\description{\r\n\\code{psm_analysis_weighted()} performs a \\bold{weighted} analysis\r\n of consumer price preferences and price sensitivity known as\r\n \\bold{van Westendorp Price Sensitivity Meter (PSM)}. The function\r\n requires a sample design from the \\pkg{survey} package as the\r\n main input. Custom weights or sample designs from other packages\r\n are not supported.\r\n\r\n To run a PSM analysis \\bold{without} weighting, use the function\r\n \\code{\\link{psm_analysis}}.\r\n\r\n}\r\n\r\n\\usage{\r\npsm_analysis_weighted(\r\n toocheap, cheap, expensive, tooexpensive,\r\n design,\r\n validate = TRUE,\r\n interpolate = FALSE,\r\n interpolation_steps = 0.01,\r\n intersection_method = \"min\",\r\n pi_cheap = NA, pi_expensive = NA,\r\n pi_scale = 5:1,\r\n pi_calibrated = c(0.7, 0.5, 0.3, 0.1, 0))\r\n}\r\n\r\n\\arguments{\r\n \\item{toocheap, cheap, expensive, tooexpensive}{Names\r\n of the variables in the data.frame/matrix that contain the\r\n survey data on the respondents' \"too cheap\", \"cheap\",\r\n \"expensive\" and \"too expensive\" price preferences.\r\n\r\n If the \\code{toocheap} price was not assessed, a\r\n variable of NAs can be used instead. If \\code{toocheap}\r\n is NA for all cases, it is possible to calculate the Point of\r\n Marginal Expensiveness and the Indifference Price Point, but it\r\n is impossible to calculate the Point of Marginal Cheapness and\r\n the Optimal Price Point.}\r\n \\item{design}{A survey design which has been created by the\r\n function \\code{\\link{svydesign}()} from the \\pkg{survey}\r\n package. The data that is used as an input of \\code{svydesign()}\r\n must include all the variable names for \\code{toocheap},\r\n \\code{cheap}, \\code{expensive} and \\code{tooexpensive} variables\r\n specified above.}\r\n \\item{validate}{logical. should only respondents with\r\n consistent price preferences (too cheap < cheap < expensive\r\n < too expensive) be considered in the analysis?}\r\n \\item{interpolate}{logical. should interpolation of the price\r\n curves be applied between the actual prices given by the\r\n respondents? If interpolation is enabled, the output appears\r\n less bumpy in regions with sparse price information. If the\r\n sample size is sufficiently large, interpolation should not\r\n be necessary.}\r\n \\item{interpolation_steps}{numeric. if \\code{interpolate} is\r\n \\code{TRUE}: the size of the interpolation steps. Set by\r\n default to 0.01, which should be appropriate for most goods\r\n in a price range of 0-50 USD/Euro.}\r\n \\item{intersection_method}{\"min\" (default), \"max\", \"mean\" or\r\n \"median\". defines the method how to determine the price\r\n points (range, indifference price, optimal price) if there\r\n are multiple possible intersections of the price curves.\r\n \"min\" uses the lowest possible prices, \"max\" uses the\r\n highest possible prices, \"mean\" calculates the mean among\r\n all intersections and \"median\" uses the median of all\r\n possible intersections}\r\n \\item{pi_cheap, pi_expensive}{Only required for the Newton\r\n Miller Smith extension. Names of the variables in the data\r\n that contain the survey data on the respondents' purchase\r\n intent at their individual cheap/expensive price.}\r\n \\item{pi_scale}{Only required for the Newton Miller Smith\r\n extension. Scale of the purchase intent variables pi_cheap and\r\n pi_expensive. By default assuming a five-point scale with 5\r\n indicating the highest purchase intent.}\r\n \\item{pi_calibrated}{Only required for the Newton Miller Smith\r\n extension. Calibrated purchase probabilities that are assumed\r\n for each value of the purchase intent scale. Must be the same\r\n order as the pi_scale variable so that the first value of\r\n pi_calibrated corresponds to the first value in the pi_scale\r\n variable. Default values are taken from the Sawtooth Software\r\n PSM implementation in Excel: 70\\% for the best value of the\r\n purchase intent scale, 50\\% for the second best value,\r\n 30\\% for the third best value (middle of the scale), 10\\%\r\n for the fourth best value and 0\\% for the worst value.}\r\n}\r\n\r\n\r\n\\details{\r\nThe main logic of the Price Sensitivity Meter Analysis is\r\nexplained in the documentation of the \\code{\\link{psm_analysis}}\r\nfunction. The \\code{psm_analysis_weighted} performs the same\r\nanalysis, but weights the survey data according to a known\r\npopulation.}\r\n\r\n\\value{\r\nThe function output consists of the following elements:\r\n\r\n \\item{\\code{data_input}:}{\\code{data.frame} object. Contains\r\n the data that was used as an input for the analysis.}\r\n \\item{\\code{validated}:}{\\code{logical} object. Indicates\r\n whether the \\code{\"validate\"} option has been used (to\r\n exclude cases with intransitive price preferences).}\r\n \\item{\\code{invalid_cases}:}{\\code{numeric} object. Number\r\n of cases with intransitive price preferences.}\r\n \\item{\\code{total_sample}:}{\\code{\"numeric\"} object.\r\n Total sample size of the input sample \\emph{before}\r\n assessing the transitivity of individual price preferences.}\r\n \\item{\\code{data_vanwestendorp}:}{\\code{data.frame} object.\r\n Output data of the Price Sensitivity Meter analysis.\r\n Contains the \\bold{weighted} cumulative distribution\r\n functions for the four price assessments (too cheap, cheap,\r\n expensive, too expensive) for all prices.}\r\n \\item{\\code{pricerange_lower}:}{\\code{numeric} object. Lower\r\n limit of the acceptable price range as defined by the\r\n Price Sensitivity Meter, also known as \\bold{point of\r\n marginal cheapness}: Intersection of the \"too cheap\" and the\r\n \"expensive\" curves.}\r\n \\item{\\code{pricerange_upper}:}{\\code{numeric} object. Upper\r\n limit of the acceptable price range as defined by the Price\r\n Sensitivity Meter, also known as \\bold{point of marginal\r\n expensiveness}: Intersection of the \"too expensive\" and the\r\n \"cheap\" curves.}\r\n \\item{\\code{idp}:}{\\code{numeric} object. \\bold{Indifference\r\n Price Point} as defined by the Price Sensitivity Meter:\r\n Intersection of the \"cheap\" and the \"expensive\" curves.}\r\n \\item{\\code{opp}:}{\\code{numeric} object. \\bold{Optimal\r\n Price Point} as defined by the Price Sensitivity Meter:\r\n Intersection of the \"too cheap\" and the \"too expensive\"\r\n curves.}\r\n \\item{\\code{weighted}:}{\\code{logical} object. Indicating\r\n if weighted data was used in the analysis. Outputs from\r\n \\code{psm_analysis_weighted()} always have the value\r\n \\code{TRUE}. When data is unweighted, use the function\r\n \\code{\\link{psm_analysis}.}}\r\n \\item{\\code{survey_design}:}{\\code{survey.design2} object.\r\n Returning the full survey design as specified with the\r\n \\code{\\link[survey]{svydesign}} function from the \\pkg{survey} package.}\r\n \\item{\\code{NMS}:}{\\code{logical} object. Indicates whether\r\n the additional analyses of the Newton Miller Smith Extension\r\n were performed.}\r\n}\r\n\r\n\\references{\r\n Van Westendorp, P (1976) \"NSS-Price Sensitivity Meter (PSM) --\r\n A new approach to study consumer perception of price\"\r\n \\emph{Proceedings of the ESOMAR 29th Congress}, 139--167. Online\r\n available at \\url{https://www.researchworld.com/a-new-approach-to-study-consumer-perception-of-price/}.\r\n\r\n Newton, D, Miller, J, Smith, P, (1993) \"A market acceptance\r\n extension to traditional price sensitivity measurement\"\r\n \\emph{Proceedings of the American Marketing Association\r\n Advanced Research Techniques Forum}.\r\n\r\n Sawtooth Software (2016) \"Templates for van Westendorp PSM for\r\n Lighthouse Studio and Excel\". Online available at\r\n \\url{https://sawtoothsoftware.com/resources/software-downloads/tools/van-westendorp-price-sensitivity-meter}\r\n}\r\n\r\n\\examples{\r\n\r\n# assuming a skewed sample with only 1/3 women and 2/3 men\r\n\r\ninput_data <- data.frame(tch = round(rnorm(n = 250, mean = 8, sd = 1.5), digits = 2),\r\n ch = round(rnorm(n = 250, mean = 12, sd = 2), digits = 2),\r\n ex = round(rnorm(n = 250, mean = 13, sd = 1), digits = 2),\r\n tex = round(rnorm(n = 250, mean = 15, sd = 1), digits = 2),\r\n gender = sample(x = c(\"male\", \"female\"),\r\n size = 250,\r\n replace = TRUE,\r\n prob = c(2/3, 1/3)))\r\n\r\n# ... and in which women have on average 1.5x the price acceptance of men\r\ninput_data$tch[input_data$gender == \"female\"] <- input_data$tch[input_data$gender == \"female\"] * 1.5\r\ninput_data$ch[input_data$gender == \"female\"] <- input_data$ch[input_data$gender == \"female\"] * 1.5\r\ninput_data$ex[input_data$gender == \"female\"] <- input_data$ex[input_data$gender == \"female\"] * 1.5\r\ninput_data$tex[input_data$gender == \"female\"] <- input_data$tex[input_data$gender == \"female\"] * 1.5\r\n\r\n# creating a sample design object using the survey package\r\n# ... assuming that gender is balanced equally in the population of 10000\r\n\r\ninput_data$gender_pop <- 5000\r\n\r\ninput_design <- survey::svydesign(ids = ~ 1, # no clusters\r\n probs = NULL, # hence no cluster samling probabilities,\r\n strata = input_data$gender, # stratified by gender\r\n fpc = input_data$gender_pop, # strata size in the population\r\n data = input_data)\r\n # data object used as input: no need to specify single variables\r\n\r\n\r\noutput_weighted_psm <- psm_analysis_weighted(toocheap = \"tch\",\r\n cheap = \"ch\",\r\n expensive = \"ex\",\r\n tooexpensive = \"tex\",\r\n design = input_design)\r\n\r\nsummary(output_weighted_psm)\r\n}\r\n\r\n", "meta": {"hexsha": "38a308ff30bea39a777c94e442773bf2cb3c55d7", "size": 9678, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/psm_analysis_weighted.rd", "max_stars_repo_name": "cran/pricesensitivitymeter", "max_stars_repo_head_hexsha": "9bcdce34f9fed026c96dd28073704df239746c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "man/psm_analysis_weighted.rd", "max_issues_repo_name": "cran/pricesensitivitymeter", "max_issues_repo_head_hexsha": "9bcdce34f9fed026c96dd28073704df239746c93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "man/psm_analysis_weighted.rd", "max_forks_repo_name": "cran/pricesensitivitymeter", "max_forks_repo_head_hexsha": "9bcdce34f9fed026c96dd28073704df239746c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9805825243, "max_line_length": 111, "alphanum_fraction": 0.6980781153, "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.35067271407909445}}
{"text": "# Data exploration and models for TSM\n\nrequire(mgcv)\nrequire(data.table)\nrequire(lme4)\nrequire(MuMIn) # for dredge\nsource('scripts/findPeaksGAM.r') # for location and number of peaks\n\n\n#############\n## functions\n#############\n\n\n#############\n# Read in dataset\n#############\ndat <- fread('temp/warmingtolerance_byspecies.csv', stringsAsFactors=TRUE)\n\n# make critical the first factor\ndat$tmax_metric <- relevel(dat$tmax_metric, 'crit')\n\n\n#####################\n## Examine dataset\n#####################\n# how much data by animal type\n\tnrow(dat) # 406\n\n\t# Tmax raw\n\ti <- complete.cases(dat[,.(Realm, lat, Tmax)])\n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\tdat[i, length(unique(Class))]\n\tdat[i, range(lat), by=Realm]\n\n\t# Tmax acclimation temp\n\ti <- complete.cases(dat[, .(Realm, lat, tmax.accsum.elev, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\t# Operative temperature\n\ti <- complete.cases(dat[, .(Realm, lat, tb_favorableGHCND95, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\t# TSM present time, without acclimation GHCND\n\ti <- complete.cases(dat[, .(Realm, lat, tmax_metric, tsm_favorableGHCND95_noacc, Phylum, Class, Order, Family, Genus)]) \n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\t# TSM present time, with acclimation GHCND\n\ti <- complete.cases(dat[, .(Realm, lat, tmax_metric, tsm_favorableGHCND95, Phylum, Class, Order, Family, Genus)]) \n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\n# how many phyla by habitat\naggregate(list(nphyla=dat$Phylum, nclass=dat$Class, norder=dat$Family, nfamily=dat$Family, ngenera=dat$Genus), by=list(Realm=dat$Realm), FUN=function(x) length(unique(x)))\n\n# how many classes?\n\t# Tmax acclimation temp\n\ti <- complete.cases(dat[, .(Realm, lat, tmax.accsum.elev, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\tt(t(table(dat$Class[i])))\n\n\t# TSM present time, with acclimation\n\ti <- complete.cases(dat[, .(Realm, lat, tmax_metric, tsm_favorable, Phylum, Class, Order, Family, Genus)]) \n\ttable(dat$Class[i])\n\n\n# latitudinal range\n\t# Tmax\n\ti <- complete.cases(dat[,.(Realm, lat, Tmax, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\taggregate(list(range=dat$lat[i]), by=list(habitat=dat$Realm[i]), FUN=range)\n\n\t# TSM present time, with acclimation\n\ti <- complete.cases(dat[, .(Realm, lat, tsm_favorableGHCND95, Phylum, Class, Order, Family, Genus)]) \n\tsum(i)\n\taggregate(list(range=dat$lat[i]), by=list(habitat=dat$Realm[i]), FUN=range)\n\n\n# acclimation effect size\n\t# acclimation temperature\ndat[Realm=='Terrestrial', summary(Tmax - tmax.accsum.elev)]\ndat[Realm=='Terrestrial', sd(Tmax - tmax.accsum.elev, na.rm=TRUE)]\n\ndat[Realm=='Marine', summary(Tmax - tmax.accsum.elev)]\ndat[Realm=='Marine', sd(Tmax - tmax.accsum.elev, na.rm=TRUE)]\n\n\n\n# odd values\n\t# tsm < 0\n\tdat[,sum(tsm_maxhr<0, na.rm=TRUE)]\n\tdat[tsm_favorable<0 | tsm_favorable95<0 | tsm_favorableGHCND95<0, .(Species, Genus, animal.type, Realm, lat, long_max, elev.grid, tmax_metric, Tmax, tmax.accsum.elev, thabmaxhr, tsm_maxhr, tsm_maxhr_accsum, tsm_favorable, tsm_favorable95, tsm_favorableGHCND95)]\n\n\n##################################\n# Average in bands and write out\n##################################\n\n# averages near equator vs. farther\n\tdat[lat > -10 & lat < 10 & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[lat > -3 & lat < 3 & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[(lat > -35 & lat < -25) & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[(lat > 20 & lat < 30) & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[((lat > -35 & lat < -15) | (lat > 15 & lat < 35)) & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\t\n# average in bands\n\tTSMbylat <- dat[Realm=='Terrestrial' & !is.na(tsm_favorableGHCND95), .(mean=mean(tsm_favorableGHCND95), se=sd(tsm_favorableGHCND95)/.N, n=.N), by=.(latband=floor(lat/10)*10+5)]\n\n\t\t# small plot to check\n\t\tsetkey(TSMbylat, latband)\n\t\tTSMbylat[,plot(latband, mean, type='o', pch=16, cex=0.5)]\n\t\tTSMbylat[,arrows(latband, mean-se, latband, mean+se, length=0, angle=90, code=3)]\n\n# write out\nwrite.csv(TSMbylat, file='temp/warmingtolerance_bylatband_land.csv', row.names=FALSE)\n\n#############\n# Models\n#############\n\n#### projections dataframe\n\tnewdat <- data.frame(Realm=rep(c('Marine', 'Terrestrial'), c(161,161)), lat=rep(-80:80, 2)) # for projection onto a regular vector of latitudes\n\t\tnewdat$tmax_metric <- 'crit'\n\n#### models for body temperature (Tb)\t\t\n\t# present-time body temperature in favorable microclimates, 95% max hr with GHCND\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tb_favorableGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTbGHCND95dat <- dat[i,]\n\tmodTbGHCND95 <- uGamm(tb_favorableGHCND95 ~ Realm + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTbGHCND95dat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTbGHCND95$gam)\n\t\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTbGHCND95$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tb_favorableGHCND95 <- temp$fit\n\t\tnewdat$tb_favorableGHCND95se <- temp$se.fit\n\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tb_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tb_favorableGHCND95 + tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tb_favorableGHCND95 - tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tb_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tb_favorableGHCND95 - tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tb_favorableGHCND95 + tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tb_favorableGHCND95 ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tb_favorableGHCND95 ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time body temperature in full sun, 95% max hr with GHCND\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tb_sunGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTbsunGHCND95 <- uGamm(tb_sunGHCND95 ~ Realm + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTbsunGHCND95$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTbsunGHCND95$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tb_sunGHCND95 <- temp$fit\n\t\tnewdat$tb_sunGHCND95se <- temp$se.fit\n\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tb_sunGHCND95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,60), xlim=c(-80,80))\n#\t\t\t\tlines(tb_sunGHCND95 + tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tb_sunGHCND95 - tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tb_sunGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tb_sunGHCND95 - tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tb_sunGHCND95 + tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tb_sunGHCND95 ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tb_sunGHCND95 ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n#\n#\t\t\tlines(tb_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='black')\n#\t\t\t\tlines(tb_favorableGHCND95 - tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='black', lty=2)\n#\t\t\t\tlines(tb_favorableGHCND95 + tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='black', lty=2)\n\n\n\n#### models for Tmax\n\t# Tmax (summer-acclimated)\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax.accsum.elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTmaxdat <- dat[i,]\n\tmodTmax <- uGamm(tmax.accsum.elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTmaxdat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTmax$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTmax$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tmax <- temp$fit\n\t\tnewdat$tmaxse <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\tplot(tmax ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(10,50), xlim=c(-80,80))\n#\t\t\tlines(tmax + tmaxse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tmax - tmaxse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\tlines(tmax ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\tlines(tmax - tmaxse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\tlines(tmax + tmaxse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\tpoints(tmax.accsum.elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\tpoints(tmax.accsum.elev ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# Tmax with species-specific ARR data\n\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax.accsumbyspp.elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTmaxARRbyspp <- uGamm(tmax.accsumbyspp.elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) \n#\t\tsummary(modTmaxARRbyspp$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTmaxARRbyspp$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tmaxARRbyspp <- temp$fit\n\t\tnewdat$tmaxARRbysppse <- temp$se.fit\n\n\n\n#### models for TSM\n\t\t\n\t# present-time TSM (annual, no acclimation)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_ann_elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMann <- uGamm(tsm_ann_elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMann$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMann$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_ann <- temp$fit\n\t\tnewdat$tsm_annse <- temp$se.fit\n\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_ann ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_ann + tsm_annse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_ann - tsm_annse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_ann ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_ann - tsm_annse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_ann + tsm_annse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_ann_elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_ann ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM (summer)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_sum_elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMsum <- uGamm(tsm_sum_elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMsum$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMsum$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_sum <- temp$fit\n\t\tnewdat$tsm_sumse <- temp$se.fit\n\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_sum ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_sum + tsm_sumse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_sum - tsm_sumse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_sum ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_sum - tsm_sumse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_sum + tsm_sumse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_sum_elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_sum_elev ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM (hottest month)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_maxmo_elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMmaxmo <- uGamm(tsm_maxmo_elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMmaxmo$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMmaxmo$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_maxmo <- temp$fit\n\t\tnewdat$tsm_maxmose <- temp$se.fit\n\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_maxmo ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_maxmo + tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_maxmo - tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_maxmo ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_maxmo - tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_maxmo + tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_maxmo_elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_maxmo_elev ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM in exposed microclimates (95% hottest hour GHCND Tb)\n\t# with summer acclimation corrections\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_exposedGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMexp <- uGamm(tsm_exposedGHCND95 ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMexp$lme)\n#\t\tsummary(modTSMexp$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMexp$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_exposedGHCND95 <- temp$fit\n\t\tnewdat$tsm_exposedGHCND95se <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_exposed ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-25,20), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_exposed + tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_exposed - tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_exposed ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_exposed - tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_exposed + tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_exposed ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_exposed ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95dat <- dat[i,]\n\tmodGHCND95 <- uGamm(tsm_favorableGHCND95 ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95dat, control=lmeControl(niterEM=0, msMaxIter=100)) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modGHCND95$lme)\n#\t\tsummary(modGHCND95$gam)\n\t\t\n\t\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modGHCND95$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_favorableGHCND95 <- temp$fit\n\t\tnewdat$tsm_favorableGHCND95se <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_favorableGHCND95 + tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95 - tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tsm_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_favorableGHCND95 - tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95 + tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_favorableGHCND95 ~ lat, data=dat[i & Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_favorableGHCND95 ~ lat, data=dat[i & Realm=='Marine',], col='blue', cex=0.5)\n#\n#\t\t\t\tdat[i & Realm=='Marine' & demers_pelag=='pelagic' & big==TRUE & mobility=='swim', points(tsm_favorableGHCND95 ~ lat, col='red', cex=0.5)]\n#\t\t\t\n#\n#\t\t\tlines(tsm_favorable95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='red')\n#\t\t\t\tlines(tsm_favorable95 - tsm_favorable95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='red', lty=2)\n#\t\t\t\tlines(tsm_favorable95 + tsm_favorable95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='red', lty=2)\n#\n#\t\n#\t\t\tdatorig <- fread('temp/warmingtolerance_byspecies_2017-12-19.csv')\n#\t\t\t# use 95% warmest hour for TSMs. favorable microclimates (shade or wet skin + behavioral thermoregulation of 10degC)\n#\t\t\tdatorig[, tsm_favorable95_10 := as.numeric(rep(NA, .N))]\n#\t\t\tdatorig[habitat=='terrestrial' & animal.type!='amphibian', tsm_favorable95_10 := tsm_NM_2m_airshade95_accsum.elev]\n#\t\t\tdatorig[habitat=='terrestrial' & animal.type=='amphibian', tsm_favorable95_10 := tsm_NM_shade_body_wet95_accsum.elev]\n#\t\t\tdatorig[habitat=='marine', tsm_favorable95_10 := tsm_95hr_marineBT10_accsum]\n#\n#\t\t\tpoints(tsm_favorable95_10 ~ lat, data=datorig[habitat=='marine',], col='red', cex=0.3, pch=16)\n\n\t\t# minimum marine TSM vs. minimum terrestrial TSM\n\t\tmin(newdat$tsm_favorableGHCND95[newdat$Realm=='Terrestrial']) - min(newdat$tsm_favorableGHCND95[newdat$Realm=='Marine'])\n\t\n\n\t# Species-specific ARR data: present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95byspp', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95ARRbysppdat <- dat[i,]\n\tmodGHCND95ARRbyspp <- uGamm(tsm_favorableGHCND95byspp ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95ARRbysppdat, control=lmeControl(niterEM=50, msMaxIter=1000))\n#\t\tsummary(modGHCND95ARRbyspp$gam)\n\n\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour GHCND Tb) (with acclimation, WITHOUT marine behavioral thermoregulation)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_nomarineBT', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodnoMBT <- uGamm(tsm_favorableGHCND95_nomarineBT ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,], control=lmeControl(niterEM=0, msMaxIter=100))\n#\t\tsummary(modnoMBT$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modnoMBT$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_favorableGHCND95_nomarineBT <- temp$fit\n\t\tnewdat$tsm_favorableGHCND95_nomarineBTse <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions. TSMs with thermoregulation in marine animals in red.\n#\t\t\tplot(tsm_favorableGHCND95_nomarineBT ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT + tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT - tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tsm_favorableGHCND95_nomarineBT ~ lat, data=newdat[newdat$Realm=='Marine',], col='red')\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT - tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Marine',], col='red', lty=2) #w/out marine BT in red\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT + tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Marine',], col='red', lty=2)\n#\n#\t\t\t# overlay with marine BT\n#\t\t\tlines(tsm_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_favorableGHCND95 - tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95 + tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_favorableGHCND95_nomarineBT ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_favorableGHCND95_nomarineBT ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, MOREs Marine BT)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_marBTmore', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95_marBTmoredat <- dat[i,]\n\tmodGHCND95_marBTmore <- uGamm(tsm_favorableGHCND95_marBTmore ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95_marBTmoredat, control=lmeControl(niterEM=0, msMaxIter=100)) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modGHCND95_marBTmore$gam)\n#\t\t\tsummary(modGHCND95$gam) # to compare\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, LESS Marine BT)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_marBTless', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95_marBTlessdat <- dat[i,]\n\tmodGHCND95_marBTless <- uGamm(tsm_favorableGHCND95_marBTless ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95_marBTlessdat, control=lmeControl(niterEM=0, msMaxIter=100)) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modGHCND95_marBTless$gam)\n#\t\t\tsummary(modGHCND95_marBTmore$gam) # to compare\n#\t\t\tsummary(modGHCND95$gam) # to compare\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_noacc', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMfav_noaccdat <- dat[i,]\n\tmodTSMfav_noacc <- uGamm(tsm_favorableGHCND95_noacc ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTSMfav_noaccdat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMfav_noacc$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMfav_noacc$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_favorable_noacc <- temp$fit\n\t\tnewdat$tsm_favorable_noaccse <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_favorable_noacc ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_favorable_noacc + tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_favorable_noacc - tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_favorable_noacc ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_favorable_noacc - tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_favorable_noacc + tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_favorable_noacc ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_favorable_noacc ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections, but acclimation temperature included as a fixed effect\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_noacc', 'tmax_acc', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMfav_acctermdat <- dat[i,]\n\tmodTSMfav_accterm <- uGamm(tsm_favorableGHCND95_noacc ~ Realm + tmax_metric + tmax_acc + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTSMfav_acctermdat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMfav_accterm$gam)\n\n\n\n# Write out predictions\nwrite.csv(newdat, file='temp/warmingtolerance_bylatlon.csv', row.names=FALSE)\n\n\n#############################\n## Calculate peak locations\n## (need models from above)\n#############################\n\n\n\t# present-time body temperature in favorable microclimates, 95% max hr with GHCND\t\t\n\t\t# how many peaks?\n\t\tpeaksmeanTbGHCND95_terr <- findPeaksGAM(modTbGHCND95$gam, newdat[newdat$Realm=='Terrestrial',], xvar='lat', xtol=4) # from the main prediction\n\t\t\tpeaksmeanTbGHCND95_terr$npeaks\n\t\t\tpeaksmeanTbGHCND95_terr$peaklocs\t\t\t\n\t\tpeaksTbGHCND95_terr <- findPeaksGAM_CI(mod=modTbGHCND95$gam, newdat=newdat[newdat$Realm=='Terrestrial',], n=1000, xvar='lat', xtol=4) # xtol sets lat window to 4° in each direction\n\t\tpeaksmeanTbGHCND95_mar <- findPeaksGAM(modTbGHCND95$gam, newdat[newdat$Realm=='Marine',], xvar='lat', xtol=4) # from the main prediction\t\t\t\n\t\tpeaksTbGHCND95_mar <- findPeaksGAM_CI(mod=modTbGHCND95$gam, newdat=newdat[newdat$Realm=='Marine',], n=1000, xvar='lat', xtol=4)\n\t\t\n\t\t# write out\n\t\tsaveRDS(peaksTbGHCND95_terr, file='temp/peaks_modTbGHCND95_terr.rds')\n\t\tsaveRDS(peaksTbGHCND95_mar, file='temp/peaks_modTbGHCND95_mar.rds')\n\n\n\n#### models for Tmax\n\t# Tmax (summer-acclimated)\n\t\t# how many peaks?\n\t\tpeaksmeanTmax_terr <- findPeaksGAM(modTmax$gam, newdat[newdat$Realm=='Terrestrial',], xvar='lat', xtol=4) # from the main prediction\n\t\t\tpeaksmeanTmax_terr$npeaks\n\t\t\tpeaksmeanTmax_terr$peaklocs\t\t\t\n\t\tpeaksTmax_terr <- findPeaksGAM_CI(mod=modTmax$gam, newdat=newdat[newdat$Realm=='Terrestrial',], n=1000, xvar='lat', xtol=4) # xtol sets lat window to 4° in each direction\n\t\tpeaksmeanTmax_mar <- findPeaksGAM(modTmax$gam, newdat[newdat$Realm=='Marine',], xvar='lat', xtol=4) # from the main prediction\t\t\t\n\t\tpeaksTmax_mar <- findPeaksGAM_CI(mod=modTmax$gam, newdat=newdat[newdat$Realm=='Marine',], n=1000, xvar='lat', xtol=4)\n\t\t\n\t\t# write out\n\t\tsaveRDS(peaksTmax_terr, file='temp/peaks_modTmax_terr.rds')\n\t\tsaveRDS(peaksTmax_mar, file='temp/peaks_modTmax_mar.rds')\n\n\n#### models for TSM\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\t\t# how many valleys?\n\t\tpeaksmeanTSM_favorableGHCND95_terr <- findPeaksGAM(modGHCND95$gam, newdat[newdat$Realm=='Terrestrial',], xvar='lat', xtol=4, findmaxima=FALSE) # from the main prediction\n\t\t\tpeaksmeanTSM_favorableGHCND95_terr$npeaks\n\t\t\tpeaksmeanTSM_favorableGHCND95_terr$peaklocs\t\t\t\n\t\tpeaksTSM_favorableGHCND95_terr <- findPeaksGAM_CI(mod=modGHCND95$gam, newdat=newdat[newdat$Realm=='Terrestrial',], n=1000, xvar='lat', xtol=4, findmaxima=FALSE) # xtol sets lat window to 4° in each direction\n\t\tpeaksmeanTSM_favorableGHCND95_mar <- findPeaksGAM(modGHCND95$gam, newdat[newdat$Realm=='Marine',], xvar='lat', xtol=4, findmaxima=FALSE)\n\t\tpeaksTSM_favorableGHCND95_mar <- findPeaksGAM_CI(mod=modGHCND95$gam, newdat=newdat[newdat$Realm=='Marine',], n=1000, xvar='lat', xtol=4, findmaxima=FALSE)\n\t\t\n\t\t# write out\n\t\tsaveRDS(peaksTSM_favorableGHCND95_terr, file='temp/peaks_modGHCND95_terr.rds')\n\t\tsaveRDS(peaksTSM_favorableGHCND95_mar, file='temp/peaks_modGHCND95_mar.rds')\n\n\n\n#############################\n## Calculate RVI\n## (need models from above)\n#############################\n\n#### models for operative temperature (Te)\n\t# present-time body temperature in favorable microclimates, 95% max hr with GHCND\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTbGHCND95s <- dredge(modTbGHCND95, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTbGHCND95s, delta < 6)\n\n\t\tmodavgTbGHCND95 <- model.avg(modTbGHCND95s)\n#\t\tsummary(modavgTEGHCND95)\n\n\n#### models for Tmax\n\t# Tmax (summer-acclimated)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTmaxs <- dredge(modTmax, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTmaxs)\n\n\t\tmodavgTmax <- model.avg(modTmaxs)\n\t\t#summary(modavgTmax)\n\n\n#### models for TSM\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND) (WITH acclimation, Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95s <- dredge(modGHCND95, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95s, delta < 6)\n\n\t\tmodavgGHCND95 <- model.avg(modGHCND95s)\n#\t\tsummary(modavgGHCND95)\n\n\n\t# Species-specific ARR data: present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95ARRbyspps <- dredge(modGHCND95ARRbyspp, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95ARRbyspps, delta < 6)\n\n\t\tmodavgGHCND95ARRbyspp <- model.avg(modGHCND95ARRbyspps)\n#\t\tsummary(modavgGHCND95ARRbyspp)\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND) (with acclimation, MORE Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95_marBTmores <- dredge(modGHCND95_marBTmore, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95_marBTmores, delta < 6)\n\n\t\tmodavgGHCND95_marBTmore <- model.avg(modGHCND95_marBTmores)\n#\t\tsummary(modavgGHCND95_marBTmore)\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND) (with acclimation, LESS Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95_marBTlesss <- dredge(modGHCND95_marBTless, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95_marBTlesss, delta < 6)\n\n\t\tmodavgGHCND95_marBTless <- model.avg(modGHCND95_marBTlesss)\n#\t\tsummary(modavgGHCND95_marBTless)\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTSMfav_noaccs <- dredge(modTSMfav_noacc, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTSMfav_noaccs, delta < 6)\n\n\t\tmodavgTSMfav_noacc <- model.avg(modTSMfav_noaccs)\n#\t\tsummary(modavgTSMfav_noacc)\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections, but acclimation temperature included as a fixed effect\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTSMfav_accterms <- dredge(modTSMfav_accterm, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTSMfav_accterms, delta < 6)\n\n\t\tmodavgTSMfav_accterm <- model.avg(modTSMfav_accterms)\n#\t\tsummary(modavgTSMfav_accterm)\n\n\n\n\n####################################################\n### Write out table of peaks and valleys in GAMMS\n####################################################\nout <- data.frame(Variable=c('T_b terrestrial', 'T_b marine', 'T_max terrestrial', 'T_max marine', 'TSM_favorable terrestrial', 'TSM_favorable marine'), Peak1=character(6), Peak2=character(6), Peak3=character(6), stringsAsFactors=FALSE)\n\n# calculate quantiles\nqTbGHCND95_terr1 <- quantile(sapply(peaksTbGHCND95_terr$peaklocs, FUN=function(x, min=-50, max=0){ret <- x[x>min & xmin & xmin & xmin & xmin & xmin & xmin & xmin & xmin & xmin & xmin & x|t|)'],2),\n\t\t\tRVI = round(ifelse(length(indxrvi)>0, no=NA, yes=modavgsout[[i]]$importance[indxrvi]),2),\n\t\t\tedf = NA,\n\t\t\tF = NA)\n\t\tout2 <- rbind(out2, temp)\n\t}\n\n\t# smooth terms\n\tfor(j in 1:nrow(summ$s.table)){\n\t\tvar <- gsub('s\\\\(lat\\\\)\\\\:Realm', '', rownames(summ$s.table)[j])\n\t\ttemp <- data.frame(\n\t\t\tmodel = names(modsout)[i],\n\t\t\tr2='',\n\t\t\tn='',\n\t\t\tvariable = paste('Latitude:', var, sep=''),\n\t\t\tsmooth = 1,\n\t\t\testimate = NA,\n\t\t\tse = NA,\n\t\t\tt = NA,\n\t\t\tp = signif(summ$s.table[j, 'p-value'],2),\n\t\t\tRVI = round(ifelse(var=='Marine', no=NA, yes=modavgsout[[i]]$importance['s(lat, by = Realm)']),2),\n\t\t\tedf = round(summ$s.table[j, 'edf'],2),\n\t\t\tF = round(summ$s.table[j, 'F'],2))\n\t\tout2 <- rbind(out2, temp)\n\t}\n}\n\n# format p-values\norig <- options(scipen=1)\n# rnd <- out2$p < 0.00001\nout2$p <- as.character(out2$p)\n# out2$p[rnd] <- '< 0.00001'\n\nout2$p\n\noptions(scipen=orig)\n\n# write out\nout2\nwrite.csv(out2, file='tables/TableS2_gamm_models.csv', row.names=FALSE, na='')\n", "meta": {"hexsha": "9a1176f3a9c3ed223cc3a926160e2fdf78baeb69", "size": 39194, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_models.r", "max_stars_repo_name": "HuckleyLab/phyto-mhw", "max_stars_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-13T02:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T04:41:09.000Z", "max_issues_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_models.r", "max_issues_repo_name": "HuckleyLab/phyto-mhw", "max_issues_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-19T10:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T19:53:09.000Z", "max_forks_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_models.r", "max_forks_repo_name": "HuckleyLab/phyto-mhw", "max_forks_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4370579915, "max_line_length": 345, "alphanum_fraction": 0.6955401337, "num_tokens": 13988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.3505094453184785}}
{"text": "[[[\n RELATIVE COMPLEXITY!\n Additional steps in my new construction for\n a self-delimiting universal Turing machine.\n\n We show that\n\n H(beta) <= n + H(n) + c for n-bit beta \n \n H(x,y) <= H(x) + H(y) + c\n \n H(H(x)|x) <= c\n \n H(x,y) <= H(x) + H(y|x) + c\n]]]\n \n[\n Here is the self-delimiting universal Turing machine\n with NO free data. P is the program.\n [Run-utm-on p expands to this.]\n]\ndefine (U p)\n cadr try no-time-limit 'eval read-exp p\n\ndefine U\nvalue (lambda (p) (car (cdr (try no-time-limit (' (eval \n (read-exp))) p))))\n\n[Here is the version of U with one piece of free data:]\n\ndefine (U2 p q) [q is a program for U for the free data]\n cadr try no-time-limit \n display cons 'read-exp [run ((read-exp) (' q))]\n cons cons \"' \n cons q \n nil \n nil \n p\n\ndefine U2\nvalue (lambda (p q) (car (cdr (try no-time-limit (displa\n y (cons (' (read-exp)) (cons (cons ' (cons q nil))\n nil))) p))))\n\n[Here's the version given two things, not one:]\n\ndefine (U3 p q r) [q, r are programs for U for the free data]\n cadr try no-time-limit \n display cons 'read-exp [run ((read-exp) (' q) (' r))]\n cons cons \"' \n cons q \n nil \n cons cons \"' \n cons r \n nil \n nil \n p\n\ndefine U3\nvalue (lambda (p q r) (car (cdr (try no-time-limit (disp\n lay (cons (' (read-exp)) (cons (cons ' (cons q nil\n )) (cons (cons ' (cons r nil)) nil)))) p))))\n\n[\n Consider an n-bit string beta.\n We show that H(beta) <= n + H(n) + 912.\n]\ndefine pi\n let (loop k)\n if = k 0 nil\n cons read-bit (loop - k 1)\n (loop eval read-exp)\n\ndefine pi\nvalue ((' (lambda (loop) (loop (eval (read-exp))))) (' (\n lambda (k) (if (= k 0) nil (cons (read-bit) (loop \n (- k 1)))))))\n\n[Size it.]\nlength bits pi\n\nexpression (length (bits pi))\nvalue 912\n\n[Use it.]\n(U\n append bits pi \n append bits 12\n '(0 0 1 1 1 1 1 1 0 0 0 1)\n)\n\nexpression (U (append (bits pi) (append (bits 12) (' (0 0 1 1\n 1 1 1 1 0 0 0 1)))))\nvalue (0 0 1 1 1 1 1 1 0 0 0 1)\n\n[\n Proof that H(x,y) <= H(x) + H(y) + 432.\n]\ndefine rho\n cons eval read-exp cons eval read-exp nil\n\ndefine rho\nvalue (cons (eval (read-exp)) (cons (eval (read-exp)) ni\n l))\n\n[Size it.]\nlength bits rho\n\nexpression (length (bits rho))\nvalue 432\n\n[Use it.]\n(U\n append bits rho\n append bits pi\n append bits 5\n append '(1 1 1 1 1)\n append bits pi\n append bits 9\n '(0 0 0 0 0 0 0 0 0)\n)\n\nexpression (U (append (bits rho) (append (bits pi) (append (b\n its 5) (append (' (1 1 1 1 1)) (append (bits pi) (\n append (bits 9) (' (0 0 0 0 0 0 0 0 0)))))))))\nvalue ((1 1 1 1 1) (0 0 0 0 0 0 0 0 0))\n\n[\n Proof that H(H(x)|x) <= 208.\n]\ndefine (alpha x*) [x* = minimum-size program for x]\n length x* \n\ndefine alpha\nvalue (lambda (x*) (length x*))\n\n [get H(x) from x*]\n[Size it.]\nlength bits alpha\n\nexpression (length (bits alpha))\nvalue 208\n\n[Use it.]\n\n(U2 \n \n[This is the program to calculate H(x):]\n\nbits alpha \n\n[This is the program x* for x,]\n[supposedly smallest possible:]\n\nbits' + 1 1 \n\n)\n\nexpression (U2 (bits alpha) (bits (' (+ 1 1))))\ndisplay ((read-exp) (' (0 0 1 0 1 0 0 0 0 0 1 0 1 0 1 1 0 \n 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 \n 1 1 0 0 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0)))\nvalue 64\n\n[Check size of program is correct]\n* 8 + 1 display size display '+ 1 1\n\nexpression (* 8 (+ 1 (display (size (display (' (+ 1 1)))))))\ndisplay (+ 1 1)\ndisplay 7\nvalue 64\n\n[\n Proof that H(x,y) <= H(x) + H(y|x) + 2872.\n\n The 2872-bit prefix gamma proves this.\n\n Gamma does the job, but it's slow.\n So below we will present delta, which is a greatly\n sped up version of gamma. The speed up is\n achieved by introducing a new primitive function\n to do the job. The was-read mechanism used below\n is much faster than our technique here using try\n to get the bits of the program p = x* as we run it.\n]\n\ndefine gamma\n\n [read program p bit by bit until we get it all]\n\n let (loop p)\n if = success car try no-time-limit 'eval read-exp p\n [then] p \n [else] (loop append p cons read-bit nil)\n\n let x* (loop nil) [get x* = program for x]\n let x run-utm-on x* [get x from x*]\n let y [get y from x* by running]\n eval cons 'read-exp [((read-exp) (' x*))]\n cons cons \"' \n cons x*\n nil \n nil \n\n [form the pair x, y]\n cons x cons y nil\n\ndefine gamma\nvalue ((' (lambda (loop) ((' (lambda (x*) ((' (lambda (x\n ) ((' (lambda (y) (cons x (cons y nil)))) (eval (c\n ons (' (read-exp)) (cons (cons ' (cons x* nil)) ni\n l)))))) (car (cdr (try no-time-limit (' (eval (rea\n d-exp))) x*)))))) (loop nil)))) (' (lambda (p) (if\n (= success (car (try no-time-limit (' (eval (read\n -exp))) p))) p (loop (append p (cons (read-bit) ni\n l)))))))\n\n[Size it.]\nlength bits gamma\n\nexpression (length (bits gamma))\nvalue 2872\n\n[Use it.]\n\nrun-utm-on\n\n[get pair x, y by combining ]\n[a program for x and a program to get y from x]\n\nappend \n\n bits gamma\n\nappend\n\n [x* = program to calculate x = 2]\n [[Supposedly x* is smallest possible,]] \n [[but this works for ANY x* for x.]]\n\n bits' + 1 1 \n\n [program to calculate y = x+1 from x*]\n\n bits' lambda(x*) + 1 run-utm-on x*\n\nexpression (car (cdr (try no-time-limit (' (eval (read-exp)))\n (append (bits gamma) (append (bits (' (+ 1 1))) (\n bits (' (lambda (x*) (+ 1 (car (cdr (try no-time-l\n imit (' (eval (read-exp))) x*))))))))))))\nvalue (2 3)\n\n[\n This technique for getting a program as well as its output\n by inching along using try is slow.\n\n Now let's speed up gamma by adding a new primitive function.\n Was-read gives the binary data read so far in the current try. \n With it we will prove that H(x,y) <= H(x) + H(y|x) + 2104.\n]\ndefine delta [knows that its own size is 2104 bits]\n let (skip n s) [skip first n bits of bit string s]\n if = n 0 s (skip - n 1 cdr s) [used to erase delta from was-read]\n let x eval read-exp [get x]\n let x* (skip 2104 was-read) [get program for x]\n let y [calculate y from the program for x by]\n eval cons 'read-exp [running ((read-exp) (' x*))]\n cons cons \"' \n cons x*\n nil \n nil \n [form the pair x, y]\n cons x cons y nil \n\ndefine delta\nvalue ((' (lambda (skip) ((' (lambda (x) ((' (lambda (x*\n ) ((' (lambda (y) (cons x (cons y nil)))) (eval (c\n ons (' (read-exp)) (cons (cons ' (cons x* nil)) ni\n l)))))) (skip 2104 (was-read))))) (eval (read-exp)\n )))) (' (lambda (n s) (if (= n 0) s (skip (- n 1) \n (cdr s))))))\n\n \n[Size it.]\nlength bits delta\n\nexpression (length (bits delta))\nvalue 2104\n\n[Use it.]\n\nrun-utm-on\n\n[get pair x, y by combining ]\n[a program for x and a program to get y from x]\n\nappend \n\n bits delta\n\nappend\n\n [x* = program to calculate x = 2]\n [[Supposedly x* is smallest possible,]] \n [[but this works for ANY x* for x.]]\n\n bits' + 1 1\n\n [program to calculate y = x+1 from x*]\n\n bits' lambda(x*) + 1 run-utm-on x*\n\nexpression (car (cdr (try no-time-limit (' (eval (read-exp)))\n (append (bits delta) (append (bits (' (+ 1 1))) (\n bits (' (lambda (x*) (+ 1 (car (cdr (try no-time-l\n imit (' (eval (read-exp))) x*))))))))))))\nvalue (2 3)\n", "meta": {"hexsha": "e20b29f8cd23ee7cec7c6ebe234ad5706047cef4", "size": 7975, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/utm2.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/utm2.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/utm2.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 25.0786163522, "max_line_length": 72, "alphanum_fraction": 0.517492163, "num_tokens": 2531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.35026006337024923}}
{"text": "#' Estimating the direct sampling (DSC) environmental contours\r\n#'\r\n#' @description\r\n#' This function estimates the direct sampling (DSC) environmental contours with standardization, as proposed in Huesby et al. (2015),\r\n#' for a given sample data set or a fitted joint distribution of class \\code{ht} or \\code{wln}.\r\n#' \r\n#' @param object either a fitted joint distribution of class \\code{wln} or \\code{ht}, or an existing sample data\r\n#' set containing \\code{hs} and \\code{tp} as columns. See details.\r\n#' \r\n#' @param output_rp the required return periods (in years) for the estimated contours.\r\n#' \r\n#' @param npy the (optional) number of data points per year. This argument is only needed if the input\r\n#' \\code{object} is a sample data set.\r\n#' \r\n#' @param n_point the number of points to output around each contour. The default value is 100.\r\n#' \r\n#' @details\r\n#' The direct sampling contour is estimated in the origianl physical scales of \\eqn{hs} and \\eqn{tp} by direct\r\n#' Monte Carlo simulations rather than applying the RosenBlatt transformation.\r\n#' \r\n#' The function can be applied to an existing sample set, which can be generated by function \\code{\\link{sample_jdistr}}\r\n#' or otherwise by importing a CSV file using function \\code{\\link[data.table]{fread}}. The input sample data\r\n#' object must contain \\code{hs} and \\code{tp} as columns. The user must also specify the number of points per year\r\n#' \\code{npy} and a valid \\code{output_rp}, i.e. the maximum \\code{output_rp} must be shorter than the total\r\n#' duration of the data set.\r\n#' \r\n#' Alternatively this function can be applied to a fitted joint distribution object\r\n#' generated by function \\code{\\link{fit_ht}} or \\code{\\link{fit_wln}}. When applied to a\r\n#' \\code{wln} or \\code{ht} object, the contour estimation makes use of the importance\r\n#' sampling technique proposed in Huseby et. al. (2014) to improve the efficiency of the function.\r\n#' \r\n#' @return\r\n#' A set of estimated DSC contours with the specified return periods in the format\r\n#' of a \\code{data.table} with \\code{rp}, \\code{hs}, and \\code{tp} as columns.\r\n#' \r\n#' @examples\r\n#' # Estimating DSC contours based on a fitted model\r\n#' data(ww3_pk)\r\n#' ht = fit_ht(data = ww3_pk, npy = nrow(ww3_pk)/10, margin_thresh_count = 50, dep_thresh_count = 500)\r\n#' ec_ht = estimate_dsc(object = ht, output_rp = c(10,100,1000,10000))\r\n#' plot_ec(ec = ec_ht, raw_data = ww3_pk)\r\n#' \r\n#' # Estimating DSC contours based on a sample data set\r\n#' data(ww3_ts)\r\n#' ec_data = estimate_dsc(object = ww3_ts, output_rp = c(.5, 1, 2), npy = ww3_ts[, .N/10])\r\n#' plot_ec(ec = ec_data, raw_data = ww3_ts)\r\n#' \r\n#' @seealso \\code{\\link{fit_ht}}, \\code{\\link{fit_wln}}, \\code{\\link{sample_jdistr}}, \\code{\\link{plot_ec}}\r\n#' \r\n#' @references\r\n#' Huseby, A., Vanem, E., Natvig, B., 2014. A new Monte Carlo method for environmental contour estimation.\r\n#' Conference Proceedings. DOI:10.1201/b17399-286.\r\n#' \r\n#' Huseby, A., Vanem, E., Natvig, B., 2015. Alternative environmental contours for structural reliability\r\n#' analysis. Struct. Saf. 54, 32-45.\r\n#' \r\n#' @export\r\nestimate_dsc = function(object, output_rp, npy = NULL, n_point = 100){\r\n \r\n if(\"wln\" %in% class(object)){\r\n \r\n res = .estimate_dsc_from_wln(wln = object, output_rp = output_rp, n_point = n_point)\r\n if(!is.null(npy)){\r\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\r\n }\r\n \r\n }else if(\"ht\" %in% class(object)){\r\n \r\n res = .estimate_dsc_from_ht(ht = object, output_rp = output_rp, n_point = n_point)\r\n if(!is.null(npy)){\r\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\r\n }\r\n \r\n }else if(\"data.table\" %in% class(object)){\r\n \r\n if(is.null(npy)){\r\n stop(\"Argument npy must be provided for estimating contours from sample data.\")\r\n }else{\r\n invalid_rp = output_rp[output_rp>object[, .N/npy]]\r\n if(length(invalid_rp)==length(output_rp)){\r\n stop(\"All output_rp values are invalid as they require extrapolation. Consider fitting a joint distribution first.\")\r\n }else if(length(invalid_rp)>=1 & length(invalid_rp)