Esempio n. 1
0
File: utils.py Progetto: wphu/UEDGE
def readcase(casedir, dirpath='data'):
    '''
    Simple script reading the requested input file from folder casedir

    readcase(casedir,**keys)

    Required parameters:
    casedir     -   The name of the case folder containin dirpath/input.py,
                    or alternatively the path to this folder
    
    Keyword parameters:
    dirpath     -   Path to input.py within casedir, default is "data"
    '''
    from os import chdir, getcwd
    from os.path import exists, abspath, relpath
    from importlib import reload
    import sys

    # Check that path is set up correctly
    if exists(casedir) is False:
        print('Case folder {} not found!'.format(casedir))
        return
    elif exists('{}/{}'.format(casedir, dirpath)) is False:
        print('Input folder{}/{} not found!'.format(casedir, dirpath))
        return

    cwd = getcwd()  # Store original location
    chdir('{}/{}'.format(casedir, dirpath))  # Move to the requested location
    import input as i  # This is ugly coding, but it is straightforward and works
    reload(i)  # Reload case: should not strictly be necessary
    i.restore_input()  # Read the new setup

    # Fix the path dependencies to be absolute paths for reading case out of data
    newaphdir = '{}/{}'.format(abspath(getcwd()),
                               aph.aphdir[0].decode('utf-8'))
    newapidir = '{}/{}'.format(abspath(getcwd()),
                               api.apidir[0].decode('utf-8'))
    # Set grid path file in V7.08 and later
    try:
        newaeqdskfname = '{}/{}'.format(abspath(getcwd()),
                                        com.aeqdskfname[0].decode('utf-8'))
        newgeqdskfname = '{}/{}'.format(abspath(getcwd()),
                                        com.geqdskfname[0].decode('utf-8'))
    except:
        pass

    chdir(cwd)  # Go back to the original directory to enable recursive loads

    # Shorten the concatenated path to fit into arrays
    aph.aphdir[0] = abspath(newaphdir)
    api.apidir[0] = abspath(newapidir)
    try:
        com.aeqdskfname[0] = abspath(newaeqdskfname)
        com.geqdskfname[0] = abspath(newgeqdskfname)
    except:
        pass
Esempio n. 2
0
def reconv(path='.', dtreal=1e-9):
    ''' Reconverges all cases in subfolders in path (default current folder)'''

    from os import chdir, getcwd, walk
    from uedge.rundt import rundt
    from uedge import bbb
    from uedge.hdf5 import hdf5_save
    from importlib import reload

    path = getcwd()
    # Get list of subdirectories in path
    dirs = natsort(next(walk(path))[1])
    f = open('reconv.log', 'w+')
    f.write('Runnin in ' + path + ':\n')
    f.close

    try:
        dirs.remove('grid')
    except:
        pass
    try:
        dirs.remove('rates')
    except:
        pass
    try:
        dirs.remove('ignore')
    except:
        pass

    for d in dirs:
        # Move to dir with input file
        chdir(path + "/" + d + "/data")
        print('==================')
        print('CONVERGING DIRECOTRY ' + d)
        print('==================')
        import input as i
        reload(i)
        i.restore_input()
        bbb.dtreal = 1e-9
        bbb.exmain()

        rundt(dtreal)
        hdf5_save('../solutions/' + bbb.label[0].decode('UTF-8') + '.hdf5')
        f = open(path + '/reconv.log', 'a')
        if bbb.iterm == 1:
            f.write('Case ' + d + ' reconverged successfully!\n')
        else:
            f.write('Case ' + d + ' NOT reconverged!\n')
        f.close
    chdir(path)
