ZGainsforth
2/27/2015 - 5:44 PM

Read alphaMELTS output files into numpy arrays for plotting and analysis

Read alphaMELTS output files into numpy arrays for plotting and analysis

# Created 2014, Zack Gainsforth
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import numpy as np
#import QuickPlot
import re
from StringIO import StringIO
import glob
import os

def GetalphaMELTSSection(FileName, SectionName):
    # Read the alphaMELTS file that has all the output.
    try:
        with open (FileName, 'r') as myfile:
            data=myfile.read()
    except:
        print 'Failed to open ' + FileName + '.  Skipping.'
        return

    DataLines = StringIO(data)

    reout = re.compile(r'%s.*?(?:\n\n|\Z)' % (SectionName), re.S)
#    reout = re.compile(r'%s.*?%s' % (SectionName, stop), re.S)
    try:
        SectionStr = reout.search(data).group(0)
    except:
        # It is possible that this MELTS computation didn't produce this mineral.  If so, just bail.
        return None
    # Convert it into a numpy array.
    SectionData = np.genfromtxt(StringIO(SectionStr), skip_header=1, skip_footer=0, names=True)
    return SectionData

def ListalphaMELTSSections(FileName):
    # Read the alphaMELTS file that has all the output.
    try:
        with open (FileName, 'r') as myfile:
            data=myfile.read()
    except:
        print 'Failed to open ' + FileName + '.  Skipping.'
        return

    DataLines = StringIO(data)
    SectionNames = list()
    while True:
        try:
            Line = DataLines.readline()
            if Line == '\n':
                s = DataLines.readline()
                snames = s.split()
                SectionNames.append(snames[0])
            if Line == '':
                break
        except:
            break

    return SectionNames

def ListAllMeltsFiles(PathName=os.getcwd()):

    fnames = glob.glob(os.path.join(PathName, '*.txt'))

    for f in fnames:
        _, filename = os.path.split(f)
        print filename + ': ' + str(ListalphaMELTSSections(f))

    # P = GetalphaMELTSSection('Phase_mass_tbl.txt', 'Phase')
    # P = GetalphaMELTSSection('Phase_main_tbl.txt', 'clinopyroxene_1')

    print 'Example code: '
    _, filename = os.path.split(f)
    print 's = GetalphaMELTSSection(\'' + filename + '\', \'' + ListalphaMELTSSections(f)[0] + '\')'
    s = GetalphaMELTSSection(f, ListalphaMELTSSections(f)[0])
    print 'plot(s[\'' + s.dtype.names[0] + '\'], s[\'' + s.dtype.names[1] + '\'])'
    return

#ListAllMeltsFiles(os.getcwd())