<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 17 15:08:14 2014

@author: bottero

Script to watch the results of a run.

TODO : _load prior profiles as well
       _

"""
### --- MODULES AND PACKAGES --- ###
import os, sys
import argparse # To deal with arguments :
# https://docs.python.org/2/library/argparse.html
import numpy as np # NumPy (multidimensional arrays, linear algebra, ...)
import glob # Unix style pathname pattern expansion
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt # Matplotlib's pyplot: MATLAB-like syntax

def pdense(x, y, sigma, M=1000):
    """ Plot probability density of y with known stddev sigma
    """
    assert len(x) == len(y) and len(x) == len(sigma)
    N = len(x)
    # TODO: better y ranging
    ymin, ymax = min(y - 2 * sigma), max(y + 2 * sigma)
    yy = np.linspace(ymin, ymax, M)
    a = [np.exp(-((Y - yy) / s) ** 2) / s for Y, s in zip(y, sigma)]
    A = np.array(a)
    A = A.reshape(N, M)
    plt.imshow(-A, cmap='gray', aspect='auto',
               origin='upper', extent=(ymin,ymax,max(x),min(x)))
   # plt.title('Density plot')

def representsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False
def representsFloat(s):
    try: 
        float(s)
        return True
    except ValueError:
        return False
        
### --- Parser arguments --- ###
parser = argparse.ArgumentParser(description='Watch the results of a run')
parser.add_argument("pathToDir", 
                    help="Path to result directory (ex : OUTPUT_FILES/XXX)")
parser.add_argument("-v","--verbose", help="Increase output verbosity",
                    action="store_true")
parser.add_argument("-a","--all", help="Plot everything",
                    action="store_true", default=False)
parser.add_argument("-d","--data", help="Plot the first guess curve (and real curves for analytical runs))",
                    action="store_true")
parser.add_argument("-g","--geometry", help="Plot the geometry used (sources and receivers)",
                    action="store_true")
parser.add_argument("-e","--energies", help="Plot the energies of the chains",
                    action="store_true")
parser.add_argument("-b","--best", help="Plot the some good models found and the residuals of the best",
                    action="store_true")
parser.add_argument("--dont_show_guess", help="Don't show first guess model on plots",
                    action="store_true", default=False)
parser.add_argument("--show_ranges", help="Show exploration ranges on plots",
                    action="store_true", default=False)
parser.add_argument("--show_averages", help="Show average models on plots",
                    action="store_true", default=False)
parser.add_argument("--no_density_plots", help="Represent uncertainties by a range",
                    action="store_true", default=False)
parser.add_argument("-r","--results",type=int, 
                    help="Plot the results from the inversion for given \
chain number",default=-1)
parser.add_argument("-t","--treshold",type=int, 
                    help="Iteration after which we show the model calculated",
                    default=0)
parser.add_argument("--recalculate_t0", help="Force recalculate t0 (even if it had not been chosen during the run)",
                    action="store_true")
parser.add_argument("-s","--swaps", help="Plot the swaps",
                    action="store_true")
parser.add_argument("--vpvs", help="Plot mean Vp/Vs ratio plus uncertainties",
                    action="store_true")
args = parser.parse_args()

### --- Test arguments --- ###

if not os.path.isdir(args.pathToDir): # If the path does not exist
    print "Directory ",args.pathToDir," not found."
    parser.print_help()
    sys.exit(0)
if args.pathToDir[-1:] != '/': # add a / at the end of the path if necessary
    args.pathToDir+='/'
code = glob.glob1(args.pathToDir,"stats0.*")[0].split('.')[1] 
#args.pathToDir.split("/")[-2] # just keep the name of the directory
if not representsInt(code):
    print "Directory ",args.pathToDir," does not seem to be a correct IMCMC \
directory... (no stats0 found)"
    sys.exit(0)

### --- Load files --- ###

# Extract informations from config.XXX.dat :
# TODO : read the cfg file

T = np.zeros(0)
with open(args.pathToDir+'config.cfg') as configFile:
    for line in configFile:
        if 'SWAVES' in line:
            if line.split(" = ")[1].split("#")[0].strip() == "1":
                swaves=True
            else:
                swaves=False
        if 'ANALYTICAL_RUN' in line:
            if line.split(" = ")[1].split("#")[0].strip() == "1":
                analytical=True
            else:<commit_msg>Add a stop in watchresults.py if nothing has to be done<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 17 15:08:14 2014

@author: bottero

Script to watch the results of a run.

TODO : _load prior profiles as well
       _

"""
### --- MODULES AND PACKAGES --- ###
import os, sys
import argparse # To deal with arguments :
# https://docs.python.org/2/library/argparse.html
import numpy as np # NumPy (multidimensional arrays, linear algebra, ...)
import glob # Unix style pathname pattern expansion
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt # Matplotlib's pyplot: MATLAB-like syntax

