• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python moves.range函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sunpy.extern.six.moves.range函数的典型用法代码示例。如果您正苦于以下问题:Python range函数的具体用法?Python range怎么用?Python range使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了range函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _resample_nearest_linear

def _resample_nearest_linear(orig, dimensions, method, offset, m1):
    """Resample Map using either linear or nearest interpolation."""

    dimlist = []

    # calculate new dims
    for i in range(orig.ndim):
        base = np.arange(dimensions[i])
        dimlist.append((orig.shape[i] - m1) / (dimensions[i] - m1) *
                       (base + offset) - offset)

    # specify old coordinates
    old_coords = [np.arange(i, dtype=np.float) for i in orig.shape]

    # first interpolation - for ndims = any
    mint = scipy.interpolate.interp1d(old_coords[-1], orig, bounds_error=False,
                                      fill_value=min(old_coords[-1]), kind=method)

    new_data = mint(dimlist[-1])

    trorder = [orig.ndim - 1] + list(range(orig.ndim - 1))
    for i in range(orig.ndim - 2, -1, -1):
        new_data = new_data.transpose(trorder)

        mint = scipy.interpolate.interp1d(old_coords[i], new_data,
            bounds_error=False, fill_value=min(old_coords[i]), kind=method)
        new_data = mint(dimlist[i])

    if orig.ndim > 1:
        # need one more transpose to return to original dimensions
        new_data = new_data.transpose(trorder)

    return new_data
开发者ID:ChrisIAm101,项目名称:sunpy,代码行数:33,代码来源:rescale.py


示例2: __init__

    def __init__(self, data, image_axes=[-2, -1], axis_ranges=None, **kwargs):

        all_axes = list(range(self.naxis))
        # Handle negative indexes
        self.image_axes = [all_axes[i] for i in image_axes]

        slider_axes = list(range(self.naxis))
        for x in self.image_axes:
            slider_axes.remove(x)

        if len(slider_axes) != self.num_sliders:
            raise ValueError("Specific the same number of axes as sliders!")
        self.slider_axes = slider_axes

        # Verify that combined slider_axes and image_axes make all axes
        ax = self.slider_axes + self.image_axes
        ax.sort()
        if ax != list(range(self.naxis)):
            raise ValueError("spatial_axes and slider_axes mismatch")

        self.axis_ranges = self._sanitize_axis_ranges(axis_ranges, data)

        # create data slice
        self.frame_slice = [slice(None)] * self.naxis
        for i in self.slider_axes:
            self.frame_slice[i] = 0

        base_kwargs = {'slider_functions': [self.update_plot] * self.num_sliders,
                       'slider_ranges': [self.axis_ranges[i] for i in self.slider_axes]}
        base_kwargs.update(kwargs)
        BaseFuncAnimator.__init__(self, data, **base_kwargs)
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:31,代码来源:imageanimator.py


示例3: randomized_auto_const_bg

    def randomized_auto_const_bg(self, amount):
        """Automatically determine background. Only consider a randomly
        chosen subset of the image.

        Parameters
        ----------
        amount : int
            Size of random sample that is considered for calculation of
            the background.
        """
        cols = [randint(0, self.shape[1] - 1) for _ in range(amount)]

        # pylint: disable=E1101,E1103
        data = self.data.astype(to_signed(self.dtype))
        # Subtract average value from every frequency channel.
        tmp = (data - np.average(self.data, 1).reshape(self.shape[0], 1))
        # Get standard deviation at every point of time.
        # Need to convert because otherwise this class's __getitem__
        # is used which assumes two-dimensionality.
        tmp = tmp[:, cols]
        sdevs = np.asarray(np.std(tmp, 0))

        # Get indices of values with lowest standard deviation.
        cand = sorted(range(amount), key=lambda y: sdevs[y])
        # Only consider the best 5 %.
        realcand = cand[:max(1, int(0.05 * len(cand)))]

        # Average the best 5 %
        bg = np.average(self[:, [cols[r] for r in realcand]], 1)

        return bg.reshape(self.shape[0], 1)
开发者ID:Alex-Ian-Hamilton,项目名称:sunpy,代码行数:31,代码来源:spectrogram.py


示例4: test_apply_shifts

