Advertisement
wagner-cipriano

Surface growth simulation - Cellular Automata Domany-kinzel

Dec 5th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.71 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Surface growth simulation using Cellular Automata Domany-kinzel
  5. Autores:
  6.  THIAGO LINHARES BRANT REIS
  7.  VANDERCI FERNANDES ARRUDA
  8.  Wagner Cipriano
  9.  Email: wagnao-gmail
  10. Disciplina: Princípios de Modelagem Matemática. CefetMG.
  11. Prof: Thiago Mattos
  12.  
  13. Options:
  14. -L #  Qtde de Sítios           Def: 10**4
  15. -T #  Unidades de tempo        Def: 10**5
  16. """
  17.  
  18. #Imports::
  19. from os import system
  20. from time import time, sleep, strftime
  21. import getopt, sys
  22. from random import randint, random
  23. import math
  24. import numpy as np
  25. from scipy.stats import linregress
  26.  
  27. #Global vars
  28. global gFileName, ExitFileNameFR, ExitFileNameEC, Funcs
  29. gFileName = 'Exit'
  30. Funcs = 'FR+EC'
  31. #FR: Flutuacao Rugosidade
  32. #EC: Expoente de crescimento
  33.  
  34. def __Pot2(i, f):
  35.     """Retorna as potencias de 2 em um intervalo [i, f]"""
  36.     v = i
  37.     idx = 1
  38.     Result = []
  39.     while(v < f):
  40.         Result.append(v)
  41.         v = 2**idx
  42.         idx+=1
  43.     Result.append(f)
  44.     return Result
  45. #
  46.  
  47. def __NormalizeDimList(List, Tam, Value=None):
  48.     """
  49.      Insere elemento fixo na lista ate que completar qtde de elementos necessária(Tam)
  50.      O lemento inserido e o param Value ou o ultimo elemento da lista caso Value = Null
  51.    """
  52.     if(not List):
  53.         raise Exception('List invalid')
  54.     elif(Value is None):
  55.         Value = List[-1]
  56.     elif(len(List) >= Tam):
  57.         print('List len Ok. List: %s, Tam: %s' %(len(List), Tam))
  58.     while (len(List) < Tam):
  59.         List.append(Value)
  60. #
  61.  
  62. def __GetNewCellValueByNeighbors(ln, rn, P1, P2):
  63.     """
  64.      Defini o valor de um sítio baseado na sua vizinhaça no instante de tempo anterior
  65.      e nos valores de P1 e P2
  66.      ln:  left neighbor
  67.      lr:  rigth neighbor
  68.      P1:  Probability P1
  69.      P2:  Probability P2
  70.    """
  71.     RNumber = random() #Pseudo random numbers!
  72.     NeigValue = '%s%s' %(ln, rn)
  73.     if(NeigValue == '00'):                #00
  74.         return 0
  75.     elif(NeigValue == '11'):              #11
  76.         return [0,1] [RNumber <= P2]
  77.     else:                                 #'01 or 10'
  78.         return [0,1] [RNumber <= P1]
  79. #
  80.  
  81. def __RMS(Height, L, mean=None):
  82.     """
  83.      Calcula a rugosidade da interface
  84.      RMS (Root Mean Square)
  85.      #Roughness of the interface at time instant t
  86.      Height: Altura da interface
  87.    """
  88.     if(mean is None): mean = Height.mean()
  89.     WLt = math.sqrt( (((Height - mean) ** 2).sum()) / L )
  90.     return WLt
  91. #
  92.  
  93. def __GetInitialCondition(L, dorandom=True, key=3):
  94.     """
  95.      Gera a condição inicial
  96.      L: Qtde de Sítios
  97.    """
  98.     if(dorandom):
  99.         first_row = [randint(0,1) for i in range(L)]
  100.     else:
  101.         first_row = [[0,1] [i%key ==0] for i in range(L)]
  102.     return np.array(first_row)
  103. #
  104.  
  105. def __SaveToFile(Text, Var='', lFileName=None, Ext='log', Mode='a+'):
  106.     """
  107.     Save result to txt file
  108.    """
  109.     global gFileName
  110.     if(lFileName): FileName = lFileName
  111.     else:          FileName = gFileName
  112.     with open('./%s.%s' %(FileName, Ext), 'a+', encoding='utf-8') as f:
  113.         f.write('%s %s\n' %(Text, str(Var)))
  114. #
  115.  
  116. def RegLinGetEq(x, y):
  117.     #Regressao linear: Encontrar a equação da reta a partir de um conjunto de pontos: vetor x, y
  118.     #http://webpages.fc.ul.pt/~aeferreira/python/aulas/11_scipy_regression.html
  119.     #y = mx + b
  120.     x = [math.log(i,10) for i in x]
  121.     y = [math.log(j,10) for j in y]
  122.     m, b, R, p, SEm = linregress(x, y)
  123.     #    m = sum(a*b for (a,b) in zip(x,y)) - sum(x) * sum(y) / len(x)
  124.     #    m /= sum(a**2 for a in x) - (sum(x)**2)/len(x)
  125.     #    b = sum(y)/len(y) - m * sum(x)/len(x)
  126.     print('y = %sx + %s' %(m, b))
  127.     return m
  128. #
  129.  
  130. def SurfaceGrowthSim(InitCond, L, T, P1, P2, PtsTime):
  131.     """
  132.      Simulate Surface Growth with ACDK
  133.      InitCond: array of inital condition
  134.      T:        Unidades de tempo
  135.      P1:       Probability P1
  136.      P2:       Probability P2
  137.    """
  138.     MeanHeightByTime = []  #hbar
  139.     RMSByTime = []  #Root Mean Square
  140.     Height = InitCond.copy()
  141.     LastOne = InitCond
  142.  
  143.     #Mean height initial condition
  144.     MeanHeightByTime.append(Height.sum() / L)
  145.     RMSByTime.append(__RMS(Height, L))
  146.  
  147.     # Determine each new row (t) based on the last old data (t-1).
  148.     ti = time()
  149.     for t in range(T-1): #Passos de tempo
  150.         NewOne = [__GetNewCellValueByNeighbors(LastOne[ (j - 1) %L ],  LastOne[ (j + 1) %L ], P1, P2)
  151.                    for j in range(L)]
  152.         NewOne = np.array(NewOne)
  153.         ActivSitGen = NewOne.sum()
  154.         #Add height
  155.         Height = Height + NewOne
  156.  
  157.         #Mean height
  158.         h_bar = Height.sum() / L             #(Pag 20, Form 2.1)
  159.         #Roughness of the interface at time instant t   --> RMS (Root Mean Square)
  160.         w = __RMS(Height, L, h_bar)
  161.  
  162.         #Armazenar dados - filtro: somente armazena alguns pontos (PtsTime)
  163.         if((not PtsTime or (t in PtsTime)) or (ActivSitGen <= 0)):
  164.             MeanHeightByTime.append(h_bar)
  165.             RMSByTime.append(w)
  166.  
  167.         #update last one to use in the next generation aa
  168.         LastOne = NewOne.copy()
  169.         print('t: %s   h_bar: %s   w: %s   AS: %s' %(str(t).ljust(6), str(round(h_bar, 3)).ljust(12), str(round(w, 3)).ljust(12), str(ActivSitGen).ljust(6)))
  170.  
  171.         #Avaliar se a minha geração já chegou no regime de saturação
  172.         if(ActivSitGen <= 0):
  173.             print('  Regime de saturação alcançado na geração %s' %(t+1+1));
  174.             #system('speaker-test -t sine -f 500 -l 1 -p 4');
  175.             break;
  176.         #
  177.     print('P1: %s   Time i: %s' %(str(P1).ljust(7), time() - ti))
  178.     return Height, MeanHeightByTime, RMSByTime
  179. #
  180.  
  181. def SurfaceGrowthSimWithProbParams(L, T, P1List, P2List, InitCond, PtsTime):
  182.     """
  183.      Simulate Surface Growth using ACDK
  184.      Results:  array of results
  185.      T:        Unidades de tempo
  186.      P1:       Probability P1
  187.      P2:       Probability P2
  188.    """
  189.     Results = []
  190.     for P1 in P1List:
  191.         for P2 in P2List:
  192.             print('\n\n\nP2: %s, P1: %s' %(P2, P1))
  193.             Height, MeanHeightByTime, RMSByTime = SurfaceGrowthSim(InitCond, L, T, P1, P2, PtsTime)
  194.             Results.append({'T':T, 'L':L, 'P1':P1, 'P2':P2, 'Height': Height, 'MeanHeightByTime':MeanHeightByTime, 'RMSByTime': RMSByTime})
  195.  
  196.             #Save Result Data
  197.             __SaveToFile(Text='\n#P1: %s, P2: %s     %s' %(P1, P2, strftime('%Y-%m-%d %H:%M:%S')))
  198.             __SaveToFile(Text='  Final Height:       ', Var=','.join(str(i) for i in Height))
  199.             __SaveToFile(Text='  MeanHeightByTime:   ', Var=MeanHeightByTime)
  200.             __SaveToFile(Text='  RMSByTime:          ', Var=RMSByTime)
  201.             __SaveToFile(Text='  Generations len:    ', Var=len(RMSByTime))
  202.  
  203.     return Results
  204. #
  205.  
  206. def GetGraphicFlutRugos(L, T, InitCond):
  207.     """Simulando a Evolução da flutuação da rugosidade"""
  208.     #CONSTs
  209.     P1 = [0.2, 0.5, 0.59, 0.595, 0.6, 0.8]
  210.     P2 = [0.95]
  211.  
  212.     #Itens Legenda
  213.     ListLeg = []
  214.     for P1i in P1:
  215.         ListLeg.append('P1 = %s' %(P1i))
  216.  
  217.     #Passos de tempo a armazenar os pontos
  218.     PtsTime = __Pot2(i=1, f=T)
  219.     #Save to file
  220.     __SaveToFile(Text='\n*Evolução da flutuação da rugosidade:\n  L:       %s\n  T:       %s\n  P1:      %s\n  P2:      %s\n  PtsTime: %s' %(L, T, P1, P2, str(PtsTime)))
  221.     #simulate surface growth
  222.     ListItems = SurfaceGrowthSimWithProbParams(L, T, P1, P2, InitCond, PtsTime)
  223.     RespItems = []
  224.     for Item in ListItems:
  225.         __NormalizeDimList(List=Item['RMSByTime'], Tam=len(PtsTime))
  226.         RespItems.append( Item['RMSByTime'] )
  227.  
  228.     #Armazenar dados geração grafico
  229.     Ext='py';
  230.     __SaveToFile(Text='# -*- coding: utf-8 -*-\n#DateTime: %s\n\nX = ' %(strftime('%Y-%m-%d %H:%M:%S')), Var=PtsTime, lFileName=ExitFileNameFR, Ext=Ext)
  231.     __SaveToFile(Text='Y = ', Var=RespItems, lFileName=ExitFileNameFR, Ext=Ext)
  232.     __SaveToFile(Text='ListLeg = ', Var=ListLeg, lFileName=ExitFileNameFR, Ext=Ext)
  233.     __SaveToFile(Text="\nxlabel = 'time step'\nylabel = r'Rugosidade $\delta \omega(L, t)$'\ntitle = 'Evolução da flutuação da rugosidade   L=%s  T=%s'\nScale = 'loglog';\nlinewidth = 0.5;\nLegLoc = 2;\n" %(L, T), lFileName=ExitFileNameFR, Ext=Ext)
  234.  
  235.     #Validações dos dados
  236.     print ('\n\nPtsTime: ', len(PtsTime));
  237.     for i in range(len( RespItems)):
  238.         print (i, len(RespItems[i]))
  239.         if(len(RespItems[i]) != len(PtsTime)):
  240.             raise Exception('Erro validacao dados')
  241. #
  242.  
  243. def GetGraphicExpCresc(L, T, InitCond):
  244.     #Evolução do expoente de crescimento
  245.  
  246.     #CONSTs
  247.     Ext = 'py';
  248.     P2 = [0.1, 0.3, 0.5, 0.7, 0.9]
  249.     #P1i = np.linspace(0.61, 0.85, 20)                  #20pts   0.61 - 0.85
  250.     #P1 = np.append(P1i, np.linspace(0.86, 1, 10))      #7pts   0.86 - 1.0
  251.     #P1List = list(P1); del P1i, P1;
  252.     ##P1 = [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.0]
  253.     ##P1 = [0.61, 0.62, 0.63, 0.64, 0.65, 0.69, 0.70, 0.71, 0.79, 0.8, 0.81, 0.89, 0.9, 0.91, 0.99, 1.0]
  254.     #novo modelo para gerar os valores de P1, conforme grafico da referencia (Allbens)
  255.     P1ListDc = { '0.1': [0.780, 0.785, 0.790, 0.795,   0.800,   0.805, 0.810, 0.815, 0.820,   0.830, 0.840,  0.850,   0.870, 0.890, 0.910, 0.930],
  256.                  '0.3': [0.760, 0.765, 0.770, 0.775,   0.780,   0.785, 0.790, 0.795, 0.800,   0.810, 0.820,  0.830,   0.850, 0.870, 0.890, 0.910],
  257.                  '0.5': [0.730, 0.735, 0.740, 0.745,   0.750,   0.755, 0.760, 0.765, 0.770,   0.780, 0.790,  0.800,   0.820, 0.840, 0.860, 0.880],
  258.                  '0.7': [0.685, 0.690, 0.695, 0.700,   0.705,   0.710, 0.715, 0.720, 0.725,   0.735, 0.745,  0.755,   0.775, 0.795, 0.815, 0.835],
  259.                  '0.9': [0.610, 0.615, 0.620, 0.625,   0.630,   0.635, 0.640, 0.645, 0.650,   0.660, 0.670,  0.680,   0.700, 0.720, 0.740, 0.760],
  260.                }
  261.     __SaveToFile(Text='# -*- coding: utf-8 -*-\n#DateTime: %s\n\nP1List = %s\n' %(strftime('%Y-%m-%d %H:%M:%S'), P1ListDc), lFileName=ExitFileNameEC, Ext=Ext)
  262.  
  263.     #Passos de tempo a armazenar os pontos
  264.     PtsTime = None
  265.     PtsTime = __Pot2(i=1, f=T)
  266.  
  267.     #Save to file
  268.     __SaveToFile(Text='\n\n*Evolução do expoente de crescimento:\n  L:       %s\n  T:       %s\n  P1:      %s\n  P2:      %s\n  PtsTime: %s' %(L, T, P1ListDc, P2, str(PtsTime)))
  269.  
  270.     #Begin simulation
  271.     ListLeg = []
  272.     RespItens = []
  273.     for ItemP2 in P2:
  274.         BetaList = []
  275.         P1List = P1ListDc[str(ItemP2)]
  276.         for ItemP1 in P1List:
  277.             #simulate surface growth
  278.             ListItems = SurfaceGrowthSimWithProbParams(L, T, [ItemP1], [ItemP2], InitCond, PtsTime)
  279.             w = ListItems[0]['RMSByTime']
  280.  
  281.             #Encontrar o coeficiente angular de cada um dos conjuntos de dados
  282.             vx = [PtsTime, range(L)] [not PtsTime]
  283.             Beta = RegLinGetEq(vx[:len(w)], w)
  284.             BetaList.append(Beta)
  285.             print ('\n\n\nP2=%s P1=%s\nt: %s\nw: %s\nB: %s\n\n' %(str(ItemP2).ljust(5), str(ItemP1).ljust(5), vx, w, Beta));
  286.  
  287.         #Save data to file (para conferencia)
  288.         LogTxt = 'P2=%s\nBetaList = %s;\n' %(ItemP2, str(BetaList))
  289.         __SaveToFile(Text=LogTxt, lFileName=ExitFileNameEC, Ext=Ext)
  290.  
  291.         #Armazenando os dados: ItemP2, P1List, BetaList
  292.         ListLeg.append('P2 = %s' %(ItemP2))
  293.         RespItens.append(BetaList)
  294.  
  295.     #Armazenar dados geração grafico
  296.     __SaveToFile(Text='\n\n\nX =', Var=P1List, lFileName=ExitFileNameEC, Ext=Ext)
  297.     __SaveToFile(Text='Y =', Var=RespItens, lFileName=ExitFileNameEC, Ext=Ext)
  298.     __SaveToFile(Text='ListLeg = ', Var=ListLeg, lFileName=ExitFileNameEC, Ext=Ext)
  299.     __SaveToFile(Text="\nxlabel = 'P1';\nylabel = r' $ \\beta $';\ntitle = 'Evolução expoente de crescimento   L=%s  T=%s'\nScale = 'linear';\nlinewidth = 0.1;\nLegLoc = 1;\n" %(L, T), lFileName=ExitFileNameEC, Ext=Ext)
  300.     ##__SaveToFile(Text='ListItems = ', Var=ListItems, lFileName=lFileName, Ext=Ext)
  301. #
  302.  
  303.  
  304. def main():
  305.     Help = """
  306.      Cellular Automata Domany-kinzel
  307.        Options:
  308.          -L   Qtde de Sítios           Def: 10**4
  309.          -T   Unidades de tempo        Def: 10**5
  310.          -F   Funcs                    Def: FR+EC
  311.                                             FR: Flutuacao Rugosidade
  312.                                             EC: Expoente de crescimento
  313.    """
  314.     global Funcs
  315.     #PARAMETROS
  316.     L = 10**4 #Qtde de Sítios
  317.     T = 10**5 #Unidades de tempo
  318.     IniCondRand = True
  319.  
  320.     #Get params (comand line options)
  321.     opts,args = getopt.getopt(sys.argv[1:],'L:T:F:h')
  322.     for key,val in opts:
  323.         if(key == '-L'):    L = int(val)
  324.         elif(key == '-T'):  T = int(val)
  325.         elif(key == '-F'):  Funcs = str(val).upper()
  326.         elif(key == '-h'):
  327.             print(Help);
  328.             sys.exit(1);
  329.     print('L:     %s\nT:     %s\nICR: %s\nFuncs: %s' %(L, T, IniCondRand, Funcs)); sleep(1);
  330.  
  331.     #Condição inicial é a mesma para todas as simulações da sessão ativa
  332.     InitCond = __GetInitialCondition(L, IniCondRand)
  333.  
  334.     #Gerar grafico 01 - Fig 3.3
  335.     if(Funcs.find('FR') != -1):
  336.         GetGraphicFlutRugos(L, T, InitCond)
  337.  
  338.     #Gerar grafico 02 - Fig 3.4
  339.     if(Funcs.find('EC') != -1):
  340.         GetGraphicExpCresc(L, T, InitCond)
  341. #
  342.  
  343. if(__name__ == '__main__'):
  344.     gFileName = 'Exit-%s' %(strftime('%Y-%m-%d-%Hh'))
  345.     ExitFileNameFR = 'DadosFlutRugos_%s' %(strftime('%Y%m%d%H%M%S'))
  346.     ExitFileNameEC = 'DadosExpCresc_%s'  %(strftime('%Y%m%d%H%M%S'))
  347.  
  348.     ini = time()
  349.     __SaveToFile(Text='--- '*20 + '\nbegin: %s ' %(strftime('%Y-%m-%d %H:%M:%S')) )
  350.  
  351.     main();
  352.  
  353.     __SaveToFile(Text='\n\nend: %s\nDur: %s min\n\n\n\n\n' %(strftime('%Y-%m-%d %H:%M:%S'), (time()-ini)/60  ))
  354.  
  355.     #Gerar os graficos
  356.     if(Funcs.find('FR') != -1):
  357.         system('python3 Plots.py -f %s' %(ExitFileNameFR));
  358.     if(Funcs.find('EC') != -1):
  359.         system('python3 Plots.py -f %s' %(ExitFileNameEC));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement