Changeset 5829 for branches/uq


Ignore:
Timestamp:
Aug 21, 2015 12:21:27 PM (9 years ago)
Author:
mmh
Message:

improved probability curve plotting, bug fixes, cleanup

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/uq/puq/puq_analyze.py

    r5746 r5829  
    1212import puq
    1313from puq.jpickle import unpickle
    14 import xml.etree.ElementTree as xml
    1514import Rappture
    1615import StringIO
     16from scipy.spatial import ConvexHull
     17# geometry library
     18from shapely.geometry import Polygon
     19from shapely.ops import unary_union
    1720
    1821# Redirect stdout and stderr to files for debugging.
     
    3740
    3841# Plots probability curves
    39 def plot_pdf_curve(xvals, vname, percent):
     42def plot_pdf_curve(io, h5, xvals, vname, percent):
    4043    print('plot_pdf_curve %s %s' % (vname, percent))
    4144    # compute upper and lower percentiles
     
    5659        ym[vindex] = pcurves[vname][vindex].ppf(pm)
    5760
    58     curve = xml.SubElement(dout, 'curve', {'id': 'curve_pdf-%s-%s' % (vname, percent)})
    59     about = xml.SubElement(curve, 'about')
     61    curve = io['output.curve(curve_pdf-%s-%s)' % (vname, percent)]
    6062    if percent == 0:
    61         xml.SubElement(about, 'label').text = "mean"
     63        curve['about.label'] = "mean"
    6264    else:
    63         xml.SubElement(about, 'label').text = "middle %s%%" % percent
    64     xml.SubElement(about, 'group').text = '%s:UQ:6' % label
    65     comp = xml.SubElement(curve, 'component')
    66     xy = xml.SubElement(comp, 'xy')
     65        curve['about.label'] = "middle %s%%" % percent
     66    curve['about.group'] = label
     67    curve['about.uqtype'] = 'Probability'
     68
    6769    pts = ""
    6870    for x, y in zip(xarr, yp):
     
    7476            pts += "%s %s " % (x, y)
    7577        pts += "%s %s\n" % (xarr[0], yp[0])
    76     xy.text = pts
    77 
    78 
    79 def plot_pdf_acurve(hf, acurves, vname, percent):
     78
     79    curve['component.xy'] = pts
     80
     81
     82def add_pts(f1, percent):
     83    # compute upper and lower percentiles
     84    pm = (100 - percent) / 200.0
     85    pp = 1 - pm
     86    prob = np.linspace(pm, pp, 31)
     87    x, y = f1.eval(prob)
     88    return np.array(zip(x, y))
     89
     90
     91def plot_pdf_acurve(io, h5, acurves, vname, percent):
    8092    """
    8193    This function plots the probability curves for parametric
     
    8395    """
    8496    print('plot_pdf_acurve %s %s' % (vname, percent))
    85     # compute upper and lower percentiles
    86     pm = (100 - percent)/200.0
    87     pp = 1 - pm
    8897
    8998    label = None
    90     maxvals = []
    91     minvals = []
     99    prev_pts = None  # last set of points
     100
     101    poly = []
    92102    for vindex in sorted(acurves[vname].keys()):
    93103        if label is None:
    94104            label = h5['/output/data/%s[%d]' % (vname, vindex)].attrs['label']
    95         f1 = unpickle(hf['/output/data/%s[%d]' % (vname, vindex)].attrs['curve'])
    96         pdf = acurves[vname][vindex]
    97         a, b = f1.eval([pdf.ppf(pm), pdf.ppf(pp)])
    98         maxvals.append((a[1], b[1]))
    99         minvals.append((a[0], b[0]))
    100 
    101     curve = xml.SubElement(dout, 'curve', {'id': 'curve_pdf-%s-%s' % (vname, percent)})
    102     about = xml.SubElement(curve, 'about')
     105        f1 = unpickle(h5['/output/data/%s[%d]' % (vname, vindex)].attrs['curve'])
     106        bpts = add_pts(f1, percent)
     107
     108        # first data set? Just remember it.
     109        if prev_pts is None:
     110            prev_pts = bpts
     111            continue
     112
     113        pts = np.array((prev_pts, bpts)).ravel().reshape(-1, 2)
     114        hull = ConvexHull(pts, qhull_options='Pp')
     115        p1 = Polygon([hull.points[v] for v in hull.vertices])
     116        poly.append(p1)
     117        prev_pts = bpts
     118
     119    u = unary_union(poly)
     120
     121    curve = io['output.curve(curve_pdf-%s-%s)' % (vname, percent)]
    103122    if percent == 0:
    104         xml.SubElement(about, 'label').text = "mean"
     123        curve['about.label'] = "mean"
    105124    else:
    106         xml.SubElement(about, 'label').text = "middle %s%%" % percent
    107     xml.SubElement(about, 'group').text = '%s:UQ:6' % label
    108     comp = xml.SubElement(curve, 'component')
    109     xy = xml.SubElement(comp, 'xy')
    110 
    111     pts = ''
    112     for v in maxvals:
    113         pts += "%s %s " % (v[0], v[1])
    114 
    115     if percent == 0:
    116         pts += '\n'
    117     else:
    118         for v in reversed(minvals):
    119             pts += "%s %s " % (v[0], v[1])
    120     xy.text = pts
    121 
    122 
    123 def plot_pdf(v, pdf, desc):
    124     id = '%s:UQ:1' % desc
    125     elem = xml.SubElement(dout, 'curve', {'id': id})
    126     about = xml.SubElement(elem, 'about')
    127     xml.SubElement(about, 'label').text = id
    128     yaxis = xml.SubElement(elem, 'yaxis')
    129     xml.SubElement(yaxis, 'label').text = 'Probability'
    130 
    131     component = xml.SubElement(elem, 'component')
    132     xy = xml.SubElement(component, 'xy')
     125        curve['about.label'] = "middle %s%%" % percent
     126    curve['about.group'] = label
     127    curve['about.uqtype'] = 'Probability'
     128    curve['component.xy'] = np.array(u.exterior.xy)
     129
     130
     131def plot_pdf(io, v, pdf, desc):
     132    p = io['output.curve(%s)' % desc]
     133    p['about.label'] = desc
     134    p['about.uqtype'] = "PDF"
     135    p['yaxis.label'] = 'Probability'
     136
    133137    pts = "%s 0\n" % pdf.x[0]
    134138    for x, y in zip(pdf.x, pdf.y):
    135139        pts += "%s %s\n" % (x, y)
    136140    pts += "%s 0\n" % pdf.x[-1]
    137     xy.text = pts
    138 
    139 # Plotting response distance
    140 # plot_resp1 distance
    141 # Plotting response maxheight
    142 # plot_resp1 maxheight
    143 # desc= The distance the projectile travels.
    144 # label= Distance
    145 
    146 # v=-0.610951707827365*angle**2 + 54.985653704463*angle - 217.610577363519
    147 
    148 # SURROGATE MODEL ERROR: 0.442%
    149 # desc= The maximum height the projectile reaches.
    150 # label= Maximum Height
    151 
    152 # v=3.42068544561648e-12*angle**2 + 8.66308066792632*angle - 134.909576819562
    153 
    154 # SURROGATE MODEL ERROR: 0.586%
    155 # [[  45.          254.92905324]
    156 #  [  30.19262971  128.95166845]
    157 #  [  59.80737029  380.90643804]
    158 #  [  34.52960806  163.81660645]
    159 #  [  55.47039194  346.04150004]]
     141    p['component.xy'] = pts
    160142
    161143
     
    180162        rout['value'] = rsp
    181163        rout['about.description'] = desc
    182         rout['about.label'] = label + ":UQ:5"
     164        rout['about.label'] = label
     165        rout['about.uqtype'] = 'Response'
    183166
    184167        rs = unpickle(rsp)
     
    247230
    248231
     232def write_sensitivity(io, h5):
     233    # If more than one variable, display sensitivity.
     234    # Curves have indexed variables, so skip them.
     235    if len(h5['/input/params']) > 1 and ['[' in x for x in h5[uqtype]].count(False):
     236        for v in h5[uqtype]:
     237            if '[' in v:
     238                # curve. skip it.
     239                continue
     240            desc = h5['/output/data/%s' % v].attrs['label']
     241            sens = unpickle(h5['/%s/%s/sensitivity' % (uqtype, v)].value)
     242
     243            hist = io['output.histogram(sens-%s)' % v]
     244            hist['about.label'] = desc
     245            hist['about.uqtype'] = 'Sensitivity'
     246            hist['about.type'] = 'scatter'
     247            hist['xaxis.label'] = 'Parameters'
     248            hist['yaxis.label'] = 'Sensitivity'
     249            pts = ''
     250            for name in sens:
     251                n = name[0]
     252                try:
     253                    n = h5['/input/params/%s' % n].attrs['label']
     254                except:
     255                    pass
     256                pts += "\"%s\" %s\n" % (n, name[1]['ustar'])
     257            hist['component.xy'] = pts
     258
    249259sw = load_from_hdf5(sys.argv[1])
    250260sw.analyze()
    251261
    252262h5 = h5py.File(sys.argv[1], 'r+')
    253 dtree = xml.parse('run_uq.xml')
    254 droot = dtree.getroot()
    255 dout = droot.find('output')
     263io = Rappture.PyXml('run_uq.xml')
    256264
    257265# curves built from pdfs
     
    260268acurves = {}
    261269
    262 reg1 = re.compile('([ \da-zA-Z]+)\[([ \d]+)\]')
     270reg1 = re.compile('([ \da-zA-Z_]+)\[([ \d]+)\]')
    263271
    264272uqtype = h5.attrs['UQtype']
     
    288296    else:
    289297        desc = h5['/output/data/%s' % v].attrs['label']
    290         plot_pdf(v, pdf, desc)
     298        plot_pdf(io, v, pdf, desc)
    291299
    292300# now do probability curves
    293301for vname in xvals:
    294     plot_pdf_curve(xvals, vname, 0)
    295     plot_pdf_curve(xvals, vname, 50)
    296     plot_pdf_curve(xvals, vname, 95)
     302    plot_pdf_curve(io, h5, xvals, vname, 95)
     303    plot_pdf_curve(io, h5, xvals, vname, 50)
    297304
    298305for vname in acurves:
    299     plot_pdf_acurve(h5, acurves, vname, 0)
    300     plot_pdf_acurve(h5, acurves, vname, 50)
    301     plot_pdf_acurve(h5, acurves, vname, 95)
    302 
    303 
    304 # If more than one variable, display sensitivity.
    305 # Curves have indexed variables, so skip them.
    306 if len(h5['/input/params']) > 1 and ['[' in x for x in h5[uqtype]].count(False):
    307     for v in h5[uqtype]:
    308         if '[' in v:
    309             continue
    310         desc = h5['/output/data/%s' % v].attrs['label']
    311         sens = unpickle(h5['/%s/%s/sensitivity' % (uqtype, v)].value)
    312         elem = xml.SubElement(dout, 'histogram', {'id': 'sens-%s' % v})
    313         about = xml.SubElement(elem, 'about')
    314         xml.SubElement(about, 'label').text = '%s:UQ:2' % desc
    315         xml.SubElement(elem, 'type').text = 'scatter'
    316         xaxis = xml.SubElement(elem, 'xaxis')
    317         xml.SubElement(xaxis, 'label').text = 'Parameters'
    318         yaxis = xml.SubElement(elem, 'yaxis')
    319         xml.SubElement(yaxis, 'label').text = 'Sensitivity'
    320         comp = xml.SubElement(elem, 'component')
    321         xy = xml.SubElement(comp, 'xy')
    322         pts = ''
    323         for name in sens:
    324             n = name[0]
    325             try:
    326                 n = h5['/input/params/%s' % n].attrs['label']
    327             except:
    328                 pass
    329             pts += "\"%s\" %s\n" % (n, name[1]['ustar'])
    330         xy.text = pts
    331 
    332 with open('run_uq.xml', 'w') as f:
    333     f.write("<?xml version=\"1.0\"?>\n")
    334     dtree.write(f)
    335 
    336 io = Rappture.PyXml('run_uq.xml')
     306    try:
     307        plot_pdf_acurve(io, h5, acurves, vname, 95)
     308    except:
     309        pass
     310    try:
     311        plot_pdf_acurve(io, h5, acurves, vname, 50)
     312    except:
     313        pass
     314
     315write_sensitivity(io, h5)
    337316write_responses(io, h5)
    338317write_summary(io, h5)
Note: See TracChangeset for help on using the changeset viewer.