### Get Glue Help Source: https://docs.glueviz.org/en/stable/_sources/installation/installation.rst Use 'glue --help' to see available command-line arguments and examples for Glue. ```bash glue --help ``` -------------------------------- ### Start Glue Application Source: https://docs.glueviz.org/en/stable/_sources/installation/installation.rst Type 'glue' in the terminal to start the Glue application after installation. ```bash glue ``` -------------------------------- ### setup() Source: https://docs.glueviz.org/en/stable/api/glue_qt.viewers.scatter.setup.html Initializes the scatter viewer setup. This function is part of the glue_qt.viewers.scatter module. ```APIDOC ## setup() ### Description Initializes the scatter viewer setup. This function is part of the glue_qt.viewers.scatter module. ### Method N/A (Function Call) ### Parameters None explicitly documented. ### Response None explicitly documented. ``` -------------------------------- ### Registering a Custom Viewer in __init__.py Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/writing_plugin.rst The setup function in your plugin's __init__.py file is used to register customizations. This example shows how to add a custom viewer. ```python def setup(): from .data_viewer import MyViewer from glue_qt.config import qt_client qt_client.add(MyViewer) ``` -------------------------------- ### setup() Source: https://docs.glueviz.org/en/stable/api/glue_qt.viewers.histogram.setup.html Initializes the histogram viewer setup. This function is part of the glue_qt.viewers.histogram module. ```APIDOC ## setup() ### Description Initializes the histogram viewer setup. This function is part of the glue_qt.viewers.histogram module. ### Function Signature `glue_qt.viewers.histogram.setup()` ### Parameters This function does not take any parameters. ### Returns This function does not explicitly return a value. ``` -------------------------------- ### Install Glueviz (New User) Source: https://docs.glueviz.org/en/stable/_sources/installation/conda.rst Install the glueviz package into the active 'glue-env' environment using mamba. This is for users who have just installed Mambaforge. ```bash mamba install glueviz ``` -------------------------------- ### Install Glueviz (New User) Source: https://docs.glueviz.org/en/stable/installation/conda.html Install the glueviz package into the activated environment using mamba. ```bash mamba install glueviz ``` -------------------------------- ### Manually Running Plugin Setup Function Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/writing_plugin.rst If a plugin fails to load, you can manually import and run its setup function to get more detailed error messages. ```python python -c 'from myplugin import setup; setup()' ``` -------------------------------- ### start Source: https://docs.glueviz.org/en/stable/api/glue_qt.app.application.GlueApplication.html Shows the GUI and starts the application. This method blocks until the application is closed. ```APIDOC ## start(_size =None_, _position =None_, _block =True_, _maximized =True_) ### Description Show the GUI and start the application. ### Parameters * **size** (tuple[int, int], optional) - The default width/height of the application. If not provided, uses the full screen. * **position** (tuple[int, int], optional) - The default position of the application. * **block** (bool, optional) - Whether to block execution until the application is closed. Defaults to True. * **maximized** (bool, optional) - Whether to start the application maximized. Defaults to True. ``` -------------------------------- ### setup() Source: https://docs.glueviz.org/en/stable/api/glue_qt.viewers.profile.setup.html The setup() function is used to initialize or configure viewer profiles within the Glue Qt environment. It is a core part of setting up the profile viewer's functionality. ```APIDOC ## setup() ### Description Initializes or configures viewer profiles within the Glue Qt environment. This function is essential for setting up the profile viewer's functionality. ### Method N/A (This appears to be a Python function call, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A (No parameters are explicitly documented in the provided text) ### Request Example N/A ### Response N/A (The response or return value is not explicitly documented in the provided text) ``` -------------------------------- ### setup() Source: https://docs.glueviz.org/en/stable/api/glue_qt.viewers.table.setup.html Initializes or sets up the table viewer component in Glue QT. ```APIDOC ## setup() ### Description Initializes or sets up the table viewer component. ### Method Python function call ### Endpoint glu_qt.viewers.table.setup.setup() ### Parameters This function does not appear to take any parameters. ### Request Example ```python setup() ``` ### Response This function does not appear to have a documented return value. ``` -------------------------------- ### Install Glueviz Qt front-end Source: https://docs.glueviz.org/en/stable/_sources/installation/pip.rst Install the Qt-based front-end for Glueviz. This requires the glue-qt package. ```bash pip install glue-qt[qt] ``` -------------------------------- ### Start Glue with a Python Script Source: https://docs.glueviz.org/en/stable/python_guide/glue_from_python.html This command shows how to execute a Python script that prepares data and starts the Glue application. ```bash $ glue startup_script.py ``` -------------------------------- ### Install Glueviz with all dependencies (including Qt) Source: https://docs.glueviz.org/en/stable/_sources/installation/pip.rst Use this command to install Glueviz with all required and optional dependencies, ensuring PyQt5 is included for the Qt front-end. ```bash pip install glueviz[qt] ``` -------------------------------- ### Install glue-vispy-viewers Source: https://docs.glueviz.org/en/stable/installation/pip.html Install the package for 3D viewers within glueviz. ```bash pip install glue-vispy-viewers ``` -------------------------------- ### setup() Source: https://docs.glueviz.org/en/stable/api/glue_qt.viewers.image.setup.html Initializes and sets up the image viewer component. This function is the primary entry point for configuring the image viewer. ```APIDOC ## setup() ### Description Initializes and sets up the image viewer component. This function is the primary entry point for configuring the image viewer. ### Method `setup()` ### Parameters This function does not take any parameters. ### Request Example ```python from glue_qt.viewers.image import setup setup() ``` ### Response This function does not return any value. Its purpose is to configure the application's state. ``` -------------------------------- ### Install glue-core (base package) Source: https://docs.glueviz.org/en/stable/installation/pip.html Install the base glue-core package if you only need the core functionality without any front-end. ```bash pip install glue-core ``` -------------------------------- ### Start and Display Glue Application GUI Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Shows the main Glue GUI window and starts the Qt event loop. Allows for specifying window size, position, and whether it should be maximized. ```python def start(self, size=None, position=None, block=True, maximized=True): """ Show the GUI and start the application. Parameters ---------- size : (int, int) Optional The default width/height of the application. If not provided, uses the full screen position : (int, int) Optional The default position of the application """ if maximized: self.showMaximized() else: self.show() if size is not None: self.resize(*size) if position is not None: self.move(*position) self.raise_() # bring window to front ``` -------------------------------- ### Minimal Custom Data Class Example Source: https://docs.glueviz.org/en/stable/developer_guide/data.html This example demonstrates a basic custom data class, `RandomData`, that inherits from `BaseCartesianData`. It generates random data on-the-fly and includes methods for retrieving data, masks, statistics, and histograms. This class is then used to initialize and start a Glue session. ```python import numpy as np from glue.core.component_id import ComponentID from glue.core.data import BaseCartesianData from glue.utils import view_shape class RandomData(BaseCartesianData): def __init__(self): super(RandomData, self).__init__() self.data_cid = ComponentID(label='data', parent=self) @property def label(self): return "Random Data" @property def shape(self): return (512, 512, 512) @property def main_components(self): return [self.data_cid] def get_kind(self, cid): return 'numerical' def get_data(self, cid, view=None): if cid is self.data_cid: return np.random.random(view_shape(self.shape, view)) else: return super(RandomData, self).get_data(cid, view=view) def get_mask(self, subset_state, view=None): return subset_state.to_mask(self, view=view) def compute_statistic(self, statistic, cid, axis=None, finite=True, positive=False, subset_state=None, percentile=None, random_subset=None): if axis is None: if statistic == 'minimum': return 0 elif statistic == 'maximum': if cid in self.pixel_component_ids: return self.shape[cid.axis] else: return 1 elif statistic == 'mean' or statistic == 'median': return 0.5 elif statistic == 'percentile': return percentile / 100 elif statistic == 'sum': return self.size / 2 else: final_shape = tuple(self.shape[i] for i in range(self.ndim) if i not in axis) return np.random.random(final_shape) def compute_histogram(self, cid, range=None, bins=None, log=False, subset_state=None, subset_group=None): return np.random.random(bins) * 100 # We now create a data object using the above class, # and launch a a glue session from glue.core import DataCollection from glue.app.application import GlueApplication d = RandomData() dc = DataCollection([d]) ga = GlueApplication(dc) ga.start() ``` -------------------------------- ### Install Glueviz Qt front-end with PyQt6 Source: https://docs.glueviz.org/en/stable/_sources/installation/pip.rst Install the Qt-based front-end for Glueviz and specify PyQt6 as the Qt binding. ```bash pip install glue-qt PyQt6 ``` -------------------------------- ### Install Glueviz core package Source: https://docs.glueviz.org/en/stable/_sources/installation/pip.rst Install only the base Glueviz package without any front-end or specific viewers. ```bash pip install glue-core ``` -------------------------------- ### Setup Application User Interface Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Loads the UI from a file, sets up the central widget, configures the tab bar, and initializes the data layers widget and toolbar. ```python self._ui = load_ui('application.ui', None, directory=os.path.dirname(__file__)) self.setCentralWidget(self._ui) self._ui.tabWidget.setTabBar(GlueTabBar()) lw = LayerTreeWidget(session=self._session) lw.set_checkable(False) self._vb = QtWidgets.QVBoxLayout() self._vb.setContentsMargins(0, 0, 0, 0) self._vb.addWidget(lw) self._ui.data_layers.setLayout(self._vb) self._layer_widget = lw # Data toolbar self._data_toolbar = QtWidgets.QToolBar("Session and Data toolbar") self._data_toolbar.setIconSize(QtCore.QSize(16, 16)) self._button_open_session = QtWidgets.QToolButton() self._button_open_session.setText("Open Session") self._button_open_session.setIcon(get_icon('glue_open')) self._button_open_session.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._button_open_session.clicked.connect(self._restore_session) self._data_toolbar.addWidget(self._button_open_session) self._button_save_session = QtWidgets.QToolButton() self._button_save_session.setText("Export Session") self._button_save_session.setIcon(get_icon('glue_filesave')) self._button_save_session.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._button_save_session.clicked.connect(self._choose_save_session) self._data_toolbar.addWidget(self._button_save_session) self._button_open_data = QtWidgets.QToolButton() self._button_open_data.setText("Import Data") self._button_open_data.setIcon(get_icon('glue_open')) self._button_open_data.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._button_open_data.clicked.connect(self._import_helper._choose_load_data_wizard) self._data_toolbar.addWidget(self._button_open_data) self._button_save_data = QtWidgets.QToolButton() self._button_save_data.setText("Export Data/Subsets") self._button_save_data.setIcon(get_icon('glue_filesave')) self._button_save_data.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._button_save_data.clicked.connect(self._choose_save_data) self._data_toolbar.addWidget(self._button_save_data) ``` -------------------------------- ### Install Glueviz (Existing User) Source: https://docs.glueviz.org/en/stable/installation/conda.html Install the glueviz package from the conda-forge channel into the activated environment. ```bash mamba install -c conda-forge glueviz ``` -------------------------------- ### Example Usage of ButtonProperty Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/utils/widget_properties.html Demonstrates how to use ButtonProperty to control a QCheckBox's state via a Python boolean attribute. This allows setting and getting the check state as if it were a simple boolean. ```python class Foo(object): bar = ButtonProperty('_button') def __init__(self): self._button = QtWidgets.QCheckBox() f = Foo() f.bar = True # equivalent to f._button.setChecked(True) assert f.bar == True ``` -------------------------------- ### Defining Plugin Entry Points in setup.py Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/writing_plugin.rst The setup.py file defines entry points to inform Glue about your plugin. This example shows the structure for registering a plugin named 'myplugin'. ```python entry_points = """ [glue.plugins] myplugin=myplugin:setup """ ``` -------------------------------- ### Install glue-samp using Pip Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-samp plugin using pip for environments not using conda. ```bash pip install glue-samp ``` -------------------------------- ### Load Data and Start Glue Application Source: https://docs.glueviz.org/en/stable/python_guide/glue_from_python.html This script demonstrates loading two datasets from FITS and VOTable files, bundling them into a DataCollection, linking their positional attributes using LinkSame, and then starting the Glue application with the prepared data. ```python from glue.core.data_factories import load_data from glue.core import DataCollection from glue.core.link_helpers import LinkSame from glue_qt.app.application import GlueApplication # load 2 datasets from files image = load_data('w5.fits') catalog = load_data('w5_psc.vot') dc = DataCollection([image, catalog]) # link positional information dc.add_link(LinkSame(image.id['Right Ascension'], catalog.id['RAJ2000'])) dc.add_link(LinkSame(image.id['Declination'], catalog.id['DEJ2000'])) # start Glue app = GlueApplication(dc) app.start() ``` -------------------------------- ### Initialize and Execute Qt Plugin Manager Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Initializes and displays the Qt Plugin Manager UI. It retrieves the list of installed plugins from glue.main. ```python def plugin_manager(self, *args): from glue.main import _installed_plugins pm = QtPluginManager(installed=_installed_plugins) pm.ui.exec_() ``` -------------------------------- ### Example Decorator for Custom Viewer Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/viewers/custom/custom_viewer.html This example shows how to use the custom_viewer decorator to define a custom viewer named 'Example'. It associates a plot_data function with the viewer. ```python v = custom_viewer('Example', checkbox=False) @v.plot_data def plot(checkbox, axes): axes.plot([1, 2, 3]) ``` -------------------------------- ### Registering a Setup Function for Court Markings Source: https://docs.glueviz.org/en/stable/customizing_guide/custom_viewer.html This snippet demonstrates how to register a setup function using the `@bball.setup` decorator. This function is called once when the viewer is created to draw static elements like court markings. ```python from glue import custom_viewer from matplotlib.colors import LogNorm from matplotlib.patches import Circle, Rectangle, Arc from matplotlib.lines import Line2D bball = custom_viewer('Shot Plot', x='att(x)', y='att(y)') @bball.plot_data def show_hexbin(axes, x, y): axes.hexbin(x, y, cmap='Purples', gridsize=40, norm=LogNorm(), mincnt=1) @bball.plot_subset def show_points(axes, x, y, style): axes.plot(x, y, 'o', alpha=style.alpha, mec=style.color, mfc=style.color, ms=style.markersize) @bball.setup def draw_court(axes): c = '#777777' opts = dict(fc='none', ec=c, lw=2) hoop = Circle((0, 63), radius=9, **opts) axes.add_patch(hoop) box = Rectangle((-6 * 12, 0), 144, 19 * 12, **opts) axes.add_patch(box) inner = Arc((0, 19 * 12), 144, 144, theta1=0, theta2=180, **opts) axes.add_patch(inner) threept = Arc((0, 63), 474, 474, theta1=0, theta2=180, **opts) axes.add_patch(threept) opts = dict(c=c, lw=2) axes.add_line(Line2D([237, 237], [0, 63], **opts)) axes.add_line(Line2D([-237, -237], [0, 63], **opts)) axes.set_ylim(0, 400) axes.set_aspect('equal', adjustable='datalim') ``` -------------------------------- ### Setup ProfileViewer in GlueQt Client Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/viewers/profile.html Adds the ProfileViewer to the GlueQt client configuration. This function should be called during application setup. ```python from glue_qt.config import qt_client qt_client.add(ProfileViewer) ``` -------------------------------- ### Install Mambaforge Source: https://docs.glueviz.org/en/stable/installation/conda.html For new conda users, download and install Mambaforge using the provided script. ```bash bash MambaForge-*.sh ``` -------------------------------- ### Starting Glue with Verbose Logging Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/writing_plugin.rst Start Glue with the -v flag to enable verbose logging, which helps in diagnosing plugin loading issues. ```bash glue -v ``` -------------------------------- ### CustomViewer.setup Source: https://docs.glueviz.org/en/stable/api/glue_qt.viewers.custom.custom_viewer.CustomViewer.html This method can be overridden by users to perform custom setup operations when a viewer is initialized. It is called automatically and does not need to be called directly. ```APIDOC ## CustomViewer.setup() ### Description Register a new custom method like "plot_data". Users need not call this directly - it is called when a method is overridden or decorated. ### Method Signature `setup()` ### Parameters None ``` -------------------------------- ### Install glue-geospatial using Pip Source: https://docs.glueviz.org/en/stable/customizing_guide/available_plugins.html Use this command to install the glue-geospatial plugin if you are not using the Mamba package manager. ```bash pip install glue-geospatial ``` -------------------------------- ### Emcee Plugin Example for Gaussian Fitting Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/fitting.rst This Python script demonstrates a comprehensive example of Gaussian fitting using the Emcee plugin, combining various concepts for advanced analysis. ```python import numpy as np import emcee import corner import matplotlib.pyplot as plt # Define the model (Gaussian) def gaussian(theta, x): amp, mu, sig = theta return amp * np.exp(-0.5 * ((x - mu) / sig) ** 2) # Define the log probability function def log_prob(theta, x, y, yerr): amp, mu, sig = theta if amp <= 0 or sig <= 0: return -np.inf # Prior for amplitude and sigma model = gaussian(theta, x) chi2 = np.sum(((y - model) / yerr) ** 2) return -0.5 * chi2 # Generate some synthetic data x = np.linspace(-10, 10, 100) yerr = np.random.uniform(0.1, 0.5, 100) y = 5.0 * np.exp(-0.5 * ((x - 1.0) / 2.0) ** 2) + np.random.normal(0, yerr, 100) # Set up the MCMC sampler ndim = 3 # Number of parameters (amp, mu, sig) nwalkers = 50 initial_state = np.random.uniform(0.1, 10, (nwalkers, ndim)) # Initial guesses for parameters sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, args=(x, y, yerr)) # Run the MCMC print("Running burn-in...") state = sampler.run_mcmc(initial_state, 1000) sampler.reset() print("Running production...") sampler.run_mcmc(state, 10000) # Analyze the results flat_samples = sampler.get_chain(discard=100, thin=10, flat=True) # Plot the corner plot figure = corner.corner(flat_samples, labels=["amp", "mu", "sig"], truths=[5.0, 1.0, 2.0]) figure.suptitle("Gaussian Fitting with Emcee") plt.show() # Plot the best fit mean_params = np.mean(flat_samples, axis=0) plt.errorbar(x, y, yerr=yerr, fmt=".b", capsize=2) plt.plot(x, gaussian(mean_params, x), "-r", label="Best Fit") plt.xlabel("x") plt.ylabel("y") plt.legend() plt.title("Gaussian Fit to Data") plt.show() ``` -------------------------------- ### Install glue-samp using Mamba Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-samp plugin using the conda package manager (mamba). ```bash mamba install -c conda-forge glue-samp ``` -------------------------------- ### Programmatic Glue Startup with Custom Data Source: https://docs.glueviz.org/en/stable/developer_guide/data.html This snippet shows how to programmatically start a Glue application with a custom data object. It involves creating an instance of your custom data class, adding it to a DataCollection, and then initializing and starting the GlueApplication. ```python # Construct your data object d = MyCustomData(...) # Create glue application and start dc = DataCollection([d]) ga = GlueApplication(dc) ga.start() ``` -------------------------------- ### Install Latest Glue-QT from Git Source: https://docs.glueviz.org/en/stable/_sources/installation/developer.rst Install the most recent developer version of the glue-qt package, which provides the Qt desktop application interface, directly from its GitHub repository using pip. This is necessary if you intend to use the graphical user interface. ```bash pip install git+https://github.com/glue-viz/glue-qt ``` -------------------------------- ### Installing a Plugin in Develop Mode Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/writing_plugin.rst Use pip to install your plugin in 'develop' mode, allowing changes to be reflected without re-installation. ```bash pip install -e . ``` -------------------------------- ### Deferred Loading of a Qt Viewer Source: https://docs.glueviz.org/en/stable/customizing_guide/customization.html Place your viewer definition and setup function in a separate file. This defers the import of Qt until the viewer is actually needed. ```python class MyQtViewer(...): ... def setup(): from glue_qt.config import qt_client qt_client.add(MyQtViewer) ``` -------------------------------- ### Launch Glueviz Application Source: https://docs.glueviz.org/en/stable/getting_started/index.html Launch the Glueviz application from the command line. This command is used after installing Glue. ```bash glue ``` -------------------------------- ### exec_ Source: https://docs.glueviz.org/en/stable/api/glue_qt.app.application.GlueApplication.html Shows the GUI and starts the application. This method blocks until the application is closed. ```APIDOC ## exec_(_size =None_, _position =None_, _block =True_, _maximized =True_) ### Description Show the GUI and start the application. ### Parameters * **size** (tuple[int, int], optional) - The default width/height of the application. If not provided, uses the full screen. * **position** (tuple[int, int], optional) - The default position of the application. * **block** (bool, optional) - Whether to block execution until the application is closed. Defaults to True. * **maximized** (bool, optional) - Whether to start the application maximized. Defaults to True. ``` -------------------------------- ### Connect Application Signals and Setup Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Initializes drag-and-drop support, sets up the layer widget, and connects signals for tab close requests and tab changes to their respective slots. ```python def _connect(self): self.setAcceptDrops(True) self._layer_widget.setup(self._data) self.tab_widget.tabCloseRequested.connect(self.close_tab) self.tab_widget.currentChanged.connect(self._update_viewer_in_focus) ``` -------------------------------- ### Registering Startup Actions Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/config.html The StartupActionRegistry manages functions to be executed after Glue starts and data is loaded. Actions can be triggered via the command line or GlueApplication initialization. ```python class StartupActionRegistry(DictRegistry): def add(self, startup_name, startup_function): """ Add a startup function to the registry. This is a function that will get called once glue has been started and any data loaded, and can be used to set up specific layouts and create links. Startup actions are triggered by either specifying comma-separated names of actions on the command-line:: glue --startup=mystartupaction or by passing an iterable of startup action names to the ``startup`` keyword of ``GlueApplication``. The startup function will be given the session object and the data collection object. """ if startup_name in self.members: raise ValueError("A startup action with the name '{0}' already exists".format(startup_name)) else: self.members[startup_name] = startup_function def __call__(self, name): def adder(func): self.add(name, func) return func return adder ``` -------------------------------- ### ButtonProperty Example Source: https://docs.glueviz.org/en/stable/developer_guide/api.html Demonstrates how to use ButtonProperty to manage the check state of a QCheckBox as a boolean property. ```python class Foo(object): bar = ButtonProperty('_button') def __init__(self): self._button = QtWidgets.QCheckBox() f = Foo() f.bar = True # equivalent to f._button.setChecked(True) assert f.bar == True ``` -------------------------------- ### Install Latest Glue Core from Git Source: https://docs.glueviz.org/en/stable/_sources/installation/developer.rst Install the most recent developer version of the glue-core package directly from its GitHub repository using pip. This is recommended for developers wanting the latest features or to test changes. ```bash pip install git+https://github.com/glue-viz/glue ``` -------------------------------- ### Setup GlueQt TableViewer Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/viewers/table.html Adds the TableViewer to the GlueQt client. This function should be called during application initialization. ```python from glue_qt.config import qt_client def setup(): qt_client.add(TableViewer) ``` -------------------------------- ### Minimal Custom Data Class Example Source: https://docs.glueviz.org/en/stable/_sources/developer_guide/data.rst This example demonstrates a minimal custom data class that generates random values and does not consider subset states. It is then used to create a Glue session. ```python from glue.core.data import BaseCartesianData from glue.core.component_id import ComponentID from glue.core.subset import Subset, SubsetManager from glue.core.link_tck import Linker from glue.core.data_collection import DataCollection from glue.core.application import GlueApplication import numpy as np class MyCustomData(BaseCartesianData): def __init__(self, **kwargs): super(MyCustomData, self).__init__(**kwargs) self.add_component(ComponentID('x'), np.random.rand(100)) self.add_component(ComponentID('y'), np.random.rand(100)) def get_data(self, cid, view=None): if cid == ComponentID('x'): return self.get_component(cid) elif cid == ComponentID('y'): return self.get_component(cid) else: return super(MyCustomData, self).get_data(cid, view) def get_subset_data(self, subset): # For this example, we ignore subset states and return all data return np.ones(self.num_entries, dtype=bool) # Construct your data object d = MyCustomData(label='random_data') # Create glue application and start dc = DataCollection([d]) ga = GlueApplication(dc) ga.start() ``` -------------------------------- ### Custom Viewer Subclass for Shot Chart Source: https://docs.glueviz.org/en/stable/customizing_guide/custom_viewer.html Subclass CustomViewer to create a specialized 'Shot Plot' viewer. This example demonstrates how to define attributes, implement selection state creation, data plotting, subset plotting, and setup for visual elements like a basketball court. ```python from glue_qt.viewers.custom import CustomViewer from glue.core.subset import RoiSubsetState from matplotlib.colors import LogNorm from matplotlib.patches import Circle, Rectangle, Arc from matplotlib.lines import Line2D import numpy as np class BBall(CustomViewer): name = 'Shot Plot' x = 'att(x)' y = 'att(y)' bins = (10, 100) hitrate = False color = ['Reds', 'Purples'] hit = 'att(shot_made)' def make_selector(self, roi, x, y): state = RoiSubsetState() state.roi = roi state.xatt = x.id state.yatt = y.id return state def plot_data(self, axes, x, y, hit, hitrate, color, bins): if hitrate: axes.hexbin(x, y, hit, reduce_C_function=lambda x: np.array(x).mean(), cmap=color, gridsize=bins, mincnt=5) else: axes.hexbin(x, y, cmap=color, gridsize=bins, norm=LogNorm(), mincnt=1) def plot_subset(self, axes, x, y, style): axes.plot(x, y, 'o', alpha=style.alpha, mec=style.color, mfc=style.color, ms=style.markersize) def setup(self, axes): c = '#777777' opts = dict(fc='none', ec=c, lw=2) hoop = Circle((0, 63), radius=9, **opts) axes.add_patch(hoop) box = Rectangle((-6 * 12, 0), 144, 19 * 12, **opts) axes.add_patch(box) inner = Arc((0, 19 * 12), 144, 144, theta1=0, theta2=180, **opts) axes.add_patch(inner) threept = Arc((0, 63), 474, 474, theta1=0, theta2=180, **opts) axes.add_patch(threept) opts = dict(c=c, lw=2) axes.add_line(Line2D([237, 237], [0, 63], **opts)) axes.add_line(Line2D([-237, -237], [0, 63], **opts)) axes.set_ylim(0, 400) axes.set_aspect('equal', adjustable='datalim') ``` -------------------------------- ### Activate Conda environment Source: https://docs.glueviz.org/en/stable/_sources/installation/conda.rst Switch to the newly created 'glue-env' environment to begin installing packages within it. ```bash mamba activate glue-env ``` -------------------------------- ### Specify Startup Action via Command Line Source: https://docs.glueviz.org/en/stable/customizing_guide/customization.html Run Glue with the `--startup` flag followed by the action name to execute a custom startup action. ```bash glue --startup=action_name ``` -------------------------------- ### Create a pandas DataFrame Source: https://docs.glueviz.org/en/stable/_sources/python_guide/data_translation.rst Initialize a pandas DataFrame with sample data. This is often the starting point for data translation into glue. ```python from pandas import DataFrame df1 = DataFrame() df1['a'] = [1.2, 3.4, 2.9] df1['g'] = ['r', 'q', 's'] df1 ``` -------------------------------- ### Load Data and Pass to Glue Application Source: https://docs.glueviz.org/en/stable/_sources/python_guide/glue_from_python.rst This script demonstrates loading data from files using glue.core.data_factories.load_data, bundling it into a DataCollection, and starting the Glue GUI. ```python from glue.core.data_factories import load_data from glue.core.data_collection import DataCollection from glue.core.link_helpers import LinkSame from glue.app import GlueApplication # Load data from files data1 = load_data('w5_image.fits') data2 = load_data('w5_catalog.vot') # Bundle data into a DataCollection c = DataCollection([data1, data2]) # Link attributes that describe the same quantity c.add_link(LinkSame('world_coordinates', 'world_coordinates')) # Start the Glue GUI with the DataCollection app = GlueApplication(c) app.start() ``` -------------------------------- ### Install Mambaforge Source: https://docs.glueviz.org/en/stable/_sources/installation/conda.rst For new conda users, download and install the Mambaforge distribution. This script is used for Linux and MacOS X installations. ```bash bash MambaForge-*.sh ``` -------------------------------- ### Install Glueviz (Existing User) Source: https://docs.glueviz.org/en/stable/_sources/installation/conda.rst Install the glueviz package from the conda-forge channel into the active 'glue-env' environment using mamba. This is for existing conda users who have installed mamba. ```bash mamba install -c conda-forge glueviz ``` -------------------------------- ### Registering a Plug-in with Lazy Loading Source: https://docs.glueviz.org/en/stable/customizing_guide/customization.html Use `lazy_add` in `config.py` to defer the loading of a plug-in. The associated `setup` function will only be called when the plug-in's functionality is required. ```python from glue_qt.config import qt_client qt_client.lazy_add('my_qt_viewer') ``` -------------------------------- ### Initialize Application Window and UI Elements Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Sets up the main application window, including window title, icon, close behavior, tab widget properties, and initializes internal components like actions and the UI layout. ```python self.set_window_title() self.setWindowIcon(icon) self.setAttribute(Qt.WA_DeleteOnClose) self._actions = {} self._terminal = None self._setup_ui() self.tab_widget.setMovable(True) self.tab_widget.setTabsClosable(True) # The following is a counter that never goes down, even if tabs are # deleted (this is by design, to avoid having two tabs called the # same if a tab is removed then a new one added again) self._total_tab_count = 0 lwidget = self._layer_widget a = PlotAction(lwidget, self) lwidget.ui.layerTree.addAction(a) self._tweak_geometry() self._create_actions() self._create_menu() self._connect() self.new_tab() self._update_viewer_in_focus() ``` -------------------------------- ### Load Data with Coordinate System Source: https://docs.glueviz.org/en/stable/customizing_guide/coordinates.html Loads an example FITS file and creates a data object. This demonstrates how data loaders can automatically set up a coordinate system. ```python from glue.core.data_factories import load_data from glue.utils import require_data require_data('Astronomy/W5/w5.fits') data = load_data('w5.fits') ``` -------------------------------- ### Initialize Qt Data Viewer with Matplotlib Canvas Source: https://docs.glueviz.org/en/stable/customizing_guide/qt_viewer.html Set up the visualization in the __init__ method and use setCentralWidget to add the custom Qt visualization. This example integrates a Matplotlib canvas. ```python from matplotlib import pyplot as plt def __init__(self, *args, **kwargs): super(TutorialDataViewer, self).__init__(*args, **kwargs) self.axes = plt.subplot(1, 1, 1) self.setCentralWidget(self.axes.figure.canvas) ``` -------------------------------- ### Create a new Conda environment Source: https://docs.glueviz.org/en/stable/_sources/installation/conda.rst Create a dedicated conda environment named 'glue-env' for installing glue. This is recommended for both new and existing users. ```bash mamba create -n glue-env ``` -------------------------------- ### Create Affine Transformation Source: https://docs.glueviz.org/en/stable/customizing_guide/coordinates.html Initialize AffineCoordinates with a numpy augmented matrix, units, and labels for custom coordinate systems. This example doubles x and y coordinates. ```python import numpy as np matrix = np.array([[2, 0, 0], [0, 2, 0], [0, 0, 1]]) affine_coords = AffineCoordinates(matrix, units=['m', 'm'], labels=['xw', 'yw']) ``` -------------------------------- ### Run Startup Action by Name Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Executes a predefined startup action based on its name. Raises an exception if the action name is not recognized. ```python if name in startup_action.members: startup_action.members[name](self.session, self.data_collection) else: raise Exception("Unknown startup action: {0}".format(name)) ``` -------------------------------- ### Ensure Matplotlib Navigation Toolbar Setup Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/viewers/matplotlib/toolbar.html Sets up a virtual Matplotlib navigation toolbar for a viewer if it doesn't already exist. This is a prerequisite for using Matplotlib tools. ```python def _ensure_mpl_nav(viewer): # Set up virtual Matplotlib navigation toolbar (don't show it) if not hasattr(viewer, '_mpl_nav'): viewer._mpl_nav = NavigationToolbar2QT(viewer.central_widget.canvas, viewer) viewer._mpl_nav.hide() ``` -------------------------------- ### Initialize Viewer Toolbar Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/viewers/common/data_viewer.html Sets up the main toolbar for the viewer, including adding custom tools and subtools. ```python def initialize_toolbar(self): from glue.config import viewer_tool self.toolbar = self._toolbar_cls(self, default_mouse_mode_cls=self._default_mouse_mode_cls) # Need to include tools and subtools declared by parent classes unless # specified otherwise tool_ids, subtool_ids = get_viewer_tools(self.__class__) for tool_id in tool_ids: mode_cls = viewer_tool.members[tool_id] if tool_id in subtool_ids: subtools = [] for subtool_id in subtool_ids[tool_id]: subtools.append(viewer_tool.members[subtool_id](self)) mode = mode_cls(self, subtools=subtools) else: mode = mode_cls(self) self.toolbar.add_tool(mode) self.addToolBar(self.toolbar) self.toolbar_added.emit() ``` -------------------------------- ### Create and Activate a Clean Conda Environment Source: https://docs.glueviz.org/en/stable/installation/developer.html Before installing developer versions, create and activate a dedicated environment to avoid conflicts. This is recommended when using conda or mamba. ```bash mamba create -n glue-dev-env mamba activate glue-dev-env ``` -------------------------------- ### Upload to PyPI Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/writing_plugin.rst Uploads the built package distributions (tar.gz and wheel files) to the Python Package Index (PyPI) using the 'twine' tool. Ensure 'twine' is installed. ```bash cd dist twine upload *.tar.gz *.whl ``` -------------------------------- ### Command-line Execution of Startup Actions Source: https://docs.glueviz.org/en/stable/api/glue_qt.config.StartupActionRegistry.html Startup actions can be triggered from the command line by specifying comma-separated action names using the --startup argument. ```bash glue --startup=mystartupaction ``` -------------------------------- ### Install glue-wwt using Pip Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-wwt plugin using pip for environments not using conda. ```bash pip install glue-wwt ``` -------------------------------- ### Install glue-wwt using Mamba Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-wwt plugin using the conda package manager (mamba). ```bash mamba install -c conda-forge glue-wwt ``` -------------------------------- ### GlueApplication Initialization Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Initializes the GlueApplication, handling existing Qt applications, setting up helpers, and loading plugins. It configures the main window icon and ensures plugins are loaded. ```python class GlueApplication(Application, QtWidgets.QMainWindow): """ The main GUI application for the Qt frontend""" def __init__(self, data_collection=None, session=None): # At this point we need to check if a Qt application already exists - # this happens for example if using the %gui qt/qt5 mode in Jupyter. We # should keep a reference to the original icon so that we can restore it # later self._original_app = QtWidgets.QApplication.instance() if self._original_app is not None: self._original_icon = self._original_app.windowIcon() self._export_helper = ExportHelper(self) self._import_helper = ImportHelper(self) # Now we can get the application instance, which involves setting it # up if it doesn't already exist. self.app = get_qapp() QtWidgets.QMainWindow.__init__(self) Application.__init__(self, data_collection=data_collection, session=session) # Pull in any keybindings from an external file self.keybindings = keyboard_shortcut icon = get_icon('app_icon') self.app.setWindowIcon(icon) # Even though we loaded the plugins in start_glue, we re-load them here # in case glue was started directly by initializing this class. load_plugins(require_qt_plugins=True) ``` -------------------------------- ### Install glue-medical using Pip Source: https://docs.glueviz.org/en/stable/customizing_guide/available_plugins.html Use this command to install the glue-medical plugin if you are not using the Mamba package manager. ```bash pip install glue-medical ``` -------------------------------- ### Create Plugins Menu Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Sets up the 'Plugins' menu, including the plugin manager action and dynamically adding any available plugins. ```python menu = QtWidgets.QMenu(mbar) menu.setTitle("&Plugins") menu.addAction(self._actions['plugin_manager']) menu.addSeparator() if 'plugins' in self._actions: for plugin in self._actions['plugins']: menu.addAction(plugin) mbar.addMenu(menu) ``` -------------------------------- ### Install astrodendro Package Source: https://docs.glueviz.org/en/stable/_sources/gui_guide/dendro.rst Install the astrodendro package using pip. This is required to enable the dendrogram viewer in Glue. ```bash pip install astrodendro ``` -------------------------------- ### Install Mamba with Conda Source: https://docs.glueviz.org/en/stable/_sources/installation/conda.rst For existing conda users, install the mamba package from the conda-forge channel using the conda command. ```bash conda install -c conda-forge mamba ``` -------------------------------- ### Create Edit and View Menus Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Sets up the 'Edit' menu with undo/redo actions and the 'View' menu with an action to show the console log. ```python menu = QtWidgets.QMenu(mbar) menu.setTitle("&Edit ") menu.addAction(self._actions['undo']) menu.addAction(self._actions['redo']) mbar.addMenu(menu) menu = QtWidgets.QMenu(mbar) menu.setTitle("&View ") a = QtWidgets.QAction("&Console Log", menu) a.triggered.connect(self._log._show) menu.addAction(a) mbar.addMenu(menu) ``` -------------------------------- ### StartupActionRegistry.add Source: https://docs.glueviz.org/en/stable/_sources/api/glue_qt.config.StartupActionRegistry.rst The add method registers a new startup action with the registry. ```APIDOC ## add ### Description Registers a new startup action with the registry. ### Method N/A (This is a method of a class) ### Parameters None explicitly documented. ### Response None explicitly documented. ``` -------------------------------- ### StartupActionRegistry.add() Source: https://docs.glueviz.org/en/stable/api/glue_qt.config.StartupActionRegistry.html Adds a startup function to the registry. These functions are executed after Glue has started and data is loaded, useful for setting up layouts and creating links. Startup actions can be triggered via command-line arguments or the `startup` keyword in `GlueApplication`. ```APIDOC ## StartupActionRegistry.add() ### Description Add a startup function to the registry. This is a function that will get called once glue has been started and any data loaded, and can be used to set up specific layouts and create links. Startup actions are triggered by either specifying comma-separated names of actions on the command-line or by passing an iterable of startup action names to the `startup` keyword of `GlueApplication`. The startup function will be given the session object and the data collection object. ### Method add ### Parameters #### Path Parameters - **_startup_name_** (string) - Description not provided - **_startup_function_** (function) - Description not provided ``` -------------------------------- ### Install PySide from Conda-Forge Source: https://docs.glueviz.org/en/stable/known_issues.html Workaround for Qt internal error on macOS: install PySide from the 'conda-forge' channel to avoid issues with the 'defaults' channel package. ```bash conda install -c conda-forge pyside ``` -------------------------------- ### Create Help Menu with Online Documentation Link Source: https://docs.glueviz.org/en/stable/_modules/glue_qt/app/application.html Adds the 'Help' menu, including an action to open the online documentation in a web browser. This is intended to be the native Mac 'Help' menu. ```python # trigger inclusion of Mac Native "Help" tool menu = mbar.addMenu("&Help") a = QtWidgets.QAction("&Online Documentation", menu) a.triggered.connect(nonpartial(webbrowser.open, DOCS_URL)) menu.addAction(a) ``` -------------------------------- ### Install glue-geospatial with Pip Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-geospatial plugin package using pip. This plugin adds support for geospatial data, including GeoTIFF files. ```bash pip install glue-geospatial ``` -------------------------------- ### Programmatic Execution of Startup Actions Source: https://docs.glueviz.org/en/stable/api/glue_qt.config.StartupActionRegistry.html Startup actions can also be triggered programmatically by passing an iterable of startup action names to the 'startup' keyword argument of GlueApplication. ```python app = GlueApplication(startup=['action1', 'action2']) ``` -------------------------------- ### Install glue-geospatial with Mamba Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-geospatial plugin package using mamba. This plugin adds support for geospatial data, including GeoTIFF files. ```bash mamba install -c conda-forge glue-geospatial ``` -------------------------------- ### Install glue-medical with Pip Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-medical plugin package using pip. This plugin provides functionality for medical imaging, including a DICOM reader. ```bash pip install glue-medical ``` -------------------------------- ### Adding a Startup Action Function Source: https://docs.glueviz.org/en/stable/api/glue_qt.config.StartupActionRegistry.html The add method registers a startup function. This function will be called after Glue starts and data is loaded, and can be used to configure layouts and create links. The startup function receives the session and data collection objects. ```python registry.add('my_startup_action', my_startup_function) ``` -------------------------------- ### Install glue-medical with Mamba Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-medical plugin package using mamba. This plugin provides functionality for medical imaging, including a DICOM reader. ```bash mamba install -c conda-forge glue-medical ``` -------------------------------- ### Programmatic Startup with Custom Data Object Source: https://docs.glueviz.org/en/stable/_sources/developer_guide/data.rst This snippet shows how to construct a custom data object and start a Glue application programmatically with it. This is useful during the initial development of custom data objects. ```python # Construct your data object d = MyCustomData(...) # Create glue application and start dc = DataCollection([d]) ga = GlueApplication(dc) ga.start() ``` -------------------------------- ### Install glue-vispy-viewers with Pip Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-vispy-viewers plugin package using pip. This package adds 3D scatter plot and volume rendering viewers. ```bash pip install glue-vispy-viewers ``` -------------------------------- ### Programmatic Viewer Configuration Source: https://docs.glueviz.org/en/stable/_sources/python_guide/data_viewer_options.rst Demonstrates creating a Glue application, adding data, creating a scatter viewer, and programmatically configuring viewer and layer states, including axis mapping and log scaling. ```python import numpy as np from glue.core import Data, DataCollection from glue_qt.app.application import GlueApplication from glue_qt.viewers.scatter import ScatterViewer # create some data d = Data(x=np.random.random(100), y=np.random.random(100)) dc = DataCollection([d]) # create a GUI session ga = GlueApplication(dc) # plot x vs y, flip the x axis, log-scale y axis scatter = ga.new_data_viewer(ScatterViewer) scatter.add_data(d) # Modify viewer-level options scatter.state.x_att = d.id['x'] scatter.state.y_att = d.id['y'] scatter.state.y_log = True # Modify settings for the (only) layer shown scatter.state.layers[0].color = 'blue' # show the GUI ga.start() ``` -------------------------------- ### Install glue-vispy-viewers with Mamba Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-vispy-viewers plugin package using mamba. This package adds 3D scatter plot and volume rendering viewers. ```bash mamba install -c conda-forge glue-vispy-viewers ``` -------------------------------- ### Install PySide from Conda-Forge Source: https://docs.glueviz.org/en/stable/_sources/known_issues.rst Workaround for the 'qt_menu.nib could not be loaded' error on MacOS X when using PySide. Install PySide from the 'conda-forge' channel instead of 'defaults'. ```bash conda install -c conda-forge pyside ``` -------------------------------- ### Install glue-plotly with Pip Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-plotly plugin package using pip. This plugin enables exporting plots to standalone interactive Plotly HTML pages. ```bash pip install glue-plotly ``` -------------------------------- ### Install glue-plotly with Mamba Source: https://docs.glueviz.org/en/stable/_sources/customizing_guide/available_plugins.rst Install the glue-plotly plugin package using mamba. This plugin enables exporting plots to standalone interactive Plotly HTML pages. ```bash mamba install -c conda-forge glue-plotly ``` -------------------------------- ### Directly Registering a Qt Client Source: https://docs.glueviz.org/en/stable/customizing_guide/customization.html Use this method to directly register a Qt client. Ensure the necessary import is present. ```python from glue_qt.config import qt_client qt_client.add(MyQtViewer) ```