Changeset 742 for mystic/examples_other


Ignore:
Timestamp:
08/06/14 14:40:38 (22 months ago)
Author:
mmckerns
Message:

add read_history to munge; moved trajectory_plotter to model_plotter;
add "option parser" to model_plotter, to build grid, select, and mask;
decouple 'grid' from parse_axes; add ability to apply 'mask' to > 2D models

File:
1 moved

Legend:

Unmodified
Added
Removed
  • mystic/examples_other/model_plotter.py

    r739 r742  
    1010from matplotlib import cm 
    1111 
    12 def read_log(file): #FIXME: should also read "solver restart file" 
    13   "read monitor or logfile (or support file) any return params and cost" 
    14  #try:  # get the name of the parameter log file 
    15  #  file = parsed_args[0] 
    16   if isinstance(file, str): 
    17     import re 
    18     file = re.sub('\.py*.$', '', file)  # strip off .py* extension 
    19     monitor = False 
    20   else: monitor = True 
    21  #except: 
    22  #  raise IOError, "please provide log file name" 
    23   try:  # read standard logfile (or monitor) 
    24     from mystic.munge import logfile_reader, raw_to_support 
    25     if monitor: 
    26       params, cost = file.x, file.y 
    27     else: #FIXME: 'logfile_reader' should work for both file and monitor 
    28       _step, params, cost = logfile_reader(file) 
    29     params, cost = raw_to_support(params, cost) 
    30   except: 
    31     exec "from %s import params" % file 
    32     exec "from %s import cost" % file 
    33   return params, cost 
    34  
     12from mystic.munge import read_history 
    3513 
    3614def get_instance(location, *args, **kwds): 
     
    4725 
    4826 
    49 def parse_axes(option): 
     27def parse_input(option): 
     28    """parse 'option' string into 'select', 'axes', and 'mask' 
     29 
     30select contains the dimension specifications on which to plot 
     31axes holds the indicies of the parameters selected to plot 
     32mask is a dictionary of the parameter indicies and fixed values 
     33 
     34For example, 
     35    >>> select, axes, mask = parse_input("-1:10:.1, 0.0, 5.0, -50:50:.5") 
     36    >>> select 
     37    [0, 3] 
     38    >>> axes 
     39    "-1:10:.1, -50:50:.5" 
     40    >>> mask 
     41    {1: 0.0, 2: 5.0} 
     42    """ 
     43    option = option.split(',') 
     44    select = [] 
     45    axes = [] 
     46    mask = {} 
     47    for index,value in enumerate(option): 
     48        if ":" in value: 
     49            select.append(index) 
     50            axes.append(value) 
     51        else: 
     52            mask.update({index:float(value)}) 
     53    axes = ','.join(axes) 
     54    return select, axes, mask 
     55 
     56 
     57def parse_axes(option, grid=True): 
    5058    """parse option string into grid axes; using modified numpy.ogrid notation 
    5159 
     60For example: 
     61  option='-1:10:.1, 0:10:.1' yields x,y=ogrid[-1:10:.1,0:10:.1], 
     62 
     63If grid is False, accept options suitable for line plotting. 
    5264For example: 
    5365  option='-1:10' yields x=ogrid[-1:10] and y=0, 
    5466  option='-1:10, 2' yields x=ogrid[-1:10] and y=2, 
    55   option='-1:10:.1, 0:10:.1' yields x,y=ogrid[-1:10:.1,0:10:.1], 
    56  
    57 Returns tuple (x,y,z) with 'x,y' defined above, and 'z' is a boolean 
    58 where if a third member is included return z=True, else return z=False. 
    59  
    60 For example: 
    61   option='-1:10:.1, 0:10:.1, z' yields x,y=ogrid[-1:10:.1,0:10:.1] and z=True 
     67 
     68Returns tuple (x,y) with 'x,y' defined above. 
    6269    """ 
    6370    import numpy 
    6471    option = option.split(',') 
    6572    opt = dict(zip(['x','y','z'],option)) 
    66     if len(option) > 3 or len(option) < 1: 
     73    if len(option) > 2 or len(option) < 1: 
    6774        raise ValueError("invalid format string: '%s'" % ','.join(option)) 
    68     z = True if len(option) == 3 else False 
     75    z = bool(grid) 
    6976    if len(option) == 1: opt['y'] = '0' 
    7077    xd = True if ':' in opt['x'] else False 
     
    9097    else: 
    9198        raise ValueError("invalid format string: '%s'" % ','.join(option)) 
    92     return x,y,z 
     99    return x,y 
    93100 
    94101 
     
    117124    # params are the parameter trajectories 
    118125    # cost is the solution trajectory 
    119     params, cost = read_log(file) 
     126    params, cost = read_history(file) 
    120127    d = {'x':0, 'y':1, 'z':2} #XXX: remove the easter egg? 
    121128    if select in d: select = d[select] 
     
    155162    # params are the parameter trajectories 
    156163    # cost is the solution trajectory 
    157     params, cost = read_log(file) 
     164    params, cost = read_history(file) 
    158165    if select is None: select = (0,1) 
    159166    d = {'x':0, 'y':1, 'z':2} #XXX: remove the easter egg? 
     
    281288   # - do the other option parsing magic... 
    282289   # - enable 'skip' plotting points (points or line or both)? 
    283    # - handle 1D, 2D, or >= 3D model and logfile 
    284290   #FIXME: should be able to: 
    285291   # - apply a constraint as a region of NaN -- apply when 'xx,yy=x[ij],y[ij]' 
     
    288294   # - build an appropriately-sized default grid (from logfile info) 
    289295   #FIXME: current issues: 
     296   # - working with 1D or >= 3D model / logfile "feels wrong" 
    290297   # - 1D slice and projection work for 2D function, but aren't "pretty" 
    291298   # - 1D slice and projection for 1D function needs further testing... 
     
    294301   #   (see https://github.com/matplotlib/matplotlib/issues/209) 
    295302 
    296     from mystic.tools import reduced 
     303    from mystic.tools import reduced, masked 
    297304 
    298305    ### INPUTS ### 
    299     select = (0,1) #FIXME: build with 'inputs' 
    300     model = 'mystic.models.zimmermann' 
     306    options = '-1:10:.1, -1:10:.1' #, 1.0' 
     307   #options = '-50:50:.5, -50:50:.5' 
     308    model = 'mystic.models.rosen' 
    301309    reducer = 'numpy.add' 
    302     source = None #'log.txt' 
    303    #spec = '-50:50:.5, -50:50:.5, z' 
    304     spec = '-1:10:.1, -1:10:.1, z' 
     310    source = 'log.txt' 
     311    surface = True 
    305312    scale = True 
    306313    shift = False 
    307314    fill = False 
    308315    demo = True 
     316    fixed = False  # if True, apply 'fixed' parameter as constraint (for demo) 
    309317    ############## 
    310318 
    311319    # process inputs 
    312320    color = 'w' if fill else 'k' 
    313     x,y,z = parse_axes(spec) 
     321    select, spec, mask = parse_input(options) 
     322    x,y = parse_axes(spec, grid=True) # grid=False for 1D plots 
     323    #FIXME: does grid=False still make sense here...? 
    314324    reducer = get_instance(reducer) 
    315     if not source and not model: 
     325    if demo and (not source or not model): 
     326        raise RuntimeError('a model and results filename are required') 
     327    elif not source and not model: 
    316328        raise RuntimeError('a model or a results file is required') 
    317     if model: #FIXME: use 'inputs' to decorate model --> e.g. model(x,0,0,y) 
     329    if model: 
    318330        model = get_instance(model) 
    319331        model = reduced(reducer, arraylike=False)(model) # need if returns array 
     332        if fixed: model = masked(mask)(model) # constrain masked parameters 
    320333 
    321334    if demo: 
    322         #-OVERRIDE-INPUTS-#  
    323         source = 'log.txt' 
    324         #-----------------# 
    325         # for demo purposes, pick a solver (then solve) 
     335        #NOTES on applying a mask: 
     336        # - before solver: reduce dim, log selected param, follow plot surface 
     337        # - after solver: all dim, log all param, don't follow plot surface 
     338        # - could apply constraint to solver to constrain to fixed axes... 
     339        #FIXME: to match surface with 'fixed' axes, use mask to constrain 'x' 
     340 
     341        # for demo purposes... pick a solver (then solve) 
    326342        from mystic.solvers import fmin, fmin_powell, diffev 
    327343        solver = fmin 
    328         initial = (0,0) 
     344        xlen = len(select)                # masked before... 
     345        xlen += 0 if fixed else len(mask) # or masked after 
     346        initial = [0]*xlen 
    329347       #solver = diffev 
    330        #initial = ((-1,10),(-1,10)) 
     348       #initial = [(-1,10)]*xlen 
    331349        from mystic.monitors import VerboseLoggingMonitor 
    332350        itermon = VerboseLoggingMonitor(filename=source, new=True) 
     
    341359        #-----------------# 
    342360 
     361    if model and not fixed: 
     362        model = masked(mask)(model) 
     363 
    343364    # project trajectory on a 1D slice of the model surface #XXX: useful? 
    344365#   fig0 = draw_slice(model, x=x, y=sol[-1], scale=scale, shift=shift) 
Note: See TracChangeset for help on using the changeset viewer.