# energyRa[:,1] : time
    # energyRa[:,2] : energy flowing across the domain borders
    # energyRa[:,3] : energy used for phase transition
    # energyRa[:,4] : energy for the internal energy
        
    energyRa = np.loadtxt(energyRa_filename)

    plt.close("all")

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig = plt.figure(figsize=(8,6))

    ax = fig.add_subplot(111)

    style = ['s-','-','o-']
    width = 3

    for i in range(0,len(style)):

        grayscale_value = 0.1 + 0.9*(float(i)/float(len(style)-1))

        plt.plot(
            energyRa[:,1],
            energyRa[:,2+i],
            style[i],
            linewidth=width,
            color=grayscale_to_RGB(grayscale_value))

    plt.show()
def create_mass_graph(simDirs,
                      legend='None',
                      width=3,
                      xlabel='',
                      ylabel='',
                      show=True,
                      figPath='',
                      add_zoom_above=False,
                      add_linear_interpolation=True,
                      borders_linear_interpolation='None',
                      step=1,
                      legendLoc='lower right',
                      styleDashed=False,
                      xlim='None',
                      ylim='None'):
    '''
    @description: create a graph with the vapor mass
    as function of time for different contact angles
    '''

    growthRate='None'


    plt.close("all")

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig = plt.figure(figsize=(8,6))


    # plot the mass as function of time
    # as the main plot
    ax = fig.add_subplot(111)

    ini_time = [100.,0.]
    ini_mass = [0.,0.]

    start_i = np.empty([len(simDirs)])
    end_i   = np.empty([len(simDirs)])

    max_mass = 0.0

    for i in range(0,len(simDirs)):
        
        mass = np.loadtxt(os.path.join(simDirs[i],'mass.txt'))

        max_mass = max(max_mass,max(mass[:,2]))

        # determine the last relevant step: timestep!=0
        start_i[i]=0
        for j in range(0,len(mass[:,0])):
            if(mass[j,2]>0.0):
                start_i[i]=j
                break

        end_i[i]=len(mass[:,0])-1
        for j in range(int(start_i[i]),len(mass[:,0])):
            if(mass[j,0]==0.0):
                end_i[i]=j-1
                break

        # extract the initial time when
        # the bubble appears
        for j in range(0,len(mass[:,0])):

            if(mass[j,2]>0.0):
                ini_time[0] = min(ini_time[0],mass[j,1])
                ini_time[1] = max(ini_time[1],mass[j,1])
                ini_mass[0] = min(ini_mass[0],mass[j,2])
                ini_mass[1] = max(ini_mass[1],mass[j,2])
                break

        # plot the mass as function
        # of time on the main graph
        if(styleDashed):
            grayscale_value = 0.2+ 0.8*float((i-i%2)/2.0)/float(len(simDirs)/2.0)
        else:
            grayscale_value = 0.2+ 0.8*float(i)/float(len(simDirs))
        
        if(styleDashed):
            if(i%2==0):
                style='-'
            else:
                style='--'
        else:
            style='-'

        plt.plot(mass[0:end_i[i]:step,1],
                 mass[0:end_i[i]:step,2],
                 style,
                 linewidth=width,
                 color=grayscale_to_RGB(grayscale_value))

    ax.set_xlabel(r''+xlabel)
    ax.set_ylabel(r''+ylabel)


    # extract the linear growth rate
    if(add_linear_interpolation):

        growthRate = []

        if(borders_linear_interpolation!='None'):
        
            for i in range(0,len(simDirs)):

                mass = np.loadtxt(os.path.join(simDirs[i],'mass.txt'))

                for j in range(0,len(borders_linear_interpolation[i])):
                    
                    i1 = borders_linear_interpolation[i][j][0]
                    i2 = borders_linear_interpolation[i][j][1]
                    
                    xi = mass[i1:i2,1]
                    A  = np.array([xi, np.ones(len(xi))])
                    yi = mass[i1:i2,2]
                    
                    pi = np.linalg.lstsq(A.T,yi)[0] #least square approximation
                    xi = mass[i1-5:i2+5,1]
                    line = pi[0]*xi + pi[1]

                    if(len(borders_linear_interpolation[i])>1 and j==0):
                        style = '--'
                    else:
                        style ='-'
                        growthRate.append(pi[0])

                    plt.plot(xi,line,'r',linestyle=style)
                    
                    print("%40s | growthrate: %3.2e" % (os.path.basename(os.path.dirname(simDirs[i])), pi[0]))

        else:

            for i in range(0,len(simDirs)):

                mass = np.loadtxt(os.path.join(simDirs[i],'mass.txt'))
                
                xi = mass[int(start_i[i]):int(end_i[i]),1]
                A  = np.array([xi, np.ones(len(xi))])
                yi = mass[int(start_i[i]):int(end_i[i]),2]
            
                pi = np.linalg.lstsq(A.T,yi)[0] #least square approximation
                line = pi[0]*xi + pi[1]
                plt.plot(xi,line,'r-')

                print("%40s | growthrate: %3.2e" % (os.path.basename(os.path.dirname(simDirs[i])), pi[0]))
                growthRate.append(pi[0])

    if(add_zoom_above):
        ax.set_ylim(0.0,max_mass*(1.0+0.2))
    else:
        ax.set_ylim(0.0,max_mass)

    if(xlim!='None'):
        ax.set_xlim(xlim[0],xlim[1])

    if(ylim!='None'):
        ax.set_ylim(ylim[0],ylim[1])

    if(legend!='None'):
        plt.legend(legend,loc=legendLoc)

    # add a zoom where the initial bubble appears
    # on the lower right part of the plot
    if(add_zoom_above):
        ax_x_lim = ax.get_xlim()
        ax_y_lim = ax.get_ylim()

        border = 0.2*(ini_time[1]-ini_time[0])

        ini_time[0]-= border
        ini_time[1]+= border
        
        ini_mass[0]  = ini_mass[0]*(1.-0.1)
        ini_mass_tmp = ini_mass[0]+(ini_time[1]-ini_time[0])*(ax_y_lim[1]-ax_y_lim[0])/(ax_x_lim[1]-ax_x_lim[0])
        
        width    = 0.5
        height_p = width*((ini_mass_tmp-ini_mass[0])/(ax_y_lim[1]-ax_y_lim[0]))/((ini_time[1]-ini_time[0])/(ax_x_lim[1]-ax_x_lim[0]))
        height   = 0.2
        
        ini_mass_tmp = height/height_p*ini_mass_tmp

        if(ini_mass_tmp>ini_mass[1]):
            ini_mass[1] = ini_mass_tmp
        
        ax_zoom = plt.axes([.15, .65, width, height]) #, axisbg='y')
        for i in range(0,len(simDirs)):
        
            mass = np.loadtxt(os.path.join(simDirs[i],'mass.txt'))
        
            grayscale_value = 0.2+ 0.8*float(i)/float(len(simDirs))
        
            p = ax_zoom.plot(mass[0:end_i[i]:step,1],
                         mass[0:end_i[i]:step,2],
                         '+-',
                         linewidth=5*width,
                         color=grayscale_to_RGB(grayscale_value))
            plt.setp(ax_zoom, xticks=[], yticks=[])
        
        ax_zoom.set_xlim(ini_time[0],ini_time[1])
        ax_zoom.set_ylim(ini_mass[0],ini_mass[1])

    if(show):
        plt.show()
        plt.close()

    if(not figPath==''):
        plt.savefig(figPath)

    return growthRate,
