예제 #1
0
def test_data_collection_combo_helper():

    state = ExampleState()

    dc = DataCollection([])

    helper = DataCollectionComboHelper(state, 'combo', dc)

    data1 = Data(x=[1, 2, 3], y=[2, 3, 4], label='data1')

    dc.append(data1)

    assert selection_choices(state, 'combo') == "data1"

    data1.label = 'mydata1'
    assert selection_choices(state, 'combo') == "mydata1"

    dc.remove(data1)

    assert selection_choices(state, 'combo') == ""
예제 #2
0
    def to_data(self, obj):
        coords = SpectralCoordinates(obj.spectral_axis)
        data = Data(coords=coords)
        data['flux'] = obj.flux
        data.get_component('flux').units = str(obj.unit)

        # Include uncertainties if they exist
        if obj.uncertainty is not None:
            data['uncertainty'] = obj.uncertainty.quantity
            data.get_component('uncertainty').units = str(obj.uncertainty.unit)
            data.meta.update(
                {'uncertainty_type': obj.uncertainty.uncertainty_type})

        # Include mask if it exists
        if obj.mask is not None:
            data['mask'] = obj.mask

        data.meta.update(obj.meta)

        return data
예제 #3
0
def main():
    a = AnalyticsEngine()
    e = ExecutionEngine()

    # Lake Burley Griffin
    dimensions = {
        'x': {
            'range': (149.07, 149.18)
        },
        'y': {
            'range': (-35.32, -35.28)
        },
        'time': {
            'range': (datetime(1990, 1, 1), datetime(1990, 12, 31))
        }
    }

    b40 = a.create_array(('LANDSAT_5', 'nbar'), ['nir'], dimensions, 'b40')
    b30 = a.create_array(('LANDSAT_5', 'nbar'), ['red'], dimensions, 'b30')

    ndvi = a.apply_expression([b40, b30],
                              '((array1 - array2) / (array1 + array2))',
                              'ndvi')

    e.execute_plan(a.plan)
    plot(e.cache['ndvi'])

    b30_result = e.cache['b30']['array_result']['red']
    b40_result = e.cache['b40']['array_result']['nir']
    ndvi_result = e.cache['ndvi']['array_result']['ndvi']

    b30_data = Data(x=b30_result[:, ::-1, :], label='B30')
    b40_data = Data(x=b40_result[:, ::-1, :], label='B40')
    ndvi_data = Data(x=ndvi_result[:, ::-1, :], label='ndvi')

    long_data = Data(x=b40_result.coords['x'], label='long')
    lat_data = Data(x=b40_result.coords['y'], label='lat')
    time_data = Data(x=b40_result.coords['time'], label='time')

    collection = DataCollection([
        ndvi_data,
        b30_data,
        b40_data,
        long_data,
        lat_data,
        time_data,
    ])
    app = GlueApplication(collection)
    app.start()
예제 #4
0
def test_data_collection_combo_helper():

    combo = QtWidgets.QComboBox()

    dc = DataCollection([])

    helper = DataCollectionComboHelper(combo, dc)

    data1 = Data(x=[1,2,3], y=[2,3,4], label='data1')

    dc.append(data1)

    assert combo_as_string(combo) == "data1"

    data1.label = 'mydata1'
    assert combo_as_string(combo) == "mydata1"

    dc.remove(data1)

    assert combo_as_string(combo) == ""
예제 #5
0
    def setup_method(self, method):

        self.data = Data(label='d1')
        self.data.coords = SimpleCoordinates()
        self.data['x'] = np.arange(240).reshape((30, 4, 2)).astype(float)

        self.app = GlueApplication()
        self.session = self.app.session
        self.hub = self.session.hub

        self.data_collection = self.session.data_collection
        self.data_collection.append(self.data)

        self.viewer = self.app.new_data_viewer(ProfileViewer)
        self.viewer.state.function = nanmean

        self.viewer.toolbar.active_tool = 'profile-analysis'

        self.profile_tools = self.viewer.toolbar.tools[
            'profile-analysis']._profile_tools
예제 #6
0
def test_translator_from_data():

    # Case where the initial data object wasn't originally created from a
    # DataFrame.

    data = Data()
    data['a'] = [3, 5, 6, 7]
    data['b'] = [1.5, 2.2, 1.3, 3.3]
    data['c'] = ['r', 'd', 'w', 'q']

    with pytest.raises(ValueError) as exc:
        df = data.get_object()
    assert exc.value.args[0] == ('Specify the object class to use with cls= - supported '
                                 'classes are:\n\n* pandas.core.frame.DataFrame')

    df = data.get_object(cls=DataFrame)
    assert_equal(list(df.columns), ['a', 'b', 'c'])
    assert_equal(df['a'].values, [3, 5, 6, 7])
    assert_equal(df['b'].values, [1.5, 2.2, 1.3, 3.3])
    assert_equal(df['c'].values, ['r', 'd', 'w', 'q'])
예제 #7
0
def test_region_from_subset_3d(jdaviz_app):
    data = Data(flux=np.ones((256, 128, 128)), label='Test 3D Flux')
    jdaviz_app.data_collection.append(data)

    jdaviz_app.add_data_to_viewer('flux-viewer', 'Test 3D Flux')

    jdaviz_app.get_viewer('flux-viewer').apply_roi(
        RectangularROI(1, 3.5, -0.2, 3.3))

    subsets = jdaviz_app.get_subsets_from_viewer('flux-viewer')
    reg = subsets.get('Subset 1')

    assert len(subsets) == 1
    assert isinstance(reg, RectanglePixelRegion)

    assert_allclose(reg.center.x, 2.25)
    assert_allclose(reg.center.x, 2.25)
    assert_allclose(reg.center.y, 1.55)
    assert_allclose(reg.width, 2.5)
    assert_allclose(reg.height, 3.5)
예제 #8
0
def test_export(tmpdir):

    filename = tmpdir.join('data')

    data = Data(x=[1, 2, 3])

    mock = MagicMock()

    test_exporter_cls = namedtuple('exporter', 'function label extension')
    test_exporter = test_exporter_cls(function=mock, label='Test', extension='')

    with patch('qtpy.compat.getsavefilename') as dialog:
        with patch('glue.config.data_exporter') as data_exporter:
            def test_iter(x):
                yield test_exporter
            data_exporter.__iter__ = test_iter
            dialog.return_value = filename, 'Test (*)'
            export_data(data)

    assert test_exporter.function.call_args[0] == (filename, data)
예제 #9
0
    def vue_collapse(self, *args, **kwargs):
        try:
            spec = self._selected_data.get_object(cls=SpectralCube)
        except AttributeError:
            snackbar_message = SnackbarMessage(
                f"Unable to perform collapse over selected data.",
                color="error",
                sender=self)
            self.hub.broadcast(snackbar_message)

            return

        collapsed_spec = getattr(spec, self.selected_func.lower())(
            axis=self.selected_axis)

        data = Data(coords=collapsed_spec.wcs)
        data['flux'] = collapsed_spec.filled_data[...]
        data.get_component('flux').units = str(collapsed_spec.unit)
        data.meta.update(collapsed_spec.meta)

        label = f"Collapsed {self._selected_data.label}"

        self.data_collection[label] = data

        # Link the new dataset pixel-wise to the original dataset. In general
        # direct pixel to pixel links are the most efficient and should be
        # used in cases like this where we know there is a 1-to-1 mapping of
        # pixel coordinates. Here which axes are linked to which depends on
        # the selected axis.
        (i1, i2), (i1c, i2c) = AXES_MAPPING[self.selected_axis]

        self.data_collection.add_link(LinkSame(self._selected_data.pixel_component_ids[i1],
                                               self.data_collection[label].pixel_component_ids[i1c]))
        self.data_collection.add_link(LinkSame(self._selected_data.pixel_component_ids[i2],
                                               self.data_collection[label].pixel_component_ids[i2c]))

        snackbar_message = SnackbarMessage(
            f"Data set '{self._selected_data.label}' collapsed successfully.",
            color="success",
            sender=self)
        self.hub.broadcast(snackbar_message)
