Esempio n. 1
0
    def response_func(self):
        iters = self.iteration_num
        ndims = len(self.params)

        # calculate the optimal flat grid based on the hierarchal grid
        vecs = []
        for p in self.params:
            x = []
            for iteration in range(0, iters):
                x = np.concatenate((x, p.values[iteration]))
            last = None
            mindist = 1e309
            for v in sorted(x):
                if v != last:
                    if last != None:
                        mindist = min(mindist, v-last)
                    last = v
            debug("%s: %s %s grids" % (p.name, mindist,
                              (p.pdf.range[1] - p.pdf.range[0])/mindist))
            vecs.append(np.arange(p.pdf.range[0], p.pdf.range[1] + mindist, mindist))

        xx = meshgridn(*vecs)
        pts = np.vstack(map(np.ndarray.flatten, xx)).T

        # add column for results
        pts = np.append(pts, np.zeros((len(pts),1)), axis=1)

        # interpolate function requires array in contiguous memory
        if pts.flags['C_CONTIGUOUS'] == False:
            pts = np.ascontiguousarray(pts)

        self._uqsolver.interpolate(pts)
        return SampledFunc(pts, params=self.params)

        """
Esempio n. 2
0
def test_meshgrid_example():
    # official example for meshgrid() from numpy docs
    X, Y = meshgridn([1, 2, 3], [4, 5, 6, 7])
    assert (X == np.array([[1, 2, 3],
                           [1, 2, 3],
                           [1, 2, 3],
                           [1, 2, 3]])).all()

    assert (Y == np.array([[4, 4, 4],
                           [5, 5, 5],
                           [6, 6, 6],
                           [7, 7, 7]])).all()
Esempio n. 3
0
    def minmax(self):
        import heapq
        from scipy.optimize import fmin_l_bfgs_b
        dims = len(self.vars)
        if dims < 3:
            steps = 20
        elif dims < 5:
            steps = 10
        else:
            steps = 3

        d = []
        for v in self.vars:
            d.append(np.linspace(*v[1], num=steps))

        xx = meshgridn(*d)
        pts = np.vstack(map(np.ndarray.flatten, xx)).T
        res = self.evala(pts)
        if type(res) is not np.ndarray:
            return res, res

        h = []
        for i, p in enumerate(pts):
            if isinstance(p, np.ndarray):
                p = p.tolist()
            heapq.heappush(h, (res[i], p))

        bounds = [x[1] for x in self.vars]

        minval = float('inf')
        for p in heapq.nsmallest(5, h):
            pt, v, d = fmin_l_bfgs_b(self.evala,
                                     p[1],
                                     approx_grad=True,
                                     bounds=bounds)
            if d['warnflag'] == 0 and v < minval:
                minval = v

        maxval = float('inf')
        for p in heapq.nlargest(5, h):
            pt, v, d = fmin_l_bfgs_b(lambda x: -self.evala(x),
                                     p[1],
                                     approx_grad=True,
                                     bounds=bounds)
            if d['warnflag'] == 0 and v < maxval:
                maxval = v

        maxval = -maxval
        return minval, maxval
Esempio n. 4
0
    def _plot2(self, steps=40, legend=True, title=True, labels=True, **kwargs):
        # 2 dimensions plus result on Z-axis = 3D plot
        x = np.linspace(*self.vars[0][1], num=steps + 1)
        y = np.linspace(*self.vars[1][1], num=steps + 1)
        xx = meshgridn(x, y)
        pts = np.vstack(map(np.ndarray.flatten, xx)).T
        pts = np.array(self.evala(pts))

        fig = kwargs.get('fig')
        if fig is None:
            fig = plt.figure()

        ax = kwargs.get('ax')
        if ax is None:
            ax = Axes3D(fig, azim=30, elev=30)

        X, Y = xx
        Z = pts.reshape(X.shape)
        surf = ax.plot_surface(X,
                               Y,
                               Z,
                               rstride=1,
                               cstride=1,
                               cmap=cm.jet,
                               alpha=0.7,
                               linewidth=0)

        # legend
        if legend:
            fig.colorbar(surf, shrink=0.5)

        # titles
        xlab = self.vars[0][0]
        ylab = self.vars[1][0]
        if self.params:
            if xlab != self.params[0].description:
                xlab = "%s (%s)" % (xlab, self.params[0].description)
            if ylab != self.params[1].description:
                ylab = "%s (%s)" % (ylab, self.params[1].description)
        if labels:
            plt.xlabel(xlab)
            plt.ylabel(ylab)
        if title:
            plt.title('Response Plot')
        return ax
Esempio n. 5
0
    def minmax(self):
        import heapq
        from scipy.optimize import fmin_l_bfgs_b
        dims = len(self.vars)
        if dims < 3:
            steps = 20
        elif dims < 5:
            steps = 10
        else:
            steps = 3

        d = []
        for v in self.vars:
            d.append(np.linspace(*v[1], num=steps))

        xx = meshgridn(*d)
        pts = np.vstack(list(map(np.ndarray.flatten, xx))).T
        res = self.evala(pts)
        if type(res) is not np.ndarray:
            return res, res

        h = []
        for i, p in enumerate(pts):
            if isinstance(p, np.ndarray):
                p = p.tolist()
            heapq.heappush(h, (res[i], p))

        bounds = [x[1] for x in self.vars]

        minval = float('inf')
        for p in heapq.nsmallest(5, h):
            pt, v, d = fmin_l_bfgs_b(self.evala, p[1], approx_grad=True, bounds=bounds)
            if d['warnflag'] == 0 and v < minval:
                minval = v

        maxval = float('inf')
        for p in heapq.nlargest(5, h):
            pt, v, d = fmin_l_bfgs_b(lambda x: -self.evala(x), p[1], approx_grad=True, bounds=bounds)
            if d['warnflag'] == 0 and v < maxval:
                maxval = v

        maxval = -maxval
        return minval, maxval
Esempio n. 6
0
def test_meshgrid_4d():
    xx = meshgridn([1, 2], [3, 4], [5, 6], [7, 8])
    assert len(xx) == 4
    assert (np.vstack(map(np.ndarray.flatten, xx)).T ==
            np.array([[1, 3, 5, 7],
                      [2, 3, 5, 7],
                      [1, 4, 5, 7],
                      [2, 4, 5, 7],
                      [1, 3, 6, 7],
                      [2, 3, 6, 7],
                      [1, 4, 6, 7],
                      [2, 4, 6, 7],
                      [1, 3, 5, 8],
                      [2, 3, 5, 8],
                      [1, 4, 5, 8],
                      [2, 4, 5, 8],
                      [1, 3, 6, 8],
                      [2, 3, 6, 8],
                      [1, 4, 6, 8],
                      [2, 4, 6, 8]])).all()
Esempio n. 7
0
def test_meshgrid_4d():
    xx = meshgridn([1, 2], [3, 4], [5, 6], [7, 8])
    assert len(xx) == 4
    assert (np.vstack(map(np.ndarray.flatten, xx)).T == np.array([[1, 3, 5, 7],
                                                                  [2, 3, 5, 7],
                                                                  [1, 4, 5, 7],
                                                                  [2, 4, 5, 7],
                                                                  [1, 3, 6, 7],
                                                                  [2, 3, 6, 7],
                                                                  [1, 4, 6, 7],
                                                                  [2, 4, 6, 7],
                                                                  [1, 3, 5, 8],
                                                                  [2, 3, 5, 8],
                                                                  [1, 4, 5, 8],
                                                                  [2, 4, 5, 8],
                                                                  [1, 3, 6, 8],
                                                                  [2, 3, 6, 8],
                                                                  [1, 4, 6, 8],
                                                                  [2, 4, 6,
                                                                   8]])).all()
Esempio n. 8
0
    def _plot2(self, steps=40, legend=True, title=True, labels=True, **kwargs):
        # 2 dimensions plus result on Z-axis = 3D plot
        x = np.linspace(*self.vars[0][1], num=steps+1)
        y = np.linspace(*self.vars[1][1], num=steps+1)
        xx = meshgridn(x, y)
        pts = np.vstack(map(np.ndarray.flatten, xx)).T
        pts = np.array(self.evala(pts))

        fig = kwargs.get('fig')
        if fig is None:
            fig = plt.figure()

        ax = kwargs.get('ax')
        if ax is None:
            ax = Axes3D(fig, azim=30, elev=30)

        X, Y = xx
        Z = pts.reshape(X.shape)
        surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet, alpha=0.7, linewidth=0)

        # legend
        if legend:
            fig.colorbar(surf, shrink=0.5)

        # titles
        xlab = self.vars[0][0]
        ylab = self.vars[1][0]
        if self.params:
            if xlab != self.params[0].description:
                xlab = "%s (%s)" % (xlab, self.params[0].description)
            if ylab != self.params[1].description:
                ylab = "%s (%s)" % (ylab, self.params[1].description)
        if labels:
            plt.xlabel(xlab)
            plt.ylabel(ylab)
        if title:
            plt.title('Response Plot')
        return ax
Esempio n. 9
0
def test_meshgrid_1d():
    X = meshgridn([1, 2])
    assert len(X) == 1
    assert (X == np.array([1, 2])).all()
Esempio n. 10
0
def test_meshgrid_empty():
    X = meshgridn([])
    assert len(X) == 1
    assert len(X[0]) == 0
Esempio n. 11
0
def test_meshgrid_example():
    # official example for meshgrid() from numpy docs
    X, Y = meshgridn([1, 2, 3], [4, 5, 6, 7])
    assert (X == np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]])).all()

    assert (Y == np.array([[4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]])).all()
Esempio n. 12
0
def test_meshgrid_1d():
    X = meshgridn([1, 2])
    assert len(X) == 1
    assert (X == np.array([1, 2])).all()
Esempio n. 13
0
def test_meshgrid_empty():
    X = meshgridn([])
    assert len(X) == 1
    assert len(X[0]) == 0