Python numpy.linspace() Examples

The following are 30 code examples of numpy.linspace(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: figures.py    From pywr with GNU General Public License v3.0 7 votes vote down vote up
def plot_percentiles(A, B, ax=None):
    if ax is None:
        ax = plt.gca()
    percentiles = np.linspace(0.001, 0.999, 1000) * 100
    A_pct = scipy.stats.scoreatpercentile(A.values, percentiles)
    B_pct = scipy.stats.scoreatpercentile(B.values, percentiles)
    percentiles = percentiles / 100.0
    ax.plot(percentiles, B_pct[::-1], color=c["Bfill"], clip_on=False, linewidth=2)
    ax.plot(percentiles, A_pct[::-1], color=c["Afill"], clip_on=False, linewidth=2)
    ax.set_xlabel("Cumulative frequency")
    ax.grid(True)
    ax.xaxis.grid(True, which="both")
    set_000formatter(ax.get_yaxis())
    ax.set_xscale("logit")
    xticks = ax.get_xticks()
    xticks_minr = ax.get_xticks(minor=True)
    ax.set_xticklabels([], minor=True)
    ax.set_xticks([0.01, 0.1, 0.5, 0.9, 0.99])
    ax.set_xticklabels(["1", "10", "50", "90", "99"])
    ax.set_xlim(0.001, 0.999)
    ax.legend([B.name, A.name], loc="best")
    return ax 
Example #2
Source File: test_PostProcessing.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_FAdMag0_fits(self):
        # get fits file path for FAdMag0 test
        classpath = os.path.split(inspect.getfile(self.__class__))[0]
        FAdMag0Path = os.path.join(classpath,'test_PostProcessing_FAdMag0.fits')

        # fits file has values for WA in [0.1, 0.2] and FAdMag0 in [10, 20]
        testWA = np.linspace(0.1, 0.2, 100)*u.arcsec

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(FAdMag0=FAdMag0Path,**self.specs)

            vals = obj.FAdMag0(testWA)

            self.assertTrue(np.all(vals >= 10),'value below range of FAdMag0 for %s'%mod.__name__)
            self.assertTrue(np.all(vals <= 20),'value above range of FAdMag0 for %s'%mod.__name__) 
Example #3
Source File: spectrum.py    From StructEngPy with MIT License 6 votes vote down vote up
def __init__(self,alpha_max,Tg,xi):
        gamma=0.9+(0.05-xi)/(0.3+6*xi)
        eta1=0.02+(0.05-xi)/(4+32*xi)
        eta1=eta1 if eta1>0 else 0
        eta2=1+(0.05-xi)/(0.08+1.6*xi)
        eta2=eta2 if eta2>0.55 else 0.55
        T=np.linspace(0,6,601)
        alpha=[]
        for t in T:
            if t<0.1:
                alpha.append(np.interp(t,[0,0.1],[0.45*alpha_max,eta2*alpha_max]))
            elif t<Tg:
                alpha.append(eta2*alpha_max)
            elif t<5*Tg:
                alpha.append((Tg/t)**gamma*eta2*alpha_max)
            else:
                alpha.append((eta2*0.2**gamma-eta1*(t-5*Tg))*alpha_max)
        self.__spectrum={'T':T,'alpha':alpha} 
Example #4
Source File: test_bayestar.py    From dustmaps with GNU General Public License v2.0 6 votes vote down vote up
def atest_plot_samples(self):
        dm = np.linspace(4., 19., 1001)
        samples = []

        for dm_k in dm:
            d = 10.**(dm_k/5.-2.)
            samples.append(self._interp_ebv(self._test_data[0], d))

        samples = np.array(samples).T
        # print samples

        import matplotlib.pyplot as plt
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        for s in samples:
            ax.plot(dm, s, lw=2., alpha=0.5)

        plt.show() 
Example #5
Source File: region_proposal_network.py    From easy-faster-rcnn.pytorch with MIT License 6 votes vote down vote up
def generate_anchors(self, image_width: int, image_height: int, num_x_anchors: int, num_y_anchors: int) -> Tensor:
        center_ys = np.linspace(start=0, stop=image_height, num=num_y_anchors + 2)[1:-1]
        center_xs = np.linspace(start=0, stop=image_width, num=num_x_anchors + 2)[1:-1]
        ratios = np.array(self._anchor_ratios)
        ratios = ratios[:, 0] / ratios[:, 1]
        sizes = np.array(self._anchor_sizes)

        # NOTE: it's important to let `center_ys` be the major index (i.e., move horizontally and then vertically) for consistency with 2D convolution
        # giving the string 'ij' returns a meshgrid with matrix indexing, i.e., with shape (#center_ys, #center_xs, #ratios)
        center_ys, center_xs, ratios, sizes = np.meshgrid(center_ys, center_xs, ratios, sizes, indexing='ij')

        center_ys = center_ys.reshape(-1)
        center_xs = center_xs.reshape(-1)
        ratios = ratios.reshape(-1)
        sizes = sizes.reshape(-1)

        widths = sizes * np.sqrt(1 / ratios)
        heights = sizes * np.sqrt(ratios)

        center_based_anchor_bboxes = np.stack((center_xs, center_ys, widths, heights), axis=1)
        center_based_anchor_bboxes = torch.from_numpy(center_based_anchor_bboxes).float()
        anchor_bboxes = BBox.from_center_base(center_based_anchor_bboxes)

        return anchor_bboxes 
Example #6
Source File: test_DulzPlavchan.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dist_albedo(self):
        """
        Test that albedos outside of the range have zero probability

        """

        spec = copy.deepcopy(self.spec)
        spec['modules']['PlanetPhysicalModel'] = 'FortneyMarleyCahoyMix1'
        with RedirectStreams(stdout=self.dev_null):
            pp = DulzPlavchan(**spec)

        p = np.linspace(pp.prange[0]-1,pp.prange[1]+1,100)

        fp = pp.dist_albedo(p)
        self.assertTrue(np.all(fp[p < pp.prange[0]] == 0),'dist_albedo high bound failed for DulzPlavchan')
        self.assertTrue(np.all(fp[p > pp.prange[1]] == 0),'dist_albedo low bound failed for DulzPlavchan')
        self.assertTrue(np.all(fp[(p >= pp.prange[0]) & (p <= pp.prange[1])] > 0),'dist_albedo generates zero probabilities within range for DulzPlavchan') 
Example #7
Source File: test_topfarm.py    From TOPFARM with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_2x3(self):
        # Loading the water depth map
        dat = loadtxt('data/WaterDepth1.dat')
        X, Y = meshgrid(linspace(0., 1000., 50), linspace(0., 1000., 50))
        depth = array(zip(X.flatten(), Y.flatten(), dat.flatten()))
        borders = array([[200, 200], [150, 500], [200, 800], [600, 900], [700, 700], [900, 500], [800, 200], [500, 100], [200, 200]])
        baseline = array([[587.5, 223.07692308], [525., 346.15384615], [837.5, 530.76923077], [525., 530.76923077], [525., 838.46153846], [837.5, 469.23076923]])

        wt_desc = WTDescFromWTG('data/V80-2MW-offshore.wtg').wt_desc
        wt_layout = GenericWindFarmTurbineLayout([WTPC(wt_desc=wt_desc, position=pos) for pos in baseline])

        t = Topfarm(
            baseline_layout = wt_layout,
            borders = borders,
            depth_map = depth,
            dist_WT_D = 5.0,
            distribution='spiral',
            wind_speeds=[4., 8., 20.],
            wind_directions=linspace(0., 360., 36)[:-1]
        )

        t.run()

        self.fail('make save function')
        t.save() 
Example #8
Source File: test_PlanetPopulation.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dist_eccen(self):
        """
        Test that eccentricities outside of the range have zero probability

        """
        for mod in self.allmods:
            if 'dist_eccen' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    pp = mod(**self.spec)

                e = np.linspace(pp.erange[0]-1,pp.erange[1]+1,100)

                fe = pp.dist_eccen(e)
                self.assertTrue(np.all(fe[e < pp.erange[0]] == 0),'dist_eccen high bound failed for %s'%mod.__name__)
                self.assertTrue(np.all(fe[e > pp.erange[1]] == 0),'dist_eccen low bound failed for %s'%mod.__name__)
                self.assertTrue(np.all(fe[(e >= pp.erange[0]) & (e <= pp.erange[1])] > 0),'dist_eccen generates zero probabilities within range for %s'%mod.__name__) 
Example #9
Source File: doa.py    From FRIDA with MIT License 6 votes vote down vote up
def compute_mode(self):
        """
        Pre-compute mode vectors from candidate locations (in spherical 
        coordinates).
        """
        if self.num_loc is None:
            raise ValueError('Lookup table appears to be empty. \
                Run build_lookup().')
        self.mode_vec = np.zeros((self.max_bin,self.M,self.num_loc), 
            dtype='complex64')
        if (self.nfft % 2 == 1):
            raise ValueError('Signal length must be even.')
        f = 1.0 / self.nfft * np.linspace(0, self.nfft / 2, self.max_bin) \
            * 1j * 2 * np.pi
        for i in range(self.num_loc):
            p_s = self.loc[:, i]
            for m in range(self.M):
                p_m = self.L[:, m]
                if (self.mode == 'near'):
                    dist = np.linalg.norm(p_m - p_s, axis=1)
                if (self.mode == 'far'):
                    dist = np.dot(p_s, p_m)
                # tau = np.round(self.fs*dist/self.c) # discrete - jagged
                tau = self.fs * dist / self.c  # "continuous" - smoother
                self.mode_vec[:, m, i] = np.exp(f * tau) 
Example #10
Source File: test_PlanetPopulation.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dist_albedo(self):
        """
        Test that albedos outside of the range have zero probability

        """

        exclude_mods = ['KeplerLike1',  'AlbedoByRadiusDulzPlavchan',  'DulzPlavchan']
        for mod in self.allmods:
            if (mod.__name__ not in exclude_mods) and ('dist_albedo' in mod.__dict__):
                with RedirectStreams(stdout=self.dev_null):
                    pp = mod(**self.spec)

                p = np.linspace(pp.prange[0]-1,pp.prange[1]+1,100)

                fp = pp.dist_albedo(p)
                self.assertTrue(np.all(fp[p < pp.prange[0]] == 0),'dist_albedo high bound failed for %s'%mod.__name__)
                self.assertTrue(np.all(fp[p > pp.prange[1]] == 0),'dist_albedo low bound failed for %s'%mod.__name__)
                self.assertTrue(np.all(fp[(p >= pp.prange[0]) & (p <= pp.prange[1])] > 0),'dist_albedo generates zero probabilities within range for %s'%mod.__name__) 
Example #11
Source File: test_PostProcessing.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ppFact_fits(self):
        # get fits file path for ppFact test
        classpath = os.path.split(inspect.getfile(self.__class__))[0]
        ppFactPath = os.path.join(classpath,'test_PostProcessing_ppFact.fits')

        # fits file has values for WA in [0.1,0.2]
        testWA = np.linspace(0.1,0.2,100)*u.arcsec

        for mod in self.allmods:
            with RedirectStreams(stdout=self.dev_null):
                obj = mod(ppFact=ppFactPath,**self.specs)

            vals = obj.ppFact(testWA)

            self.assertTrue(np.all(vals > 0),'negative value of ppFact for %s'%mod.__name__)
            self.assertTrue(np.all(vals <= 1),'ppFact > 1 for %s'%mod.__name__) 
Example #12
Source File: test_xrft.py    From xrft with MIT License 6 votes vote down vote up
def test_cross_phase_2d(self, dask):
        Ny, Nx = (32, 16)
        x = np.linspace(0, 1, num=Nx, endpoint=False)
        y = np.ones(Ny)
        f = 6
        phase_offset = np.pi/2
        signal1 = np.cos(2*np.pi*f*x)  # frequency = 1/(2*pi)
        signal2 = np.cos(2*np.pi*f*x - phase_offset)
        da1 = xr.DataArray(data=signal1*y[:,np.newaxis], name='a',
                          dims=['y','x'], coords={'y':y, 'x':x})
        da2 = xr.DataArray(data=signal2*y[:,np.newaxis], name='b',
                          dims=['y','x'], coords={'y':y, 'x':x})
        with pytest.raises(ValueError):
            xrft.cross_phase(da1, da2, dim=['y','x'])

        if dask:
            da1 = da1.chunk({'x': 16})
            da2 = da2.chunk({'x': 16})
        cp = xrft.cross_phase(da1, da2, dim=['x'])
        actual_phase_offset = cp.sel(freq_x=f).values
        npt.assert_almost_equal(actual_phase_offset, phase_offset) 
Example #13
Source File: thames.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
def figures(ext, show):

    for name, df in TablesRecorder.generate_dataframes('thames_output.h5'):
        df.columns = ['Very low', 'Low', 'Central', 'High', 'Very high']

        fig, (ax1, ax2) = plt.subplots(figsize=(12, 4), ncols=2, sharey='row',
                                       gridspec_kw={'width_ratios': [3, 1]})
        df['2100':'2125'].plot(ax=ax1)
        df.quantile(np.linspace(0, 1)).plot(ax=ax2)

        if name.startswith('reservoir'):
            ax1.set_ylabel('Volume [$Mm^3$]')
        else:
            ax1.set_ylabel('Flow [$Mm^3/day$]')

        for ax in (ax1, ax2):
            ax.set_title(name)
            ax.grid(True)
        plt.tight_layout()

        if ext is not None:
            fig.savefig(f'{name}.{ext}', dpi=300)

    if show:
        plt.show() 
Example #14
Source File: FakeCatalog.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def inverse_method(self,N,d):
        
        t = np.linspace(1e-3,0.999,N)
        f = np.log( t / (1 - t) )
        f = f/f[0]
        
        psi= np.pi*f
        cosPsi = np.cos(psi)
        sinTheta = ( np.abs(cosPsi) + (1-np.abs(cosPsi))*np.random.rand(len(cosPsi)))
        
        theta = np.arcsin(sinTheta)
        theta = np.pi-theta + (2*theta - np.pi)*np.round(np.random.rand(len(t)))
        cosPhi = cosPsi/sinTheta
        phi = np.arccos(cosPhi)*(-1)**np.round(np.random.rand(len(t)))
        
        coords = SkyCoord(phi*u.rad,(np.pi/2-theta)*u.rad,d*np.ones(len(phi))*u.pc)

        return coords 
Example #15
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def curve_length(self, start=None, end=None, precision=0.01):
        '''
        Calculates the length of the curve by dividing the curve up
        into pieces of parameterized-length <precision>.
        '''
        if start is None: start = self.t[0]
        if end is None: end = self.t[-1]
        from scipy import interpolate
        if self.order == 1:
            # we just want to add up along the steps...
            ii = [ii for (ii,t) in enumerate(self.t) if start < t and t < end]
            ts = np.concatenate([[start], self.t[ii], [end]])
            xy = np.vstack([[self(start)], self.coordinates[:,ii].T, [self(end)]])
            return np.sum(np.sqrt(np.sum((xy[1:] - xy[:-1])**2, axis=1)))
        else:
            t = np.linspace(start, end, int(np.ceil((end-start)/precision)))
            dt = t[1] - t[0]
            dx = interpolate.splev(t, self.splrep[0], der=1)
            dy = interpolate.splev(t, self.splrep[1], der=1)
            return np.sum(np.sqrt(dx**2 + dy**2)) * dt 
Example #16
Source File: xrft.py    From xrft with MIT License 6 votes vote down vote up
def _radial_wvnum(k, l, N, nfactor):
    """ Creates a radial wavenumber based on two horizontal wavenumbers
    along with the appropriate index map
    """

    # compute target wavenumbers
    k = k.values
    l = l.values
    K = np.sqrt(k[np.newaxis,:]**2 + l[:,np.newaxis]**2)
    nbins = int(N/nfactor)
    if k.max() > l.max():
        ki = np.linspace(0., l.max(), nbins)
    else:
        ki = np.linspace(0., k.max(), nbins)

    # compute bin index
    kidx = np.digitize(np.ravel(K), ki)
    # compute number of points for each wavenumber
    area = np.bincount(kidx)
    # compute the average radial wavenumber for each bin
    kr = (np.bincount(kidx, weights=K.ravel())
          / np.ma.masked_where(area==0, area))

    return ki, kr[1:-1] 
Example #17
Source File: test_Observatory.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_cent(self):
        r"""Test cent method.

        Approach: Probes for a range of inputs.
        """

        print('cent()')
        obs = self.fixture
        # origin at 12:00 on 2000.Jan.01
        t_ref_string = '2000-01-01T12:00:00.0'
        t_ref = Time(t_ref_string, format='isot', scale='utc')
        self.assertEqual(obs.cent(t_ref), 0.0)

        # even-julian-year probes
        t_probe = np.linspace(1950.0, 2050.0, 101)
        for t_ref in t_probe:
            # get the Time object, required by the cent() method
            t_probe_2 = Time(t_ref, format='jyear')
            # exosims century (offset from 2000)
            t_exo = obs.cent(t_probe_2)
            # reference century
            t_ref_cent = (t_ref - 2000.0) / 100.0
            # they are not exactly equal
            self.assertAlmostEqual(t_exo, t_ref_cent, places=10) 
Example #18
Source File: test_recorders.py    From pywr with GNU General Public License v3.0 5 votes vote down vote up
def test_sdc_recorder():
    """
    Test the StorageDurationCurveRecorder
    """
    model = load_model("timeseries3.json")
    inpt = model.nodes['catchment1']
    strg = model.nodes['reservoir1']

    percentiles = np.linspace(20., 100., 5)
    flow_rec = NumpyArrayNodeRecorder(model, inpt)
    rec = StorageDurationCurveRecorder(model, strg, percentiles, temporal_agg_func="max", agg_func="min")

    # test retrieval of recorder
    assert model.recorders['storagedurationcurverecorder.reservoir1'] == rec

    model.run()

    # Manually calculate expected storage and percentiles
    strg_volume = strg.initial_volume + np.cumsum(flow_rec.data - 23.0, axis=0)
    strg_pciles = np.percentile(strg_volume, percentiles, axis=0)

    assert_allclose(rec.sdc, strg_pciles)
    assert_allclose(np.max(rec.sdc, axis=0), rec.values())
    assert_allclose(np.min(np.max(rec.sdc, axis=0)), rec.aggregated_value())

    assert rec.sdc.shape == (len(percentiles), len(model.scenarios.combinations))
    df = rec.to_dataframe()
    assert df.shape == (len(percentiles), len(model.scenarios.combinations)) 
Example #19
Source File: test_recorders.py    From pywr with GNU General Public License v3.0 5 votes vote down vote up
def test_fdc_recorder(self, agg_func):
        """
        Test the FlowDurationCurveRecorder
        """
        model = load_model("timeseries2.json")
        input = model.nodes['catchment1']

        percentiles = np.linspace(20., 100., 5)
        rec = FlowDurationCurveRecorder(model, input, percentiles, temporal_agg_func=agg_func, agg_func="min")

        # test retrieval of recorder
        assert model.recorders['flowdurationcurverecorder.catchment1'] == rec
        # test changing name of recorder
        rec.name = 'timeseries.Input'
        assert model.recorders['timeseries.Input'] == rec
        with pytest.raises(KeyError):
            model.recorders['flowdurationcurverecorder.catchment1']

        model.run()

        func = TestAggregatedRecorder.funcs[agg_func]

        assert_allclose(rec.fdc[:, 0], [20.42,  21.78,  23.22,  26.47,  29.31])
        assert_allclose(func(rec.fdc, axis=0), rec.values())
        assert_allclose(np.min(func(rec.fdc, axis=0)), rec.aggregated_value())

        assert rec.fdc.shape == (len(percentiles), len(model.scenarios.combinations))
        df = rec.to_dataframe()
        assert df.shape == (len(percentiles), len(model.scenarios.combinations)) 
Example #20
Source File: cocoeval.py    From cascade-rcnn_Pytorch with MIT License 5 votes vote down vote up
def setKpParams(self):
        self.imgIds = []
        self.catIds = []
        # np.arange causes trouble.  the data point on arange is slightly larger than the true value
        self.iouThrs = np.linspace(.5, 0.95, np.round((0.95 - .5) / .05) + 1, endpoint=True)
        self.recThrs = np.linspace(.0, 1.00, np.round((1.00 - .0) / .01) + 1, endpoint=True)
        self.maxDets = [20]
        self.areaRng = [[0 ** 2, 1e5 ** 2], [32 ** 2, 96 ** 2], [96 ** 2, 1e5 ** 2]]
        self.areaRngLbl = ['all', 'medium', 'large']
        self.useCats = 1 
Example #21
Source File: thames.py    From pywr with GNU General Public License v3.0 5 votes vote down vote up
def plot_res2(ext, show):

    end_year = '2105'

    data = {}
    for name, df in TablesRecorder.generate_dataframes('thames_output.h5'):
        df.columns = ['Very low', 'Low', 'Central', 'High', 'Very high']
        data[name] = df

    fig1, ax1 = plt.subplots(figsize=(16, 5), dpi=300)
    data['reservoir1'].loc[:end_year].plot(ax=ax1)
    ax1.set_ylabel('Volume [$Mm^3$]')
    plt.legend()
    plt.tight_layout()

    fig2, ax2 = plt.subplots(figsize=(16, 5), dpi=300)
    data['reservoir1'].quantile(np.linspace(0, 1)).plot(ax=ax2)
    ax2.set_ylabel('Volume [$Mm^3$]')
    ax2.set_xlabel('Quantile')
    plt.tight_layout()

    fig3, ax3 = plt.subplots(figsize=(16, 5), dpi=300)
    df = data['demand_saving_level'].apply(pandas.Series.value_counts)
    df /= df.sum(axis=0)
    df.plot.bar(ax=ax3)
    ax3.set_ylabel('Proportion of time.')
    ax3.set_xlabel('Demand saving level')
    plt.tight_layout()

    for ax in (ax1, ax2, ax3):
        ax.grid(True)

    if ext is not None:
        fig1.savefig(f'Reservoir (scenarios).{ext}', dpi=300)
        fig2.savefig(f'Reservoir SDC (scenarios).{ext}', dpi=300)
        fig3.savefig(f'Demand saving level count (scenarios).{ext}', dpi=300)

    if show:
        plt.show() 
Example #22
Source File: expt_design.py    From ernest with Apache License 2.0 5 votes vote down vote up
def _get_training_points(self):
        '''Enumerate all the training points given the params for experiment design'''
        mcs_range = xrange(self.mcs_min, self.mcs_max + 1)

        scale_min = float(self.parts_min) / float(self.total_parts)
        scale_max = float(self.parts_max) / float(self.total_parts)
        scale_range = np.linspace(scale_min, scale_max, self.num_parts_interpolate)

        for scale in scale_range:
            for mcs in mcs_range:
                if np.round(scale * self.total_parts) >= self.cores_per_mc * mcs:
                    yield [scale, mcs] 
Example #23
Source File: regression.py    From Kaggler with MIT License 5 votes vote down vote up
def gini(y, p):
    """Normalized Gini Coefficient.

    Args:
        y (numpy.array): target
        p (numpy.array): prediction

    Returns:
        e (numpy.float64): normalized Gini coefficient
    """

    # check and get number of samples
    assert y.shape == p.shape

    n_samples = y.shape[0]

    # sort rows on prediction column
    # (from largest to smallest)
    arr = np.array([y, p]).transpose()
    true_order = arr[arr[:, 0].argsort()][::-1, 0]
    pred_order = arr[arr[:, 1].argsort()][::-1, 0]

    # get Lorenz curves
    l_true = np.cumsum(true_order) / np.sum(true_order)
    l_pred = np.cumsum(pred_order) / np.sum(pred_order)
    l_ones = np.linspace(1/n_samples, 1, n_samples)

    # get Gini coefficients (area between curves)
    g_true = np.sum(l_ones - l_true)
    g_pred = np.sum(l_ones - l_pred)

    # normalize to true Gini coefficient
    return g_pred / g_true 
Example #24
Source File: test_parameters.py    From pywr with GNU General Public License v3.0 5 votes vote down vote up
def test_uniform_drawdown_profile(self, simple_linear_model):
        """Test the uniform drawn profile over a leap year and non-leap year."""

        m = simple_linear_model
        m.timestepper.start = '2015-04-01'
        m.timestepper.end = '2017-04-01'

        expected_values = np.r_[
            np.linspace(1, 1/366, 366),  # This period covers Apr-2015 to Apr-2016 (i.e. 366 days)
            np.linspace(1, 1/365, 365),  # This period covers Apr-2016 to Apr-2017 (i.e. 365 days)
            np.linspace(1, 1/365, 365),  # This period covers Apr-2017 to Apr-2018 (i.e. 365 days)
        ]

        data = {
            'type': 'uniformdrawdownprofile',
            "reset_day": 1,
            "reset_month": 4
        }

        p = load_parameter(m, data)

        @assert_rec(m, p)
        def expected_func(timestep, scenario_index):
            return expected_values[timestep.index]

        m.run() 
Example #25
Source File: tutorial.py    From TOPFARM with GNU Affero General Public License v3.0 5 votes vote down vote up
def contour_plot(func):
    rose = func()
    XS, YS = plt.meshgrid(np.linspace(-2, 2, 20), np.linspace(-2,2, 20));
    ZS = np.array([rose(x1=x, x2=y).f_xy for x,y in zip(XS.flatten(),YS.flatten())]).reshape(XS.shape);
    plt.contourf(XS, YS, ZS, 50);
    plt.colorbar() 
Example #26
Source File: examples.py    From numpynet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_activations():
    for activation in common.Activation.available:
        x = np.linspace(-10.0, 10.0, 100)
        y = common.Activation(activation).function(x, deriv=False)
        dy = common.Activation(activation).function(x, deriv=True)
        viz_client.plot_func(x, y, title=activation)
        viz_client.plot_func(x, dy, title="d_" + activation)


# TODO write this! 
Example #27
Source File: eval.py    From kitti-object-eval-python with MIT License 5 votes vote down vote up
def do_coco_style_eval(gt_annos,
                       dt_annos,
                       current_classes,
                       overlap_ranges,
                       compute_aos,
                       z_axis=1,
                       z_center=1.0):
    # overlap_ranges: [range, metric, num_class]
    min_overlaps = np.zeros([10, *overlap_ranges.shape[1:]])
    for i in range(overlap_ranges.shape[1]):
        for j in range(overlap_ranges.shape[2]):
            min_overlaps[:, i, j] = np.linspace(*overlap_ranges[:, i, j])
    mAP_bbox, mAP_bev, mAP_3d, mAP_aos = do_eval_v2(
        gt_annos,
        dt_annos,
        current_classes,
        min_overlaps,
        compute_aos,
        z_axis=z_axis,
        z_center=z_center)
    # ret: [num_class, num_diff, num_minoverlap]
    mAP_bbox = mAP_bbox.mean(-1)
    mAP_bev = mAP_bev.mean(-1)
    mAP_3d = mAP_3d.mean(-1)
    if mAP_aos is not None:
        mAP_aos = mAP_aos.mean(-1)
    return mAP_bbox, mAP_bev, mAP_3d, mAP_aos 
Example #28
Source File: utils.py    From pruning_yolov3 with GNU General Public License v3.0 5 votes vote down vote up
def compute_ap(recall, precision):
    """ Compute the average precision, given the recall and precision curves.
    Source: https://github.com/rbgirshick/py-faster-rcnn.
    # Arguments
        recall:    The recall curve (list).
        precision: The precision curve (list).
    # Returns
        The average precision as computed in py-faster-rcnn.
    """

    # Append sentinel values to beginning and end
    mrec = np.concatenate(([0.], recall, [min(recall[-1] + 1E-3, 1.)]))
    mpre = np.concatenate(([0.], precision, [0.]))

    # Compute the precision envelope
    for i in range(mpre.size - 1, 0, -1):
        mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])

    # Integrate area under curve
    method = 'interp'  # methods: 'continuous', 'interp'
    if method == 'interp':
        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)
        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate
    else:  # 'continuous'
        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x axis (recall) changes
        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve

    return ap 
