Changeset 808


Ignore:
Timestamp:
07/24/15 17:09:24 (10 months ago)
Author:
mmckerns
Message:

added function interface for hypercube_measures

Location:
mystic
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • mystic/mystic/support.py

    r807 r808  
    99""" 
    1010 
    11 __all__ = ['convergence', 'hypercube'] 
     11__all__ = ['convergence', 'hypercube', 'hypercube_measures'] 
    1212 
    1313from mpl_toolkits.mplot3d import Axes3D as _Axes3D 
     
    2121from mystic.munge import read_history 
    2222from mystic.munge import logfile_reader, raw_to_support 
    23 from mystic.tools import factor 
     23from mystic.tools import factor, flatten 
    2424 
    2525# globals 
     
    363363    parsed_opts, parsed_args = parser.parse_args(cmdargs) 
    364364 
     365    from StringIO import StringIO 
     366    f = StringIO() 
     367    parser.print_help(file=f) 
     368    f.seek(0) 
     369    if 'Options:' not in hypercube.__doc__: 
     370        hypercube.__doc__ += '\nOptions:%s' % f.read().split('Options:')[-1] 
     371    f.close() 
     372 
    365373    if __quit: return 
    366374 
     
    505513    #steps = [[0,1],[1,2],[2,3],[3,4,5,6,7,8]] or similar 
    506514    if flatten: 
    507         from mystic.tools import flatten 
    508515        steps = [list(flatten(steps))] 
    509516 
     
    528535 
    529536 
     537def hypercube_measures(filename, **kwds): 
     538    """ 
     539generate measure support plots from file written with 'write_support_file' 
     540 
     541Available from the command shell as: 
     542  support_hypercube_measures.py filename [options] 
     543 
     544or as a function call as: 
     545  mystic.support.hypercube_measures(filename, **options) 
     546 
     547The options "bounds", "axes", 'weight", and "iters" all take indicator strings. 
     548The bounds should be given as comma-separated slices. For example, using 
     549bounds = "60:105, 0:30, 2.1:2.8" will set the lower and upper bounds for 
     550x to be (60,105), y to be (0,30), and z to be (2.1,2.8).  Similarly, axes 
     551also accepts comma-separated groups of ints; however, for axes, each entry 
     552indicates which parameters are to be plotted along each axis -- the first 
     553group for the x direction, the second for the y direction, and third for z.  
     554Thus, axes = "2 3, 6 7, 10 11" would set 2nd and 3rd parameters along x. The 
     555corresponding weights are used to color the measure points, where 1.0 is black 
     556and 0.0 is white. For example, using weight = "0 1, 4 5, 8 9" would use 
     557the 0th and 1st parameters to weight x. Iters is also similar, however only 
     558accepts comma-separated ints. Hence, iters = "-1" will plot the last iteration, 
     559while iters = "0, 300, 700" will plot the 0th, 300th, and 700th in three plots. 
     560***Note that if weights are not normalized (to 1), an error will be thrown.*** 
     561 
     562The option "label" takes comma-separated strings. For example, label = "x,y," 
     563will place 'x' on the x-axis, 'y' on the y-axis, and nothing on the z-axis. 
     564LaTeX is also accepted. For example, label = "$ h $, $ {\\alpha}$, $ v$" will 
     565label the axes with standard LaTeX math formatting. Note that the leading 
     566space is required, while a trailing space aligns the text with the axis 
     567instead of the plot frame. 
     568 
     569INTENDED FOR VISUALIZING WEIGHTED MEASURES (i.e. weights and positions) 
     570 
     571Required Inputs: 
     572  filename            name of the python convergence logfile (e.g paramlog.py) 
     573""" 
     574    import shlex 
     575    global __quit 
     576    __quit = False 
     577 
     578    # handle the special case where list is provided by sys.argv 
     579    if isinstance(filename, (list,tuple)) and not kwds: 
     580        cmdargs = filename # (above is used by script to parse command line) 
     581    elif isinstance(filename, basestring) and not kwds: 
     582        cmdargs = shlex.split(filename) 
     583    # 'everything else' is essentially the functional interface 
     584    else: 
     585        out = kwds.get('out', None) 
     586        bounds = kwds.get('bounds', None) 
     587        axes = kwds.get('axes', None) 
     588        weight = kwds.get('weight', None) 
     589        iters = kwds.get('iters', None) 
     590        label = kwds.get('label', None) 
     591        nid = kwds.get('nid', None) 
     592        scale = kwds.get('scale', None) 
     593        flat = kwds.get('flat', False) 
     594 
     595        # process "commandline" arguments 
     596        cmdargs = '' 
     597        cmdargs += '' if out is None else '--out={} '.format(out) 
     598        cmdargs += '' if bounds is None else '--bounds="{}" '.format(bounds) 
     599        cmdargs += '' if axes is None else '--axes="{}" '.format(axes) 
     600        cmdargs += '' if weight is None else '--weight="{}" '.format(weight) 
     601        cmdargs += '' if iters is None else '--iters="{}" '.format(iters) 
     602        cmdargs += '' if label is None else '--label="{}" '.format(label) 
     603        cmdargs += '' if nid is None else '--nid={} '.format(nid) 
     604        cmdargs += '' if scale is None else '--scale={} '.format(scale) 
     605        cmdargs += '' if flat == False else '--flat ' 
     606        cmdargs = filename.split() + shlex.split(cmdargs) 
     607 
     608    #XXX: note that 'argparse' is new as of python2.7 
     609    from optparse import OptionParser 
     610    def _exit(self, **kwds): 
     611        global __quit 
     612        __quit = True 
     613    OptionParser.exit = _exit 
     614 
     615    parser = OptionParser(usage=hypercube_measures.__doc__.split('\n\nOptions:')[0]) 
     616    parser.add_option("-u","--out",action="store",dest="out",\ 
     617                      metavar="STR",default=None, 
     618                      help="filepath to save generated plot") 
     619    parser.add_option("-b","--bounds",action="store",dest="bounds",\ 
     620                      metavar="STR",default="0:1, 0:1, 0:1", 
     621                      help="indicator string to set hypercube bounds") 
     622    parser.add_option("-x","--axes",action="store",dest="xyz",\ 
     623                      metavar="STR",default="1, 3, 5", 
     624                      help="indicator string to assign spatial parameter to axis") 
     625    parser.add_option("-w","--weight",action="store",dest="wxyz",\ 
     626                      metavar="STR",default="0, 2, 4", 
     627                      help="indicator string to assign weight parameter to axis") 
     628    parser.add_option("-i","--iters",action="store",dest="iters",\ 
     629                      metavar="STR",default="-1", 
     630                      help="indicator string to select iterations to plot") 
     631    parser.add_option("-l","--label",action="store",dest="label",\ 
     632                      metavar="STR",default=",,", 
     633                      help="string to assign label to axis") 
     634    parser.add_option("-n","--nid",action="store",dest="id",\ 
     635                      metavar="INT",default=None, 
     636                      help="id # of the nth simultaneous points to plot") 
     637    parser.add_option("-s","--scale",action="store",dest="scale",\ 
     638                      metavar="INT",default=1.0, 
     639                      help="grayscale contrast multiplier for points in plot") 
     640    parser.add_option("-f","--flat",action="store_true",dest="flatten",\ 
     641                      default=False,help="show selected iterations in a single plot") 
     642    parsed_opts, parsed_args = parser.parse_args(cmdargs) 
     643 
     644    from StringIO import StringIO 
     645    f = StringIO() 
     646    parser.print_help(file=f) 
     647    f.seek(0) 
     648    if 'Options:' not in hypercube_measures.__doc__: 
     649        hypercube_measures.__doc__ += '\nOptions:%s' % f.read().split('Options:')[-1] 
     650    f.close() 
     651 
     652    if __quit: return 
     653 
     654    # get the name of the parameter log file 
     655    params, _cost = read_history(parsed_args[0]) 
     656    # would be nice to use meta = ['wx','wx2','x','x2','wy',...] 
     657    # exec "from %s import meta" % file 
     658 
     659    try: # select the bounds 
     660        bounds = parsed_opts.bounds.split(",")  # format is "60:105, 0:30, 2.1:2.8" 
     661        bounds = [tuple(float(j) for j in i.split(':')) for i in bounds] 
     662    except: 
     663        bounds = [(0,1),(0,1),(0,1)] 
     664 
     665    try: # select which params are along which axes 
     666        xyz = parsed_opts.xyz.split(",")  # format is "0 1, 4 5, 8 9" 
     667        xyz = [tuple(int(j) for j in i.split()) for i in xyz] 
     668    except: 
     669        xyz = [(1,),(3,),(5,)] 
     670     
     671    try: # select which params are along which axes 
     672        wxyz = parsed_opts.wxyz.split(",")  # format is "0 1, 4 5, 8 9" 
     673        wxyz = [tuple(int(j) for j in i.split()) for i in wxyz] 
     674    except: 
     675        wxyz = [(0,),(2,),(4,)] 
     676     
     677    try: # select labels for the axes 
     678        label = parsed_opts.label.split(',')  # format is "x, y, z" 
     679    except: 
     680        label = ['','',''] 
     681     
     682    x = params[max(xyz[0])] 
     683    try: # select which iterations to plot 
     684        select = parsed_opts.iters.split(',')  # format is "2, 4, 5, 6" 
     685    except: 
     686        select = ['-1'] 
     687       #select = ['0','1','2','3'] 
     688 
     689    try: # collapse non-consecutive iterations into a single plot... 
     690        flatten = parsed_opts.flatten 
     691    except: 
     692        flatten = False 
     693 
     694    try: # select which 'id' to plot results for 
     695        id = int(parsed_opts.id) 
     696    except: 
     697        id = None # i.e. 'all' **or** use id=0, which should be 'best' energy ? 
     698 
     699    try: # scale the color in plotting the weights 
     700        scale = float(parsed_opts.scale) 
     701    except: 
     702        scale = 1.0 # color = color**scale 
     703 
     704    # ensure all terms of bounds and xyz are tuples 
     705    for bound in bounds: 
     706        if not isinstance(bound, tuple): 
     707            raise TypeError, "bounds should be tuples of (lower_bound,upper_bound)" 
     708    for i in range(len(xyz)): 
     709        if isinstance(xyz[i], int): 
     710            xyz[i] = (xyz[i],) 
     711        elif not isinstance(xyz[i], tuple): 
     712            raise TypeError, "xyz should be tuples of (param1,param2,param3,...)" 
     713    for i in range(len(wxyz)): 
     714        if isinstance(wxyz[i], int): 
     715            wxyz[i] = (wxyz[i],) 
     716        elif not isinstance(wxyz[i], tuple): 
     717            raise TypeError, "wxyz should be tuples of (param1,param2,param3,...)" 
     718 
     719    # ensure all terms of select are strings of ints 
     720    for i in range(len(select)): 
     721        if isinstance(select[i], int): select[i] = str(select[i]) 
     722        if select[i].count(':'): 
     723            raise ValueError, "iters should be ints" 
     724       #if select[i] == '-1': select[i] = 'len(x)-1:len(x)' 
     725       #elif not select[i].count(':'): 
     726       #    select[i] += ':' + str(int(select[i])+1) 
     727 
     728    # take only the selected 'id' 
     729    if id != None: 
     730        param = [] 
     731        for j in range(len(params)): 
     732            param.append([p[id] for p in params[j]]) 
     733        params = param[:] 
     734 
     735    # at this point, we should have: 
     736    #bounds = [(60,105),(0,30),(2.1,2.8)] or [(None,None),(None,None),(None,None)] 
     737    #xyz = [(2,3),(6,7),(10,11)] for any length tuple 
     738    #wxyz = [(0,1),(4,5),(8,9)] for any length tuple (should match up with xyz) 
     739    #select = ['-1'] or ['1','2','3','-1'] or similar 
     740    #id = 0 or None 
     741 
     742    plots = len(select) 
     743    if not flatten: 
     744        dim1,dim2 = best_dimensions(plots) 
     745    else: dim1,dim2 = 1,1 
     746 
     747    # use the default bounds where not specified 
     748    bounds = [list(i) for i in bounds] 
     749    for i in range(len(bounds)): 
     750        if bounds[i][0] is None: bounds[i][0] = 0 
     751        if bounds[i][1] is None: bounds[i][1] = 1 
     752 
     753    # correctly bound the first plot.  there must be at least one plot 
     754    fig = plt.figure() 
     755    ax1 = Subplot3D(fig, dim1,dim2,1) 
     756    ax1.plot([bounds[0][0]],[bounds[1][0]],[bounds[2][0]]) 
     757    ax1.plot([bounds[0][1]],[bounds[1][1]],[bounds[2][1]]) 
     758    globals = {'plt':plt,'fig':fig,'dim1':dim1,'dim2':dim2,\ 
     759               'Subplot3D':Subplot3D,'bounds':bounds,'label':label} 
     760    if not flatten: 
     761        code = "plt.title('iterations[%s]');" % select[0] 
     762    else:  
     763        code = "plt.title('iterations[*]');" 
     764    code = compile(code, '<string>', 'exec') 
     765    exec code in globals 
     766    ax1.set_xlabel(label[0]) 
     767    ax1.set_ylabel(label[1]) 
     768    ax1.set_zlabel(label[2]) 
     769    a = [ax1] 
     770 
     771    # set up additional plots 
     772    if not flatten: 
     773        for i in range(2, plots + 1): 
     774            code = "ax = ax%d = Subplot3D(fig, dim1,dim2,%d);" % (i,i) 
     775            code += "ax.plot([bounds[0][0]],[bounds[1][0]],[bounds[2][0]]);" 
     776            code += "ax.plot([bounds[0][1]],[bounds[1][1]],[bounds[2][1]]);" 
     777            code += "plt.title('iterations[%s]');" % select[i - 1] 
     778            code += "ax.set_xlabel(label[0]);" 
     779            code += "ax.set_ylabel(label[1]);" 
     780            code += "ax.set_zlabel(label[2]);" 
     781            code = compile(code, '<string>', 'exec') 
     782            exec code in globals 
     783            a.append(globals['ax']) 
     784 
     785    # turn each "n:m" in select to a list 
     786   #_select = [] 
     787   #for sel in select: 
     788   #    if sel[0] == ':': _select.append("0"+sel) 
     789   #    else: _select.append(sel) 
     790   #for i in range(len(_select)): 
     791   #    if _select[i][-1] == ':': select[i] = _select[i]+str(len(x)) 
     792   #    else: select[i] = _select[i] 
     793   #for i in range(len(select)): 
     794   #    p = select[i].split(":") 
     795   #    if p[0][0] == '-': p[0] = "len(x)"+p[0] 
     796   #    if p[1][0] == '-': p[1] = "len(x)"+p[1] 
     797   #    select[i] = p[0]+":"+p[1] 
     798   #steps = [eval("range(%s)" % sel.replace(":",",")) for sel in select] 
     799    steps = [eval("[int(%s)]" % sel) for sel in select] 
     800 
     801    # at this point, we should have: 
     802    #xyz = [(2,3),(6,7),(10,11)] for any length tuple 
     803    #wxyz = [(0,1),(4,5),(8,9)] for any length tuple (should match up with xyz) 
     804    #steps = [[0],[1],[3],[8]] or similar 
     805    if flatten: 
     806        steps = [list(flatten(steps))] 
     807 
     808    # adjust for logarithmic scaling of intensity 
     809    from numpy import e 
     810    scale = e**(scale - 1.0) 
     811 
     812    # dot color is based on a product of weights 
     813    t = [] 
     814    for v in range(len(steps)): 
     815        t.append([]) 
     816        for s in steps[v]: 
     817            for i in eval("[params[q][%s] for q in wxyz[0]]" % s): 
     818                for j in eval("[params[q][%s] for q in wxyz[1]]" % s): 
     819                    for k in eval("[params[q][%s] for q in wxyz[2]]" % s): 
     820                        t[v].append([str((1.0 - i[q]*j[q]*k[q])**scale) for q in range(len(i))]) 
     821                        if float(t[v][-1][-1]) > 1.0 or float(t[v][-1][-1]) < 0.0: 
     822                            raise ValueError, "Weights must be in range 0-1. Check normalization and/or assignment." 
     823 
     824    # build all the plots 
     825    for v in range(len(steps)): 
     826        for s in steps[v]: 
     827            u = 0 
     828            for i in eval("[params[q][%s] for q in xyz[0]]" % s): 
     829                for j in eval("[params[q][%s] for q in xyz[1]]" % s): 
     830                    for k in eval("[params[q][%s] for q in xyz[2]]" % s): 
     831                        for q in range(len(t[v][u])): 
     832                            a[v].plot([i[q]],[j[q]],[k[q]],marker='o',color=t[v][u][q],ms=10) 
     833                        u += 1 
     834 
     835    if not parsed_opts.out: 
     836        plt.show() 
     837    else: 
     838        fig.savefig(parsed_opts.out) 
     839 
     840 
    530841if __name__ == '__main__': 
    531842    pass 
  • mystic/scripts/support_hypercube_measures.py

    r776 r808  
    66#  - http://mmckerns.github.io/project/mystic/browser/mystic/LICENSE 
    77 
    8 __doc__ = """ 
    9 support_hypercube_measures.py [options] filename 
     8from mystic.support import hypercube_measures 
    109 
    11 generate measure support plots from file written with 'write_support_file' 
    12  
    13 The options "bounds", "axes", 'weight", and "iters" all take indicator strings. 
    14 The bounds should be given as comma-separated slices. For example, using 
    15 bounds = "60:105, 0:30, 2.1:2.8" will set the lower and upper bounds for 
    16 x to be (60,105), y to be (0,30), and z to be (2.1,2.8).  Similarly, axes 
    17 also accepts comma-separated groups of ints; however, for axes, each entry 
    18 indicates which parameters are to be plotted along each axis -- the first 
    19 group for the x direction, the second for the y direction, and third for z.  
    20 Thus, axes = "2 3, 6 7, 10 11" would set 2nd and 3rd parameters along x. The 
    21 corresponding weights are used to color the measure points, where 1.0 is black 
    22 and 0.0 is white. For example, using weight = "0 1, 4 5, 8 9" would use 
    23 the 0th and 1st parameters to weight x. Iters is also similar, however only 
    24 accepts comma-separated ints. Hence, iters = "-1" will plot the last iteration, 
    25 while iters = "0, 300, 700" will plot the 0th, 300th, and 700th in three plots. 
    26 ***Note that if weights are not normalized (to 1), an error will be thrown.*** 
    27  
    28 The option "label" takes comma-separated strings. For example, label = "x,y," 
    29 will place 'x' on the x-axis, 'y' on the y-axis, and nothing on the z-axis. 
    30 LaTeX is also accepted. For example, label = "$ h $, $ {\\alpha}$, $ v$" will 
    31 label the axes with standard LaTeX math formatting. Note that the leading 
    32 space is required, while a trailing space aligns the text with the axis 
    33 instead of the plot frame. 
    34  
    35 INTENDED FOR VISUALIZING WEIGHTED MEASURES (i.e. weights and positions) 
    36  
    37 Required Inputs: 
    38   filename            name of the python convergence logfile (e.g paramlog.py) 
    39 """ 
    40  
    41 from support_convergence import best_dimensions 
    42  
     10__doc__ = hypercube_measures.__doc__ 
    4311 
    4412if __name__ == '__main__': 
    4513 
    46   #XXX: note that 'argparse' is new as of python2.7 
    47   from optparse import OptionParser 
    48   parser = OptionParser(usage=__doc__) 
    49   parser.add_option("-b","--bounds",action="store",dest="bounds",\ 
    50                     metavar="STR",default="0:1, 0:1, 0:1", 
    51                     help="indicator string to set hypercube bounds") 
    52   parser.add_option("-x","--axes",action="store",dest="xyz",\ 
    53                     metavar="STR",default="1, 3, 5", 
    54                     help="indicator string to assign spatial parameter to axis") 
    55   parser.add_option("-w","--weight",action="store",dest="wxyz",\ 
    56                     metavar="STR",default="0, 2, 4", 
    57                     help="indicator string to assign weight parameter to axis") 
    58   parser.add_option("-i","--iters",action="store",dest="iters",\ 
    59                     metavar="STR",default="-1", 
    60                     help="indicator string to select iterations to plot") 
    61   parser.add_option("-l","--label",action="store",dest="label",\ 
    62                     metavar="STR",default=",,", 
    63                     help="string to assign label to axis") 
    64   parser.add_option("-n","--nid",action="store",dest="id",\ 
    65                     metavar="INT",default=None, 
    66                     help="id # of the nth simultaneous points to plot") 
    67   parser.add_option("-s","--scale",action="store",dest="scale",\ 
    68                     metavar="INT",default=1.0, 
    69                     help="grayscale contrast multiplier for points in plot") 
    70   parser.add_option("-f","--flat",action="store_true",dest="flatten",\ 
    71                     default=False,help="show selected iterations in a single plot") 
    72   parsed_opts, parsed_args = parser.parse_args() 
     14    import sys 
    7315 
    74   # get the name of the parameter log file 
    75   from mystic.munge import read_history 
    76   params, _cost = read_history(parsed_args[0]) 
    77   # would be nice to use meta = ['wx','wx2','x','x2','wy',...] 
    78   # exec "from %s import meta" % file 
     16    hypercube_measures(sys.argv[1:]) 
    7917 
    80   try: # select the bounds 
    81     bounds = parsed_opts.bounds.split(",")  # format is "60:105, 0:30, 2.1:2.8" 
    82     bounds = [tuple(float(j) for j in i.split(':')) for i in bounds] 
    83   except: 
    84     bounds = [(0,1),(0,1),(0,1)] 
    85  
    86   try: # select which params are along which axes 
    87     xyz = parsed_opts.xyz.split(",")  # format is "0 1, 4 5, 8 9" 
    88     xyz = [tuple(int(j) for j in i.split()) for i in xyz] 
    89   except: 
    90     xyz = [(1,),(3,),(5,)] 
    91      
    92   try: # select which params are along which axes 
    93     wxyz = parsed_opts.wxyz.split(",")  # format is "0 1, 4 5, 8 9" 
    94     wxyz = [tuple(int(j) for j in i.split()) for i in wxyz] 
    95   except: 
    96     wxyz = [(0,),(2,),(4,)] 
    97      
    98   try: # select labels for the axes 
    99     label = parsed_opts.label.split(',')  # format is "x, y, z" 
    100   except: 
    101     label = ['','',''] 
    102      
    103   x = params[max(xyz[0])] 
    104   try: # select which iterations to plot 
    105     select = parsed_opts.iters.split(',')  # format is "2, 4, 5, 6" 
    106   except: 
    107     select = ['-1'] 
    108    #select = ['0','1','2','3'] 
    109  
    110   try: # collapse non-consecutive iterations into a single plot... 
    111     flatten = parsed_opts.flatten 
    112   except: 
    113     flatten = False 
    114  
    115   try: # select which 'id' to plot results for 
    116     id = int(parsed_opts.id) 
    117   except: 
    118     id = None # i.e. 'all' **or** use id=0, which should be 'best' energy ? 
    119  
    120   try: # scale the color in plotting the weights 
    121     scale = float(parsed_opts.scale) 
    122   except: 
    123     scale = 1.0 # color = color**scale 
    124  
    125   # ensure all terms of bounds and xyz are tuples 
    126   for bound in bounds: 
    127     if not isinstance(bound, tuple): 
    128       raise TypeError, "bounds should be tuples of (lower_bound,upper_bound)" 
    129   for i in range(len(xyz)): 
    130     if isinstance(xyz[i], int): 
    131       xyz[i] = (xyz[i],) 
    132     elif not isinstance(xyz[i], tuple): 
    133       raise TypeError, "xyz should be tuples of (param1,param2,param3,...)" 
    134   for i in range(len(wxyz)): 
    135     if isinstance(wxyz[i], int): 
    136       wxyz[i] = (wxyz[i],) 
    137     elif not isinstance(wxyz[i], tuple): 
    138       raise TypeError, "wxyz should be tuples of (param1,param2,param3,...)" 
    139  
    140   # ensure all terms of select are strings of ints 
    141   for i in range(len(select)): 
    142     if isinstance(select[i], int): select[i] = str(select[i]) 
    143     if select[i].count(':'): 
    144       raise ValueError, "iters should be ints" 
    145    #if select[i] == '-1': select[i] = 'len(x)-1:len(x)' 
    146    #elif not select[i].count(':'): 
    147    #  select[i] += ':' + str(int(select[i])+1) 
    148  
    149   # take only the selected 'id' 
    150   if id != None: 
    151     param = [] 
    152     for j in range(len(params)): 
    153       param.append([p[id] for p in params[j]]) 
    154     params = param[:] 
    155  
    156   # at this point, we should have: 
    157   #bounds = [(60,105),(0,30),(2.1,2.8)] or [(None,None),(None,None),(None,None)] 
    158   #xyz = [(2,3),(6,7),(10,11)] for any length tuple 
    159   #wxyz = [(0,1),(4,5),(8,9)] for any length tuple (should match up with xyz) 
    160   #select = ['-1'] or ['1','2','3','-1'] or similar 
    161   #id = 0 or None 
    162  
    163   from mpl_toolkits.mplot3d import Axes3D 
    164   import matplotlib.pyplot as plt 
    165   from matplotlib.axes import subplot_class_factory 
    166   Subplot3D = subplot_class_factory(Axes3D) 
    167  
    168   plots = len(select) 
    169   if not flatten: 
    170     dim1,dim2 = best_dimensions(plots) 
    171   else: dim1,dim2 = 1,1 
    172  
    173   # use the default bounds where not specified 
    174   bounds = [list(i) for i in bounds] 
    175   for i in range(len(bounds)): 
    176     if bounds[i][0] is None: bounds[i][0] = 0 
    177     if bounds[i][1] is None: bounds[i][1] = 1 
    178  
    179   # correctly bound the first plot.  there must be at least one plot 
    180   fig = plt.figure() 
    181   ax1 = Subplot3D(fig, dim1,dim2,1) 
    182   ax1.plot([bounds[0][0]],[bounds[1][0]],[bounds[2][0]]) 
    183   ax1.plot([bounds[0][1]],[bounds[1][1]],[bounds[2][1]]) 
    184   if not flatten: 
    185     exec "plt.title('iterations[%s]')" % select[0] 
    186   else:  
    187     exec "plt.title('iterations[*]')" 
    188   ax1.set_xlabel(label[0]) 
    189   ax1.set_ylabel(label[1]) 
    190   ax1.set_zlabel(label[2]) 
    191   a = [ax1] 
    192  
    193   # set up additional plots 
    194   if not flatten: 
    195     for i in range(2, plots + 1): 
    196       exec "ax%d = Subplot3D(fig, dim1,dim2,%d)" % (i,i) 
    197       exec "ax%d.plot([bounds[0][0]],[bounds[1][0]],[bounds[2][0]])" % i 
    198       exec "ax%d.plot([bounds[0][1]],[bounds[1][1]],[bounds[2][1]])" % i 
    199       exec "plt.title('iterations[%s]')" % select[i - 1] 
    200       exec "ax%d.set_xlabel(label[0])" % i 
    201       exec "ax%d.set_ylabel(label[1])" % i 
    202       exec "ax%d.set_zlabel(label[2])" % i 
    203       exec "a.append(ax%d)" % i 
    204  
    205   # turn each "n:m" in select to a list 
    206  #_select = [] 
    207  #for sel in select: 
    208  #  if sel[0] == ':': _select.append("0"+sel) 
    209  #  else: _select.append(sel) 
    210  #for i in range(len(_select)): 
    211  #  if _select[i][-1] == ':': select[i] = _select[i]+str(len(x)) 
    212  #  else: select[i] = _select[i] 
    213  #for i in range(len(select)): 
    214  #  p = select[i].split(":") 
    215  #  if p[0][0] == '-': p[0] = "len(x)"+p[0] 
    216  #  if p[1][0] == '-': p[1] = "len(x)"+p[1] 
    217  #  select[i] = p[0]+":"+p[1] 
    218  #steps = [eval("range(%s)" % sel.replace(":",",")) for sel in select] 
    219   steps = [eval("[int(%s)]" % sel) for sel in select] 
    220  
    221   # at this point, we should have: 
    222   #xyz = [(2,3),(6,7),(10,11)] for any length tuple 
    223   #wxyz = [(0,1),(4,5),(8,9)] for any length tuple (should match up with xyz) 
    224   #steps = [[0],[1],[3],[8]] or similar 
    225   if flatten: 
    226     from mystic.tools import flatten 
    227     steps = [list(flatten(steps))] 
    228  
    229   # adjust for logarithmic scaling of intensity 
    230   from numpy import e 
    231   scale = e**(scale - 1.0) 
    232  
    233   # dot color is based on a product of weights 
    234   t = [] 
    235   for v in range(len(steps)): 
    236     t.append([]) 
    237     for s in steps[v]: 
    238       for i in eval("[params[q][%s] for q in wxyz[0]]" % s): 
    239         for j in eval("[params[q][%s] for q in wxyz[1]]" % s): 
    240           for k in eval("[params[q][%s] for q in wxyz[2]]" % s): 
    241             t[v].append([str((1.0 - i[q]*j[q]*k[q])**scale) for q in range(len(i))]) 
    242             if float(t[v][-1][-1]) > 1.0 or float(t[v][-1][-1]) < 0.0: 
    243               raise ValueError, "Weights must be in range 0-1. Check normalization and/or assignment." 
    244  
    245   # build all the plots 
    246   for v in range(len(steps)): 
    247     for s in steps[v]: 
    248       u = 0 
    249       for i in eval("[params[q][%s] for q in xyz[0]]" % s): 
    250         for j in eval("[params[q][%s] for q in xyz[1]]" % s): 
    251           for k in eval("[params[q][%s] for q in xyz[2]]" % s): 
    252             for q in range(len(t[v][u])): 
    253               a[v].plot([i[q]],[j[q]],[k[q]],marker='o',color=t[v][u][q],ms=10) 
    254             u += 1 
    255  
    256   plt.show() 
    25718 
    25819# EOF 
Note: See TracChangeset for help on using the changeset viewer.