{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\nCreated on Tue Nov  9 19:03:18 2021\n\n@author: maout\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\n\n#from matplotlib import pyplot as plt\n\nfrom scipy.spatial.distance import cdist\nimport time\nimport ot\nimport numba\nimport math\nimport random\nimport sys\nimport pickle\n\ndim = 2\nh = 0.001\nt1 = 0\nt2 = 1.5\nT = t2-t1\ntimegrid = np.arange(0,T+h/2,h)\nN = 2000#0#0#0#2000\n#g = 1\nk = timegrid.size\nM = 80\n\ny2 = np.ones(dim)  \nsigmas = np.array([0.1,0.5,1])\nrep_bridge = 5   #10 different bridge instances for every setting\nreps = 20 ##instanses for stochastic path evaluation of each bridge\n# dy0 = np.array([np.pi/4, np.pi/2, np.pi, 3*np.pi/2])    \n# y0s = np.zeros((dim,rep_bridge, dy0.size))\nrandom.seed(22)\n# for i in range(rep_bridge):\n#     y0s[0, i, :] = np.random.uniform( low=0, high=2*np.pi,size=1 ) \n#     y0s[1, i, :] = (y0s[0, i, :] + dy0) %(2* np.pi)\n\n\n\nKs   = np.linspace(0,4,11) \ndy0 = np.array([np.pi/4, np.pi/2])    \ny0s = np.zeros((dim,rep_bridge, dy0.size))\nRttcont = np.zeros(( rep_bridge, Ks.size, dy0.size, sigmas.size, timegrid.size,reps   ))*np.nan\nRttnon = np.zeros(( rep_bridge, Ks.size, dy0.size, sigmas.size, timegrid.size,reps   ))*np.nan\nused_us = np.zeros((dim, rep_bridge, Ks.size, dy0.size, sigmas.size,timegrid.size,  reps   ))*np.nan\nbis = [2,3,4]\nfor bi in bis:#range(rep_bridge):\n    ###loop over bridge iterations\n    \n    #for ki,K in enumerate(Ks): ##loop over interaction strengths\n    for ki,K in enumerate(Ks):\n        \n        \n        for yi in range(dy0.size): ###loop over initial distances\n            \n            \n            \n            for gii,g in enumerate(sigmas):\n                \n                #naming = 'kuramot\\\\2N_systematic_Kuramoto_homogeneous_repb_%d_ki_%d_yi_%d__gi_%d_N_%d_M_%d'%(bi, ki,yi,gii,N, M)\n                naming = 'kurgamot\\\\New_2N_systematic_Kuramoto_homogeneous_repb_%d_ki_%d_yi_%d__gi_%d_N_%d_M_%d'%(bi, ki,yi,gii,N, M)\n                \n                try:\n                    file = open(naming+'.dat','rb')\n                    to_save = pickle.load(file)   \n                    # naming2 = 'kuramot\\\\2N_systematic_Kuramoto_homogeneous_repb_%d_ki_%d_yi_%d__gi_%d_N_%d_M_%d_UNCONTROLLED'%(bi, ki,yi,gii,N, M)\n                    # file2 = open(naming2+'.dat','rb')\n                    # to_save2 = pickle.load(file2)\n                    \n                    #Fcont = to_save['Fcont'] \n                    Rttcont[bi,ki,yi, gii,:,:] = to_save['Rttcont']  \n                    #Fnon = to_save2['Fnon'] \n                    Rttnon[bi,ki,yi, gii,:,:] = to_save['Rttnon']  \n                    Kin = to_save['K']                     \n                    y0s[:, bi, yi] = to_save['y0']                \n                    used_us[:,bi,ki,yi, gii,:] = to_save['used_us']                     \n                except FileNotFoundError:\n                    i=0\n                    print(naming)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from scipy.spatial.distance import cdist\nimport time\nimport ot\nimport numba\nimport math\nimport random\nimport sys\nimport pickle\n\ndim = 2\nh = 0.001\nt1 = 0\nt2 = 1.5\nT = t2-t1\ntimegrid = np.arange(0,T+h/2,h)\nN = 2000#0#0#0#2000\n#g = 1\nk = timegrid.size\nM = 80\nbi = 2\nki = 3\ngii = 2\nyi = 1\ng=1\nnaming = 'kurgamot\\\\New_2N_systematic_Kuramoto_homogeneous_repb_%d_ki_%d_yi_%d__gi_%d_N_%d_M_%d'%(bi, ki,yi,gii,N, M)\n\nfile = open(naming+'.dat','rb')\nto_save = pickle.load(file) \nRttconti = to_save['Rttcont'] \nFcont = to_save['Fcont']\nFnon = to_save['Fnon']  \nRttnoni = to_save['Rttnon']       \nused_u = to_save['used_us']"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import seaborn as sns\nfrom matplotlib import pyplot as plt\nrepi = 0\npali = sns.diverging_palette(145, 300, s=60, as_cmap=True)\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset\nimport matplotlib.gridspec as gridspec\nplt.figure(figsize= (8,2.)),\nplt.subplot(1,3,1),\n#cols = [pali(0), pali(0.99) ]\n#cols2 = [pali(0.3),pali(0.7)]\ncols = [pali(0.99), pali(0.8) ]\ncols2 = [pali(0.),pali(0.2)]\nfor di in range(dim):\n    plt.plot(timegrid[:-1],Fcont[di,:-1,repi],'-',lw=4,c=cols[di],label=r'$\\theta_{%d}$'%(di+1))\n    plt.plot(timegrid[:-1],Fnon[di,:-1,repi],'.',lw=3,c=cols2[di],alpha=0.7,zorder=0)\nfor di in range(dim):\n    plt.plot(timegrid[:-1],Fnon[di,:-1, repi],'-',lw=3,c=cols2[di],zorder=0,label=r'$\\theta_{%d}$'%(di+1)) #this line is only for the legend entry\n    \n    \nplt.xlabel('time')\nplt.ylabel(r'phase $\\theta$')\nax = plt.gca()\nax.tick_params(axis='both',which='both',direction='out', length=3, width=1,colors='#4f4949',zorder=3)\nax.tick_params(bottom=True, top=False, left=True, right=False)\n\nax.set_yticks([0,np.pi/2,np.pi, 3*np.pi/2, 2*np.pi])\nax.set_yticklabels([r'$0$',r'$\\pi/2$',r'$\\pi$', r'${3 \\pi}/{2}$', r'$2 \\pi$'])\n\n\n# legend = plt.legend(frameon = 1,prop={'size': 15})\n# frame = legend.get_frame()\n# frame.set_facecolor('white')\n# frame.set_edgecolor('white')\nplt.xticks([0,0.5,1,1.5])\nlegend = ax.legend()        \nlegend.get_frame().set_linewidth(1.8)\nlegend.get_frame().set_facecolor('white')\nlegend.get_frame().set_edgecolor('white')\nhandles, labels = ax.get_legend_handles_labels()\n\nif True:#g==0.5:\n    ax.legend(handles, labels, title='controlled   uncontrolled',\n              handletextpad=0.5, columnspacing=3.2,handlelength=0.8, bbox_to_anchor=[0.0, 0.785],\n              loc=3, ncol=2, frameon=True,fontsize = 'small',shadow=None,framealpha =0,edgecolor ='#0a0a0a')\n    \nelse:\n    ax.legend(handles, labels, title='controlled   uncontrolled',\n              handletextpad=0.5, columnspacing=3.2,handlelength=0.8,\n              loc=3, ncol=2, frameon=True,fontsize = 8,shadow=None,framealpha =0,edgecolor ='#0a0a0a')\n    \nplt.setp(plt.gca().get_legend().get_title(), fontsize='10')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.subplot(1,3,2),\nplt.plot(timegrid[:-1],Rttnoni[:-1,repi],lw=3,c= cols2[0],zorder=3,label='uncontrolled'),\nplt.plot(timegrid[:-1],Rttconti[:-1,repi],lw=3, c=cols[0],zorder=4,label='controlled'),\n\nplt.plot([0,timegrid[-1]], [1/np.sqrt(dim),1/np.sqrt(dim) ],linestyle=(0,(4,3)),lw=3, c='#ee9222',alpha=0.5,label='independent'),\nplt.plot([0,timegrid[-1]], [1,1 ],linestyle=(0,(4,3)),c='grey',lw=3,dash_capstyle = \"round\"),\nplt.xlabel('time')\nplt.xticks([0,0.5,1,1.5])\nplt.ylabel(r'order  param. $R$')   \nax7 = plt.gca()\nax7.tick_params(axis='both',which='both',direction='out', length=3, width=1,colors='#4f4949',zorder=3)\nax7.tick_params(bottom=True, top=False, left=True, right=False)\n\nlegend = ax7.legend()        \nlegend.get_frame().set_linewidth(1.8)\nlegend.get_frame().set_facecolor('white')\nlegend.get_frame().set_edgecolor('white')\nhandles, labels = ax7.get_legend_handles_labels()\nhandles = [ handles[-2],handles[0] , handles[-1]]\nlabels= [ labels[-2],labels[0] , labels[-1]]\nif True:\n    ax7.legend(handles, labels, \n              handletextpad=0.5, columnspacing=0.3,handlelength=0.5, bbox_to_anchor=[-0.4, 0.99],\n              loc=3, ncol=3, frameon=True,fontsize = 'small',shadow=None,framealpha =0,edgecolor ='#0a0a0a')    \n\n\n###########\n# axins = zoomed_inset_axes(ax,2, loc=1, bbox_to_anchor=(2400,800))\n# mark_inset(ax, axins, loc1=2, loc2=1, fc=\"none\", ec=\"0.5\")\n# axins.set_xlim([0.5,1.2])\n# axins.set_ylim([0.95,1.01])\n\n# # # Plot zoom window\n# axins.plot(timegrid[:tti],Rtt[:tti],lw=3,c= cols2[0],zorder=3),\n# axins.plot(timegrid[:tti],Rttcont[:tti],lw=3, c=cols[0],zorder=4),\n# axins.plot([0,timegrid[tti]], [1,1 ],linestyle=(0,(4,3)),c='grey',lw=3,dash_capstyle = \"round\"),\n# axins.tick_params(bottom=False, top=False, left=True, right=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.subplot(1,3,3),\n#for ti in range(2):\nfor di in range(dim):\n    plt.plot(timegrid[:],h*g**2*used_u[di,:,repi],lw=2.5, c=cols[di],label=r'$u_{%d}$'%(di+1))\nplt.xticks([0,0.5,1,1.5])\nplt.xlabel('time')\nplt.ylabel(r'control $u$')   \nax = plt.gca()\nax.tick_params(axis='both',which='both',direction='out', length=3, width=1,colors='#4f4949',zorder=3)\nax.tick_params(bottom=True, top=False, left=True, right=False)\nlegend = ax.legend()        \nlegend.get_frame().set_linewidth(1.8)\nlegend.get_frame().set_facecolor('white')\nlegend.get_frame().set_edgecolor('white')\nhandles, labels = ax.get_legend_handles_labels()\nax.legend(handles, labels, title=None,\n          handletextpad=0.5, columnspacing=0,handlelength=1, bbox_to_anchor=[0.50, 0.35],\n          loc=1, ncol=1, frameon=True,fontsize = 'small',shadow=None,framealpha =0,edgecolor ='#0a0a0a')\n\n\nnaming2 = 'Kuramoto_2N_trajectories'    \n##%%\n#plt.savefig( 'naming.png', bbox_inches='tight')\n#plt.savefig( 'naming.pdf', bbox_inches='tight')\nplt.savefig( naming2+'.png', bbox_inches='tight')\nplt.savefig(naming2 +'.pdf', bbox_inches='tight')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from matplotlib import pyplot as plt                     \n\n#figure and plotting settings\nimport seaborn as sns\nplt.rcParams['figure.dpi'] = 300\nplt.rcParams['savefig.dpi'] = 300\nplt.rcParams['savefig.facecolor'] = (1,1,1,0)\nplt.rcParams['savefig.bbox'] = \"tight\"\nplt.rcParams['font.size'] = 10*1.2\n# plt.rcParams['font.family'] = 'sans-serif'     # not available in Colab\n# plt.rcParams['font.sans-serif'] = 'Helvetica'  # not available in Colab\nplt.rcParams['pdf.fonttype'] = 42\nplt.rcParams['xtick.labelsize'] = 10*1.2\nplt.rcParams['ytick.labelsize'] = 10*1.2\nplt.rcParams['axes.labelsize'] = 12*1.2\nplt.rcParams['axes.linewidth'] = 2\nplt.rcParams['axes.spines.top'] = False\nplt.rcParams['axes.spines.right'] = False\n#plt.rcParams['axes.Axes.tick_params'] = True\n#plt.rcParams['axes.solid_capstyle'] = 'round'\nplt.rc('axes',edgecolor='#4f4949')\nplt.rcParams['figure.frameon'] = False\nplt.rcParams['figure.subplot.hspace'] = 0.51\nplt.rcParams['figure.subplot.wspace'] = 0.51\nplt.rcParams['figure.subplot.left'] = 0.1\nplt.rcParams['figure.subplot.right'] = 0.9\nplt.rcParams['figure.subplot.top'] = 0.9\nplt.rcParams['figure.subplot.bottom'] = 0.1\nplt.rcParams['lines.solid_capstyle'] = 'round'\nplt.rcParams['lines.solid_joinstyle'] = 'round'\n#plt.rcParams['xtick.major.size'] = 20\n#plt.rcParams['xtick.major.width'] = 4\nplt.rcParams['text.usetex'] = True"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "bi=2                   \n###bi=22 , k=4 and k=5 is good for plotting                    \n# R [ bi, ki, yi, gi, :,:]\nplt.figure(),\nfor ki in range(Ks.size):\n    plt.subplot(2,6,ki+1)\n    plt.title(ki)\n    yi=0\n    #for yi in range(dy0.size):\n        #plt.subplot(1,dy0.size,yi+1)\n    plt.plot(timegrid[:-2], np.nanmean(Rttcont[2:4,ki, :, :2,:-2 ], axis=(0,2,-1)).T  ) \n    plt.plot(timegrid[:-2], np.nanmean(Rttnon[2:4,ki, :, :2,:-2 ], axis=(0,2,-1)).T ,'--',alpha=0.4 ) \n    plt.ylim(0.5,1.1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# R [ bi, ki, yi, gi, :,:]\nbi=3\nplt.figure(),\nfor yi in range(dy0.size):\n    plt.subplot(1,dy0.size,yi+1)\n    ax = plt.gca()\n    # color = next(ax._get_lines.prop_cycler)['color']\n    # plt.plot(Ks, np.nanmean(np.nanmean(Rttcont[bi,:, yi, 0 ], axis=-2), axis=(-1)) , c=color)\n    # plt.plot(Ks, np.nanmean(np.nanmean(Rttnon[bi,:, yi, 0 ], axis=-2), axis=(-1)) ,'--', c=color)\n    color = next(ax._get_lines.prop_cycler)['color']\n    plt.plot(Ks[0::2], np.nanmean(np.nanmean(Rttcont[2:5,0::2, yi, 1,:-2 ], axis=-2), axis=(0,-1)), c=color,marker='.' )  \n    plt.plot(Ks[0::2], np.nanmean(np.nanmean(Rttnon[2:5,0::2, yi, 1,:-2 ], axis=-2), axis=(0,-1)) ,'--', c=color,marker='.' )\n    color = next(ax._get_lines.prop_cycler)['color']\n    plt.plot(Ks[0::2], np.nanmean(np.nanmean(Rttcont[2:5,0::2, yi, 2 ,:-2], axis=-2), axis=(0,-1)) , c=color,marker='.' )                                       \n    plt.plot(Ks[0::2], np.nanmean(np.nanmean(Rttnon[2:5,0::2, yi, 2,:-2 ], axis=-2), axis=(0,-1)) ,'--', c=color,marker='.' )\n    plt.ylim(0.5,1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.figure()\nplt.plot(Rttcont[2,3,1,2,:-2]),\nplt.plot(Rttnon[2,3,1,2,:-2],'grey')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.figure()\nplt.plot(Rttcont[2,5,1,1,:-2]),\nplt.plot(Rttnon[2,5,1,1,:-2],'grey',alpha=0.5)\n\nplt.figure()\nplt.plot(Rttcont[2,5,1,2,:-2]),\nplt.plot(Rttnon[2,5,1,2,:-2],'grey',alpha=0.5)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "bis= 2\nbie = 5\n\nplt.figure(),\nfor yi in range(dy0.size):\n    plt.subplot(1,dy0.size,yi+1)\n    ax = plt.gca()\n    # color = next(ax._get_lines.prop_cycler)['color']\n    # plt.plot(Ks, np.nanmean(np.nanmean(Rttcont[bi,:, yi, 0 ], axis=-2), axis=(-1)) , c=color)\n    # plt.plot(Ks, np.nanmean(np.nanmean(Rttnon[bi,:, yi, 0 ], axis=-2), axis=(-1)) ,'--', c=color)\n    color = next(ax._get_lines.prop_cycler)['color']\n    plt.plot(Ks[1::2], np.nanmean(np.nanmean(Rttcont[bis:bie,1::2, yi, 1,:-2 ], axis=-2), axis=(0,-1)), c=color,marker='.' )  \n    plt.plot(Ks[1::2], np.nanmean(np.nanmean(Rttnon[bis:bie,1::2, yi, 1,:-2 ], axis=-2), axis=(0,-1)) ,'--', c=color,marker='.' )\n    color = next(ax._get_lines.prop_cycler)['color']\n    plt.plot(Ks[1::2], np.nanmean(np.nanmean(Rttcont[bis:bie,1::2, yi, 2 ,:-2], axis=-2), axis=(0,-1)) , c=color,marker='.' )                                       \n    plt.plot(Ks[1::2], np.nanmean(np.nanmean(Rttnon[bis:bie,1::2, yi, 2,:-2 ], axis=-2), axis=(0,-1)) ,'--', c=color,marker='.' )\n    plt.ylim(0.5,1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "bi=3\nplt.figure(),\nfor yi in range(0,4):\n    plt.subplot(1,4,yi+1)\n    ax = plt.gca()\n    # color = next(ax._get_lines.prop_cycler)['color']\n    # plt.plot(Ks[1::2], np.nanmean(np.nanmean(Rttcont[yi+0:5,1::2, :, 0,:-2 ], axis=-2), axis=(0,2,-1)), c=color,marker='.' )  \n    # plt.plot(Ks[1::2], np.nanmean(np.nanmean(Rttnon[yi+0:5,1::2, :, 0,:-2 ], axis=-2), axis=(0,2,-1)) ,'--', c=color,marker='.' )\n    # plt.plot(Ks, np.nanmean(np.nanmean(Rttnon[bi,:, yi, 0 ], axis=-2), axis=(-1)) ,'--', c=color)\n    color = next(ax._get_lines.prop_cycler)['color']\n    plt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttcont[yi+0:5,1::2, :, 1,:-2 ], axis=-2), axis=(0,2,-1)), c=color,marker='.' )  \n    plt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttnon[yi+0:5,1::2, :, 1,:-2 ], axis=-2), axis=(0,2,-1)) ,'--', c=color,marker='.' )\n    color = next(ax._get_lines.prop_cycler)['color']\n    plt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttcont[yi+0:5,1::2, :, 2 ,:-2], axis=-2), axis=(0,2,-1)) , c=color,marker='.' )                                       \n    plt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttnon[yi+0:5, 1::2, :, 2,:-2 ], axis=-2), axis=(0,2,-1)) ,'--', c=color,marker='.' )\n    plt.ylim(0.5,1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "#figure and plotting settings\nimport seaborn as sns\nplt.rcParams['figure.dpi'] = 300\nplt.rcParams['savefig.dpi'] = 300\nplt.rcParams['savefig.facecolor'] = (1,1,1,0)\nplt.rcParams['savefig.bbox'] = \"tight\"\nplt.rcParams['font.size'] = 10*1.2\n# plt.rcParams['font.family'] = 'sans-serif'     # not available in Colab\n# plt.rcParams['font.sans-serif'] = 'Helvetica'  # not available in Colab\nplt.rcParams['pdf.fonttype'] = 42\nplt.rcParams['xtick.labelsize'] = 10*1.2\nplt.rcParams['ytick.labelsize'] = 10*1.2\nplt.rcParams['axes.labelsize'] = 12*1.2\nplt.rcParams['axes.linewidth'] = 2\nplt.rcParams['axes.spines.top'] = False\nplt.rcParams['axes.spines.right'] = False\n#plt.rcParams['axes.Axes.tick_params'] = True\n#plt.rcParams['axes.solid_capstyle'] = 'round'\nplt.rc('axes',edgecolor='#4f4949')\nplt.rcParams['figure.frameon'] = False\nplt.rcParams['figure.subplot.hspace'] = 0.51\nplt.rcParams['figure.subplot.wspace'] = 0.51\nplt.rcParams['figure.subplot.left'] = 0.1\nplt.rcParams['figure.subplot.right'] = 0.9\nplt.rcParams['figure.subplot.top'] = 0.9\nplt.rcParams['figure.subplot.bottom'] = 0.1\nplt.rcParams['lines.solid_capstyle'] = 'round'\nplt.rcParams['lines.solid_joinstyle'] = 'round'\nplt.rcParams['xtick.minor.size'] = 10\n#plt.rcParams['xtick.major.width'] = 4\nplt.rcParams['text.usetex'] = True"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "pali = sns.diverging_palette(145, 300, s=80, as_cmap=True)\ncols = [pali(0.99), pali(0.95), pali(0.85), pali(0.80), pali(0.75), pali(0.70) ]\ncols2 = [pali(0.),pali(0.05),pali(0.1),pali(0.15),pali(0.2),pali(0.25)]\n\nfrecmap = plt.get_cmap( 'plasma')\n# minw = np.abs(np.min(ws))+0.3\n# maxw = np.max(ws)\n# intervalw = maxw +minw +0.4\n# print([ ( (wsi + np.pi/2)/(np.pi)   ) for wsi in ws       ])\n# wscols = [ frecmap( (wsi + minw)/(intervalw)   ) for wsi in ws       ]\n\nfig9 = plt.figure(constrained_layout=False, figsize=(6,3))\ngs1 = fig9.add_gridspec(nrows=4, ncols=8, wspace=1.5, hspace=1.2)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "ax01 = fig9.add_subplot(gs1[0:2,0:2 ]) \n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig9.text(0.7, -0.05, 'time', ha='center',fontsize=16)\nfig9.text(0.45, 0.5, r'order  param. $R$', va='center', rotation='vertical',fontsize=14)\n\nfig9.text(0.7, 0.95, r'coupling  $J= 2.0$', ha='center',fontsize=10)\nfig9.text(0.95, 0.95, r'noise', ha='center',fontsize=10)\nfig9.text(0.95, 0.73, r'$\\sigma= 0.5$', ha='center',fontsize=10)\nfig9.text(0.95, 0.23, r'$\\sigma= 1.0$', ha='center',fontsize=10)\n# plt.ylabel(r'order  param. $R$')   \n# plt.xlabel('time')\n# plt.ylabel(r'order  param. $R$')   \n\nax02 = fig9.add_subplot(gs1[0:4,0:4 ]) \n\n\n\n\n#color = next(ax02._get_lines.prop_cycler)['color']\nplt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttcont[2:5,1::2, :, 1,:-2 ], axis=-2), axis=(0,2,-1)), c=cols[5],marker='^',label=r'$\\sigma=0.5$',zorder=5 ,lw=2,markersize=6,markeredgecolor='#4f4949')  \n\n#color = next(ax02._get_lines.prop_cycler)['color']\nplt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttcont[2:5,1::2, :, 2 ,:-2], axis=-2), axis=(0,2,-1)) , c=cols[1],marker='.',label=r'$\\sigma=1.0$' ,zorder=5,lw=2,markersize=10,markeredgecolor='#4f4949')    \nplt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttnon[2:5,1::2, :, 1,:-2 ], axis=-2), axis=(0,2,-1)) ,'--', c=cols2[5],marker='^',label=r'$\\sigma=0.5$',lw=2 ,markersize=6,markeredgecolor='#4f4949')                                   \nplt.plot(Ks[1:-1:2], np.nanmean(np.nanmean(Rttnon[2:5, 1::2, :, 2,:-2 ], axis=-2), axis=(0,2,-1)) ,'--', c=cols2[1],marker='.' ,label=r'$\\sigma=1.0$',lw=2,markersize=10,markeredgecolor='#4f4949')\nplt.ylim(0.5,1)    \n#plt.xlim(0,4.01)\n\nlegend = ax02.legend()        \nlegend.get_frame().set_linewidth(1.8)\nlegend.get_frame().set_facecolor('white')\nlegend.get_frame().set_edgecolor('white')\nhandles, labels = ax02.get_legend_handles_labels()\n#handles = [ handles[-2],handles[0] , handles[-1]]\n#labels= [ labels[-2],labels[0] , labels[-1]]\nif True:\n    ax02.legend(handles, labels, title=r'controlled $\\,$    uncontrolled',\n              handletextpad=0.5, columnspacing=0.5,handlelength=1.3, bbox_to_anchor=[-0.0, 0.0],\n              loc=3, ncol=2, frameon=True,fontsize = 10,shadow=None,framealpha =0,edgecolor ='#0a0a0a')    \n\nplt.setp(plt.gca().get_legend().get_title(), fontsize='10') \nplt.ylabel(r'order  param. $R$') \nplt.xlabel(r'coupling $J$')\n\nax1 = fig9.add_subplot(gs1[0:2,4:6 ] ) \n\nplt.plot(timegrid[:-2],Rttcont[2,5,1,1,:-2],c=cols[5],alpha=1),\nplt.plot(timegrid[:-2],np.mean(Rttcont[2,5,1,1,:-2],axis=1), '--',c='#4f4949')\n\nax1.set_ylim(0.0,1.01)\n#plt.yticks([0.5,1.0])\nplt.xticks([0.5,1.5])\nax1b = fig9.add_subplot(gs1[0:2,6:8 ] ,  sharey = ax1) \n\nplt.plot(timegrid[:-2],Rttnon[2,5,1,1,:-2],c=cols2[5],alpha=0.5)\nax1b.set_ylim(0.0,1.01)\nplt.plot(timegrid[:-2],np.mean(Rttnon[2,5,1,1,:-2],axis=1), '--',c='#4f4949')\n#plt.ylabel(r'order  param. $R$')   \nplt.xticks([0.5,1.5])\n#plt.yticks([0.5,1.0])\nax2 = fig9.add_subplot(gs1[ 2:4,4:6], sharex = ax1)\nax2.set_ylim(0.0,1.01)\nplt.plot(timegrid[:-2],Rttcont[2,5,1,2,:-2],c=cols[1],alpha=1),\nplt.plot(timegrid[:-2],np.mean(Rttcont[2,5,1,2,:-2],axis=1), '--',c='#4f4949')\n#plt.xlabel('time')\n#plt.ylabel(r'order  param. $R$')   \nplt.xticks([0.5,1.5])\n#plt.yticks([0.5,1.0])\nax2b = fig9.add_subplot(gs1[ 2:4,6:8], sharex = ax1b, sharey = ax2) \nplt.plot(timegrid[:-2],Rttnon[2,5,1,2,:-2],c=cols2[1],alpha=0.5)\nplt.plot(timegrid[:-2],np.mean(Rttnon[2,5,1,2,:-2],axis=1), '--',c='#4f4949')\nax2b.set_ylim(0.0,1.01)\nplt.xticks([0.5,1.5])\n\n\n\n#plt.savefig(\"Kuramoto_2.png\", bbox_inches='tight')\n#plt.savefig(\"Kuramoto_2.pdf\", bbox_inches='tight')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# R [ bi, ki, yi, gi, :,:]\n\nonset_cont = np.zeros((3,Ks.size,2,3,20)) *np.nan\nonset_uncont = np.zeros((3,Ks.size,2,3,20)) *np.nan\n\ncont_synched_durations_m = np.zeros((3,Ks.size,2,3,20)) *np.nan\ncont_synched_durations_std  = np.zeros((3,Ks.size,2,3,20)) *np.nan\ncont_synched_durations_max = np.zeros((3,Ks.size,2,3,20)) *np.nan\ncont_synched_durations_sum  = np.zeros((3,Ks.size,2,3,20)) *np.nan\n\nuncont_synched_durations_m = np.zeros((3,Ks.size,2,3,20)) *np.nan\nuncont_synched_durations_std  = np.zeros((3,Ks.size,2,3,20)) *np.nan\nuncont_synched_durations_max = np.zeros((3,Ks.size,2,3,20)) *np.nan\nuncont_synched_durations_sum  = np.zeros((3,Ks.size,2,3,20)) *np.nan\n\ncounter_cont = np.zeros((3,Ks.size,2,3))\ncounter_uncont =  np.zeros((3,Ks.size,2,3))\n\nthreshold = 0.99\nmin_duri = 20\nfor bi in range(3):\n    bii = bi+2 ###bi should start from 2 for the data matrices since I don't have simulation results for bi:0-1\n    for ki in range(Ks.size):\n        for yi in range(2):#\n            for gi in range(1,3):#3                \n                for repi in range(20):                    \n                    positions = np.where( Rttcont[bii, ki, yi, gi,1:-2, repi] >=threshold)[0]  ###this one detects if there is at all any synchronisation\n                    synch_or_not = Rttcont[bii, ki, yi, gi,1:-2, repi] >=threshold ##this is boolean indicating the synchronised positions\n                    \n                    if positions.size==0: \n                        onset_cont[bi,ki,yi,gi,repi] = np.nan\n                    else:\n                        diffpos = np.diff(synch_or_not.astype(int)   ) #difference between consecutive steps\n                        \n                        diffpos2 = np.zeros(diffpos.size+1) # extend by one step at the beginning to detect \n                        diffpos2[1:] = diffpos\n                        starts = np.argwhere(diffpos2 == 1)\n                        stops = np.argwhere(diffpos2 == -1)                        \n                        if starts.size == 0:\n                            onset_cont[bi,ki,yi,gi,repi] = np.nan\n                        elif stops.size == 0:\n                            onset_cont[bi,ki,yi,gi,repi] = timegrid[ starts[0] ]\n                            counter_cont[bi,ki,yi,gi] += 1\n                            dur = timegrid[ -1 ] - timegrid[ starts[0] ]\n                            cont_synched_durations_m[bi,ki,yi,gi,repi]  = dur\n                            cont_synched_durations_std[bi,ki,yi,gi,repi]  = 0\n                            cont_synched_durations_max[bi,ki,yi,gi,repi]  = dur\n                            cont_synched_durations_sum[bi,ki,yi,gi,repi]  = np.sum(  synch_or_not )/ (timegrid.size-1 - starts[0] )\n                        else:\n                            durations = stops[:,0] - starts[:stops.size, 0]                            \n                            synchned_more_than_50 = np.where( durations>=min_duri )[0]\n                            if synchned_more_than_50.size == 0:\n                                onset_cont[bi,ki,yi,gi,repi] = np.nan\n                            else:                                \n                                onset_cont[bi,ki,yi,gi,repi] = timegrid[ starts[synchned_more_than_50[0]] ]\n                                counter_cont[bi,ki,yi,gi] += 1                                \n                                cont_synched_durations_m[bi,ki,yi,gi,repi]  = np.mean(  durations  )\n                                cont_synched_durations_std[bi,ki,yi,gi,repi]  = np.std(  durations )\n                                cont_synched_durations_max[bi,ki,yi,gi,repi]  = np.max(  durations )\n                                cont_synched_durations_sum[bi,ki,yi,gi,repi]  = np.sum(  synch_or_not[ starts[synchned_more_than_50[0]][0] :   ] )/(timegrid.size-1 -starts[synchned_more_than_50[0]] ) ##timesteps in synchronied\n\n                       \n                        \n                    positions = np.where( Rttnon[bii, ki, yi, gi, 1:-2,repi] >=threshold)[0]\n                    synch_or_not = Rttnon[bii, ki, yi, gi,1:-2, repi] >=threshold                     \n                    if positions.size ==0: \n                        onset_uncont[bi,ki,yi,gi,repi] = np.nan\n                    else:\n                        diffpos = np.diff(synch_or_not.astype(int)   ) #difference between consecutive steps\n                        \n                        diffpos2 = np.zeros(diffpos.size+1) # extend by one step at the beginning to detect \n                        diffpos2[1:] = diffpos\n                        starts = np.argwhere(diffpos2 == 1)\n                        stops = np.argwhere(diffpos2 == -1)\n                        #start_stop =[starts, stops - starts]\n                        if starts.size == 0:\n                            onset_uncont[bi,ki,yi,gi,repi] = np.nan\n                        elif stops.size == 0:\n                            onset_uncont[bi,ki,yi,gi,repi] = timegrid[ starts[0] ]\n                            counter_uncont[bi,ki,yi,gi] += 1\n                            dur = timegrid[ -1 ] - timegrid[ starts[0] ]\n                            uncont_synched_durations_m[bi,ki,yi,gi,repi]  = dur\n                            uncont_synched_durations_std[bi,ki,yi,gi,repi]  = 0\n                            uncont_synched_durations_max[bi,ki,yi,gi,repi]  = dur\n                            uncont_synched_durations_sum[bi,ki,yi,gi,repi]  = np.sum(  synch_or_not )/ (timegrid.size-1 - starts[0] )\n                        else:\n                            durations = stops[:,0] - starts[:stops.size, 0]                            \n                            synchned_more_than_50 = np.where( durations>=min_duri )[0]\n                            \n                            if synchned_more_than_50.size == 0:\n                                onset_uncont[bi,ki,yi,gi,repi] = np.nan\n                            else:                                \n                                onset_uncont[bi,ki,yi,gi,repi] = timegrid[starts[synchned_more_than_50[0]] ]\n                                counter_uncont[bi,ki,yi,gi] += 1\n                                uncont_synched_durations_m[bi,ki,yi,gi,repi]  = np.mean(  durations )\n                                uncont_synched_durations_std[bi,ki,yi,gi,repi]  = np.std(  durations )\n                                uncont_synched_durations_max[bi,ki,yi,gi,repi]  = np.max(  durations  )\n                                uncont_synched_durations_sum[bi,ki,yi,gi,repi]  = np.sum(  synch_or_not[ starts[synchned_more_than_50[0]][0] :   ] ) /(timegrid.size-1 -starts[synchned_more_than_50[0]] )"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "count_perc = np.sum(counter_uncont[0:3,1::2,:1, :],axis=0)/60         #counts the percentage of synchronised uncontrolled network for the annotations               \n                        \nplt.figure(figsize=(6.5,2)) \nyi = 0\ngi = 1\nplt.subplot(1,2,1)\nax1 = plt.gca()\n#er1 = plt.errorbar(Ks[1:-1:2], np.nanmean(onset_cont[0:3,1::2,yi, 1], axis=(0,-1)), yerr=np.nanstd(onset_cont[0:3,1::2,yi, 1], axis=(0,-1)), marker=\"o\", linestyle=\"-\",uplims=True,lolims=True,)\n#er2 = plt.errorbar(Ks[1:-1:2], np.nanmean(onset_uncont[0:3,1::2,yi, 1], axis=(0,-1)), yerr=np.nanstd(onset_uncont[0:3,1::2,yi, 1], axis=(0,-1)), marker=\"o\", linestyle=\"-\",uplims=True,lolims=True)\nplt.plot(Ks[1:-1:2], np.nanmean(onset_cont[0:3,1::2,:1, 1], axis=(0,2,-1)) , c=cols[5],marker='^',label=r'$\\sigma=0.5$',zorder=5 ,lw=2.8,markersize=6,markeredgecolor='#4f4949') \nplt.plot(Ks[1:-1:2], np.nanmean(onset_uncont[0:3,1::2,:1, 1], axis=(0,2,-1)),'--', c=cols2[5],marker='^',label=r'$\\sigma=0.5$' ,zorder=5,lw=2.8,markersize=6,markeredgecolor='#4f4949')  \n\nplt.text(0.29, 0.49,\"%.2f\"%count_perc[0, 0 ,1], fontsize =8 , color = \"grey\")\n\nplt.text(0.97, 0.57,\"%.2f\"%count_perc[1, 0 ,1], fontsize =8 , color = \"grey\")\n\nplt.text(2.05, 0.44,\"%.2f\"%count_perc[2, 0 ,1], fontsize =8 , color = \"grey\")\n\n\nplt.text(0.29, 0.28,\"%.2f\"%count_perc[0, 0 ,2], fontsize =8 , color = \"grey\")\n\nplt.text(1.1, 0.37,\"%.2f\"%count_perc[1, 0 ,2], fontsize =8 , color = \"grey\")\n\nplt.text(1.89, 0.28,\"%.2f\"%count_perc[2, 0 ,2], fontsize =8 , color = \"grey\")\n\n\nplt.plot(Ks[1:-1:2], np.nanmean(onset_cont[0:3,1::2,:1, 2], axis=(0,2,-1)) , c=cols[1],marker='.',label=r'$\\sigma=1.0$',lw=2.8 ,markersize=12,markeredgecolor='#4f4949') \nplt.plot(Ks[1:-1:2], np.nanmean(onset_uncont[0:3,1::2,:1, 2], axis=(0,2,-1)),'--', c=cols2[0],marker='.' ,label=r'$\\sigma=1.0$',lw=2.8,markersize=12,markeredgecolor='#4f4949')   \n\n#plt.yscale('log')                    \nplt.ylabel(r'onset of synchrony $t^{syn}$') \nplt.xlabel(r'coupling $J$')                \n\nax6 = plt.gca()\n\nax6.tick_params(axis='both',which='both',direction='in', length=3, width=1,colors='#4f4949',zorder=3)\nax6.tick_params(bottom=True, top=True, left=True, right=True)\nax6.spines['top'].set_visible(True)\nax6.spines['right'].set_visible(True)\nax6.minorticks_on()\nax6.tick_params(axis='both',which='major',direction='in', length=3.5, width=1,colors='#4f4949',zorder=3)\nax6.tick_params(axis='both',which='minor',direction='in', length=2.5, width=0.5,colors='#4f4949',zorder=3)\nax6.tick_params(bottom=True, top=True, left=True, right=True)\nax6.tick_params(axis='both', which='minor', bottom=True, top=True, left=True, right=True)\n\n\nplt.subplot(1,2,2)\n\nplt.plot(Ks[1:-1:2], np.nanmean(cont_synched_durations_sum[0:3,1::2,:1, 1], axis=(0,2,-1)) , c=cols[5],marker='^',label=r'$\\sigma=0.5$',zorder=2 ,lw=2.8,markersize=6,markeredgecolor='#4f4949') \nplt.plot(Ks[1:-1:2], np.nanmean(uncont_synched_durations_sum[0:3,1::2,:1, 1], axis=(0,2,-1)),'--', c=cols2[5],marker='^',label=r'$\\sigma=0.5$' ,zorder=2,lw=2.8,markersize=6,markeredgecolor='#4f4949')  \n\n\nplt.plot(Ks[1:-1:2], np.nanmean(cont_synched_durations_sum[0:3,1::2,:1, 2], axis=(0,2,-1)) , c=cols[1],marker='.',label=r'$\\sigma=1.0$',lw=2.8 ,markersize=12,markeredgecolor='#4f4949') \nplt.plot(Ks[1:-1:2], np.nanmean(uncont_synched_durations_sum[0:3,1::2,:1, 2], axis=(0,2,-1)),'--', c=cols2[0],marker='.' ,label=r'$\\sigma=1.0$',lw=2.8,markersize=12,markeredgecolor='#4f4949')   \n\nplt.ylabel('$\\%$ time synchronised\\nafter $t^{syn}$', multialignment='center',labelpad=-0.1) # \"Mat\\nTTp\\n123\"\nplt.xlabel(r'coupling $J$') \nplt.yticks([0, 0.5,1])\nax7 = plt.gca()\nax7.tick_params(axis='both',which='both',direction='in', length=3, width=1,colors='#4f4949',zorder=3)\nax7.tick_params(bottom=True, top=True, left=True, right=True)\nax7.spines['top'].set_visible(True)\nax7.spines['right'].set_visible(True)\nax7.minorticks_on()\nax7.tick_params(axis='both',which='major',direction='in', length=3.5, width=1,colors='#4f4949',zorder=3)\nax7.tick_params(axis='both',which='minor',direction='in', length=2.5, width=0.5,colors='#4f4949',zorder=3)\nax7.tick_params(bottom=True, top=True, left=True, right=True)\nax7.tick_params(axis='both', which='minor', bottom=True, top=True, left=True, right=True)\n\nlegend = ax7.legend()        \nlegend.get_frame().set_linewidth(1.8)\nlegend.get_frame().set_facecolor('white')\nlegend.get_frame().set_edgecolor('white')\nhandles, labels = ax7.get_legend_handles_labels()\nhandles = [ handles[0],handles[2] , handles[1], handles[3]]\nlabels= [ labels[0],labels[2] , labels[1], labels[3]]\nif True:\n    ax7.legend(handles, labels, title=r'$\\,$controlled $\\,\\,$ uncontrolled',\n              handletextpad=0.5, columnspacing=1,handlelength=0.45, bbox_to_anchor=[-0.65, 0.99],\n              loc=3, ncol=2, frameon=True,fontsize = 'small',shadow=None,framealpha =0,edgecolor ='#0a0a0a')    \nplt.setp(plt.gca().get_legend().get_title(), fontsize='10') \nplt.subplots_adjust(wspace=0.325)#, hspace=0)\nplt.savefig(\"Kuramoto_2_onset.png\", bbox_inches='tight')\nplt.savefig(\"Kuramoto_2_onset.pdf\", bbox_inches='tight')\n\"\"\"\nplt.subplot(1,2,2)#,sharey=ax1)\n\n# plt.plot(Ks[1:-1:2], np.nanmean(onset_cont[:,1::2,yi, 1], axis=(0,-1)) , c=cols[5],marker='^',label=r'$\\sigma=0.5$',zorder=5 ,lw=2.8,markersize=6,markeredgecolor='#4f4949') \n# plt.plot(Ks[1:-1:2], np.nanmean(onset_uncont[:,1::2,yi, 1], axis=(0,-1)),'--', c=cols2[5],marker='.',label=r'$\\sigma=1.0$' ,zorder=5,lw=2.8,markersize=10,markeredgecolor='#4f4949')  \nplt.plot(Ks[1:-1:2], np.nanmean(onset_cont[0:3,1::2,0, 2], axis=(0,-1)) , c=cols[1],marker='^',label=r'$\\sigma=0.5$',lw=2.8 ,markersize=6,markeredgecolor='#4f4949') \nplt.plot(Ks[1:-1:2], np.nanmean(onset_uncont[0:3,1::2,0, 2], axis=(0,-1)),'--', c=cols2[2],marker='.' ,label=r'$\\sigma=1.0$',lw=2.8,markersize=12,markeredgecolor='#4f4949')   \n\n\nplt.plot(Ks[1:-1:2], np.nanmean(onset_cont[0:3,1::2,1, 2], axis=(0,-1)) , c=cols[1],marker='d',label=r'$\\sigma=0.5$',lw=2.8 ,markersize=6,markeredgecolor='#4f4949') \nplt.plot(Ks[1:-1:2], np.nanmean(onset_uncont[0:3,1::2,1, 2], axis=(0,-1)),'--', c=cols2[2],marker='p' ,label=r'$\\sigma=1.0$',lw=2.8,markersize=7,markeredgecolor='#4f4949')   \n\n#plt.yscale('log')                    \nplt.ylabel(r'onset of synchrony $t^{syn}$') \nplt.xlabel(r'coupling $J$')        \n\n\"\"\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ki=1\nyi=0\ngi=1\nbi=1\nfor repi in range(1):\n    positions = np.where( Rttnon[bii, ki, yi, gi, 1:-2,repi] >=threshold)[0]\n    print(positions)\n    if positions.size ==0: \n        onset_uncont[bi,ki,yi,gi,repi] = np.nan\n    else:\n        diffpos = np.diff(positions)\n        positions_consecutive = np.where(diffpos < 5)[0]\n        if positions_consecutive.size ==0:\n            onset_uncont[bi,ki,yi,gi,repi] =  np.nan\n        else:\n            onset_uncont[bi,ki,yi,gi,repi] =  timegrid[positions[positions_consecutive[0]] ]\n    print(onset_uncont[bi,ki,yi,gi,repi])\n    # print()\n    # print()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.15"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}