def pdense(x, y, sigma, M=1000):
    """ Plot probability density of y with known stddev sigma
    """
    assert len(x) == len(y) and len(x) == len(sigma)
    N = len(x)
    # TODO: better y ranging
    ymin, ymax = min(y - 2 * sigma), max(y + 2 * sigma)
    yy = np.linspace(ymin, ymax, M)
    a = [np.exp(-((Y - yy) / s) ** 2) / s for Y, s in zip(y, sigma)]
    A = np.array(a)
    A = A.reshape(N, M)
    plt.imshow(-A, cmap='gray', aspect='auto',
               origin='upper', extent=(ymin,ymax,max(x),min(x)))
   # plt.title('Density plot')

def representsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False
def representsFloat(s):
    try: 
        float(s)
        return True
    except ValueError:
        return False
        
### --- Parser arguments --- ###
parser = argparse.ArgumentParser(description='Watch the results of a run')
parser.add_argument("pathToDir", 
                    help="Path to result directory (ex : OUTPUT_FILES/XXX)")
parser.add_argument("-v","--verbose", help="Increase output verbosity",
                    action="store_true")
parser.add_argument("-a","--all", help="Plot everything",
                    action="store_true", default=False)
parser.add_argument("-d","--data", help="Plot the first guess curve (and real curves for analytical runs))",
                    action="store_true")
parser.add_argument("-g","--geometry", help="Plot the geometry used (sources and receivers)",
                    action="store_true")
parser.add_argument("-e","--energies", help="Plot the energies of the chains",
                    action="store_true")
parser.add_argument("-b","--best", help="Plot the some good models found and the residuals of the best",
                    action="store_true")
parser.add_argument("--dont_show_guess", help="Don't show first guess model on plots",
                    action="store_true", default=False)
parser.add_argument("--show_ranges", help="Show exploration ranges on plots",
                    action="store_true", default=False)
parser.add_argument("--show_averages", help="Show average models on plots",
                    action="store_true", default=False)
parser.add_argument("--no_density_plots", help="Represent uncertainties by a range",
                    action="store_true", default=False)
parser.add_argument("-r","--results",type=int, 
                    help="Plot the results from the inversion for given \
chain number",default=-1)
parser.add_argument("-t","--treshold",type=int, 
                    help="Iteration after which we show the model calculated",
                    default=0)
parser.add_argument("--recalculate_t0", help="Force recalculate t0 (even if it had not been chosen during the run)",
                    action="store_true")
parser.add_argument("-s","--swaps", help="Plot the swaps",
                    action="store_true")
parser.add_argument("--vpvs", help="Plot mean Vp/Vs ratio plus uncertainties",
                    action="store_true")
args = parser.parse_args()

### --- Test arguments --- ###

if not os.path.isdir(args.pathToDir): # If the path does not exist
    print "Directory ",args.pathToDir," not found."
    parser.print_help()
    sys.exit(0)
if args.pathToDir[-1:] != '/': # add a / at the end of the path if necessary
    args.pathToDir+='/'
code = glob.glob1(args.pathToDir,"stats0.*")[0].split('.')[1] 
#args.pathToDir.split("/")[-2] # just keep the name of the directory
if not representsInt(code):
    print "Directory ",args.pathToDir," does not seem to be a correct IMCMC \
directory... (no stats0 found)"
    sys.exit(0)

if not (args.all or args.data or args.geometry or args.energies or args.best or (args.results != -1) or args.swaps or args.vpvs):
    print "Nothing has to be done!"
    sys.exit(0)

### --- Load files --- ###

# Extract informations from config.XXX.dat :
# TODO : read the cfg file

T = np.zeros(0)
with open(args.pathToDir+'config.cfg') as configFile:
    for line in configFile:
        if 'SWAVES' in line:
            if line.split(" = ")[1].split("#")[0].strip() == "1":
                swaves=True
            else:
                swaves=False
        if 'ANALYTICAL_RUN' in line:
            if line.split(" = ")[1].split("#")[0].strip() == "1":
                analytical=True
            else:
{'fraction_non_alphanumeric': 0.14703158761189422, 'fraction_numerical': 0.009054429468052268, 'mean_word_length': 2.7312859884836853, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3999784', 'n_tokens_mistral': 3046, 'n_tokens_neox': 2913, 'n_words': 846}