예제 #10
0
    def test_removed_subset(self):

        # Regression test for a bug in v0.11.0 that meant that if a subset
        # was removed, the image viewer would then crash when changing view
        # (e.g. zooming in). The bug was caused by undeleted references to
        # ModestImage due to circular references. We therefore check in this
        # test how many ModestImage objects exist.

        def get_modest_images():
            mi = []
            gc.collect()
            for obj in gc.get_objects():
                try:
                    if isinstance(obj, ModestImage):
                        mi.append(obj)
                except ReferenceError:
                    pass
            return mi

        # The viewer starts off with one ModestImage. This is also a good test
        # that other ModestImages in other tests have been removed.
        assert len(get_modest_images()) == 1

        large_image = Data(x=np.random.random((2048, 2048)))
        self.data_collection.append(large_image)

        # The subset group can be made from any dataset
        subset_group = self.data_collection.new_subset_group(subset_state=self.image1.id['x'] > 1, label='A')

        self.viewer.add_data(large_image)

        # Since the dataset added has a subset, and each subset has its own
        # ModestImage, this increases the count.
        assert len(get_modest_images()) == 2

        assert len(self.viewer.layers) == 2

        self.data_collection.remove_subset_group(subset_group)

        # Removing the subset should bring the count back to 1 again
        assert len(get_modest_images()) == 1
예제 #11
0
def pre_nircam_image_reader(file_name):
    """
    Data loader for simulated NIRCam image. This is for the
    full image, where cut-outs will be created on the fly.

    From the header:
    If ISWFS is T, structure is:

            -  Plane 1: Signal [frame3 - frame1] in ADU
            -  Plane 2: Signal uncertainty [sqrt(2*RN/g + \|frame3\|)]

    If ISWFS is F, structure is:

            -  Plane 1: Signal from linear fit to ramp [ADU/sec]
            -  Plane 2: Signal uncertainty [ADU/sec]

    Note that in the later case, the uncertainty is simply the formal
    uncertainty in the fit parameter (eg. uncorrelated, WRONG!). Noise
    model to be implemented at a later date.
    In the case of WFS, error is computed as SQRT(2*sigma_read + \|frame3\|)
    which should be a bit more correct - ~Fowler sampling.

    The FITS file has a single extension with a data cube.
    The data is the first slice of the cube and the uncertainty
    is the second slice.

    """

    hdulist = fits.open(file_name)
    data = Data(label='NIRCam Image')
    data.header = hdulist[0].header
    wcs = WCS(hdulist[0].header)

    # drop the last axis since the cube will be split
    data.coords = coordinates_from_wcs(wcs)
    data.add_component(hdulist[0].data, 'Flux')
    data.add_component(hdulist[0].data / 100, 'Uncertainty')

    hdulist.close()

    return data
예제 #12
0
def herschel_data(filename):
    """
    Data loader customized for Herschel fits files

    This function extracts extension named 'image',
    'error', 'coverage', etc
    from a file. Each is returned as a glue Data object.
    To handle PACS cubes, if ImageIndex extension is present
    it is used to provide wavelengths

    astropy.wcs.WCS objects are used to parse wcs.

    Any other extensions are ignored
    """

    hdulist = fits.open(filename, memmap=True, ignore_missing_end=True)

    d = Data("data")
    # Fix for invalid CUNIT values in 12.1 PACS data
    for c in ['CUNIT1', 'CUNIT2']:
        if (c in hdulist['image'].header.keys()):
            hdulist['image'].header[c] = 'deg'
    if ('CUNIT3' in hdulist['image'].header.keys()):
        hdulist['image'].header['CUNIT3'] = 'um'
    d.coords = coordinates_from_wcs(WCS(hdulist['image'].header))
    wavelengths = None
    for h in hdulist:
        if (h.name in ['image', 'error', 'coverage']):
            d.add_component(hdulist[h.name].data, h.name)
        if (h.name == 'ImageIndex'):
            wavelengths = hdulist[h.name].data.field(0)

    # Fix up wavelengths if needed
    if ((wavelengths != None)
            and (d['Wavelength'].shape[0] == len(wavelengths))):
        warray = np.zeros(d['Wavelength'].shape, dtype=d['Wavelength'].dtype)
        warray += wavelengths[:, np.newaxis, np.newaxis]
        d.remove_component('Wavelength')
        d.add_component(warray, label='Wavelength')

    return d
예제 #13
0
def test_manual_data_combo_helper(initialize_data_collection):

    # The case with initialize_data_collection=False is a regression test for a
    # bug which meant that when a ManualDataComboHelper was initialized without
    # a data collection, it did not change when a data object added later has a
    # label changed.

    callback = MagicMock()
    state = ExampleState()
    state.add_callback('combo', callback)

    dc = DataCollection([])

    if initialize_data_collection:
        helper = ManualDataComboHelper(state, 'combo', dc)
    else:
        helper = ManualDataComboHelper(state, 'combo')

    data1 = Data(x=[1, 2, 3], y=[2, 3, 4], label='data1')

    dc.append(data1)

    assert callback.call_count == 0

    assert selection_choices(state, 'combo') == ""

    helper.append_data(data1)
    assert callback.call_count == 1

    assert selection_choices(state, 'combo') == "data1"

    data1.label = 'mydata1'
    assert selection_choices(state, 'combo') == "mydata1"
    assert callback.call_count == 2

    if initialize_data_collection:

        dc.remove(data1)

        assert selection_choices(state, 'combo') == ""
        assert callback.call_count == 3
예제 #14
0
def test_change_components():

    # Regression test for a bug that caused table viewers to not update when
    # adding/removing components.

    app = get_qapp()  # noqa

    d = Data(a=[1, 2, 3, 4, 5],
             b=[3.2, 1.2, 4.5, 3.3, 2.2],
             c=['e', 'b', 'c', 'a', 'f'], label='test')

    dc = DataCollection([d])

    gapp = GlueApplication(dc)

    viewer = gapp.new_data_viewer(TableViewer)
    viewer.add_data(d)

    data_changed = MagicMock()
    viewer.model.dataChanged.connect(data_changed)

    # layoutChanged needs to be emitted for the new/removed columns to be
    # registered (dataChanged is not enough)
    layout_changed = MagicMock()
    viewer.model.layoutChanged.connect(layout_changed)

    assert data_changed.call_count == 0
    assert layout_changed.call_count == 0
    viewer.model.columnCount() == 2

    d.add_component([3, 4, 5, 6, 2], 'z')

    assert data_changed.call_count == 1
    assert layout_changed.call_count == 1
    viewer.model.columnCount() == 3

    d.remove_component(d.id['z'])

    assert data_changed.call_count == 2
    assert layout_changed.call_count == 2
    viewer.model.columnCount() == 2
예제 #15
0
def test_not_all_points_inside_limits(tmpdir):

    # Regression test for a bug that occurred when not all points were inside
    # the visible limits and the color or size mode is linear.

    data1 = Data(label="Data", x=[1, 2, 3])

    dc = DataCollection([data1])
    ga = GlueApplication(dc)
    ga.show()

    scatter = ga.new_data_viewer(VispyScatterViewer)
    scatter.add_data(data1)

    scatter.state.layers[0].color_mode = 'Linear'
    scatter.state.layers[0].size_mode = 'Linear'

    scatter.state.x_min = -0.1
    scatter.state.x_max = 2.1

    ga.close()
예제 #16
0
    def setup_method(self, method):

        self.data = Data(x=[-3.2, 4.3, 2.2, 5.4, 7.2, -1.1, 2.3],
                         y=['a', 'f', 'd', 'e', 'f', 'f', 'a'], label='test_data')

        self.data_collection = DataCollection([self.data])

        class SimpleState(State):

            layer = CallbackProperty()
            comp = CallbackProperty()
            x_min = CallbackProperty()
            x_max = CallbackProperty()
            n_bin = CallbackProperty()

        self.state = SimpleState()

        self.helper = StateAttributeHistogramHelper(self.state, attribute='comp',
                                                    lower='x_min', upper='x_max', n_bin='n_bin')

        self.state.data = self.data
예제 #17
0
def test_region_from_subset_profile(jdaviz_app, spectral_cube_wcs):
    data = Data(flux=np.ones((256, 128, 128)),
                label='Test 1D Flux',
                coords=spectral_cube_wcs)
    jdaviz_app.data_collection.append(data)

    jdaviz_app.add_data_to_viewer('spectrum-viewer', 'Test 1D Flux')

    jdaviz_app.get_viewer("spectrum-viewer").apply_roi(XRangeROI(1, 3.5))

    subsets = jdaviz_app.get_subsets_from_viewer('spectrum-viewer',
                                                 subset_type='spectral')
    reg = subsets.get('Subset 1')

    assert len(subsets) == 1
    assert isinstance(reg, RectanglePixelRegion)

    assert_allclose(reg.center.x, 2.25)
    assert_allclose(reg.center.y, 128)
    assert_allclose(reg.width, 2.5)
    assert_allclose(reg.height, 256)
예제 #18
0
def main():
    a = AnalyticsEngine()
    e = ExecutionEngine()

    # Lake Burley Griffin
    dimensions = {'x':    {'range': (149.07, 149.18)},
                  'y':    {'range': (-35.32, -35.28)},
                  'time': {'range': (datetime(1990, 1, 1), datetime(1990, 12, 31))}}

    arrays = a.create_array(('LANDSAT_5', 'nbar'), ['nir', 'red'], dimensions, 'get_data')

    ndvi = a.apply_bandmath(arrays, '((array1 - array2) / (array1 + array2))', 'ndvi')
    pq = a.create_array(('LANDSAT_5', 'pqa'), ['pixelquality'], dimensions, 'pq')
    mask = a.apply_cloud_mask(ndvi, pq, 'mask')

    e.execute_plan(a.plan)

    plot(e.cache['mask'])

    b30_result = e.cache['get_data']['array_result']['red']
    b40_result = e.cache['get_data']['array_result']['nir']
    ndvi_result = e.cache['ndvi']['array_result']['ndvi']
    pq_result = e.cache['pq']['array_result']['pixelquality']
    mask_result = e.cache['mask']['array_result']['mask']

    b30_data = Data(x=b30_result[:, ::-1, :], label='B30')
    b40_data = Data(x=b40_result[:, ::-1, :], label='B40')
    ndvi_data = Data(x=ndvi_result[:, ::-1, :], label='ndvi')
    pq_data = Data(x=pq_result[:, ::-1, :], label='pq')
    mask_data = Data(x=mask_result[:, ::-1, :], label='mask')

    long_data = Data(x=b40_result.coords['x'], label='long')
    lat_data = Data(x=b40_result.coords['y'], label='lat')
    time_data = Data(x=b40_result.coords['time'], label='time')

    collection = DataCollection([mask_data, pq_data, ndvi_data, b30_data, b40_data, long_data, lat_data, time_data, ])
    app = GlueApplication(collection)
    app.start()
예제 #19
0
def test_to_spectral_cube(spectral_cube_wcs):

    data = Data(label='spectral_cube', coords=spectral_cube_wcs)
    values = np.random.random((4, 5, 3))
    data.add_component(Component(values, units='Jy'), 'x')

    spec = data.get_object(SpectralCube, attribute=data.id['x'])

    assert_quantity_allclose(spec.spectral_axis, [1, 2, 3, 4] * u.m / u.s)
    assert_quantity_allclose(spec.filled_data[...], values * u.Jy)

    data.add_subset(data.id['x'] > 0.5, label='bright')

    spec_subset = data.get_subset_object(cls=SpectralCube, subset_id=0,
                                         attribute=data.id['x'])

    assert_quantity_allclose(spec_subset.spectral_axis, [1, 2, 3, 4] * u.m / u.s)
    expected = values.copy()
    expected[expected <= 0.5] = np.nan
    assert_quantity_allclose(spec_subset.filled_data[...], expected * u.Jy)
    assert_equal(spec_subset.mask.include(), values > 0.5)
예제 #20
0
    def to_glue(self, label="yt", data_collection=None):
        """
        Takes the data in the FITSImageData instance and exports it to
        Glue (http://www.glueviz.org) for interactive analysis. Optionally 
        add a *label*. If you are already within the Glue environment, you 
        can pass a *data_collection* object, otherwise Glue will be started.
        """
        from glue.core import DataCollection, Data
        from glue.core.coordinates import coordinates_from_header
        from glue.qt.glue_application import GlueApplication

        image = Data(label=label)
        image.coords = coordinates_from_header(self.wcs.to_header())
        for k, f in self.items():
            image.add_component(f.data, k)
        if data_collection is None:
            dc = DataCollection([image])
            app = GlueApplication(dc)
            app.start()
        else:
            data_collection.append(image)
예제 #21
0
    def setup_method(self, method):

        self.viewer_state = HistogramViewerState()

        ax = plt.subplot(1, 1, 1)

        self.data = Data(x=[1, 2, 3], y=[2, 3, 4])
        self.subset = self.data.new_subset()
        self.subset.subset_state = self.data.id['x'] > 1

        dc = DataCollection([self.data])

        # TODO: The following line shouldn't be needed
        self.viewer_state.data_collection = dc

        self.artist = HistogramLayerArtist(ax, self.viewer_state, layer=self.subset)
        self.layer_state = self.artist.state
        self.viewer_state.layers.append(self.layer_state)

        self.call_counter = CallCounter()
        sys.setprofile(self.call_counter)
예제 #22
0
def test_table_with_dask_column():

    da = pytest.importorskip('dask.array')

    app = get_qapp()

    d = Data(d=da.asarray([1, 2, 3, 4, 5]), e=np.arange(5) + 1)

    dc = DataCollection([d])

    gapp = GlueApplication(dc)

    widget = gapp.new_data_viewer(TableViewer)
    widget.add_data(d)

    sg1 = dc.new_subset_group('D <= 3', d.id['d'] <= 3)
    sg1.style.color = '#aa0000'
    sg2 = dc.new_subset_group('1 < E < 4', (d.id['e'] > 1) & (d.id['e'] < 4))
    sg2.style.color = '#0000cc'

    assert widget.state.layers[0].visible
    assert widget.state.layers[1].visible
    assert widget.state.layers[2].visible

    model = widget.ui.table.model()

    # We now check what the data and colors of the table are, and try various
    # sorting methods to make sure that things are still correct.

    data = {'d': [1, 2, 3, 4, 5], 'e': [1, 2, 3, 4, 5]}

    colors = ['#aa0000', '#380088', '#380088', None, None]

    check_values_and_color(model, data, colors)

    widget.state.layers[2].visible = False

    colors = ['#aa0000', '#aa0000', '#aa0000', None, None]

    check_values_and_color(model, data, colors)
예제 #23
0
def test_region_spectral_spatial(jdaviz_app, spectral_cube_wcs):
    data = Data(flux=np.ones((256, 128, 128)),
                label='Test Flux',
                coords=spectral_cube_wcs)
    jdaviz_app.data_collection.append(data)

    jdaviz_app.add_data_to_viewer('spectrum-viewer', 'Test Flux')
    jdaviz_app.add_data_to_viewer('flux-viewer', 'Test Flux')

    jdaviz_app.get_viewer("spectrum-viewer").apply_roi(XRangeROI(1, 3.5))

    flux_viewer = jdaviz_app.get_viewer("flux-viewer")
    # We set the active tool here to trigger a reset of the Subset state to "Create new"
    flux_viewer.toolbar.active_tool = flux_viewer.toolbar.tools[
        'bqplot:rectangle']
    flux_viewer.apply_roi(RectangularROI(1, 3.5, -0.2, 3.3))

    subsets = jdaviz_app.get_subsets_from_viewer('spectrum-viewer',
                                                 subset_type='spectral')
    reg = subsets.get('Subset 1')

    assert len(subsets) == 1
    assert isinstance(reg, RectanglePixelRegion)

    assert_allclose(reg.center.x, 2.25)
    assert_allclose(reg.center.y, 128)
    assert_allclose(reg.width, 2.5)
    assert_allclose(reg.height, 256)

    subsets = jdaviz_app.get_subsets_from_viewer('flux-viewer',
                                                 subset_type='spatial')
    reg = subsets.get('Subset 2')

    assert len(subsets) == 1
    assert isinstance(reg, RectanglePixelRegion)
    assert_allclose(reg.center.x, 2.25)
    assert_allclose(reg.center.x, 2.25)
    assert_allclose(reg.center.y, 1.55)
    assert_allclose(reg.width, 2.5)
    assert_allclose(reg.height, 3.5)
예제 #24
0
파일: common.py 프로젝트: nden/cubeviz
def add_to_2d_container(cubeviz_layout, data, component_data, label):
    """
    Given the cubeviz layout, a data object, a new 2D layer and a label, add
    the 2D layer to the data object and update the cubeviz layout accordingly.
    This creates the 2D container dataset if needed.
    """

    # If the 2D container doesn't exist, we create it here. This container is
    # basically just a Data object but we keep it in an attribute
    # ``container_2d`` on its parent dataset.
    if getattr(data, 'container_2d', None) is None:

        # For now, we assume that the 2D maps are always computed along the
        # spectral axis, so that the resulting WCS is always celestial
        coords = WCSCoordinates(wcs=data.coords.wcs.celestial)
        data.container_2d = Data(label=data.label + " [2d]", coords=coords)

        data.container_2d.add_component(component_data, label)

        cubeviz_layout.session.data_collection.append(data.container_2d)

        # Set up pixel links so that selections in the image plane propagate
        # between 1D and 2D views. Again this assumes as above that the
        # moments are computed along the spectral axis
        link1 = LinkSame(data.pixel_component_ids[2],
                         data.container_2d.pixel_component_ids[1])
        link2 = LinkSame(data.pixel_component_ids[1],
                         data.container_2d.pixel_component_ids[0])
        cubeviz_layout.session.data_collection.add_link(link1)
        cubeviz_layout.session.data_collection.add_link(link2)

        for helper in cubeviz_layout._viewer_combo_helpers:
            helper.append_data(data.container_2d)

        for viewer in cubeviz_layout.all_views:
            viewer._widget.add_data(data.container_2d)

    else:

        data.container_2d.add_component(component_data, label)
예제 #25
0
def test_reset(tmpdir, capsys):

    app = GlueApplication()
    viewer = app.new_data_viewer(VispyScatterViewer)
    data = Data(x=[1, 2, 3], label='Data')
    app.data_collection.append(data)
    app.show()
    viewer.add_data(data)

    assert viewer.state.x_min == 1.
    assert viewer.state.y_min == 1.
    assert viewer.state.z_min == 1.

    assert viewer.state.x_max == 3.
    assert viewer.state.y_max == 3.
    assert viewer.state.z_max == 3.

    viewer.state.x_min = 2
    viewer.state.y_min = 3
    viewer.state.z_min = 5

    viewer.state.x_max = 6
    viewer.state.y_max = 7
    viewer.state.z_max = 8

    viewer.toolbar.actions['vispy:reset'].trigger()

    assert viewer.state.x_min == 1.
    assert viewer.state.y_min == 1.
    assert viewer.state.z_min == 1.

    assert viewer.state.x_max == 3.
    assert viewer.state.y_max == 3.
    assert viewer.state.z_max == 3.

    out, err = capsys.readouterr()
    assert out.strip() == ""
    assert err.strip() == ""

    app.close()
예제 #26
0
def test_indexed_data(capsys):

    # Make sure that the image viewer works properly with IndexedData objects

    data_4d = Data(label='hypercube_wcs',
                   x=np.random.random((3, 5, 4, 3)),
                   coords=WCS(naxis=4))

    data_2d = IndexedData(data_4d, (2, None, 3, None))

    application = GlueApplication()

    session = application.session

    hub = session.hub

    data_collection = session.data_collection
    data_collection.append(data_4d)
    data_collection.append(data_2d)

    viewer = application.new_data_viewer(ImageViewer)
    viewer.add_data(data_2d)

    assert viewer.state.x_att is data_2d.pixel_component_ids[1]
    assert viewer.state.y_att is data_2d.pixel_component_ids[0]
    assert viewer.state.x_att_world is data_2d.world_component_ids[1]
    assert viewer.state.y_att_world is data_2d.world_component_ids[0]

    process_events()

    application.close()

    # Some exceptions used to happen during callbacks, and these show up
    # in stderr but don't interrupt the code, so we make sure here that
    # nothing was printed to stdout nor stderr.

    out, err = capsys.readouterr()

    assert out.strip() == ""
    assert err.strip() == ""
예제 #27
0
def example_data_xyz(seed=42, N=500, loc=0, scale=1, label='xyz'):
    """
    Create an example dataset with three attributes x, y, and z set to random
    values.
    """
    from glue.core import Data
    import numpy as np
    rng = np.random.RandomState(seed)
    x, y, z = rng.normal(loc, scale, size=(3, N))
    vx = x - x.mean()
    vy = y - y.mean()
    vz = z - z.mean()
    speed = np.sqrt(vx**2 + vy**2 + vz**2)
    data_xyz = Data(x=x,
                    y=y,
                    z=z,
                    vx=vx,
                    vy=vy,
                    vz=vz,
                    speed=speed,
                    label=label)
    return data_xyz
예제 #28
0
def test_nan_inf_minmax():

    data = Data(x=[3, 1, -2, np.inf, np.nan], label='test_data')

    class SimpleState(State):

        layer = CallbackProperty()
        comp = CallbackProperty()
        lower = CallbackProperty()
        upper = CallbackProperty()
        percentile = CallbackProperty()
        log = CallbackProperty()

    state = SimpleState()

    helper = StateAttributeLimitsHelper(
        state,
        attribute='comp',  # noqa
        lower='lower',
        upper='upper',
        percentile='percentile',
        log='log')

    state.data = data
    state.comp = data.id['x']

    assert state.lower == -2
    assert state.upper == +3

    state.log = True

    assert state.lower == +1
    assert state.upper == +3

    state.log = False
    state.percentile = 99

    assert_allclose(state.lower, -1.97)
    assert_allclose(state.upper, +2.98)
예제 #29
0
 def cube_to_data(self, cube, output_label=None, output_component_id=None):
     """
     Convert SpectralCube to final output.
     self.output_as_component is checked here.
     if self.output_as_component:
         add new component to self.data
     else:
         create new data and return it.
     :param cube: SpectralCube
     :param output_label: Name of new Data.
     :param output_component_id: label of new component
     :return:
     """
     original_data = self.data
     if self.output_as_component:
         original_data.add_component(cube._data.copy(), output_component_id)
         return None
     else:
         new_data = Data(label=output_label)
         new_data.coords = coordinates_from_header(cube.header)
         new_data.add_component(cube._data.copy(), output_component_id)
         return new_data
예제 #30
0
def test_two_custom_viewer_classes():
    class MyWidget1(CustomViewer):

        text_box1_Widget1 = '_Hello'

        def setup(self, text_box1_Widget1):
            pass

    class MyWidget2(CustomViewer):

        text_box1_Widget2 = '_Hello'
        text_box2_Widget2 = '_world'

        def setup(self, text_box1_Widget2, text_box2_Widget2):
            pass

    app = GlueApplication()
    dc = app.data_collection
    d = Data(x=[1, 2, 3], label='test')
    dc.append(d)
    app.new_data_viewer(MyWidget1._widget_cls)
    app.new_data_viewer(MyWidget2._widget_cls)