def test_apply_shifts(aia171_test_map):
    # take two copies of the AIA image and create a test mapcube.
    mc = map.Map([aia171_test_map, aia171_test_map], cube=True)

    # Pixel displacements have the y-displacement as the first entry
    numerical_displacements = {"x": np.asarray([0.0, -2.7]), "y": np.asarray([0.0, -10.4])}
    astropy_displacements = {"x": numerical_displacements["x"] * u.pix,
                             "y": numerical_displacements["y"] * u.pix}

    # Test to see if the code can detect the fact that the input shifts are not
    # astropy quantities
    with pytest.raises(TypeError):
        tested = apply_shifts(mc, numerical_displacements["y"], astropy_displacements["x"])
    with pytest.raises(TypeError):
        tested = apply_shifts(mc, astropy_displacements["y"], numerical_displacements["x"])
    with pytest.raises(TypeError):
        tested = apply_shifts(mc, numerical_displacements["y"], numerical_displacements["x"])

    # Test returning with no extra options - the code returns a mapcube only
    test_output = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"])
    assert(isinstance(test_output, map.MapCube))

    # Test returning with no clipping.  Output layers should have the same size
    # as the original input layer.
    test_mc = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"], clip=False)
    assert(test_mc[0].data.shape == aia171_test_map.data.shape)
    assert(test_mc[1].data.shape == aia171_test_map.data.shape)

    # Test returning with clipping.  Output layers should be smaller than the
    # original layer by a known amount.
    test_mc = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"],  clip=True)
    for i in range(0, len(test_mc.maps)):
        clipped = calculate_clipping(astropy_displacements["y"], astropy_displacements["x"])
        assert(test_mc[i].data.shape[0] == mc[i].data.shape[0] - np.max(clipped[0].value))
        assert(test_mc[i].data.shape[1] == mc[i].data.shape[1] - np.max(clipped[1].value))

    # Test returning with default clipping.  The default clipping is set to
    # true, that is the mapcube is clipped.  Output layers should be smaller
    # than the original layer by a known amount.
    test_mc = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"])
    for i in range(0, len(test_mc.maps)):
        clipped = calculate_clipping(astropy_displacements["y"], astropy_displacements["x"])
        assert(test_mc[i].data.shape[0] == mc[i].data.shape[0] - np.max(clipped[0].value))
        assert(test_mc[i].data.shape[1] == mc[i].data.shape[1] - np.max(clipped[1].value))

    # Test that keywords are correctly passed
    # Test for an individual keyword
    test_mc = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"], clip=False,
                           cval=np.nan)
    assert(np.all(np.logical_not(np.isfinite(test_mc[1].data[:, -1]))))

    # Test for a combination of keywords, and that changing the interpolation
    # order and how the edges are treated changes the results.
    test_mc1 = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"], clip=False,
                            order=2, mode='reflect')
    test_mc2 = apply_shifts(mc, astropy_displacements["y"], astropy_displacements["x"], clip=False)
    assert(np.all(test_mc1[1].data[:, -1] != test_mc2[1].data[:, -1]))
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:57,代码来源:test_coalignment.py


示例5: range

    def range(self, timerange):
        """
        Gets the directories for a certain range of time
        (i.e. using `~sunpy.time.TimeRange`).

        Parameters
        ----------

        timerange : `~sunpy.time.timerange.TimeRange`
            Time interval where to find the directories for a given
            pattern.

        Returns
        -------

        directories : list of strings
            List of all the possible directories valid for the time
            range given. Notice that these directories may not exist
            in the archive.
        """
        # find directory structure - without file names
        directorypattern = os.path.dirname(self.pattern) + '/'
        # TODO what if there's not slashes?
        rangedelta = timerange.dt
        timestep = self._smallerPattern(directorypattern)
        if timestep is None:
            return [directorypattern]
        else:
            # Number of elements in the time range (including end)
            n_steps = rangedelta.total_seconds()/timestep.total_seconds()
            TotalTimeElements = int(round(n_steps)) + 1
            directories = [(timerange.start + n * timestep).strftime(directorypattern)
                           for n in range(TotalTimeElements)]  # TODO if date <= endate
            return directories
开发者ID:bwgref,项目名称:sunpy,代码行数:34,代码来源:scraper.py


示例6: get_dates

 def get_dates(self):
     """
     Return all partial days contained within the timerange
     """
     dates = []
     dates = [self.start.date() + timedelta(days=i) for i in range(int(self.days.value) + 1)]
     return dates
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:7,代码来源:timerange.py


示例7: split

    def split(self, n=2):
        """
        Splits the TimeRange into multiple equally sized parts.

        Parameters
        ----------
        n : int
            The number of times to split the time range (must >= 1)

        Returns
        -------
        time ranges: list
            An list of equally sized TimeRange objects between
            the start and end times.

        Raises
        ------
        ValueError
            If requested amount is less than 1
        """
        if n <= 0:
            raise ValueError('n must be greater than or equal to 1')
        subsections = []
        previous_time = self.start
        next_time = None
        for _ in range(n):
            next_time = previous_time + self.dt // n
            next_range = TimeRange(previous_time, next_time)
            subsections.append(next_range)
            previous_time = next_time
        return subsections
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:31,代码来源:timerange.py


示例8: test_combine_freqs

def test_combine_freqs():
    image = np.random.rand(5, 3600)
    spec = LinearTimeSpectrogram(image,
        np.linspace(0, image.shape[1] - 1, image.shape[1]),
        np.array([8, 6, 4, 2, 0]),
        datetime(2010, 1, 1, 0, 15),
        datetime(2010, 1, 1, 0, 30),
        900,
        0.25
    )
    image = np.random.rand(5, 3600)
    spec2 = LinearTimeSpectrogram(image,
        np.linspace(0, image.shape[1] - 1, image.shape[1]),
        np.array([9, 7, 5, 3, 1]),
        datetime(2010, 1, 1, 0, 15),
        datetime(2010, 1, 1, 0, 30),
        900,
        0.25
    )
    comb = LinearTimeSpectrogram.combine_frequencies([spec, spec2])
    stuff = [spec, spec2]

    # print comb

    for freq in range(10):
        assert np.array_equal(
            comb[9 - freq, :], stuff[freq % 2][4 - freq // 2, :]
        )
开发者ID:derdon,项目名称:sunpy,代码行数:28,代码来源:test_spectrogram.py


示例9: __getitem__

 def __getitem__(self, key):
     if isinstance(key, slice):
         entries = []
         start = 0 if key.start is None else key.start
         stop = len(self) if key.stop is None else key.stop
         step = 1 if key.step is None else key.step
         for i in range(start, stop, step):
             try:
                 entry = self[i]
             except IndexError:
                 break
             else:
                 self._cache[entry.id]
                 entries.append(entry)
         return entries
     # support negative indices
     if key < 0 < abs(key) <= len(self):
         key %= len(self)
     for i, entry in enumerate(self):
         if i == key:
             # "touch" the entry in the cache to intentionally cause
             # possible side-effects
             self._cache[entry.id]
             return entry
     raise IndexError
开发者ID:Punyaslok,项目名称:sunpy,代码行数:25,代码来源:database.py


示例10: test_setting_cache_size

def test_setting_cache_size(database_using_lrucache):
    assert database_using_lrucache.cache_maxsize == 3
    assert database_using_lrucache.cache_size == 0
    for _ in range(5):
        database_using_lrucache.add(DatabaseEntry())
    assert len(database_using_lrucache) == 3
    assert database_using_lrucache.cache_size == 3
    assert database_using_lrucache.cache_maxsize == 3
    database_using_lrucache.set_cache_size(5)
    assert database_using_lrucache.cache_size == 3
    assert database_using_lrucache.cache_maxsize == 5
    for _ in range(5):
        database_using_lrucache.add(DatabaseEntry())
    assert len(database_using_lrucache) == 5
    assert database_using_lrucache.cache_size == 5
    assert database_using_lrucache.cache_maxsize == 5
开发者ID:mirca,项目名称:sunpy,代码行数:16,代码来源:test_database.py


示例11: make_mask

 def make_mask(self, max_dist):
     mask = np.zeros(self.shape, dtype=np.bool)
     for n, item in enumerate(range(len(self))):
         freq = self.arr.freq_axis[0] - item * self.delt
         if abs(self.get_freq(item) - freq) > max_dist:
             mask[n, :] = True
     return mask
开发者ID:Alex-Ian-Hamilton,项目名称:sunpy,代码行数:7,代码来源:spectrogram.py


示例12: test_split_series_using_lytaf

def test_split_series_using_lytaf():
    '''test the downloading of the LYTAF file and subsequent queries'''
    tmp_dir = tempfile.mkdtemp()
    lyra.download_lytaf_database(lytaf_dir=tmp_dir)
    assert os.path.exists(os.path.join(tmp_dir, 'annotation_ppt.db'))

    # test split_series_using_lytaf
    # construct a dummy signal for testing purposes
    basetime = parse_time('2010-06-13 02:00')
    seconds = 3600
    dummy_time = [basetime + datetime.timedelta(0, s) for s in range(seconds)]
    dummy_data = np.random.random(seconds)

    lytaf_tmp = lyra.get_lytaf_events('2010-06-13 02:00', '2010-06-13 06:00',
                                      lytaf_path=tmp_dir,
                                      combine_files=["ppt"])
    split = lyra.split_series_using_lytaf(dummy_time, dummy_data, lytaf_tmp)
    assert type(split) == list
    assert len(split) == 4
    assert split[0]['subtimes'][0] == datetime.datetime(2010, 6, 13, 2, 0)
    assert split[0]['subtimes'][-1] == datetime.datetime(2010, 6, 13, 2, 7, 2)
    assert split[3]['subtimes'][0] == datetime.datetime(2010, 6, 13, 2, 59, 41)
    assert split[3]['subtimes'][-1] == datetime.datetime(2010, 6, 13, 2, 59, 58)

    # Test case when no LYTAF events found in time series.
    split_no_lytaf = lyra.split_series_using_lytaf(dummy_time,
                                                   dummy_data, LYTAF_TEST)
    assert type(split_no_lytaf) == list
    assert type(split_no_lytaf[0]) == dict
    assert not set(split_no_lytaf[0].keys()).symmetric_difference({'subtimes', 'subdata'})
    assert split_no_lytaf[0]["subtimes"] == dummy_time
    assert split_no_lytaf[0]["subdata"].all() == dummy_data.all()
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:32,代码来源:test_lyra.py


示例13: _add_widgets

    def _add_widgets(self):
        self.buttons = []
        for i in range(0, self.num_buttons):
            x = i*2
            # The i+1/10. is a bug that if you make two axes directly on top of
            # one another then the divider doesn't work.
            self.buttons.append(self.fig.add_axes((0., 0., 0.+i/10., 1.)))
            locator = self.divider.new_locator(nx=x, ny=self.button_ny)
            self.buttons[-1].set_axes_locator(locator)
            self.buttons[-1]._button = widgets.Button(self.buttons[-1],
                                                      self.button_labels[i])
            self.buttons[-1]._button.on_clicked(self.button_func[i])

        self.sliders = []
        self.slider_buttons = []
        for i in range(self.num_sliders):
            x = i * 2
            self.sliders.append(self.fig.add_axes((0., 0., 0.01+i/10., 1.)))
            if self.num_buttons == 0:
                nx1 = 1
            else:
                nx1 = -3
            locator = self.divider.new_locator(nx=0, ny=x, nx1=nx1)
            self.sliders[-1].set_axes_locator(locator)
            sframe = SliderPB(self.sliders[-1], "{slide:d}".format(slide=i),
                              self.slider_ranges[i][0],
                              self.slider_ranges[i][-1]-1,
                              valinit=self.slider_ranges[i][0],
                              valfmt='%4.1f')
            sframe.on_changed(self._slider_changed, sframe)
            sframe.slider_ind = i
            sframe.cval = sframe.val
            self.sliders[-1]._slider = sframe

            self.slider_buttons.append(
                self.fig.add_axes((0., 0., 0.05+x/10., 1.)))
            if self.num_buttons == 0:
                nx = 2
            else:
                nx = 2 + 2*(self.num_buttons-1)
            locator = self.divider.new_locator(nx=nx, ny=x)

            self.slider_buttons[-1].set_axes_locator(locator)
            butt = ButtonPB(self.slider_buttons[-1], ">")
            butt.on_clicked(self._click_slider_button, butt, sframe)
            butt.clicked = False
            self.slider_buttons[-1]._button = butt
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:47,代码来源:imageanimator.py


示例14: test_repair_image_nonfinite

def test_repair_image_nonfinite():
    for i in range(0, 9):
        for non_number in [np.nan, np.inf]:
            a = np.ones((9))
            a[i] = non_number
            b = a.reshape(3, 3)
            c = repair_image_nonfinite(b)
            assert(np.isfinite(c).all())
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:8,代码来源:test_coalignment.py


示例15: draw

 def draw(self):
     """
     Draw current state of progress bar onto and empty bar.
     """
     cur = self.current
     self.current = 0
     for _ in range(cur):
         self.poke()
开发者ID:Alex-Ian-Hamilton,项目名称:sunpy,代码行数:8,代码来源:progressbar.py


示例16: test_lytaf_event2string

def test_lytaf_event2string():
    """Test _lytaf_event2string() associates correct numbers and events."""
    out_test = lyra._lytaf_event2string(list(range(12)))
    assert out_test == ['LAR', 'N/A', 'UV occult.', 'Vis. occult.', 'Offpoint',
                        'SAA', 'Auroral zone', 'Moon in LYRA', 'Moon in SWAP',
                        'Venus in LYRA', 'Venus in SWAP']
    out_test_single = lyra._lytaf_event2string(1)
    assert out_test_single == ['LAR']
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:8,代码来源:test_lyra.py


示例17: test_parse_time_pandas_index

def test_parse_time_pandas_index():
    inputs = [datetime(2012, 1, i) for i in range(1, 13)]
    ind = pandas.DatetimeIndex(inputs)

    dts = parse_time(ind)

    assert isinstance(dts, np.ndarray)
    assert all([isinstance(dt, datetime) for dt in dts])
    assert list(dts) == inputs
开发者ID:Hypnus1803,项目名称:sunpy,代码行数:9,代码来源:test_time.py


示例18: test_add_many

def test_add_many(database):
    assert len(database) == 0
    database.add_many((DatabaseEntry() for _ in range(5)))
    assert len(database) == 5
    database.undo()
    with pytest.raises(EmptyCommandStackError):
        database.undo()
    assert len(database) == 0
    database.redo()
    assert len(database) == 5
开发者ID:mirca,项目名称:sunpy,代码行数:10,代码来源:test_database.py


示例19: undo

    def undo(self, n=1):
        """Undo the last n commands. The default is to undo only the last
        command. If there is no command that can be undone because n is too big
        or because no command has been executed yet,
        :exc:`sunpy.database.commands.EmptyCommandStackError` is raised.

        """
        for _ in range(n):
            command = self.pop_undo_command()
            command.undo()
            self.push_redo_command(command)
开发者ID:Alex-Ian-Hamilton,项目名称:sunpy,代码行数:11,代码来源:commands.py


示例20: test_setting_cache_size_shrinking

def test_setting_cache_size_shrinking(database_using_lrucache):
    assert database_using_lrucache.cache_maxsize == 3
    assert database_using_lrucache.cache_size == 0
    for _ in range(5):
        database_using_lrucache.add(DatabaseEntry())
    assert len(database_using_lrucache) == 3
    assert database_using_lrucache.cache_maxsize == 3
    assert database_using_lrucache.cache_size == 3
    database_using_lrucache.set_cache_size(2)
    assert database_using_lrucache.cache_maxsize == 2
    assert database_using_lrucache.cache_size == 2
    assert len(database_using_lrucache) == 2
    assert list(database_using_lrucache) == [
        DatabaseEntry(id=4),
        DatabaseEntry(id=5)]
    for _ in range(5):
        database_using_lrucache.add(DatabaseEntry())
    assert len(database_using_lrucache) == 2
    assert database_using_lrucache.cache_maxsize == 2
    assert database_using_lrucache.cache_size == 2
开发者ID:mirca,项目名称:sunpy,代码行数:20,代码来源:test_database.py



注:本文中的sunpy.extern.six.moves.range函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python transform.affine_transform函数代码示例发布时间:2022-05-27
下一篇:
Python six.iteritems函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap