{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fb7d2fd5",
   "metadata": {},
   "source": [
    "# Ising-Lenz Ergodicity: Analysis of Time Power-laws in Kappa for Fields\n",
    "\n",
    "    \n",
    "     (c) 2013, 2014, 2015, 2016, 2025 Süzen\n",
    "     GPL v3 \n",
    "\n",
    "$\\Omega_{G}(t)$ : Modified TM G-metric, ergodic convergence.  \n",
    "$\\Gamma_{G}(t)$ : Rate of ergodic convergence.  \n",
    "$\\Kappa_{G}(t)$ : Inverse rate of ergodic convergence.   \n",
    "\n",
    "\n",
    "This notebook plots power-laws and writes out latex table. \n",
    "$\\Kappa_{G}(t) \\sim C t^{\\alpha}$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cf6a110",
   "metadata": {
    "vscode": {
     "languageId": "r"
    }
   },
   "outputs": [],
   "source": [
    "rm(list=ls()) \n",
    "require(\"isingLenzMC\"); # Developed and tested on v0.2.5 and R v4.5.1\n",
    "library(parallel)       # Core package\n",
    "library(Hmisc) # for latex tables from data.frame\n",
    "source(\"../src/power_utilities.R\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2153dde9",
   "metadata": {
    "vscode": {
     "languageId": "r"
    }
   },
   "outputs": [],
   "source": [
    "df_pl_kappa <- readRDS(\"../datasets/ising1DrateErgodicityPowerlawsTimeFields.rds\")\n",
    "ergoRates <- readRDS(\"../datasets/ising1DrateErgodicityFields.rds\")\n",
    "latex(df_pl_kappa, file=\"../tables/kappa_powerlaw_time_fields.latex\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16e003eb",
   "metadata": {
    "vscode": {
     "languageId": "r"
    }
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af496f2f",
   "metadata": {
    "vscode": {
     "languageId": "r"
    }
   },
   "outputs": [],
   "source": [
    "plot_case <- function(result, powerl, meta_on_plot=FALSE) {\n",
    "    base_plot <- \"../plots/powerLawKappaFields/\"\n",
    "    dynamics <- result$dynamics\n",
    "    N <- result$N\n",
    "    ikBT <- result$ikBT\n",
    "    H <- result$H\n",
    "    nrepeat <- powerl$nrepeat\n",
    "    fsize <- 18\n",
    "    if(meta_on_plot) fsize <- 14\n",
    "\n",
    "    jsonlite::write_json(powerl, path = paste(base_plot, dynamics, \"N\", N, \"field\", H, \".json\", sep = \"\"), pretty = TRUE)\n",
    "    tlog <- seq(powerl$xmin_mean, 7, 0.01) # up-to 6M steps.\n",
    "    pdf(paste(base_plot, dynamics, \"N\", N, \"field\", H, \".pdf\", sep = \"\"), pointsize = fsize) # pointsize will effect all label and title font sizes.\n",
    "    #\n",
    "    # Log-Log plot: First raw Omega' evolution\n",
    "    #\n",
    "    lx <- length(result$accept_times_repeats[[1]])\n",
    "    x <- log10(result$accept_times_repeats[[1]][2:lx])\n",
    "    y <- log10(1.0 / result$gamma_repeats[[1]][2:lx])\n",
    "    par(mar=c(5,6,4,1)+.1)\n",
    "    if(meta_on_plot) {\n",
    "      layout(matrix(c(1, 2), 2, 1), heights = c(1, 0.1), widths = c(1))\n",
    "      par(mar = c(12, 10, 6, 4) + 0.1) # clock-wise from the bottom\n",
    "    }\n",
    "    plot(10^x, 10^y,\n",
    "      type = \"l\", axes = FALSE, ann = FALSE,\n",
    "      lwd = 0.7, cex.lab = 1.2, cex.axis = 1.2, cex.main = 1, cex.sub = 1,\n",
    "      log = \"xy\", lty = 1, xlim = c(10, 1.1e7),\n",
    "    )\n",
    "    #\n",
    "    # Re-write axis labels\n",
    "    #\n",
    "    AT <- c(10, 100, 1000, 10000, 100000, 1000000, 10000000)\n",
    "    AT.label <- expression(10^1, 10^2, 10^3, 10^4, 10^5, 10^6, 10^7)\n",
    "    AT2 <- c(10^0, 10^1, 10^2, 10^3, 10^4, 10^5, 10^6, 10^7)\n",
    "    AT2.label <- expression(10^0, 10^1, 10^2, 10^3, 10^4, 10^5, 10^6, 10^7)\n",
    "    axis(1, at = AT, labels = AT.label)\n",
    "    axis(2, at = AT2, labels = AT2.label)\n",
    "    box()\n",
    "    #\n",
    "    # Title-subtitle and axis labels\n",
    "    # Variable parameters are printed, including power-law\n",
    "    #\n",
    "    cmean <- sprintf(\"%.3f\", powerl$C_mean)\n",
    "    Cboot95ci <- sprintf(\" [%.3f,%.3f]\", powerl$C_lower, powerl$C_upper)\n",
    "\n",
    "    alphamean <- sprintf(\"%.3f\", powerl$alpha_mean)\n",
    "    alpheboot95ci <- sprintf(\" [%.3f,%.3f]\", powerl$alpha_lower, powerl$alpha_upper)\n",
    "\n",
    "\n",
    "    adjR2mean <- sprintf(\"%.3f\", powerl$adjR2_mean)\n",
    "    adjR2boot95ci <- sprintf(\" [%.3f,%.3f]\", powerl$adjR2_lower, powerl$adjR2_upper)\n",
    "\n",
    "    optDsmean <- sprintf(\"%.3f\", powerl$optDs_mean)\n",
    "    optDsboot95ci <- sprintf(\" [%.3f,%.3f]\", powerl$optDs_lower, powerl$optDs_upper)\n",
    "\n",
    "    title_main <- bquote(paste(\"Inverse rate power law \", Kappa(t), \" ~ \", Ct^{alpha}))\n",
    "    subtitle <- bquote(paste(\n",
    "      \" N=\", .(N), \" \", H, \"=\", .(H), \" \", .(dynamics)\n",
    "    ))\n",
    "    ylabel <- bquote(atop(\"Log Scale Inverse Rate\", log[10](K[G])))\n",
    "    xlabel <- bquote(atop(log[10](t), \"Log Scale Monte Carlo Time\"))\n",
    "    title(main = title_main, xlab = xlabel, ylab = ylabel)\n",
    "    mtext(subtitle)\n",
    "    #\n",
    "    # Plot all Omega' independent runs.\n",
    "    # All Raw functional-trajectories.\n",
    "    #\n",
    "    for (i in 2:nrepeat) {\n",
    "      x <- log10(result$accept_times_repeats[[i]][2:lx])\n",
    "      y <- log10(1.0 / result$gamma_repeats[[i]][2:lx])\n",
    "      lines(10^x, 10^y, type = \"l\", lty = 1)\n",
    "    }\n",
    "    #\n",
    "    # Plot Fitted Power law with CI\n",
    "    #\n",
    "    x <- tlog\n",
    "    y <- powerl$alpha_mean * tlog + powerl$C_mean\n",
    "    lines(10^x, 10^y, type = \"l\", col = \"red\", lwd = 3, lty = 2)\n",
    "    y <- powerl$alpha_upper * tlog + powerl$C_upper\n",
    "    lines(10^x, 10^y, type = \"l\", col = \"red\", lwd = 3, lty = 3)\n",
    "    y <- powerl$alpha_lower * tlog + powerl$C_lower\n",
    "    lines(10^x, 10^y, type = \"l\", col = \"red\", lwd = 3, lty = 3)\n",
    "    #\n",
    "    # Plot KS-stats law with CI\n",
    "    # The location, that we start fitting.\n",
    "    #\n",
    "    x <- powerl$xmin_mean\n",
    "    abline(v = 10^x, col = \"blue\", lwd = 3, lty = 4)\n",
    "    x <- powerl$xmin_upper\n",
    "    abline(v = 10^x, col = \"blue\", lwd = 3, lty = 5)\n",
    "    x <- powerl$xmin_lower\n",
    "    abline(v = 10^x, col = \"blue\", lwd = 3, lty = 5)\n",
    "    #\n",
    "    # R puts legends based on color/lty respectively\n",
    "    # in case of black, though there are nrepeat,\n",
    "    # it only displays once, which is great!\n",
    "    #\n",
    "    legend(\"topleft\",\n",
    "      legend = c(\"Power-Law fit\", \"Time of minimum \\n KS-statistic\", \"MC Runs\"),\n",
    "      col = c(\"red\", \"blue\", \"black\"),\n",
    "      lty = c(2, 4, 1),\n",
    "      lwd = 2,\n",
    "      bty = \"n\",\n",
    "    )\n",
    "    if(meta_on_plot) {\n",
    "      par(mar = c(0, 0, 0, 0))\n",
    "      plot.new()\n",
    "      metainfo_power_law <- bquote(paste(K[G], \"=\", C, t^alpha))\n",
    "      metainfo_fit_a <- bquote(paste(alpha, \"=\", .(alphamean), .(alpheboot95ci)))\n",
    "      metainfo_fit_C <- bquote(paste(\"log(C)=\", .(cmean), .(Cboot95ci)))\n",
    "      metainfo_fitr2 <- bquote(paste(\"adj-\", R^2, \"=\", .(adjR2mean), .(adjR2boot95ci)))\n",
    "      metainfo_fitD <- bquote(paste(\"KS-stat:\", \"D=\", .(optDsmean), .(optDsboot95ci)))\n",
    "      mtext(metainfo_power_law, line = 6.0, xpd = TRUE)\n",
    "      mtext(metainfo_fit_a, line = 4.5, xpd = TRUE)\n",
    "      mtext(metainfo_fit_C, line = 3.0, xpd = TRUE)\n",
    "      mtext(metainfo_fitr2, line = 1.5, xpd = TRUE)\n",
    "      mtext(metainfo_fitD, line = 0.0, xpd = TRUE)\n",
    "    }\n",
    "    dev.off()\n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3f0972d",
   "metadata": {
    "vscode": {
     "languageId": "r"
    }
   },
   "outputs": [],
   "source": [
    "ncase <- length(ergoRates)\n",
    "for(i in 1:ncase) {\n",
    "    result <- ergoRates[[i]]\n",
    "    powerl <- df_pl_kappa[i,]\n",
    "    plot_case(result, powerl, meta_on_plot=FALSE) \n",
    "}"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "4.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