Example #29
Source File: fermionic_simulation_test.py    From OpenFermion-Cirq with Apache License 2.0 5 votes vote down vote up
def test_weights_and_exponent(weights):
    exponents = np.linspace(-1, 1, 8)
    gates = tuple(
        ofc.QuarticFermionicSimulationGate(
            weights / exponent, exponent=exponent, absorb_exponent=True)
        for exponent in exponents)

    for g1, g2 in itertools.combinations(gates, 2):
        assert cirq.approx_eq(g1, g2, atol=1e-100)

    for i, (gate, exponent) in enumerate(zip(gates, exponents)):
        assert gate.exponent == 1
        new_exponent = exponents[-i]
        new_gate = gate._with_exponent(new_exponent)
        assert new_gate.exponent == new_exponent 
Example #30
Source File: viz.py    From libTLDA with MIT License 5 votes vote down vote up
def plotc(parameters, ax=[], color='k', gridsize=(101, 101)):
    """
    Plot a linear classifier in a 2D scatterplot.

    INPUT   (1) tuple 'parameters': consists of a list of class proportions
                (1 by K classes), an array of class means (K classes by
                D features), an array of class-covariance matrices (D features
                by D features by K classes)
            (2) object 'ax': axes of a pyplot figure or subject (def: empty)
            (3) str 'colors': colors of the contours in the plot (def: 'k')
            (4) tuple 'gridsize': number of points in the grid
                (def: (101, 101))
    OUTPUT  None
    """
    # Check for figure object
    if fig:
        ax = fig.gca()
    else:
        fig, ax = plt.subplots()

    # Get axes limits
    xl = ax.get_xlim()
    yl = ax.get_ylim()

    # Define grid
    gx = np.linspace(xl[0], xl[1], gridsize[0])
    gy = np.linspace(yl[0], yl[1], gridsize[1])
    x, y = np.meshgrid(gx, gy)
    xy = np.vstack((x.ravel(), y.ravel())).T

    # Values of grid
    z = np.dot(xy, parameters[:-1, :]) + parameters[-1, :]
    z = np.reshape(z[:, 0] - z[:, 1], gridsize)

    # Plot grid
    ax.contour(x, y, z, levels=0, colors=colors)