def create_growthrate_graph(heatFlux,
                            growthRate,
                            width=3,
                            xlabel='',
                            ylabel='',
                            show=True,
                            legend='None',
                            xlim='None',
                            ylim='None'):
    '''
    @description: draw a graph with the mass growth rate
    as a function of the heat flux
    '''


    # open new figure for the mass growth rate
    plt.close("all")
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig = plt.figure(figsize=(8,6))
    ax = fig.add_subplot(111)


    # plot the mass growth rate
    plt.plot(heatFlux,
             growthRate,
             'o',
             linewidth=width,
             color=grayscale_to_RGB(0.8))

    ax.set_xlabel(r''+xlabel)
    ax.set_ylabel(r''+ylabel)


    # add the linear interpolation
    xi = np.array(heatFlux)
    A  = np.array([xi, np.ones(len(xi))])
    yi = np.array(growthRate)

    pi = np.linalg.lstsq(A.T,yi)[0] #least square approximation
    xi = np.insert(xi,0,0.0)
    xi = np.append(xi,0.11)
    line = pi[0]*xi + pi[1]

    plt.plot(xi,line,'r-')

    plt.plot([-pi[1]/pi[0]],[0.0],'rs')
    plt.plot([0.0,0.11],[0.0,0.0],'k--')

    print 'equivalent_latent_heat: ', pi[0]
    print 'equivalent_temperature: ', 1.0 - (pi[0]/15.08)**2


    # graph properties
    if(xlim!='None'):
        ax.set_xlim(xlim[0],xlim[1])

    if(ylim!='None'):
        ax.set_ylim(ylim[0],ylim[1])

    if(legend!='None'):
        plt.legend(legend,loc=legendLoc)


    # show the graph
    if(show):
        plt.show()
