### Install Dependencies and Build Chemiscope
Source: https://chemiscope.org/docs/_sources/embedding.rst.txt
Install Node.js and npm, then navigate to the chemiscope directory to install dependencies and build the project. This creates minified JavaScript libraries in the 'dist' directory.
```bash
cd chemiscope
npm install
npm run build
```
--------------------------------
### Headless Initialization Output
Source: https://chemiscope.org/docs/examples/11-headless.html
Example output indicating the successful initialization of the headless Chemiscope widget and the start of snapshot capturing.
```text
Initializing headless chemiscope...
Capturing structure snapshots...
Capturing atom snapshots...
```
--------------------------------
### Minimal Chemiscope HTML and JavaScript Example
Source: https://chemiscope.org/docs/embedding.html
This example demonstrates the basic HTML structure and JavaScript required to load and initialize the default Chemiscope visualizer. It includes loading dependencies and setting up DOM elements for the interface.
```html
Chemiscope basic example
powered by chemiscope
```
--------------------------------
### Metadata Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
An example of the 'meta' section in a chemiscope JSON file, containing dataset name, description, authors, and references.
```json
"meta": {
"name": "MAD PCA",
"description": "1000 validation structures from the *MAD dataset* under PCA",
"authors": ["Author 1"],
"references": ["https://arxiv.org/abs/2506.19674"]
}
```
--------------------------------
### Install Chemiscope with Optional Dependencies
Source: https://chemiscope.org/docs/getting-started/installation.html
Install Chemiscope along with optional dependencies for advanced features like automatic dataset exploration.
```bash
pip install chemiscope[explore]
```
--------------------------------
### Install Chemiscope with Streamlit Extra
Source: https://chemiscope.org/docs/_sources/python/streamlit.rst.txt
Install chemiscope with the streamlit extra to enable the Streamlit component.
```bash
pip install chemiscope[streamlit]
```
--------------------------------
### Structure Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
An example of a 'structures' entry in a chemiscope JSON file, defining atomic configuration with size, names, and coordinates.
```json
{
"size": 3,
"names": ["O", "H", "H"],
"x": [0.0, 0.76, -0.76],
"y": [0.0, 0.59, 0.59],
"z": [0.0, 0.0, 0.0]
}
```
--------------------------------
### Install Development Version of Chemiscope
Source: https://chemiscope.org/docs/_sources/getting-started/installation.rst.txt
Installs a development version from the GitHub repository. Requires Node.js and npm for TypeScript compilation.
```bash
git clone https://github.com/lab-cosmo/chemiscope.git
cd chemiscope
pip install .
```
--------------------------------
### Install Chemiscope Explore Dependency
Source: https://chemiscope.org/docs/_downloads/dfc154bea0f4cc5252869df3c3192477/6-explore.ipynb
Install the necessary dependencies for the chemiscope explore functionality using pip.
```bash
pip install chemiscope[explore]
```
--------------------------------
### Install Core Chemiscope Package
Source: https://chemiscope.org/docs/_sources/getting-started/installation.rst.txt
Installs the main chemiscope package and its essential utilities for Jupyter widgets and JSON generation.
```bash
pip install chemiscope
```
--------------------------------
### oncreate
Source: https://chemiscope.org/docs/api/classes/ViewersGrid.html
Callback fired when a new viewer is created in the grid. It provides the GUID of the new viewer, its marker color, and the environment indexes it displays.
```APIDOC
## oncreate
### Description
Callback fired when a new viewer is created.
### Method
Callback
### Parameters
#### Parameters
- **guid** (GUID) - Required - GUID of the new viewer
- **color** (string) - Required - GUID of the marker indicating the new viewer
- **indexes** (Indexes) - Required - environment showed in the new viewer
### Returns
void
```
--------------------------------
### Basic Chemiscope Streamlit Viewer Usage
Source: https://chemiscope.org/docs/_sources/python/streamlit.rst.txt
A minimal example demonstrating how to read structures, create a Chemiscope dataset, and display the viewer in a Streamlit app.
```python
import ase.io
import chemiscope
import streamlit as st
# Read structures
structures = ase.io.read("structures.xyz", ":")
# Create or load your chemiscope dataset
dataset = chemiscope.create_input(structures)
# Display the viewer
chemiscope.streamlit.viewer(dataset, mode="structure")
```
--------------------------------
### Create and Display Chemiscope Widget
Source: https://chemiscope.org/docs/_sources/python/jupyter.rst.txt
Basic example demonstrating the creation and display of a Chemiscope widget in a Jupyter cell. This is the initial step for using Chemiscope interactively.
```python
# Cell 1: Create and display the widget
import chemiscope
widget = chemiscope.show(structures, properties)
widget
```
--------------------------------
### Define and Write Shapes Example
Source: https://chemiscope.org/docs/_sources/examples/5-shapes.rst.txt
This snippet demonstrates how to define various shapes for structures and write them to a JSON file using chemiscope.write_input. It includes examples of smooth and sharp cubes, molecular dipoles, atomic polarizability as ellipsoids, and wireframe tetrahedrons. It also shows how to set default visualization settings.
```Python
chemiscope.write_input(
"shapes-example.json.gz",
structures=structures,
properties=chemiscope.extract_properties(structures, only=["alpha"]),
shapes={
# cubes with smooth shading, centered on atoms
"smooth_cubes": smooth_cubes,
# demonstrates showing a "global" shape for each structure
"cube": sharp_cubes,
# (molecular) electric dipole
"dipole": dipoles_auto,
# atomic decomposition of the polarizability as ellipsoids. use utility to
# extract from the ASE structures
"alpha": chemiscope.ase_tensors_to_ellipsoids(
structures, "alpha", force_positive=True, scale=0.2
),
# shapes with a bit of flair
"irreverence": irreverent_shape,
# wireframe tetrahedron using cylinders
"tetrahedron": wireframe_tetrahedron,
# spheres at tetrahedron vertices
"tet_vertices": tetrahedron_vertices,
# combined: edges + vertices as one shape entry
"tet_combined": wireframe_with_vertices,
},
# the write_input function also allows defining the default visualization settings
settings={
"map": {
"x": {"property": "alpha[1]"},
"y": {"property": "alpha[2]"},
"z": {"property": "alpha[3]"},
"color": {"property": "", "palette": "seismic"},
},
"structure": [
{
"spaceFilling": False,
"atomLabels": False,
"atoms": False,
# multiple shapes can be visualized at the same time!
"shape": "alpha,dipole",
"axes": "off",
"keepOrientation": False,
"playbackDelay": 700,
"environments": {
"activated": True,
"bgColor": "CPK",
"bgStyle": "licorice",
"center": False,
"cutoff": 0.5,
},
}
],
},
environments=chemiscope.all_atomic_environments(structures),
)
```
--------------------------------
### Explore Structures with a Metatomic Featurizer
Source: https://chemiscope.org/docs/python/jupyter.html
This example demonstrates how to use `metatomic_featurizer` to generate features from structures and then visualize them using `chemiscope.explore`. Ensure you have a 'model.pt' file and compiled extensions in the 'extensions/' directory.
```python
import chemiscope
import ase.io
# Read the structures from the dataset
structures = ase.io.read("data/explore_c-gap-20u.xyz", ":")
# Provide model file ("model.pt") to `metatomic_featurizer`
featurizer = chemiscope.metatomic_featurizer(
"model.pt", extensions_directory="extensions"
)
chemiscope.explore(structures, featurizer=featurizer)
```
--------------------------------
### Customizing Chemiscope Viewer with Settings
Source: https://chemiscope.org/docs/_sources/python/streamlit.rst.txt
Example of using the 'settings' parameter to customize the Chemiscope viewer's appearance and behavior, including property mapping and structure visualization options.
```python
settings = chemiscope.quick_settings(
x="property_1",
y="property_2",
color="energy",
structure_settings={
"bonds": True,
"unitCell": True,
}
)
chemiscope.streamlit.viewer(
dataset,
settings=settings,
mode="default"
)
```
--------------------------------
### Loading Dataset with Saved Settings from URL
Source: https://chemiscope.org/docs/getting-started/sharing.html
Combine dataset loading with saved visualization settings by specifying the URL for both the dataset and the settings file using GET parameters.
```URL
https://chemiscope.org/?load=https://university.edu/dataset.json.gz&settings=https://university.edu/settings.json
```
--------------------------------
### Initialize and Configure Headless Chemiscope Widget
Source: https://chemiscope.org/docs/_downloads/a1d77812cf5c12c656ce1a2ed2044716/11-headless.ipynb
Initialize the headless widget with structure data and configure settings for capturing snapshots. This setup is for capturing full structure views with ellipsoids enabled.
```python
print("Initializing headless chemiscope...")
headless_widget = headless(
structures=structures,
properties=properties,
shapes=shapes,
settings=settings,
environments=environments,
width=400, # smaller width for smaller file size
)
# 1. Capture snapshots of the two whole structures with ellipsoids
print("Capturing structure snapshots...")
# Configure for structure view (ellipsoids enabled)
headless_widget.settings = {
"target": "structure",
"structure": [
{
"shape": "alpha", # Enable ellipsoids
"axes": "off",
"keepOrientation": True,
"atoms": True,
"bonds": True,
# Disable environment highlighting and centering for full structure view
"environments": {"activated": False, "center": False},
}
],
}
structure_images = []
for i in range(len(structures)):
# Select the structure (clearing atom selection)
headless_widget.selected_ids = {"structure": i}
time.sleep(0.5) # Wait for render
img_data = headless_widget.get_structure_image()
structure_images.append(plt.imread(io.BytesIO(img_data)))
# 2. Capture snapshots of specific atomic environments
print("Capturing atom snapshots...")
# Configure for atom view (color by Trace, no ellipsoids)
headless_widget.settings = {
"target": "atom",
"structure": [
{
"shape": "", # Disable ellipsoids
"color": {
"property": "Atomic Trace",
"palette": "magma",
}, # Use magma palette
"axes": "off",
"keepOrientation": False, # Re-orient for each atom
"environments": {
"activated": True,
"center": True, # Center on the environment
"cutoff": 3.5,
"bgStyle": "licorice",
"bgColor": "grey",
},
}
],
}
# Select atoms with min/max Trace and Anisotropy, and some intermediate points
sorted_trace_indices = np.argsort(atomic_trace)
indices_to_show = [
np.argmin(atomic_trace),
np.argmax(atomic_trace),
np.argmin(atomic_anisotropy),
np.argmax(atomic_anisotropy),
]
indices_to_show = sorted(list(set(indices_to_show)))
atom_images = []
for i in indices_to_show:
env = environments[i] # tuple: (structure_index, atom_index, cutoff)
headless_widget.selected_ids = {"structure": int(env[0]), "atom": int(env[1])}
time.sleep(0.5)
img_data = headless_widget.get_structure_image()
atom_images.append(plt.imread(io.BytesIO(img_data)))
headless_widget.close()
```
--------------------------------
### Rebuilding Standalone Visualizer from Source
Source: https://chemiscope.org/docs/getting-started/sharing.html
Steps to rebuild the standalone Chemiscope HTML visualizer from its source code, including cloning the repository, installing dependencies, and running the build script.
```Shell
git clone https://github.com/lab-cosmo/chemiscope
cd chemiscope
npm install
npm run build
python3 ./utils/generate_standalone.py
```
--------------------------------
### Define Dataset Properties
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Example of defining a dataset property with its target, values, units, and description.
```python
properties = {
"something": {
"target": "atom",
"values": [0.1, 0.0, -0.1, 0.2, -0.1, 0.0],
"units": "Cd / mol",
"description": "some description"
}
}
```
--------------------------------
### foreachOption Method
Source: https://chemiscope.org/docs/api/classes/StructureOptions.html
Iterates over each setting within the StructureOptions and applies a callback function. Keys starting with an underscore are ignored.
```APIDOC
## foreachOption
### Description
Calls the given callback on each setting inside the given SettingGroup. Keys starting with an underscore character are ignored.
### Signature
`foreachOption(callback): void`
### Parameters
* **callback** (OptionsCallback) - The callback function to apply to each setting.
* **callback(keys: string[], value: unknown): void**
### Returns
* **void**
```
--------------------------------
### Define Atom-Centered Environments
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Example of defining atom-centered environments, specifying structure, center atom, and cutoff radius.
```json
"environments": [
{"structure": 0, "center": 0, "cutoff": 3.5},
{"structure": 0, "center": 1, "cutoff": 3.5},
{"structure": 0, "center": 2, "cutoff": 3.5}
]
```
--------------------------------
### Programmatic Structure Selection with Slider
Source: https://chemiscope.org/docs/python/streamlit.html
This example demonstrates how to programmatically control the selected structure in the Chemiscope viewer using a Streamlit slider and synchronizing it with the viewer's `selected_index` and `on_select` callback.
```python
import streamlit as st
import chemiscope
st.slider(
"Select structure by index",
min_value=0,
max_value=len(structures) - 1,
key="selected_id",
)
def handle_selection(selection_id):
print(f"Selected structure: {selection_id}")
# You can set state variables to update automatically the text
st.session_state.selected_id = selection_id
if "selected_id" not in st.session_state:
st.session_state["selected_id"] = None
chemiscope.streamlit.viewer(
dataset,
selected_index=st.session_state.selected_id,
on_select=handle_selection
)
st.text(f"Selected structure ID: {st.session_state.selected_id}")
```
--------------------------------
### Interactive Structure Selection with Callback
Source: https://chemiscope.org/docs/_sources/python/streamlit.rst.txt
Example of using the 'on_select' callback to handle structure selection changes in the Chemiscope viewer and update Streamlit session state.
```python
import streamlit as st
import chemiscope
def handle_selection(selection_id):
print(f"Selected structure: {selection_id}")
# You can set state variables to update automatically the text
st.session_state.selected_id = selection_id
if "selected_id" not in st.session_state:
st.session_state["selected_id"] = None
chemiscope.streamlit.viewer(
dataset,
key="viewer",
on_select=handle_selection
)
st.text(f"Selected structure ID: {st.session_state.selected_id}")
```
--------------------------------
### Explore Structures with Custom Featurizer
Source: https://chemiscope.org/docs/_downloads/dfc154bea0f4cc5252869df3c3192477/6-explore.ipynb
This example shows how to pass a custom featurizer function to chemiscope.explore. It also configures the exploration settings to use specific features for the x and y axes.
```python
settings = chemiscope.quick_settings(x="features[1]", y="features[2]")
chemiscope.explore(
structures,
featurizer=fractional_composition_featurize,
settings=settings,
)
```
--------------------------------
### Chemiscope Exploration with Custom Featurizer
Source: https://chemiscope.org/docs/python/jupyter.html
Shows how to use `chemiscope.explore` with a custom featurization function. This example defines a function that computes SOAP descriptors and applies Kernel PCA for dimensionality reduction.
```python
import chemiscope
import ase.io
import dscribe.descriptors
import sklearn.decomposition
# Read the structures from the dataset
structures = ase.io.read("trajectory.xyz", ":")
# Define a function for dimensionality reduction
def soap_kpca_featurize(structures, environments):
if environments is not None:
raise ValueError("'environments' are not supported by this featurizer")
# Compute descriptors
soap = dscribe.descriptors.SOAP(
species=["C"],
r_cut=4.5,
n_max=8,
l_max=6,
periodic=True,
)
descriptors = soap.create(structures)
# Apply KPCA
kpca = sklearn.decomposition.KernelPCA(n_components=2, gamma=0.05)
# Return a 2D array of reduced features
return kpca.fit_transform(descriptors)
# 2) Example with a custom featurizer function
chemiscope.explore(structures, featurizer=soap_kpca_featurize)
```
--------------------------------
### Basic Chemiscope Exploration
Source: https://chemiscope.org/docs/examples/6-explore.html
Generates an interactive Chemiscope visualization using provided structures and a specified featurizer. This is the most basic way to start exploring your data.
```python
chemiscope.explore(structures, featurizer="pet-mad-1.0")
```
--------------------------------
### Per-Atom Arrows Example
Source: https://chemiscope.org/docs/getting-started/json-format.html
Illustrates creating per-atom arrows, useful for visualizing vectors like forces. Requires 'atom' array to match the total number of atoms.
```json
"shapes": {
"forces": {
"kind": "arrow",
"parameters": {
"global": {"baseRadius": 0.1, "headRadius": 0.2, "headLength": 0.3},
"atom": [
{"vector": [1.0, 0.0, 0.0]},
{"vector": [0.0, 1.0, 0.0]},
/* ... */
]
}
}
}
```
--------------------------------
### Custom Featurization with Fractional Composition and PCA
Source: https://chemiscope.org/docs/_sources/examples/6-explore.rst.txt
This example demonstrates how to define a custom featurization function for Chemiscope. It calculates fractional composition vectors and applies PCA for dimensionality reduction, suitable for advanced analysis where standard featurizers are insufficient.
```Python
import numpy as np # noqa
from sklearn.decomposition import PCA # noqa
def fractional_composition_featurize(structures, environments):
if environments is not None:
raise ValueError("'environments' are not supported by this featurizer")
dimentionality = 100
features = []
for structure in structures:
unique, counts = np.unique(structure.numbers, return_counts=True)
fractions = counts / len(structure.numbers)
feature_vector = np.zeros(dimentionality)
for element_number, franction in zip(unique, fractions, strict=True):
feature_vector[element_number - 1] = franction
features.append(feature_vector)
```
--------------------------------
### Serve Sphinx Documentation Locally
Source: https://chemiscope.org/docs/_sources/python/sphinx.rst.txt
Run a local HTTP server from the Sphinx build directory to view the generated HTML documentation, which is necessary for loading chemiscope widgets.
```bash
cd docs/build/html
python3 -m http.server 8765
```
--------------------------------
### Show Chemiscope Viewer from File
Source: https://chemiscope.org/docs/_downloads/6d034d5f3233213ef78ac81dfceae0a2/4-colors.ipynb
Displays the Chemiscope viewer directly from a previously generated input file ('colors-example.json.gz'). This bypasses the need to create a JSON file if the viewer is intended for immediate use, such as in a notebook.
```python
chemiscope.show_input("colors-example.json.gz")
```
--------------------------------
### constructor
Source: https://chemiscope.org/docs/api/classes/Warnings.html
Initializes a new instance of the Warnings class.
```APIDOC
## constructor
### Description
Initializes a new instance of the Warnings class.
### Method
constructor
### Returns
Warnings
```
--------------------------------
### Install Chemiscope via npm
Source: https://chemiscope.org/docs/_sources/embedding.rst.txt
Install the Chemiscope library into your existing JavaScript project using npm. This command adds the package to your project's dependencies.
```bash
npm install chemiscope
```
--------------------------------
### Get Structure Image Data
Source: https://chemiscope.org/docs/python/jupyter.html
Asynchronously requests a snapshot of the active structure viewer. This method should be 'await'ed in a Jupyter notebook to get the PNG formatted image data.
```python
data = await widget.get_structure_image()
```
--------------------------------
### Import Necessary Packages
Source: https://chemiscope.org/docs/_downloads/dfc154bea0f4cc5252869df3c3192477/6-explore.ipynb
Import the ase.io and chemiscope libraries for data loading and visualization.
```python
import ase.io
import chemiscope
```
--------------------------------
### Get and Display Map Image Data
Source: https://chemiscope.org/docs/python/jupyter.html
Asynchronously requests a snapshot of the map panel and displays it. This method should be 'await'ed in a Jupyter notebook to get the PNG formatted image data.
```python
# Get raw image data
data = await widget.get_map_image()
# Display it
from IPython.display import Image
display(Image(data))
```
--------------------------------
### Write and List Compressed Dataset Files
Source: https://chemiscope.org/docs/_sources/examples/1-base.rst.txt
This snippet shows how to write a compressed dataset file and then list all generated showcase and structure files. It's useful for understanding file output and organization.
```python
chemiscope.write_input(
"showcase-nostructures.json.gz",
structures=external_structures,
)
print("\nCompressed dataset files:")
for f in sorted(glob.glob("showcase*.json.gz")):
size = os.path.getsize(f)
print(f" {f} ({size} bytes)")
print("External structure files:")
for f in sorted(glob.glob("structure-*.json.gz")):
print(" ", f)
```
--------------------------------
### version()
Source: https://chemiscope.org/docs/api/functions/version.html
Get the version of chemiscope as a string.
```APIDOC
## version()
### Description
Get the version of chemiscope as a string.
### Returns
string
```
--------------------------------
### Callback for Settings Changes
Source: https://chemiscope.org/docs/python/streamlit.html
Demonstrates how to use the `on_settings_change` callback to capture and process changes made to the viewer's visualization settings. This allows for bi-directional manipulation of settings.
```python
def handle_settings_change(settings):
print("Visualization settings changed:", settings)
# store settings in session state, e.g. to update other components
st.session_state.viewer_settings = settings
chemiscope.streamlit.viewer(
dataset,
settings=settings,
on_settings_change=handle_settings_change
)
```
--------------------------------
### MapVisualizer.indexer
Source: https://chemiscope.org/docs/api/classes/MapVisualizer.html
Gets the indexer used by this visualizer.
```APIDOC
## MapVisualizer.indexer
### Description
Get the indexer used by this visualizer.
### Returns
EnvironmentIndexer
```
--------------------------------
### defaultTimeout
Source: https://chemiscope.org/docs/api/classes/Warnings.html
Gets or sets the default timeout for warning messages.
```APIDOC
## defaultTimeout
### Description
Represents the default timeout value for warning messages.
### Property
defaultTimeout: number = 0
```
--------------------------------
### structuresCount
Source: https://chemiscope.org/docs/api/classes/EnvironmentIndexer.html
Gets the total number of structures known by the indexer.
```APIDOC
## structuresCount
### Description
Get the total number of structures we know about.
### Returns
number - The total count of structures.
```
--------------------------------
### atomsCount
Source: https://chemiscope.org/docs/api/classes/EnvironmentIndexer.html
Gets the total number of atoms in a specified structure.
```APIDOC
## atomsCount
### Description
Get the total number of atom in the `structure` with given index.
### Parameters
* **structure** (number) - Required - The index of the structure.
### Returns
number - The total count of atoms in the structure.
```
--------------------------------
### removeMarker
Source: https://chemiscope.org/docs/api/classes/PropertiesMap.html
Removes a specific marker from the map using its GUID.
```APIDOC
## removeMarker
* removeMarker(guid): void
* Removes a marker from the map.
#### Parameters
* **guid** (GUID) - GUID of the marker to remove
#### Returns void
```
--------------------------------
### Remove Viewer
Source: https://chemiscope.org/docs/api/classes/ViewersGrid.html
Remove a specific viewer from the grid using its GUID.
```APIDOC
## removeViewer
### Description
Removes the viewer with the given `guid` from the viewer grid.
### Method
DELETE
### Endpoint
/viewers/{guid}
### Parameters
#### Path Parameters
- **guid** (GUID) - Required - The GUID of the viewer to remove.
```
--------------------------------
### Explore Structures with Featurizer and Environments
Source: https://chemiscope.org/docs/_downloads/270084ca30c16b2464906b9b5c6f72e0/8-explore-with-metatomic.ipynb
Visualize computed features from structures using chemiscope.explore. This requires the structures, a featurizer function, and a list of atomic environments.
```python
chemiscope.explore(
structures=structures,
featurizer=featurizer,
environments=chemiscope.all_atomic_environments(structures),
)
```
--------------------------------
### Get Pinned Environments
Source: https://chemiscope.org/docs/api/classes/ViewersGrid.html
Retrieve the list of environments currently displayed in the viewers.
```APIDOC
## pinned
### Description
Get the current list of environments showed inside the different viewer.
### Method
GET
### Endpoint
/viewers/pinned
### Returns
- **Indexes[]**: An array of indexes representing the pinned environments.
```
--------------------------------
### EnvironmentInfo Constructor
Source: https://chemiscope.org/docs/api/classes/EnvironmentInfo.html
Initializes a new EnvironmentInfo instance. This constructor sets up the UI elements for displaying and interacting with environment properties.
```APIDOC
## constructor
### Description
Create a new EnvironmentInfo inside the DOM element with given `id`.
### Method
constructor
### Signature
`new EnvironmentInfo(element: string | HTMLElement, properties: { [name: string]: Property }, indexer: EnvironmentIndexer, target: DisplayTarget, parameters?: { [name: string]: Parameter }, warnings?: Warnings): EnvironmentInfo`
### Parameters
#### element
(string | HTMLElement) - HTML element or string 'id' of the element where the sliders and tables should live.
#### properties
({ [name: string]: Property }) - Properties to be displayed.
* ##### [name: string]: Property
#### indexer
(EnvironmentIndexer) - EnvironmentIndexer used to translate indexes from environments index to structure/atom indexes.
#### target
(DisplayTarget) - Display target, either atom or structure.
#### parameters (Optional)
({ [name: string]: Parameter }) - Used to describe multidimensional properties.
* ##### [name: string]: Parameter
#### warnings (Optional)
(Warnings)
### Returns
EnvironmentInfo
```
--------------------------------
### setActive
Source: https://chemiscope.org/docs/api/classes/PropertiesMap.html
Sets a specific marker as the active marker on the map, identified by its GUID.
```APIDOC
## setActive
* setActive(guid): void
* Set the marker with given GUID as the active marker.
#### Parameters
* **guid** (GUID) - the GUID of the new active viewer
#### Returns void
```
--------------------------------
### Define Atom Properties
Source: https://chemiscope.org/docs/getting-started/json-format.html
Example of defining an atom-scoped property with its values, units, and description.
```python
properties = {
"something": {
"target": "atom",
"values": [0.1, 0.0, -0.1, 0.2, -0.1, 0.0],
"units": "Cd / mol",
"description": "some description"
}
}
```
--------------------------------
### Basic Chemiscope Exploration with Default Featurizer
Source: https://chemiscope.org/docs/python/jupyter.html
Demonstrates the basic usage of `chemiscope.explore` with the default PET-MAD featurizer for automatic feature extraction and dimensionality reduction. Structures are loaded from an XYZ file.
```python
import chemiscope
import ase.io
import dscribe.descriptors
import sklearn.decomposition
# Read the structures from the dataset
structures = ase.io.read("trajectory.xyz", ":")
# 1) Basic usage with default featurizer (PET-MAD featurization + Sketch-Map)
chemiscope.explore(structures, featurizer="pet-mad-1.0")
# or
featurizer = chemiscope.get_featurizer("pet-mad-1.0")
chemiscope.explore(structures, featurizer=featurizer)
```
--------------------------------
### Target Field Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Specifies the default view for the Chemiscope application. Can be 'atom' or 'structure'.
```json
"atom"
```
--------------------------------
### chemiscope.quick_settings
Source: https://chemiscope.org/docs/_sources/python/reference.rst.txt
Provides quick settings for chemiscope.
```APIDOC
## chemiscope.quick_settings
### Description
Provides quick settings for chemiscope.
### Function Signature
`chemiscope.quick_settings(*args, **kwargs)`
### Parameters
This function accepts arbitrary positional and keyword arguments.
### Returns
Details about the return value are not specified in the source.
```
--------------------------------
### Set Active Viewer
Source: https://chemiscope.org/docs/api/classes/ViewersGrid.html
Set the active viewer for communication with the map using its GUID.
```APIDOC
## setActive
### Description
Function to set the active viewer for communicating with the map.
### Method
PUT
### Endpoint
/viewers/active
### Parameters
#### Path Parameters
- **guid** (GUID) - Required - The GUID of the viewer to be set as active.
```
--------------------------------
### Add Viewer
Source: https://chemiscope.org/docs/api/classes/ViewersGrid.html
Add a new empty viewer to the grid and retrieve its color and GUID.
```APIDOC
## addViewer
### Description
Add a new empty viewer to the grid.
### Method
POST
### Endpoint
/viewers
### Returns
- **object**: An object containing the color and optional GUID of the new viewer.
- **color** (string) - The color assigned to the new viewer.
- **guid** (GUID) - Optional. The GUID of the new viewer, undefined if the viewer limit is reached.
```
--------------------------------
### Write Chemiscope Input File
Source: https://chemiscope.org/docs/_downloads/6d034d5f3233213ef78ac81dfceae0a2/4-colors.ipynb
Creates a Chemiscope input file ('colors-example.json.gz') with structures and computed properties. It configures visualization settings, including mapping properties to axes and colors, and enabling atom labels with specific property values.
```python
chemiscope.write_input(
"colors-example.json.gz",
structures=structures,
# properties can also be extracted from the ASE.Atoms structures
properties={
"polarizability": np.vstack(polarizability),
"anisotropy": np.vstack(anisotropy),
"alpha_eigenvalues": np.vstack(alpha_eigenvalues),
},
# it is also possible to define the default visualization settings, e.g. map axes,
# color property and palette, and to indicate that we want to show atom labels
# with the anisotropy value
settings={
"map": {
"x": {"property": "alpha_eigenvalues[1]"},
"y": {"property": "alpha_eigenvalues[2]"},
"z": {"property": "alpha_eigenvalues[3]"},
"color": {"property": "anisotropy", "palette": "inferno"},
},
"structure": [
{
"color": {"property": "anisotropy", "palette": "bwr"},
"atomLabels": True,
"labelsProperty": "anisotropy",
}
],
},
# the properties we want to visualise are atomic properties - in order to view them
# in map panel we must indicate the list of environments (all atoms in this case)
environments=chemiscope.all_atomic_environments(structures),
)
```
--------------------------------
### onremove
Source: https://chemiscope.org/docs/api/classes/ViewersGrid.html
Callback fired when a viewer is removed from the grid. It receives the GUID of the removed viewer.
```APIDOC
## onremove
### Description
Callback fired when a viewer is removed from the grid.
### Method
Callback
### Parameters
#### Parameters
- **guid** (GUID) - Required - GUID of the new viewer
### Returns
void
```
--------------------------------
### Loading Dataset from URL
Source: https://chemiscope.org/docs/getting-started/sharing.html
You can host your dataset on a web server and load it directly into Chemiscope using a URL. This allows for creating direct links to open specific datasets.
```URL
https://chemiscope.org/?load=https://university.edu/~myself/dataset.json
```
--------------------------------
### Clone Chemiscope Repository
Source: https://chemiscope.org/docs/_sources/embedding.rst.txt
Clone the Chemiscope repository from GitHub to build from sources. Ensure you have git installed.
```bash
git clone https://github.com/lab-cosmo/chemiscope
```
--------------------------------
### Static Method: DefaultVisualizer.load
Source: https://chemiscope.org/docs/api/classes/DefaultVisualizer.html
Loads a dataset and creates a DefaultVisualizer instance. This is an asynchronous operation that returns a Promise.
```APIDOC
## Static Method: load
### Description
Load a dataset and create a visualizer. This function returns a `Promise` to prevent blocking the browser while everything is loading.
### Parameters
- **config** (DefaultConfig): Configuration of the visualizer.
- **dataset** (Dataset): Visualizer input, containing a dataset and optional visualization settings.
- **warnings** (Warnings, optional): Optional warnings object.
### Returns
- Promise: Promise that resolves to a `DefaultVisualizer` instance.
```
--------------------------------
### Pinned Field Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Defines the indices of environments or structures to be pinned in viewers. Supports up to 9 indices.
```json
[0, 5, 10]
```
--------------------------------
### Creating a Chemiscope Widget
Source: https://chemiscope.org/docs/python/jupyter.html
Demonstrates how to create and display a Chemiscope visualizer within a Jupyter notebook. It covers modifying visualization settings and saving the dataset.
```APIDOC
## Creating a chemiscope widget
When inside a jupyter notebook, the returned object will create a new chemiscope visualizer displaying the dataset. The object exposes a `settings` traitlet, that allows to modify the visualization options (possibly even linking the parameters to another widget). Printing the value of the `settings` property is also a good way to see a full list of the available options.
The returned object also have a `save` function that can be used to save the dataset to a `.json` or `.json.gz` file to load it in the main website later. The visualization options will be those used in the active widget, so this is also a good way to tweak the appearance of the visualization before saving it.
```python
import chemiscope
from sklearn.decomposition import PCA
import ase.io
pca = PCA(n_components=3)
structures = ase.io.read(...)
properties = {
"PCA": pca.fit_transform(some_data),
}
widget = chemiscope.show(structures, properties)
# display the dataset in a chemiscope visualizer inside the notebook
widget
# ...
# NB: due to how traitlet work, you should always set the value of
# the `settings` property. Only the properties that are explicitly
# indicated will be modified.
widget.settings = {"map": {"symbol": "tag"}}
widget.settings["map"]["symbol"] = "tag" # << does nothing!
# Save the file for later use
widget.save("dataset.json")
```
```
--------------------------------
### Map Use LOD Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Enables level-of-detail rendering for large datasets in the scatter plot to improve performance.
```json
true
```
--------------------------------
### Combined Shape Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Groups multiple shapes (cylinders and spheres) into a single 'combined' shape for unified control.
```json
"shapes": {
"wireframe_box": {
"kind": "combined",
"shapes": [
{
"kind": "cylinders",
"parameters": {
"global": {"vectors": [[1,0,0], [0,1,0]], "radii": 0.05}
}
},
{
"kind": "spheres",
"parameters": {
"global": {"centers": [[0,0,0], [1,0,0], [0,1,0]], "radii": 0.1}
}
}
]
}
}
```
--------------------------------
### Headless Widget Initialization and Usage
Source: https://chemiscope.org/docs/_sources/python/jupyter.rst.txt
Demonstrates how to create and use a headless Chemiscope widget for programmatic interaction without a Jupyter interface. This requires installing the optional 'chemiscope[headless]' dependency and Playwright. The widget can modify settings, save images and sequences, export data, and must be closed to clean up resources.
```python
import chemiscope
from chemiscope import headless
# Load your data
structures = ...
properties = ...
# Create a headless widget instance
# This automatically downloads and configures the required browser
widget = headless(structures=structures, properties=properties, mode="structure")
# Modify settings programmatically
widget.settings = {'structure': [{'spaceFilling': True}]}
# Save a snapshot of the active structure
widget.save_structure_image("snapshot.png")
# Save a sequence of images
indices = [0, 1, 2]
paths = ["frame_0.png", "frame_1.png", "frame_2.png"]
widget.save_structure_sequence(indices, paths)
# Save the dataset to a JSON file
widget.save("dataset.json")
# Clean up resources
widget.close()
```
--------------------------------
### Define Parameters for Multidimensional Properties
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Example of defining parameters for multidimensional properties, including values, name, and units.
```json
"parameters": {
"time": {
"values": [0, 10, 20, 30], // matches length in linked property
"name": "Simulation time",
"units": "fs"
}
}
// linked property (from properties section)
"properties": {
"energy": {
"target": "structure",
"values": [[-1.0, -1.1, -1.2, -1.3], /* ... */],
"parameters": ["time"],
"units": "eV"
}
}
```
--------------------------------
### Importing Structures with Chemiscope and ASE
Source: https://chemiscope.org/docs/examples/9-stk-custom-bonds.html
This snippet shows how to read a structure from a temporary file using ASE and display it with chemiscope. It highlights chemiscope's automatic bond detection, which may be inaccurate for non-equilibrium structures.
```python
with tempfile.NamedTemporaryFile(suffix=".xyz") as tmpfile:
structures[0].write(tmpfile.name)
chemiscope.show(
structures=[ase.io.read(tmpfile.name)],
properties={i: [properties[i][0]] for i in properties},
settings=chemiscope.quick_settings(
x="aspheriticty",
y="uffenergy",
structure_settings={
"atoms": True,
"bonds": True,
"spaceFilling": False,
},
),
)
```
--------------------------------
### Map Camera Configuration Example
Source: https://chemiscope.org/docs/_sources/getting-started/json-format.rst.txt
Sets the initial camera position and zoom level for 3D plots in the scatter plot.
```json
{"eye": [1.5, 1.5, 1.5], "center": [0, 0, 0], "up": [0, 0, 1], "zoom": 1}
```