Esempio n. 3
0
def animate_vectordt(casedir,
                     varx,
                     vary,
                     show=True,
                     savename=False,
                     interval=1000,
                     figsize=(1.618 * 6, 6),
                     keys={},
                     commands=[],
                     heatmap=False,
                     steps="t=",
                     unitlength=False):
    """ Function creating a vector animation 
    
    animate_vectordt(casedir,var,keys**)   
        Arguments:
        casedir:            Path (absolute or relative) to the directory containing the data and solutions folders. 
                            The data folder should contain the input file 'input.py'. The solutions folder should contain
                            an ascii-file named label_dtout.txt, where label is the variable label[0] defined in 'input.py'.
                            The dtout-file should be a csv file with the name of the savefile and the corresponding
                            time of the save.
        var:                String of the variable that should be plotted (e.g 'bbb.ne', 'bbb.tg[:,:,1]/1.602e-19')
        
        Keyword arguments
        show[=True]:        Boolean determining whether to show plot or not
        savename[=False]:       If animation is to be saved, save must be set as path and save file name
        interval[=1000]:    Time in ms each frame is shown
        figsize             Tuple containing the figure width and height
        keys:        A dictionary containing the keyword arguments of heatmap
                            Must contain entry "var" with string of parameter to be plotted
        commands:           List of strings containing UEDGE commands to be executed before evaluation,
                            e.g. turning coefficients on or off
        steps:              String with text to displayed in front of second col values in animation title

    """
    from pandas import read_csv
    from os import chdir, getcwd
    from uedge.contrib.holm10.ue_plot import vector
    from uedge.hdf5 import hdf5_restore
    from PIL import Image
    from StringIO import StringIO
    from matplotlib.pyplot import figure, imshow, show, get_current_fig_manager, close, axes, subplots_adjust
    from matplotlib.animation import ArtistAnimation, writers
    from getpass import getuser

    cwd = getcwd()  # Get original directory
    chdir(
        casedir + "/data"
    )  # Go to data directory of specified case: required as required files might be stored here
    # Execute and store variables globally
    import input as i
    i.restore_input()

    # Loop through list of commands in case coefficients need to be changed
    for i in commands:
        exec(i) in globals(), locals()

    svs = read_csv("../solutions/" + bbb.label[0].decode('UTF-8') +
                   "_dtout.txt")  # Get list of saves to animate
    # Output list
    print("Save repository and save times:")
    print(svs)
    svs = svs.values  # Create array

    # Extract original title for title timestamp
    if "labels" in keys.keys():
        if "title" in keys["labels"]:
            origtitle = keys["labels"]["title"]
    else:
        origtitle = ""

    if heatmap is not False:
        ex = heatmap["var"]

    # Fig for dislpay
    fig = figure(figsize=figsize)
    fig.patch.set_visible(False)

    ims = []  # Empty array to store frames
    for frame in range(len(svs)):

        # Add timestamp to plot title
        if "labels" in keys.keys():
            if "title" in keys["labels"]:
                keys["labels"][
                    "title"] = origtitle + " " + steps + "%.2E" % svs[frame, 1]
            else:
                keys["labels"]["title"] = steps + "%.2E" % svs[frame, 1]
        else:
            keys["labels"] = {"title": steps + "%.2E" % svs[frame, 1]}

        # Recover all parameters from case
        print("Frame " + str(frame + 1) + " of " + str(len(svs)))
        print("===========================")
        hdf5_restore("../solutions/" + svs[frame, 0])
        bbb.ftol = 1e20
        bbb.issfon = 0
        bbb.exmain()

        if heatmap is not False:

            exec('keys["heatmap"]=heatmap["var"]')

        # This is a dirty solution, but as the Forthon objects are only pointed to by python the values stored cannot (to my knowledge) be directly accessed by python (list of vars, etc). Instead one must execute a string statement to get the parameter passed onto the function

        exec('ims.append([create_im(' + varx + ',' + vary +
             ',keys,figsize)])')  # Append frame to list

    chdir(cwd)  # Move back to original directory
    ani = ArtistAnimation(fig,
                          ims,
                          interval=interval,
                          blit=True,
                          repeat_delay=0)  # Create animation

    # Turn off extra pair of axes, make the animation "fullscreen"
    ax = axes()
    ax.axis('off')
    subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)

    # Show and store as requested
    if savename is not False:
        Writer = writers['ffmpeg']
        writer = Writer(fps=round(1 / (interval * 1e-3)),
                        metadata=dict(artist=getuser()),
                        bitrate=1800)
        ani.save(savename + ".mp4", writer=writer)
    if show:
        show()
Esempio n. 4
0
def create_EIRENE(path='.',subpath='data'):
    ''' Creates a database
        Parameters:
            savename        If set, saves dict as pickle named 'savename'
            sortlocation    Location for sorting by te: 'core' or 'mp'
            outpath         Path to location where pickle is saved
            path            Path to parent directory
            subpath         Path to input.py within child directories of path: 
                            path/*/supath/input.py
            commands        List of commands to be executed before restoring solution
            variables       List of all variable names, including package, to be stored
            ret             Boolean whether to return dict or not
    '''
    from os import getcwd,chdir,remove,walk
    from os.path import abspath  
    from uedge import bbb,com
    from importlib import reload



    def natsort(l): 
        from re import split
        convert = lambda text: int(text) if text.isdigit() else text.lower() 
        alphanum_key = lambda key: [ convert(c) for c in split('([0-9]+)', key) ] 
        return sorted(l, key = alphanum_key)

    chdir(path)                 # Go to the parent directory
    parent=getcwd()               # Get path to parent
    # Get list of subdirectories in path
    dirs=natsort(next(walk(path))[1])
    # Omit supporting file directories
    try:
        dirs.remove('grid')
    except:    
        pass
    try:
        dirs.remove('rates')
    except:
        pass
    try:
        dirs.remove('ignore')
    except:
        pass
    
    if len(dirs)==0:
        return 'No directories found! Aborting...'


    loop=0
    for child in dirs:      # Loop through all directories
        loop+=1


        # TODO: exmain every Nth step
        print('******************************')
        print('*** Directory: '+child+' ***')
        print('******************************')

        chdir('{}/{}'.format(child,subpath))
        
        import input as i
        reload(i)
        i.restore_input()


        # Read and repopulate all arrays
        bbb.issfon=0;bbb.ftol=1e20;bbb.exmain()
        bbb.write_eirene(verbatim=False)


        chdir(parent)