def create_temperature_graph(simDirs,
                             legend='None',
                             width=3,
                             xlabel='',
                             ylabel='',
                             show=True,
                             figPath='',
                             borders='None',
                             legendLoc='lower right',
                             xlim='None',
                             ylim='None'):
    '''
    @description: create a graph with the temperature
    at the interface for different conditions
    '''


    # figure initialization
    plt.close("all")
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig = plt.figure(figsize=(8,6))
    ax = fig.add_subplot(111)


    for i in range(0,len(simDirs)):
        
        temperature = np.loadtxt(os.path.join(simDirs[i],'temperature.txt'))


        # data plotted
        if(borders!='None'):
            i_start = borders[i][0]
            i_end   = borders[i][1]
        else:
            
            for j in range(0,len(temperature[:,0])):
                if(temperature[j,1]>0):
                    i_start = j
                    break

            for j in range(len(temperature[:,0])-1,0,-1):
                if(temperature[j,1]>0):
                    i_end = j
                    break

        # color
        grayscale_value = 0.2+ 0.8*float(i)/float(len(simDirs))
        
        # plot
        plt.plot(temperature[i_start:i_end,1],
                 temperature[i_start:i_end,2],
                 '-',
                 linewidth=width,
                 color=grayscale_to_RGB(grayscale_value))

    ax.set_xlabel(r''+xlabel)
    ax.set_ylabel(r''+ylabel)


    # graph properties
    if(xlim!='None'):
        ax.set_xlim(xlim[0],xlim[1])

    if(ylim!='None'):
        ax.set_ylim(ylim[0],ylim[1])

    if(legend!='None'):
        plt.legend(legend,loc=legendLoc)


    # show the graph
    if(show):
        plt.show()
def create_nucleation_time_graph(dirs,
                                 velocities,
                                 styles,
                                 legend='None',
                                 legendLoc='lower right',
                                 width=3,
                                 xlabel='$v$',
                                 ylabel='$t_n$',
                                 bothDirs=False,
                                 show=True):
    '''
    @description: create a graph with the nucleation times
    for different velocities and fluxes
    
    - dirs   : 2D array containing the directory paths
    - styles : array with the style corresponding to dirs[i]
    - leg    : legend for dirs[i]
    - width  : width of the lines
    - xlabel : xlabel for the plot
    - ylabel : ylabel for the plot
    - show   : show the plot at the end
    '''

    plt.close("all")

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig = plt.figure(figsize=(8,6))
    ax = fig.add_subplot(111)

    i=0

    for simDirs,simVelocities,simStyle in zip(dirs,velocities,styles):

        # determine the color for the plot
        if(bothDirs):
            grayscale_value = 0.2+ 0.8*float(i%(len(dirs)/2))/float(len(dirs)/2)
        else:
            grayscale_value = 0.2+ 0.8*float(i)/float(len(dirs))
        simColor = grayscale_to_RGB(grayscale_value)        

        # array containing the data at fixed flux
        x_data = []
        y_data = []

        for simDir,simVelocity in zip(simDirs,simVelocities):

            # get the nucleation time and mass
            mass = np.loadtxt(os.path.join(simDir,'contours','mass.txt'))
            for j in range(0,len(mass[:,0])):
                if(mass[j,2]>0):
                    nucleation_time = mass[j,1]
                    nucleation_mass = mass[j,2]
                    break

            # extract the velocity corresponding to the directory
            # it is simVelocity

            # create the corresponding database for plotting
            x_data.append(simVelocity)
            y_data.append(nucleation_time)

        # plot the data
        plt.plot(x_data,
                 y_data,
                 simStyle,
                 linewidth=width,
                 color=simColor)

        i+=1

    ax.set_xlabel(r''+xlabel)
    ax.set_ylabel(r''+ylabel)

    if(legend!='None'):
        plt.legend(legend,loc=legendLoc)

    if(show):
        plt.show()
        plt.close()