keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
2D | cbouy/mols2grid | DEVELOPMENT.md | .md | 2,333 | 71 | This is a short guide to setup a dev environment for mols2grid.
1. Install [uv](https://docs.astral.sh/uv/)
2. Create a new environment and install:
```
uv sync --python 3.11
```
We use [poethepoet](https://poethepoet.natn.io/) to define tasks to run in development environments.
You can run all of the checks detailed below using the command
```
uv run poe check
```
You can also get a list of available checks with:
```
uv run poe --help
```
a. Running tests
To run the test suite, simply execute:
```
uv run poe tests
```
You can select/skip the UI testing by specifying the `webdriver` mark in the pytest
command: `-m webdriver` to select UI tests only, or `-m "not webdriver"` to skip them.
b. Building the documentation
Building the HTML files for the documentation and tutorials can be done with the following command:
```
uv run poe docs
```
You can then open the `docs/_build/html/index.html` file with your browser to navigate the docs and
see any changes that you've made.
If you're adding a new module, you will need to update some `.rst` files in the `docs/api/`
folder.
You will find the tutorials notebooks in the `docs/notebooks/` section. These are Jupyter-notebook
files with a twist for Markdown cells: you can use the
[MyST syntax](https://myst-nb.readthedocs.io/en/latest/authoring/jupyter-notebooks.html#syntax)
to format the content. See the [Authoring section](https://myst-parser.readthedocs.io/en/latest/syntax/typography.html)
for more details.
c. Code formatting and linting
You can check if your code complies with our code style standards with the following command:
```
uv run poe style-check
```
You can automatically format your changes to match with the style used in this project, as well as
fixing any lint errors (unused imports, type annotations...etc.) with the following command:
```
uv run poe style-fix
```
Making a pull request will automatically run the tests and documentation build for you.
Don't forget to update the `CHANGELOG.md` file with your changes.
For versioning, you'll have to update both `package.json` and `mols2grid/_version.py`
files.
The build and deployment process is run automatically when making a release on
GitHub.
To make a prerelease, bump the versions accordingly (`X.Y.Z-rc1` format) and run
the `build` GitHub Action manually.
| Markdown |
2D | cbouy/mols2grid | mols2grid/datafiles.py | .py | 331 | 11 | import atexit
from contextlib import ExitStack
from importlib import resources
_file_manager = ExitStack()
atexit.register(_file_manager.close)
_data_resource = resources.files("mols2grid") / "data/"
datapath = _file_manager.enter_context(resources.as_file(_data_resource))
SOLUBILITY_SDF = str(datapath / "solubility.test.sdf")
| Python |
2D | cbouy/mols2grid | mols2grid/__init__.py | .py | 619 | 17 | from mols2grid import datafiles as datafiles
from mols2grid._version import __version__ as __version__
from mols2grid.callbacks import make_popup_callback as make_popup_callback
from mols2grid.dispatch import display as display
from mols2grid.dispatch import save as save
from mols2grid.molgrid import MolGrid as MolGrid
from mols2grid.select import get_selection as get_selection
from mols2grid.select import list_grids as list_grids
from mols2grid.utils import sdf_to_dataframe as sdf_to_dataframe
try:
from google.colab import output
except ImportError:
pass
else:
output.enable_custom_widget_manager()
| Python |
2D | cbouy/mols2grid | mols2grid/callbacks.py | .py | 6,334 | 183 | from typing import NamedTuple
from mols2grid.utils import env
class _JSCallback(NamedTuple):
"""Class that holds JavaScript code for running a callback function. If an external
library is required for the callback to function correctly, it can be passed in
the optional ``library_src`` as a ``<script>`` tag.
"""
code: str
library_src: str | None = None
def make_popup_callback(title=None, subtitle=None, svg=None, html="", js="", style=""):
"""Creates a JavaScript callback that displays a popup window
Parameters
----------
title : str
Title of the popup. Use ``title='${data["Name"]}'`` to use the value
of the column "Name" as a title
subtitle : str
Secondary title which works the same as title.
svg : str
SVG depiction of the molecule
html : str
Content of the popup window
js : str
JavaScript code executed before making the content of the popup window.
This allows you to create variables and reuse them later in the `html`
content of the popup, using the ``${my_variable}`` syntax
style : str
CSS style assigned to the popup window
Returns
-------
js_callback : str
JavaScript code that allows to display a popup window
"""
return env.get_template("js/popup.js").render(
title=title, subtitle=subtitle, html=html, svg=svg, js=js, style=style
)
def _get_title_field(title):
return "${data['" + title + "']}" if title else None
def info(title="SMILES", subtitle=None, img_size=(400, 300), style="") -> _JSCallback:
"""Displays a bigger image of the molecule, alongside some useful descriptors:
molecular weight, number of Hydrogen bond donors and acceptors, TPSA, Crippen ClogP
and InChIKey.
Parameters
----------
title : str
Title of the popup. Use ``title='${data["Name"]}'`` to use the value
of the column "Name" as a title
subtitle : str
Secondary title which works the same as title.
img_size : tuple
Width and height of the molecule depiction.
style : str
CSS style applied to the modal window.
"""
code = make_popup_callback(
title=_get_title_field(title),
subtitle=_get_title_field(subtitle),
svg="${svg}",
js=f"""
let mol = RDKit.get_mol(data["SMILES"]);
let svg = mol.get_svg({img_size[0]}, {img_size[1]});
let desc = JSON.parse(mol.get_descriptors());
let inchikey = RDKit.get_inchikey_for_inchi(mol.get_inchi());
mol.delete();
""",
html="""
<b>Molecular weight</b>: ${desc.exactmw}<br/>
<b>HBond Acceptors</b>: ${desc.NumHBA}<br/>
<b>HBond Donors</b>: ${desc.NumHBD}<br/>
<b>TPSA</b>: ${desc.tpsa}<br/>
<b>ClogP</b>: ${desc.CrippenClogP}<br/>
<hr>
<b>InChIKey</b>: ${inchikey}
""",
style=style,
)
return _JSCallback(code=code)
def show_3d(
title="SMILES",
subtitle=None,
query=None,
height="100%",
style="width:100%;height:100%",
) -> _JSCallback:
"""Queries the API(s) listed in ``query`` using the SMILES of the structure, to
fetch the 3D structure and display it with ``3Dmol.js``
Parameters
----------
title : str
Title of the popup. Use ``title='${data["Name"]}'`` to use the value
of the column "Name" as a title
subtitle : str
Secondary title which works the same as title.
query : list or dict
List of APIs used to fetch the 3D structure from (by order of priority). To use
a custom API, use a dict with the following format::
{
"url": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{}/SDF?record_type=3d",
"format": "sdf",
"field": "SMILES",
"encode": True,
}
In this example, the value in the ``SMILES`` field will be URI-encoded and
replace the curly-braces in the ``url`` strings to create the URL to fetch
the 3D structure from in the SDF format.
height : str
Height of the 3Dmol.js viewer in the modal.
style : str
CSS style applied to the modal window.
"""
if query is None:
query = ["pubchem", "cactus"]
js_script = env.get_template("js/callbacks/show_3d.js").render(query=query)
code = make_popup_callback(
title=_get_title_field(title),
subtitle=_get_title_field(subtitle),
html=f'<div id="molviewer" style="width: 100%; height: {height};"></div>',
js=js_script,
style=style,
)
library = (
'<script src="https://cdnjs.cloudflare.com/ajax/libs/3Dmol/1.8.0/'
'3Dmol-nojquery-min.js" integrity="sha512-9iiTgstim185ZZPL/nZ+t+MLMmIbZEMfoZ1sw'
'SBUhxt4AukOPY34yyO2217X1dN5ziVMKi+YLmp/JBj+KyEaUQ==" crossorigin="anonymous" '
'referrerpolicy="no-referrer"></script>'
)
return _JSCallback(code=code, library_src=library)
def external_link(
url="https://leruli.com/search/{}/home",
field="SMILES",
url_encode=False,
b64_encode=True,
) -> _JSCallback:
"""Opens an external link using ``url`` as a template string and the value in the
corresponding ``field``. The value can be URL-encoded or base64-encoded if needed.
Parameters
----------
url : str
Template string used to generate the URL that will be opened.
field : str
Field name used to generate the URL that will be opened. The value can be
encoded (see below).
url_encode : bool
Encode the value fetched from the specified field to replace characters that are
not allowed in a URL e.g., spaces become ``%20``.
b64_encode : bool
Base64-encode the value fetched from the field.
Raises
------
ValueError : Both ``url_encode`` and ``b64_encode`` have been specified.
"""
if url_encode and b64_encode:
raise ValueError("Setting both URL and B64 encoding is not supported")
code = env.get_template("js/callbacks/external_link.js").render(
url=url,
field=field,
url_encode=url_encode,
b64_encode=b64_encode,
)
return _JSCallback(code=code)
| Python |
2D | cbouy/mols2grid | mols2grid/select.py | .py | 1,810 | 64 | import warnings
from ast import literal_eval
from mols2grid.utils import is_running_within_marimo
class SelectionRegister:
"""Register for grid selections
Attributes
----------
SELECTIONS : dict
Stores each grid selection according to their name
current_selection : str
Name of the most recently updated grid
"""
def __init__(self):
self.SELECTIONS = {}
def _update_current_grid(self, name):
self.current_selection = name
def _init_grid(self, name):
overwrite = self.SELECTIONS.get(name, False)
if overwrite and not is_running_within_marimo():
warnings.warn(
f"Overwriting non-empty {name!r} grid selection: {overwrite!s}",
stacklevel=2,
)
self.SELECTIONS[name] = {}
self._update_current_grid(name)
def selection_updated(self, name, event):
self.SELECTIONS[name] = literal_eval(event.new)
self._update_current_grid(name)
def get_selection(self, name=None):
"""Returns the selection for a specific MolGrid instance
Parameters
----------
name : str or None
Name of the grid to fetch the selection from. If `None`, the most
recently updated grid is returned
"""
name = self.current_selection if name is None else name
return self.SELECTIONS[name]
def list_grids(self):
"""Returns a list of grid names"""
return list(self.SELECTIONS.keys())
def _clear(self):
"""Clears all selections"""
if hasattr(self, "current_selection"):
del self.current_selection
self.SELECTIONS.clear()
register = SelectionRegister()
get_selection = register.get_selection
list_grids = register.list_grids
| Python |
2D | cbouy/mols2grid | mols2grid/utils.py | .py | 3,946 | 146 | import gzip
import re
from ast import literal_eval
from functools import partial, wraps
from importlib.util import find_spec
from pathlib import Path
import pandas as pd
from jinja2 import Environment, FileSystemLoader
from rdkit import Chem
env = Environment(
loader=FileSystemLoader(Path(__file__).parent / "templates"), autoescape=False
)
def requires(module):
def inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
if find_spec(module):
return func(*args, **kwargs)
raise ModuleNotFoundError(
f"The module {module!r} is required to use {func.__name__!r} "
"but it is not installed!"
)
return wrapper
return inner
def tooltip_formatter(s, subset, fmt, style, transform):
"""Function to generate tooltips from a pandas Series
Parameters
----------
s : pandas.Series
Row in the internal pandas DataFrame
subset : list
Subset of columns that are used for the tooltip
fmt : str
Format string for each key-value pair of the tooltip
style : dict
CSS styling applied to each item independently
transform : dict
Functions applied to each value before rendering
"""
items = []
for k, v in s[subset].to_dict().items():
displayed = transform[k](v) if transform.get(k) else v
value = (
f'<span class="copy-me" style="{style[k](v)}">{displayed}</span>'
if style.get(k)
else f'<span class="copy-me">{displayed}</span>'
)
items.append(fmt.format(key=k, value=value))
return "<br>".join(items)
def mol_to_smiles(mol):
"""Returns a SMILES from an RDKit molecule, or None if not an RDKit mol"""
return Chem.MolToSmiles(mol) if mol else None
def mol_to_record(mol, mol_col="mol"):
"""Function to create a dict of data from an RDKit molecule"""
return {**mol.GetPropsAsDict(includePrivate=True), mol_col: mol} if mol else {}
def sdf_to_dataframe(sdf_path, mol_col="mol"):
"""Creates a dataframe of molecules from an SDFile. All property fields in
the SDFile are made available in the resulting dataframe
Parameters
----------
sdf_path : str, Path
Path to the SDFile, ending with either ``.sdf`` or ``.sdf.gz``
mol_col : str
Name of the column containing the RDKit molecules in the dataframe
Returns
-------
df : pandas.DataFrame
"""
read_file = gzip.open if str(sdf_path).endswith(".gz") else partial(open, mode="rb")
with read_file(sdf_path) as f:
return pd.DataFrame(
[mol_to_record(mol, mol_col) for mol in Chem.ForwardSDMolSupplier(f)]
)
def remove_coordinates(mol):
"""Removes the existing coordinates from the molecule. The molecule is
modified inplace"""
mol.RemoveAllConformers()
return mol
def slugify(string):
"""Replaces whitespaces with hyphens"""
return re.sub(r"\s+", "-", string)
def callback_handler(callback, event):
"""Handler for applying the callback function on change"""
data = literal_eval(event.new)
callback(data)
def _get_streamlit_script_run_ctx():
from streamlit.runtime.scriptrunner import get_script_run_ctx
return get_script_run_ctx()
def is_running_within_streamlit():
"""
Function to check whether python code is run within streamlit
Returns
-------
use_streamlit : boolean
True if code is run within streamlit, else False
"""
try:
ctx = _get_streamlit_script_run_ctx()
except ImportError:
return False
else:
return ctx is not None
def is_running_within_marimo():
"""
Function to check whether python code is run within marimo
Returns
-------
use_marimo : boolean
True if code is run within marimo, else False
"""
import sys
return "marimo" in sys.modules
| Python |
2D | cbouy/mols2grid | mols2grid/dispatch.py | .py | 12,747 | 303 | import inspect
from functools import singledispatch
from pathlib import Path
from pandas import DataFrame, Series
from mols2grid.molgrid import MolGrid
_SIGNATURE = {
method: dict(inspect.signature(getattr(MolGrid, method)).parameters.items())
for method in ["render", "to_interactive", "to_static", "display"]
}
for method in ["render", "to_interactive", "to_static", "display"]:
_SIGNATURE[method].pop("self")
if method in {"render", "display"}:
_SIGNATURE[method].pop("kwargs")
def _prepare_kwargs(kwargs, kind):
"""Separate kwargs for the init and render methods of MolGrid"""
template = kwargs.pop("template", _SIGNATURE["render"]["template"].default)
render_kwargs = {
param: kwargs.pop(param, sig.default)
for param, sig in _SIGNATURE[f"to_{template}"].items()
}
if kind == "display":
render_kwargs.update(
{
param: kwargs.pop(param, sig.default)
for param, sig in _SIGNATURE["display"].items()
}
)
return template, kwargs, render_kwargs
@singledispatch
def display(arg, **kwargs): # noqa: ARG001
"""Display molecules on an interactive grid.
Parameters: Data
----------------
arg : pandas.DataFrame, SDF file or list of molecules
The input containing your molecules.
smiles_col : str or None, default="SMILES"
If a pandas dataframe is used, name of the column with SMILES.
mol_col : str or None, default=None
If a pandas dataframe is used, name of the column with RDKit molecules.
If available, coordinates and atom/bonds annotations from this will be
used for depiction.
Parameters: Display
-------------------
template : str, default="interactive"
Either ``"interactive"`` or ``"static"``. See ``render()`` for more details.
size : tuple, default=(130, 90)
The size of the drawing canvas. The cell minimum width is set to the
width of the image, so if the cell padding is increased, the image will
be displayed smaller.
useSVG : bool, default=True
Use SVG images instead of PNG.
prerender : bool, default=False
Prerender images for the entire dataset, or generate them on-the-fly.
Prerendering is slow and memory-hungry, but required when ``template="static"``
or ``useSVG=False``.
subset: list or None, default=None
Columns to be displayed in each cell of the grid. Each column's
value will be displayed from top to bottom in the order provided.
The ``"img"`` and ``"mols2grid-id"`` columns are displayed by default,
however you can still add the ``"img"`` column if you wish to change
the display order.
tooltip : list, None or False, default=None
Columns to be displayed inside the tooltip. When no subset is set,
all columns will be listed in the tooltip by default. Use ``False``
to hide the tooltip.
tooltip_fmt : str, default="<strong>{key}</strong>: {value}"
Format string of each key/value pair in the tooltip.
tooltip_trigger : str, default="focus"
Only available for the "static" template.
Sequence of triggers for the tooltip: ``click``, ``hover`` or ``focus``
tooltip_placement : str, default="auto"
Position of the tooltip: ``auto``, ``top``, ``bottom``, ``left`` or
``right``
transform : dict or None, default=None
Functions applied to specific items in all cells. The dict must follow
a ``key: function`` structure where the key must correspond to one of
the columns in ``subset`` or ``tooltip``. The function takes the item's
value as input and transforms it, for example::
transform={
"Solubility": lambda x: f"{x:.2f}",
"Melting point": lambda x: f"MP: {5/9*(x-32):.1f}°C"
}
These transformations only affect columns in ``subset`` and
``tooltip``, and do not interfere with ``style``.
sort_by : str or None, default=None
Sort the grid according to the following field (which must be
present in ``subset`` or ``tooltip``).
truncate: bool, default=True/False
Whether to truncate the text in each cell if it's too long.
Defaults to ``True`` for interactive grids, ``False`` for static grid.
n_items_per_page, default=24
Only available for the "interactive" template.
Number of items to display per page. A multiple of 12 is recommended
for optimal display.
n_cols : int, default=5
Only available for the "static" template.
Number of columns in the table.
selection : bool, default=True
Only available for the "interactive" template.
Enables the selection of molecules and displays a checkbox at the
top of each cell. In the context of a Jupyter Notebook, this gives
you access to your selection (index and SMILES) through
:func:`mols2grid.get_selection()` or :meth:`MolGrid.get_selection()`.
In all cases, you can export your selection by clicking on the triple-dot menu.
cache_selection : bool, default=False
Only available for the "interactive" template.
Restores the selection from a previous grid with the same name.
use_iframe : bool, default=False
Whether to use an iframe to display the grid. When the grid is displayed
inside a Jupyter Notebook or JupyterLab, this will default to ``True``.
iframe_width : str, default="100%
Width of the iframe
iframe_height : int or None, default=None
Height of the frame. When set to ``None``, the height is set dynamically
based on the content.
Parameters: Mols
----------------
removeHs : bool, default=False
Remove hydrogen atoms from the drawings.
use_coords : bool, default=False
Use the coordinates of the molecules (only relevant when an SDF file, a
list of molecules or a DataFrame of RDKit molecules were used as input.)
coordGen : bool, default=True
Use the CoordGen library instead of the RDKit one to depict the
molecules in 2D.
MolDrawOptions : rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions or None, default=None
Drawing options. Useful for making highly customized drawings.
substruct_highlight : bool or None, default=None
Highlight substructure when using the SMARTS search. Active by default
when ``prerender=False``.
single_highlight : bool, default=False
Highlight only the first match of the substructure query.
Parameters: CSS
---------------
border : str, default="1px solid #cccccc"
Styling of the border around each cell.
gap : int, default=0
Size in pixels of the gap between cells.
pad : int, default=10
Size in pixels of the cell padding.
fontsize : str, default="12px"
Font size of the text displayed in each cell.
fontfamily : str, default="'DejaVu', sans-serif"
Font used for the text in each cell.
textalign : str, default="center"
Alignment of the text in each cell.
background_color : str, default="white"
Only available for the "interactive" template.
Background color of a cell.
hover_color : str, default="rgba(0,0,0,0.05)"
Only available for the "interactive" template.
Background color when hovering a cell
custom_css : str or None, default=None
Custom CSS properties applied to the generated HTML. Please note that
the CSS will apply to the entire page if no iframe is used (see
``use_iframe`` for more details).
style : dict or None, default=None
CSS styling applied to each item in a cell. The dict must follow a
``key: function`` structure where the key must correspond to one of the
columns in ``subset`` or ``tooltip``. The function takes the item's
value as input, and outputs a valid CSS styling. For example, if you
want to color the text corresponding to the "Solubility" column in your
dataframe::
style={"Solubility": lambda x: "color: red" if x < -5 else ""}
You can also style a whole cell using the ``__all__`` key, the
corresponding function then has access to all values for each cell::
style={"__all__": lambda x: "color: red" if x["Solubility"] < -5 else ""}
Parameters: Customization
-------------------------
name : str, default="default"
Name of the grid. Used when retrieving selections from multiple grids
at the same time
rename : dict or None, default=None
Rename the properties in the final document.
custom_header : str or None, default=None
Custom libraries to be loaded in the header of the document.
callback : str, callable or None, default=None
Only available for the "interactive" template.
JavaScript or Python callback to be executed when clicking on an image.
A dictionnary containing the data for the full cell is directly available
as ``data`` in JS. For Python, the callback function must have ``data``
as the first argument to the function. All the values in the ``data`` dict
are parsed as strings, except "mols2grid-id" which is always an integer.
Note that fields containing spaces in their name will be replaced by
hyphens, i.e. "mol weight" becomes available as ``data["mol-weight"]``.
Returns
-------
view : IPython.core.display.HTML
Notes
-----
You can also directly use RDKit's
:class:`~rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions` parameters as arguments.
Additionally, ``atomColourPalette`` is available to customize the atom
palette if you're not prerendering image (``prerender=False``).
.. versionadded:: 0.1.0
Added ``sort_by``, ``custom_css``, ``custom_header`` and ``callback``
arguments. Added the ability to style an entire cell with
``style={"__all__": <function>}``.
.. versionadded:: 0.2.0
Added ``substruct_highlight`` argument.
.. versionchanged:: 0.2.2
If both ``subset`` and ``tooltip`` are ``None``, the index and image
will be directly displayed on the grid while the remaining fields will
be in the tooltip.
.. versionchanged:: 1.0.0
``callback`` can now be a *lambda* function. If ``prerender=True``,
substructure highlighting will be automatically disabled if it wasn't
explicitely set to ``True`` instead of raising an error.
"""
raise TypeError(f"No display method registered for type {type(arg)!r}")
@display.register(DataFrame)
@display.register(dict)
def _(df, **kwargs):
template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "display")
return MolGrid(df, **kwargs).display(template=template, **render_kwargs)
@display.register(str)
@display.register(Path)
def _(sdf, **kwargs):
template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "display")
return MolGrid.from_sdf(sdf, **kwargs).display(template=template, **render_kwargs)
@display.register(Series)
@display.register(list)
@display.register(tuple)
def _(mols, **kwargs):
template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "display")
return MolGrid.from_mols(mols, **kwargs).display(template=template, **render_kwargs)
@singledispatch
def save(arg, **kwargs): # noqa: ARG001
"""Generate an interactive grid of molecules and save it.
Parameters
----------
arg : pandas.DataFrame, SDF file or list of molecules
The input containing your molecules.
output : str
Name and path of the output document.
Notes
-----
See :func:`display` for the full list of arguments.
"""
raise TypeError(f"No save method registered for type {type(arg)!r}")
@save.register(DataFrame)
def _(df, **kwargs):
template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "save")
output = kwargs.pop("output")
return MolGrid(df, **kwargs).save(output, template=template, **render_kwargs)
@save.register(str)
@save.register(Path)
def _(sdf, **kwargs):
template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "save")
output = kwargs.pop("output")
return MolGrid.from_sdf(sdf, **kwargs).save(
output, template=template, **render_kwargs
)
@save.register(Series)
@save.register(list)
@save.register(tuple)
def _(mols, **kwargs):
template, kwargs, render_kwargs = _prepare_kwargs(kwargs, "save")
output = kwargs.pop("output")
return MolGrid.from_mols(mols, **kwargs).save(
output, template=template, **render_kwargs
)
| Python |
2D | cbouy/mols2grid | mols2grid/widget.py | .py | 1,108 | 36 | from pathlib import Path
import anywidget
from traitlets import Bool, List, Unicode
from mols2grid._version import __version__ # noqa: F401
BUNDLER_OUTPUT_DIR = Path(__file__).parent / "static"
class MolGridWidget(anywidget.AnyWidget):
"""A custom widget for the MolGrid class. Handles selections and callbacks.
Attributes
----------
grid_id : str
Name of the grid controlling the widget
selection : str
JSON string containing the molecule selection as a dictionnary. Index
are keys and SMILES string are values.
callback_kwargs : str
JSON string containing the keyword arguments with which to call the
callback function.
filter_mask : List[bool]
List stating wether a molecule should be kept (True) or filtered out
(False)
"""
_esm = BUNDLER_OUTPUT_DIR / "widget.js"
_css = BUNDLER_OUTPUT_DIR / "widget.css"
grid_id = Unicode("default").tag(sync=True)
selection = Unicode("{}").tag(sync=True)
callback_kwargs = Unicode("{}").tag(sync=True)
filter_mask = List(Bool(), []).tag(sync=True)
| Python |
2D | cbouy/mols2grid | mols2grid/_version.py | .py | 22 | 2 | __version__ = "2.2.0"
| Python |
2D | cbouy/mols2grid | mols2grid/molgrid.py | .py | 43,650 | 1,137 | import ast
import json
import warnings
from base64 import b64encode
from functools import partial
from html import escape
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Draw
from mols2grid.callbacks import _JSCallback
from mols2grid.select import register
from mols2grid.utils import (
callback_handler,
env,
is_running_within_marimo,
is_running_within_streamlit,
mol_to_record,
mol_to_smiles,
remove_coordinates,
requires,
sdf_to_dataframe,
slugify,
tooltip_formatter,
)
from mols2grid.widget import MolGridWidget
try:
from IPython.display import HTML, Javascript, display
except ModuleNotFoundError:
pass
else:
warnings.filterwarnings("ignore", "Consider using IPython.display.IFrame instead.")
# Detect if mols2grid is running inside a Jupyter Notebook/Lab.
# If it is, we wrap the HTML in an iframe.
try:
get_ipython() # This is callable only in Jupyter Notebook.
is_jupyter = True
except NameError:
is_jupyter = False
class MolGrid:
"""Class that handles drawing molecules, rendering the HTML document and
saving or displaying it in a Jupyter Notebook.
Parameters: Data
----------------
df : pandas.DataFrame, dict or list, required
Dataframe containing a SMILES or mol column, or dictionary containing a
list of SMILES, or list of dictionnaries containing a SMILES field.
smiles_col : str or None, default="SMILES"
Name of the SMILES column in the dataframe, if available.
mol_col : str or None, default=None
Name of an RDKit molecule column. If available, coordinates and
atom/bonds annotations from this will be used for depiction.
Parameters: Display
-------------------
size : tuple, default=(130, 90)
The size of the drawing canvas. The cell minimum width is set to the
width of the image, so if the cell padding is increased, the image will
be displayed smaller.
useSVG : bool, default=True
Use SVG images instead of PNG.
prerender : bool, default=False
Prerender images for the entire dataset, or generate them on-the-fly.
Prerendering is slow and memory-hungry, but required when ``template="static"``
or ``useSVG=False``.
cache_selection : bool, default=False
Restores the selection from a previous grid with the same name.
Parameters: Mols
----------------
removeHs : bool, default=False
Remove hydrogen atoms from the drawings.
use_coords : bool, default=False
Use the coordinates of the molecules (only relevant when an SDF file, a
list of molecules or a DataFrame of RDKit molecules were used as input.)
coordGen : bool, default=True
Use the CoordGen library instead of the RDKit one to depict the
molecules in 2D.
MolDrawOptions : rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions or None, default=None
Drawing options. Useful for making highly customized drawings.
Parameters: Customization
-------------------------
name : str, default="default"
Name of the grid. Used when retrieving selections from multiple grids
at the same time.
rename : dict or None, default=None
Rename the properties in the final document.
kwargs : object
:class:`~rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions` attributes, and
the additional ``atomColourPalette``.
Notes
-----
On-the-fly rendering of images does not read the atom colour palette
from the :class:`~rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions` parameter.
If this is needed, use the following::
MolGrid(df, atomColourPalette={1: (.8, 0, 1)})
.. versionchanged:: 0.1.0
Added ``rename`` parameter to replace ``mapping``.
.. versionadded:: 0.2.0
Added ``prerender`` and ``cache_selection`` parameters.
.. versionchanged:: 0.2.0
Images are now generated on-the-fly. ``use_coords`` is now ``False`` by
default to avoid a systematic error when using ``MolGrid.from_sdf``.
"""
def __init__( # noqa: PLR0912
self,
df,
smiles_col="SMILES",
mol_col=None,
size=(130, 90),
useSVG=True,
prerender=False,
cache_selection=False,
removeHs=False,
use_coords=False,
coordGen=True,
MolDrawOptions=None,
name="default",
rename=None,
**kwargs,
):
if not (smiles_col or mol_col):
raise ValueError("One of `smiles_col` or `mol_col` must be set")
if not isinstance(name, str):
raise TypeError(
f"`name` must be a string. Currently of type {type(name).__name__}"
)
if not prerender:
if not useSVG:
raise ValueError("On-the-fly rendering of PNG images not supported")
if use_coords and mol_col:
raise ValueError("Cannot use coordinates with on-the-fly rendering")
self.prefer_coordGen = coordGen
self.removeHs = removeHs
self.useSVG = useSVG
self.use_coords = use_coords
self.img_size = size
self.prerender = prerender
self.smiles_col = smiles_col
self.mol_col = mol_col
dataframe = df.copy() if isinstance(df, pd.DataFrame) else pd.DataFrame(df)
if rename:
dataframe = dataframe.rename(columns=rename)
self._extra_columns = ["img", "mols2grid-id"]
# Add index.
dataframe["mols2grid-id"] = list(range(len(dataframe)))
# Generate drawing options.
if prerender:
Draw.rdDepictor.SetPreferCoordGen(coordGen)
opts = MolDrawOptions or Draw.MolDrawOptions()
for key, value in kwargs.items():
setattr(opts, key, value)
self.MolDrawOptions = opts
self._MolDraw2D = Draw.MolDraw2DSVG if useSVG else Draw.MolDraw2DCairo
else:
opts = {}
if MolDrawOptions:
for key in dir(MolDrawOptions):
value = getattr(MolDrawOptions, key)
if not (
key.startswith("_")
or callable(value)
or value.__class__.__module__ != "builtins"
):
opts[key] = value
opts.update(kwargs)
opts.update({"width": self.img_size[0], "height": self.img_size[1]})
self.json_draw_opts = json.dumps(opts)
# Prepare smiles and images.
self.dataframe = self._prepare_dataframe(dataframe)
# Register instance.
self._grid_id = name
if cache_selection:
try:
self._cached_selection = register.get_selection(name)
except KeyError:
self._cached_selection = {}
register._init_grid(name)
else:
register._update_current_grid(name)
else:
self._cached_selection = {}
register._init_grid(name)
# Create widget.
widget = MolGridWidget(grid_id=name, selection=str(self._cached_selection))
selection_handler = partial(register.selection_updated, name)
widget.observe(selection_handler, names=["selection"])
# Register widget JS-side.
if not is_running_within_marimo():
display(widget)
self.widget = widget
@classmethod
def from_mols(cls, mols, **kwargs):
"""Set up the dataframe used by mols2grid directly from a list of RDKit
molecules.
Parameters
----------
mols : list
List of RDKit molecules
kwargs : object
Other arguments passed on initialization
"""
mol_col = kwargs.pop("mol_col", "mol")
df = pd.DataFrame([mol_to_record(mol, mol_col=mol_col) for mol in mols])
return cls(df, mol_col=mol_col, **kwargs)
@classmethod
def from_sdf(cls, sdf_file, **kwargs):
"""Set up the dataframe used by mols2grid directly from an SDFile.
Parameters
----------
sdf_file : str, pathlib.Path
Path to the SDF file (.sdf or .sdf.gz)
kwargs : object
Other arguments passed on initialization
.. versionchanged:: 0.2.0
Added support for `.sdf.gz` files
"""
mol_col = kwargs.pop("mol_col", "mol")
df = sdf_to_dataframe(sdf_file, mol_col=mol_col)
return cls(df, mol_col=mol_col, **kwargs)
@property
def template(self):
"""Kind of grid displayed, one of:
* interactive
* static
"""
return self._template
@template.setter
def template(self, value):
if value not in {"interactive", "static"}:
raise ValueError(
f"template={value!r} not supported. "
"Use either 'interactive' or 'static'."
)
self._template = value
def draw_mol(self, mol):
"""Draw a molecule."""
d2d = self._MolDraw2D(*self.img_size)
d2d.SetDrawOptions(self.MolDrawOptions)
hl_atoms = getattr(mol, "__sssAtoms", [])
d2d.DrawMolecule(mol, highlightAtoms=hl_atoms)
d2d.FinishDrawing()
return d2d.GetDrawingText()
def mol_to_img(self, mol):
"""Convert an RDKit mol to an inline PNG image containing a drawing of the
molecule."""
img = self.draw_mol(mol)
if self.useSVG:
return img
data = b64encode(img).decode()
return f'<img src="data:image/png;base64,{data}">'
def _prepare_dataframe(self, dataframe):
"""Prepares the dataframe with SMILES and images depending on user input. The
dataframe is modified inplace."""
if self.prerender:
if self.mol_col:
keep_mols = True
else:
# Make temporary mol column if not present.
self.mol_col = "mol"
keep_mols = False
dataframe[self.mol_col] = dataframe[self.smiles_col].apply(
Chem.MolFromSmiles
)
# Drop empty mols.
dataframe = dataframe.dropna(axis=0, subset=[self.mol_col])
# Modify mol according to user pref.
if not self.use_coords:
dataframe[self.mol_col] = dataframe[self.mol_col].apply(
remove_coordinates
)
if self.removeHs:
dataframe[self.mol_col] = dataframe[self.mol_col].apply(Chem.RemoveHs)
# Render.
dataframe["img"] = dataframe[self.mol_col].apply(self.mol_to_img)
# Cleanup.
if not keep_mols:
dataframe = dataframe.drop(columns=self.mol_col)
self.mol_col = None
else:
dataframe["img"] = None
# Generate smiles col if not present or needs to be updated.
if self.mol_col and self.smiles_col not in dataframe.columns:
dataframe[self.smiles_col] = dataframe[self.mol_col].apply(mol_to_smiles)
return dataframe
def render(self, template="interactive", **kwargs):
"""Returns the HTML document corresponding to the "interactive" or "static"
template. See :meth:`to_interactive` and :meth:`to_static` for the full list
of arguments.
Parameters
----------
template : str
What kind of grid to draw:
* interactive
An interactive grid that layouts the original set of
molecules on several pages, allowing for selecting molecules and
filtering them using text or substructure queries.
* static
A simple table with all molecules displayed at once, similarly
to RDKit's :func:`~rdkit.Chem.Draw.rdMolDraw2D.MolsToGridImage`.
This template is mainly used for printing on paper or in a PDF
file. Most of the interactive actions aren't available.
"""
self.template = template
return getattr(self, f"to_{self.template}")(**kwargs)
def to_interactive( # noqa: PLR0912
self,
# Display
subset=None,
tooltip=None,
tooltip_fmt="<strong>{key}</strong>: {value}",
tooltip_placement="auto",
transform=None,
sort_by=None,
use_iframe=False,
truncate=True,
n_items_per_page=24,
selection=True,
# Mols
substruct_highlight=None,
single_highlight=False,
# CSS
border="1px solid #cccccc",
gap=0,
pad=10,
fontsize="12px",
fontfamily="'DejaVu', sans-serif",
textalign="center",
background_color="white",
hover_color="rgba(0,0,0,0.05)",
custom_css=None,
style=None,
# Customization
custom_header=None,
callback=None,
):
"""Returns the HTML document for the "interactive" template.
Parameters: Display
-------------------
subset: list or None, default=None
Columns to be displayed in each cell of the grid. Each column's
value will be displayed from top to bottom in the order provided.
The ``"img"`` and ``"mols2grid-id"`` columns are displayed by default,
however you can still add the ``"img"`` column if you wish to change
the display order.
tooltip : list, None or False, default=None
Columns to be displayed inside the tooltip. When no subset is set,
all columns will be listed in the tooltip by default. Use ``False``
to hide the tooltip.
tooltip_fmt : str, default="<strong>{key}</strong>: {value}"
Format string of each key/value pair in the tooltip.
tooltip_placement : str, default="auto"
Position of the tooltip: ``auto``, ``top``, ``bottom``, ``left`` or
``right``.
transform : dict or None, default=None
Functions applied to specific items in all cells. The dict must follow
a ``key: function`` structure where the key must correspond to one of
the columns in ``subset`` or ``tooltip``. The function takes the item's
value as input and transforms it, for example::
transform={
"Solubility": lambda x: f"{x:.2f}",
"Melting point": lambda x: f"MP: {5/9*(x-32):.1f}°C"
}
These transformations only affect columns in ``subset`` and
``tooltip``, and do not interfere with ``style``.
sort_by : str or None, default=None
Sort the grid according to the following field (which must be
present in ``subset`` or ``tooltip``).
use_iframe : bool, default=False
Whether to use an iframe to display the grid. When the grid is displayed
inside a Jupyter Notebook or JupyterLab, this will default to ``True``.
truncate: bool, default=True/False
Whether to truncate the text in each cell if it's too long.
Defaults to ``True`` for interactive grids, ``False`` for static grid.
n_items_per_page, default=24
Number of items to display per page. A multiple of 12 is recommended
for optimal display.
selection : bool, default=True
Enables the selection of molecules and displays a checkbox at the
top of each cell. In the context of a Jupyter Notebook, this gives
you access to your selection (index and SMILES) through
:func:`mols2grid.get_selection()` or :meth:`MolGrid.get_selection()`.
In all cases, you can export your selection by clicking on the triple-dot
menu.
Parameters: Mols
----------------
substruct_highlight : bool or None, default=None
Highlight substructure when using the SMARTS search. Active by default
when ``prerender=False``.
single_highlight : bool, default=False
Highlight only the first match of the substructure query.
Parameters: CSS
---------------
border : str, default="1px solid #cccccc"
Styling of the border around each cell.
gap : int, default=0
Size in pixels of the gap between cells.
pad : int, default=10
Size in pixels of the cell padding.
fontsize : str, default="12px"
Font size of the text displayed in each cell.
fontfamily : str, default="'DejaVu', sans-serif"
Font used for the text in each cell.
textalign : str, default="center"
Alignment of the text in each cell.
background_color : str, default="white"
Background color of a cell.
hover_color : str, default="rgba(0,0,0,0.05)"
Background color when hovering a cell.
custom_css : str or None, default=None
Custom CSS properties applied to the generated HTML. Please note that
the CSS will apply to the entire page if no iframe is used (see
``use_iframe`` for more details).
style : dict or None, default=None
CSS styling applied to each item in a cell. The dict must follow a
``key: function`` structure where the key must correspond to one of the
columns in ``subset`` or ``tooltip``. The function takes the item's
value as input, and outputs a valid CSS styling. For example, if you
want to color the text corresponding to the "Solubility" column in your
dataframe::
style={"Solubility": lambda x: "color: red" if x < -5 else ""}
You can also style a whole cell using the ``__all__`` key, the
corresponding function then has access to all values for each cell::
style={
"__all__": lambda x: "color: red" if x["Solubility"] < -5 else ""
}
Parameters: Customization
-------------------------
custom_header : str or None, default=None
Custom libraries to be loaded in the header of the document.
callback : str, callable or None, default=None
JavaScript or Python callback to be executed when clicking on an image.
A dictionnary containing the data for the full cell is directly available
as ``data`` in JS. For Python, the callback function must have ``data``
as the first argument to the function. All the values in the ``data`` dict
are parsed as strings, except "mols2grid-id" which is always an integer.
Note that fields containing spaces in their name will be replaced by
hyphens, i.e. "mol weight" becomes available as ``data["mol-weight"]``.
Returns
-------
html_document : str
Notes
-----
If ``subset=None, tooltip=None``, the index and image will be directly
displayed on the grid while the remaining fields will be in the
tooltip.
The cell width is defined by the size[0] parameter.
.. versionadded:: 0.1.0
Added ``sort_by``, ``custom_css``, ``custom_header`` and
``callback`` arguments.
Added the ability to style an entire cell with
``style={"__all__": <function>}``.
.. versionadded:: 0.2.0
Added ``substruct_highlight`` argument.
.. versionchanged:: 0.2.2
If both ``subset`` and ``tooltip`` are ``None``, the index and
image will be directly displayed on the grid while the remaining
fields will be in the tooltip.
.. versionchanged:: 1.0.0
``callback`` can now be a *lambda* function. If ``prerender=True``,
substructure highlighting will be automatically disabled if it
wasn't explicitely set to ``True`` instead of raising an error.
"""
if substruct_highlight is None:
substruct_highlight = not self.prerender
if substruct_highlight and self.prerender:
raise ValueError(
"Cannot highlight substructure search with prerendered images"
)
if self.mol_col:
df = self.dataframe.drop(columns=self.mol_col).copy()
else:
df = self.dataframe.copy()
smiles = self.smiles_col
content = [] # Gets filled with the HTML content of each cell.
column_map = {}
if subset is None:
if tooltip is None:
subset = ["mols2grid-id", "img"]
tooltip = [x for x in df.columns.tolist() if x not in subset]
else:
# When no subset is defined, all columns are displayed.
subset = df.columns.tolist()
else:
# work on a copy
subset = subset[:]
if "mols2grid-id" not in subset:
subset.insert(0, "mols2grid-id")
if "img" not in subset:
subset.insert(0, "img")
# Always make sure the image comes first.
# subset = [subset.pop(subset.index("img"))] + subset
#
# This was removed at Cedric's request, so you can choose
# to have certain properties displayed above the image.
# Define fields that are searchable and sortable.
search_cols = [f"data-{col}" for col in subset if col != "img"]
if tooltip:
search_cols.extend([f"data-{col}" for col in tooltip])
for col in tooltip:
if col not in subset:
s = (
f'<div class="data data-{slugify(col)}" '
'style="display: none;"></div>'
)
content.append(s)
column_map[col] = f"data-{col}"
else:
tooltip = []
sort_cols = search_cols.copy()
sort_cols = ["data-mols2grid-id", *sort_cols]
# Get unique list but keep order.
sort_cols = list(dict.fromkeys(sort_cols))
if style is None:
style = {}
if transform is None:
transform = {}
value_names = list({*subset, smiles, *tooltip})
value_names = [f"data-{col}" for col in value_names]
# Force id, SMILES, and tooltip values to be present in the data.
final_columns = subset[:]
final_columns.extend(["mols2grid-id", smiles])
if tooltip:
final_columns.extend(tooltip)
final_columns = list(set(final_columns))
# Make a copy of id shown explicitly.
id_name = "mols2grid-id-display"
df[id_name] = df["mols2grid-id"]
value_names.append(f"data-{id_name}")
final_columns.append(id_name)
subset = [id_name if x == "mols2grid-id" else x for x in subset]
id_display_html = f'<div class="data-{id_name}"></div>'
# Organize data.
temp = []
for col in subset:
if col == "mols2grid-id-display":
s = "" # Avoid an empty div to be created for the display id.
elif col == "img" and tooltip:
s = f'<a class="data data-{col}"></a>'
elif style.get(col):
s = (
f'<div class="data data-{slugify(col)} '
f'copy-me style-{slugify(col)}" style=""></div>'
)
else:
s = f'<div class="data data-{slugify(col)} copy-me"></div>'
temp.append(s)
column_map[col] = f"data-{col}"
content = temp + content
# Add but hide SMILES div if not present.
if smiles not in (subset + tooltip):
s = (
f'<div class="data data-{slugify(smiles)} copy-me" '
'style="display: none;"></div>'
)
content.append(s)
column_map[smiles] = f"data-{smiles}"
# Set mapping for list.js.
if "__all__" in style:
whole_cell_style = True
x = "[{data: ['mols2grid-id', 'cellstyle']}, "
else:
whole_cell_style = False
x = "[{data: ['mols2grid-id']}, "
value_names = [slugify(c) for c in value_names]
value_names = x + str(value_names)[1:]
# Apply CSS styles.
for col, func in style.items():
if col == "__all__":
name = "cellstyle"
df[name] = df.apply(func, axis=1)
else:
name = f"style-{slugify(col)}"
df[name] = df[col].apply(func)
final_columns.append(name)
value_names = value_names[:-1] + f", {{ attr: 'style', name: {name!r} }}]"
# Create tooltip.
if tooltip:
df["m2g-tooltip"] = df.apply(
tooltip_formatter, axis=1, args=(tooltip, tooltip_fmt, style, transform)
)
final_columns += ["m2g-tooltip"]
value_names = (
value_names[:-1] + ", {attr: 'data-content', name: 'm2g-tooltip'}]"
)
info_btn_html = '<div class="m2g-info">i</div>'
else:
info_btn_html = ""
# Apply custom user function.
for col, func in transform.items():
df[col] = df[col].apply(func)
# Add checkboxes.
if selection:
if self._cached_selection:
df["cached_checkbox"] = False
df.loc[
df["mols2grid-id"].isin(self._cached_selection.keys()),
"cached_checkbox",
] = True
final_columns += ["cached_checkbox"]
value_names = (
value_names[:-1] + ", {attr: 'checked', name: 'cached_checkbox'}]"
)
checkbox_html = (
'<input type="checkbox" tabindex="-1" '
'class="position-relative float-left cached_checkbox">'
)
else:
checkbox_html = ""
# Add callback button.
callback_btn_html = '<div class="m2g-callback"></div>' if callback else ""
# Generate cell HTML.
item = (
'<div class="m2g-cell" data-mols2grid-id="0" tabindex="0">'
'<div class="m2g-cb-wrap">{checkbox_html}<div class="m2g-cb"></div>' # noqa: RUF027
"{id_display_html}</div>" # noqa: RUF027
'<div class="m2g-cell-actions">{info_btn_html}{callback_btn_html}</div>' # noqa: RUF027
"{content}" # noqa: RUF027
"{tooltip_html}"
"</div>"
)
item = item.format(
checkbox_html=checkbox_html,
id_display_html=id_display_html,
info_btn_html=info_btn_html,
callback_btn_html=callback_btn_html,
content="".join(content),
tooltip_html=(
'<div class="m2g-tooltip" data-toggle="popover" data-content="."></div>'
)
if tooltip
else "",
)
# Callback
if isinstance(callback, _JSCallback):
if custom_header and callback.library_src:
custom_header = callback.library_src + custom_header
else:
custom_header = callback.library_src
callback = callback.code
if callable(callback):
callback_type = "python"
cb_handler = partial(callback_handler, callback)
self.widget.observe(cb_handler, names=["callback_kwargs"])
else:
callback_type = "js"
# Sort
if sort_by and sort_by != "mols2grid-id":
if sort_by in (subset + tooltip):
sort_by = f"data-{slugify(sort_by)}"
else:
raise ValueError(
f"{sort_by!r} is not an available field in `subset` or `tooltip`"
)
else:
sort_by = "mols2grid-id"
# Slugify remaining vars.
column_map = {k: slugify(v) for k, v in column_map.items()}
sort_cols = [slugify(c) for c in sort_cols]
search_cols = [slugify(c) for c in search_cols]
smiles = slugify(smiles)
df = df[final_columns].rename(columns=column_map).sort_values(sort_by)
template = env.get_template("interactive.html")
template_kwargs = {
"tooltip": tooltip,
"tooltip_placement": repr(tooltip_placement),
"n_items_per_page": n_items_per_page,
"selection": selection,
"truncate": truncate,
"sort_by": sort_by,
"use_iframe": use_iframe,
"border": border,
"gap": gap,
"gap_px": "-1px -1px 0 0" if gap == 0 else f"{gap}px",
"pad": pad,
"fontsize": fontsize,
"fontfamily": fontfamily,
"textalign": textalign,
"background_color": background_color,
"hover_color": hover_color,
"iframe_padding": 18,
"cell_width": self.img_size[0],
"image_width": self.img_size[0],
"image_height": self.img_size[1],
"item": item,
"item_repr": repr(item),
"value_names": value_names,
"search_cols": search_cols,
"data": json.dumps(
df.to_dict("records"),
indent=None,
default=lambda x: "🤷♂️", # noqa: ARG005
),
"cached_selection": (
[
list(self._cached_selection.keys()),
list(self._cached_selection.values()),
]
if self._cached_selection
else False
),
"smiles_col": smiles,
"sort_cols": sort_cols,
"grid_id": self._grid_id,
"whole_cell_style": whole_cell_style,
"custom_css": custom_css or "",
"custom_header": custom_header or "",
"callback": callback,
"callback_type": callback_type,
"removeHs": self.removeHs,
"prefer_coordGen": self.prefer_coordGen,
"onthefly": not self.prerender,
"substruct_highlight": substruct_highlight,
"json_draw_opts": getattr(self, "json_draw_opts", ""),
"single_highlight": single_highlight,
}
return template.render(**template_kwargs)
def get_selection(self):
"""Retrieve the dataframe subset corresponding to your selection.
Returns
-------
pandas.DataFrame
"""
sel = list(register.get_selection(self._grid_id).keys())
return self.dataframe.loc[self.dataframe["mols2grid-id"].isin(sel)].drop(
columns=self._extra_columns
)
def get_marimo_selection(self):
"""Returns a marimo state object containing the list of selected indices.
Only available when running in marimo.
Returns
-------
getter
A getter function for the selection state.
Calling it with no arguments returns the current list of selected IDs.
"""
if not is_running_within_marimo():
raise RuntimeError("This method is only available in a marimo notebook.")
import marimo as mo
get_state, set_state = mo.state([])
def _on_change(change):
try:
sel = ast.literal_eval(change["new"])
set_state(list(sel.keys()))
except (ValueError, SyntaxError):
pass
if not getattr(self.widget, "_marimo_hooked", False):
self.widget.observe(_on_change, names=["selection"])
self.widget._marimo_hooked = True
return get_state
def filter(self, mask):
"""Filters the grid using a mask (boolean array).
Parameters
----------
mask : list, pandas.Series or numpy.ndarray
Boolean array: ``True`` when the item should be displayed,
``False`` if it should be filtered out.
"""
if isinstance(mask, (pd.Series, np.ndarray)):
mask = mask.tolist()
if is_running_within_streamlit():
filtering_script = env.get_template("js/filter.js").render(
grid_id=self._grid_id, mask=json.dumps(mask)
)
return Javascript(filtering_script)
self.widget.filter_mask = mask
return None
def filter_by_index(self, indices):
"""Filters the grid using the dataframe's index."""
# convert index to mask
mask = self.dataframe.index.isin(indices)
return self.filter(mask)
def to_static( # noqa: PLR0912
self,
# Display
subset=None,
tooltip=None,
tooltip_fmt="<strong>{key}</strong>: {value}",
tooltip_trigger="focus",
tooltip_placement="auto",
transform=None,
sort_by=None,
use_iframe=False,
truncate=False,
n_cols=5,
# CSS Styling
border="1px solid #cccccc",
gap=0,
pad=10,
fontsize="12px",
fontfamily="'DejaVu', sans-serif",
textalign="center",
custom_css=None,
style=None,
# Customization
custom_header=None,
):
"""Returns the HTML document for the "static" template
Parameters: Display
-------------------
subset: list or None, default=None
Columns to be displayed in each cell of the grid. Each column's
value will be displayed from top to bottom in the order provided.
The ``"img"`` and ``"mols2grid-id"`` columns are displayed by default,
however you can still add the ``"img"`` column if you wish to change
the display order.
tooltip : list, None or False, default=None
Columns to be displayed inside the tooltip. When no subset is set,
all columns will be listed in the tooltip by default. Use ``False``
to hide the tooltip.
tooltip_fmt : str, default="<strong>{key}</strong>: {value}"
Format string of each key/value pair in the tooltip.
tooltip_trigger : str, default="focus"
Sequence of triggers for the tooltip: ``click``, ``hover`` or ``focus``
tooltip_placement : str, default="auto"
Position of the tooltip: ``auto``, ``top``, ``bottom``, ``left`` or
``right``.
transform : dict or None, default=None
Functions applied to specific items in all cells. The dict must follow
a ``key: function`` structure where the key must correspond to one of
the columns in ``subset`` or ``tooltip``. The function takes the item's
value as input and transforms it, for example::
transform={
"Solubility": lambda x: f"{x:.2f}",
"Melting point": lambda x: f"MP: {5/9*(x-32):.1f}°C"
}
These transformations only affect columns in ``subset`` and
``tooltip``, and do not interfere with ``style``.
sort_by : str or None, default=None
Sort the grid according to the following field (which must be
present in ``subset`` or ``tooltip``).
use_iframe : bool, default=False
Whether to use an iframe to display the grid. When the grid is displayed
inside a Jupyter Notebook or JupyterLab, this will default to ``True``.
truncate: bool, default=False
Whether to truncate the text in each cell if it's too long.
n_cols : int, default=5
Number of columns in the table.
Parameters: CSS
---------------
border : str, default="1px solid #cccccc"
Styling of the border around each cell.
gap : int, default=0
Size in pixels of the gap between cells.
pad: int, default=10
Size in pixels of the cell padding.
fontsize : str, default="12pt"
Font size of the text displayed in each cell.
fontfamily : str, default="'DejaVu', sans-serif"
Font used for the text in each cell.
textalign : str, default="center"
Alignment of the text in each cell.
custom_css : str or None, default=None
Custom CSS properties applied to the generated HTML. Please note that
the CSS will apply to the entire page if no iframe is used (see
``use_iframe`` for more details).
style : dict or None, default=None
CSS styling applied to each item in a cell. The dict must follow a
``key: function`` structure where the key must correspond to one of the
columns in ``subset`` or ``tooltip``. The function takes the item's
value as input, and outputs a valid CSS styling. For example, if you
want to color the text corresponding to the "Solubility" column in your
dataframe::
style={"Solubility": lambda x: "color: red" if x < -5 else ""}
You can also style a whole cell using the ``__all__`` key, the
corresponding function then has access to all values for each cell::
style={
"__all__": lambda x: "color: red" if x["Solubility"] < -5 else ""
}
Parameters: Customization
-------------------------
custom_header : str or None
Custom libraries to be loaded in the header of the document
Returns
-------
html_document : str
Notes
-----
If ``subset=None, tooltip=None``, the index and image will be directly
displayed on the grid while the remaining fields will be in the
tooltip.
.. versionadded:: 0.1.0
Added the ability to style an entire cell with
``style={"__all__": <function>}``
.. versionadded:: 0.2.2
Added ``sort_by``, ``custom_css``, ``custom_header`` arguments.
.. versionchanged:: 0.2.2
If both ``subset`` and ``tooltip`` are ``None``, the index and
image will be directly displayed on the grid while the remaining
fields will be in the tooltip.
"""
if not self.prerender:
raise ValueError(
"Please set `prerender=True` when using the 'static' template"
)
tr = []
data = []
sort_by = sort_by or "mols2grid-id"
df = self.dataframe.sort_values(sort_by).reset_index(drop=True)
if subset is None:
if tooltip is None:
subset = ["mols2grid-id", "img"]
tooltip = [x for x in df.columns.tolist() if x not in subset]
else:
# When no subset is defined, all columns are displayed.
subset = df.columns.tolist()
else:
# work on a copy
subset = subset[:]
if "mols2grid-id" not in subset:
subset.insert(0, "mols2grid-id")
if "img" not in subset:
subset.insert(0, "img")
# Always make surer the image comes first.
subset = [subset.pop(subset.index("img")), *subset]
if style is None:
style = {}
if transform is None:
transform = {}
if not tooltip:
tooltip = []
for i, row in df.iterrows():
ncell = i + 1
nrow, ncol = divmod(i, n_cols)
popover = tooltip_formatter(row, tooltip, tooltip_fmt, style, transform)
td = [
f'<td class="col-{ncol} m2g-tooltip" tabindex="0" '
f'data-toggle="popover" data-content="{escape(popover)}">'
]
if "__all__" in style:
s = style["__all__"](row)
div = [f'<div class="m2g-cell-{i}" style="{s}">']
else:
div = [f'<div class="m2g-cell-{i}">']
for col in subset:
v = row[col]
if col == "img" and tooltip:
item = f'<div class="data data-img">{v}</div>'
else:
func = style.get(col)
slug_col = slugify(col)
if func:
item = (
f'<div class="data copy-me data-{slug_col}" '
f'style="{func(v)}">'
)
else:
item = f'<div class="data copy-me data-{slug_col}">'
func = transform.get(col)
v = func(v) if func else v
item += f"{v}</div>"
div.append(item)
div.append("</div>")
td.extend(("\n".join(div), "</td>"))
tr.append("\n".join(td))
if (ncell % n_cols == 0) or (ncell == len(df)):
cell = [f'<tr class="row-{nrow}">']
cell.extend(("\n".join(tr), "</tr>"))
data.append("\n".join(cell))
tr = []
template = env.get_template("static.html")
template_kwargs = {
"tooltip": tooltip,
"tooltip_trigger": repr(tooltip_trigger),
"tooltip_placement": repr(tooltip_placement),
"use_iframe": use_iframe,
"truncate": truncate,
"border": border,
"gap": gap,
"pad": pad,
"textalign": textalign,
"fontsize": fontsize,
"fontfamily": fontfamily,
"iframe_padding": 18,
"cell_width": self.img_size[0],
"custom_css": custom_css or "",
"custom_header": custom_header or "",
"data": "\n".join(data),
}
return template.render(**template_kwargs)
@requires("IPython.display")
def display(
self,
use_iframe=False,
iframe_width="100%",
iframe_height=None,
iframe_allow="clipboard-write",
iframe_sandbox=(
"allow-scripts allow-same-origin allow-downloads allow-popups allow-modals"
),
**kwargs,
):
"""Render and display the grid in a Jupyter notebook.
Returns
-------
view : IPython.core.display.HTML
"""
requires_marimo = is_running_within_marimo()
if requires_marimo:
use_iframe = True
use_iframe = is_jupyter or use_iframe
doc = self.render(**kwargs, use_iframe=use_iframe)
if use_iframe:
# Render HTML in iframe.
iframe = env.get_template("html/iframe.html").render(
width=iframe_width,
height=iframe_height,
allow=iframe_allow,
sandbox=iframe_sandbox,
doc=escape(doc),
)
if requires_marimo:
import marimo as mo
return mo.vstack([self.widget, mo.Html(iframe)])
return HTML(iframe)
# Render HTML regularly.
return HTML(doc)
def save(self, output, **kwargs):
"""Render and save the grid in an HTML document."""
with open(output, "w", encoding="utf-8") as f:
f.write(self.render(**kwargs))
| Python |
2D | cbouy/mols2grid | mols2grid/templates/__init__.py | .py | 0 | 0 | null | Python |
2D | cbouy/mols2grid | docs/contents.md | .md | 6,489 | 116 | # 💡 Introduction
- [](https://pypi.python.org/pypi/mols2grid)
[](https://anaconda.org/conda-forge/mols2grid)
- [](https://github.com/cbouy/mols2grid/actions/workflows/ci.yml)
[](https://github.com/cbouy/mols2grid/actions/workflows/build.yml)
[](https://mols2grid.readthedocs.io/en/latest/?badge=latest)
[](https://codecov.io/gh/cbouy/mols2grid)
- [](https://www.rdkit.org/)
[](https://hub.knime.com/cbouy/spaces/Public/latest/Interactive%20Grid%20of%20Molecules)
**mols2grid** is an interactive molecule viewer for 2D structures, based on RDKit.

# 🐍 Installation
---
mols2grid was developped for Python 3.10+ and requires rdkit, pandas and jinja2 as dependencies.
The easiest way to install it is from conda:
```shell
conda install -c conda-forge mols2grid
```
Alternatively, you can also use pip:
```shell
pip install mols2grid
```
**Compatibility**
mols2grid is mainly meant to be used in notebooks (Jupyter notebooks, Jupyter Lab, and Google Colab) but it can also be used as a standalone HTML page opened with your favorite web browser, or embedded in a Streamlit app.
Since v2.2.0, mols2grid is also compatible with [Marimo](https://marimo.io/). An example is available in [`scripts/marimo_example.py`](https://github.com/cbouy/mols2grid/blob/master/scripts/marimo_example.py).
Since Streamlit doesn't seem to support ipywidgets yet, some features aren't functional: retrieving the selection from Python (you can still export it from the GUI) and using Python callbacks.
<img alt="knime logo" align="left" style="padding:6px" src="https://www.knime.com/sites/default/files/favicons/favicon-32x32.png"/>
<p>You can also use mols2grid directly in <a href="https://www.knime.com/">KNIME</a>, by looking for the `Interactive Grid of Molecules` component on the Knime HUB.<br/>
Make sure you have setup <a href="https://docs.knime.com/latest/python_installation_guide">Knime's Python integration</a> for the node to work.</p>
# 📜 Usage
---
You can display a grid from:
- an SDFile
```python
import mols2grid
mols2grid.display("path/to/molecules.sdf")
```
- a `pandas.DataFrame`:
```python
mols2grid.display(df, smiles_col="Smiles")
```
- a list of RDKit molecules:
```python
mols2grid.display(mols)
```
Please head to the [notebooks](notebooks/quickstart.html) and [API reference](api/simple.html) sections for a complete overview of the features available.
# 🚀 Resources
---
* [Simple example](https://iwatobipen.wordpress.com/2021/06/13/draw-molecules-on-jupyter-notebook-rdkit-mols2grid/) by iwatobipen
* Creating a web app with Streamlit for filtering datasets:
* [Blog post](https://blog.reverielabs.com/building-web-applications-from-python-scripts-with-streamlit/) by Justin Chavez
* [Video tutorial](https://www.youtube.com/watch?v=0rqIwSeUImo) by Data Professor
* [Viewing clustered chemical structures](https://practicalcheminformatics.blogspot.com/2021/07/viewing-clustered-chemical-structures.html) and [Exploratory data analysis](https://practicalcheminformatics.blogspot.com/2021/10/exploratory-data-analysis-with.html) by Pat Walters
* [Advanced notebook (RDKit UGM 2021)](https://colab.research.google.com/github/rdkit/UGM_2021/blob/main/Notebooks/Bouysset_mols2grid.ipynb)
Feel free to open a pull request if you'd like your snippets to be added to this list!
# 👏 Acknowledgments
---
* [@themoenen](https://github.com/themoenen) (contributor)
* [@fredrikw](https://github.com/fredrikw) (contributor)
* [@JustinChavez](https://github.com/JustinChavez) (contributor)
* [@hadim](https://github.com/hadim) (conda feedstock maintainer)
* [@N283T](https://github.com/N283T) (contributor)
# 🎓 Citing
---
You can refer to mols2grid in your research by using the following DOI:
[](https://zenodo.org/badge/latestdoi/348814588)
# ⚖ License
---
Unless otherwise noted, all files in this directory and all subdirectories are distributed under the Apache License, Version 2.0:
```text
Copyright 2021-2025 Cédric BOUYSSET
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
| Markdown |
2D | cbouy/mols2grid | docs/conf.py | .py | 4,097 | 133 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# ruff: noqa: PTH100
import os
import sys
from datetime import datetime
from recommonmark.transform import AutoStructify
sys.path.insert(0, os.path.abspath("."))
# -- Project information -----------------------------------------------------
project = "mols2grid"
copyright = f"2021-{datetime.now().year}, Cédric Bouysset" # noqa: A001
author = "Cédric Bouysset"
# -- General configuration ---------------------------------------------------
github_doc_root = "https://github.com/cbouy/mols2grid/tree/master/docs/"
needs_sphinx = "5.3.0"
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.viewcode",
"sphinx.ext.napoleon",
"sphinx.ext.autosectionlabel",
"recommonmark",
"IPython.sphinxext.ipython_console_highlighting",
"IPython.sphinxext.ipython_directive",
"myst_nb",
"sphinx_copybutton",
]
myst_enable_extensions = [
"colon_fence",
]
nb_execution_allow_errors = False
nb_execution_raise_on_error = True
copybutton_exclude = ".linenos, .gp"
autosectionlabel_prefix_document = True
napoleon_google_docstring = False
source_suffix = {
".rst": "restructuredtext",
".md": "myst-nb",
".ipynb": "myst-nb",
".myst": "myst-nb",
}
# Add any paths that contain templates here, relative to this directory.
templates_path = []
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_book_theme"
pygments_style = "sphinx"
html_logo = "_static/mols2grid_logo.png"
html_theme_options = {
"repository_url": "https://github.com/cbouy/mols2grid",
"path_to_docs": "docs",
"use_source_button": True,
"use_download_button": True,
"use_repository_button": True,
"use_issues_button": True,
"launch_buttons": {"colab_url": "https://colab.research.google.com"},
"icon_links": [
{
"name": "GitHub",
"url": "https://github.com/cbouy/mols2grid",
"icon": "fa-brands fa-square-github",
"type": "fontawesome",
},
],
}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
###
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"numpy": ("https://numpy.org/doc/stable/", None),
"rdkit": ("https://www.rdkit.org/docs/", None),
"pandas": ("https://pandas.pydata.org/docs/", None),
"ipython": ("https://ipython.readthedocs.io/en/stable/", None),
}
# app setup hook
def setup(app):
app.add_config_value(
"recommonmark_config",
{
# 'url_resolver': lambda url: github_doc_root + url,
"auto_toc_tree_section": "Contents",
"enable_math": False,
"enable_inline_math": False,
"enable_eval_rst": True,
},
True,
)
app.add_transform(AutoStructify)
app.add_css_file("custom.css")
| Python |
2D | cbouy/mols2grid | docs/notebooks/customization.ipynb | .ipynb | 5,589 | 176 | {
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Customization\n",
"\n",
"[](https://colab.research.google.com/github/cbouy/mols2grid/blob/master/docs/notebooks/customization.ipynb)\n",
"\n",
"The grid can be customized quite extensively, from the content that is displayed to the look of the grid and images."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# uncomment and run if you're on Google Colab\n",
"# !pip install mols2grid\n",
"\n",
"# for development purposes only\n",
"# %load_ext autoreload\n",
"# %autoreload 2\n",
"# %env ANYWIDGET_HMR=1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mols2grid"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"To display all the arguments available, type `help(mols2grid.display)`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols2grid.display(\n",
" mols2grid.datafiles.SOLUBILITY_SDF,\n",
" # rename fields for the output document\n",
" rename={\"SOL\": \"Solubility\", \"SOL_classification\": \"Class\", \"NAME\": \"Name\"},\n",
" # set what's displayed on the grid\n",
" subset=[\"ID\", \"img\", \"Solubility\"],\n",
" # set what's displayed on the hover tooltip\n",
" tooltip=[\"Name\", \"SMILES\", \"Class\", \"Solubility\"],\n",
" # style for the grid labels and tooltips\n",
" style={\n",
" \"Solubility\": lambda x: \"color: red; font-weight: bold;\" if x < -3 else \"\",\n",
" \"__all__\": lambda x: \"background-color: azure;\" if x[\"Solubility\"] > -1 else \"\",\n",
" },\n",
" # change the precision and format (or other transformations)\n",
" transform={\"Solubility\": lambda x: round(x, 2)},\n",
" # sort the grid in a different order by default\n",
" sort_by=\"Name\",\n",
" # molecule drawing parameters\n",
" fixedBondLength=25,\n",
" clearBackground=False,\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"See [rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions](https://www.rdkit.org/docs/source/rdkit.Chem.Draw.rdMolDraw2D.html#rdkit.Chem.Draw.rdMolDraw2D.MolDrawOptions) for the molecule drawing options available.\n",
"\n",
"The grid's look can also be customized to an even greater extent:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# some unnecessarily complicated CSS stylesheet 🌈\n",
"# use .m2g-cell to select each grid's cell\n",
"# or .data for every data field\n",
"# or .data-<field> for a specific field\n",
"css_style = \"\"\"\n",
"/* rainbow background */\n",
".m2g-cell {\n",
" background: linear-gradient(124deg, #ff2400, #e81d1d, #e8b71d, #e3e81d, #1de840, #1ddde8, #2b1de8, #dd00f3, #dd00f3);\n",
" background-size: 500% 500%;\n",
" -webkit-animation: rainbow 10s ease infinite;\n",
" animation: rainbow 10s ease infinite;\n",
"}\n",
".m2g-cell:hover {\n",
" border-color: red !important;\n",
"}\n",
"/* rainbow font color */\n",
".data {\n",
" font-weight: bold;\n",
" -webkit-text-stroke: 1px black;\n",
" background: linear-gradient(to right, #ef5350, #f48fb1, #7e57c2, #2196f3, #26c6da, #43a047, #eeff41, #f9a825, #ff5722);\n",
" -webkit-background-clip: text;\n",
" color: transparent;\n",
"}\n",
"/* background animation */\n",
"@-webkit-keyframes rainbow {\n",
" 0% {background-position: 0% 50%}\n",
" 50% {background-position: 100% 50%}\n",
" 100% {background-position: 0% 50%}\n",
"}\n",
"@keyframes rainbow { \n",
" 0% {background-position: 0% 50%}\n",
" 50% {background-position: 100% 50%}\n",
" 100% {background-position: 0% 50%}\n",
"}\n",
"\"\"\"\n",
"\n",
"mols2grid.display(\n",
" mols2grid.datafiles.SOLUBILITY_SDF,\n",
" # RDKit drawing options\n",
" comicMode=True,\n",
" fixedBondLength=20,\n",
" bondLineWidth=1,\n",
" # custom atom colour palette (all white)\n",
" atomColourPalette={z: (1, 1, 1) for z in range(1, 295)},\n",
" # mols2grid options\n",
" subset=[\"NAME\", \"img\"],\n",
" custom_css=css_style,\n",
" fontfamily='\"Comic Sans MS\", \"Comic Sans\", cursive;',\n",
" # image size\n",
" size=(130, 80),\n",
" # number of results per page\n",
" n_items_per_page=20,\n",
" # border around each cell\n",
" border=\"5px ridge cyan\",\n",
" # gap between cells\n",
" gap=3,\n",
" # disable selection\n",
" selection=False,\n",
")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| Unknown |
2D | cbouy/mols2grid | docs/notebooks/callbacks.ipynb | .ipynb | 10,486 | 316 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Callbacks\n",
"\n",
"[](https://colab.research.google.com/github/cbouy/mols2grid/blob/master/docs/notebooks/callbacks.ipynb)\n",
"\n",
"Callbacks are **functions that are executed when you click on a cell's callback button**. They can be written in *JavaScript* or *Python*.\n",
"\n",
"This functionality can be used to display some additional information on the molecule or run some more complex code such as database queries, docking or machine-learning predictions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# uncomment and run if you're on Google Colab\n",
"# !pip install mols2grid py3Dmol\n",
"\n",
"# for development purposes only\n",
"# %load_ext autoreload\n",
"# %autoreload 2\n",
"# %env ANYWIDGET_HMR=1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import urllib.parse\n",
"import urllib.request\n",
"from urllib.error import HTTPError\n",
"\n",
"import py3Dmol\n",
"from IPython.display import display\n",
"from ipywidgets import widgets\n",
"\n",
"import mols2grid\n",
"\n",
"\n",
"# Optional: read SDF file and sample 50 mols from it (to keep this notebook light)\n",
"df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF).sample(\n",
" 50, random_state=0xAC1D1C\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python\n",
"\n",
"*Note: if you are reading this from the documentation web page, clicking on the images will not trigger anything. Try running the notebook on Google Colab instead (see link at the top of the page).*\n",
"\n",
"For Python callbacks, you need to declare a function that takes a dictionnary as first argument. This dictionnary contains all the data related to the molecule you've just clicked on. All the data fields are **parsed as strings**, except for the index, \"mols2grid-id\", which is always parsed as an integer.\n",
"\n",
"For example, the SMILES of the molecule will be available as `data[\"SMILES\"]`. If the field contains spaces, they will be converted to hyphens, *i.e.* a field called `mol weight` will be available as `data[\"mol-weight\"]`.\n",
"\n",
"Also, using print or any other \"output\" functions inside the callback will not display anything by default. You need to use ipywidgets's `Output` widget to capture what the function is trying to display, and then show it.\n",
"\n",
"### Basic print example\n",
"\n",
"In this simple example, we'll just show the content of the data dictionnary."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output = widgets.Output()\n",
"\n",
"\n",
"# the Output widget let's us capture the output generated by the callback function\n",
"# its presence is mandatory if you want to print/display some info with your callback\n",
"@output.capture(clear_output=True, wait=True)\n",
"def show_data(data):\n",
" data.pop(\"img\")\n",
" for key, value in data.items():\n",
" print(key, value)\n",
"\n",
"\n",
"view = mols2grid.display(\n",
" df,\n",
" callback=show_data,\n",
")\n",
"display(view)\n",
"output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also make more complex operations with callbacks.\n",
"\n",
"### Displaying the 3D structure with py3Dmol\n",
"\n",
"Here, we'll query PubChem for the molecule based on its SMILES, then fetch the 3D structure and display it with py3Dmol."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output = widgets.Output()\n",
"\n",
"\n",
"@output.capture(clear_output=True, wait=True)\n",
"def show_3d(data):\n",
" \"\"\"Query PubChem to download the SDFile with 3D coordinates and\n",
" display the molecule with py3Dmol\n",
" \"\"\"\n",
" url = \"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{}/SDF?record_type=3d\"\n",
" smi = urllib.parse.quote(data[\"SMILES\"])\n",
" try:\n",
" response = urllib.request.urlopen(url.format(smi))\n",
" except HTTPError:\n",
" print(f\"Could not find corresponding match on PubChem\")\n",
" print(data[\"SMILES\"])\n",
" else:\n",
" sdf = response.read().decode()\n",
" view = py3Dmol.view(height=300, width=800)\n",
" view.addModel(sdf, \"sdf\")\n",
" view.setStyle({\"stick\": {}})\n",
" view.zoomTo()\n",
" view.show()\n",
"\n",
"\n",
"view = mols2grid.display(\n",
" df,\n",
" callback=show_3d,\n",
")\n",
"display(view)\n",
"output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## JavaScript\n",
"\n",
"We can also write JavaScript callbacks, which have the advantage to be able to run on almost any platform.\n",
"\n",
"JS callbacks don't require to declare a function, and you can directly access and use the `data` object similarly to Python in your callback script.\n",
"\n",
"### Basic JS example"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"js_callback = \"\"\"\n",
"// remove image from data\n",
"delete data[\"img\"];\n",
"// convert data object to text\n",
"txt = JSON.stringify(data);\n",
"// show data in alert window\n",
"alert(txt);\n",
"\"\"\"\n",
"\n",
"mols2grid.display(\n",
" df,\n",
" callback=js_callback,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To display fancy popup windows on click, a helper function is available: `mols2grid.make_popup_callback`.\n",
"\n",
"It requires a title as well as some html code to format and display the information that you'd like to show. All of the values inside the data object can be inserted in the `title` and `html` arguments using `${data[\"field_name\"]}`. Additionally, you can execute a prerequisite JavaScript snippet to create variables that are then also accessible in the html code.\n",
"\n",
"### Display a popup containing descriptors\n",
"\n",
"In the following exemple, we create an RDKit molecule using the SMILES of the molecule (the SMILES field is always present in the data object, no matter your input when creating the grid).\n",
"\n",
"We then create a larger SVG image of the molecule, and calculate some descriptors.\n",
"\n",
"Finally, we inject these variables inside the HTML code. You can also style the popup window through the style argument."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"js_callback = mols2grid.make_popup_callback(\n",
" title=\"${data['NAME']}\",\n",
" subtitle=\"${data['SMILES']}\",\n",
" svg=\"${svg}\",\n",
" js=\"\"\"\n",
" var mol = RDKit.get_mol(data[\"SMILES\"]);\n",
" var svg = mol.get_svg(400, 300);\n",
" var desc = JSON.parse(mol.get_descriptors());\n",
" var inchikey = RDKit.get_inchikey_for_inchi(mol.get_inchi());\n",
" mol.delete();\n",
" \"\"\",\n",
" html=\"\"\"\n",
" <b>Molecular weight</b>: ${desc.exactmw}<br/>\n",
" <b>HBond Acceptors</b>: ${desc.NumHBA}<br/>\n",
" <b>HBond Donors</b>: ${desc.NumHBD}<br/>\n",
" <b>TPSA</b>: ${desc.tpsa}<br/>\n",
" <b>ClogP</b>: ${desc.CrippenClogP}<br/>\n",
" <hr>\n",
" <b>InChIKey</b>: ${inchikey}\n",
" \"\"\",\n",
" style=\"border-radius: 10px\",\n",
")\n",
"\n",
"mols2grid.display(\n",
" df,\n",
" callback=js_callback,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This functionality is directly available in `mols2grid` by using the `mols2grid.callbacks.info()` function:\n",
"\n",
"```python\n",
"mols2grid.display(\n",
" df, callback=mols2grid.callbacks.info(),\n",
")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is possible to load additional JS libraries by passing `custom_header=\"<script src=...></script>\"` to `mols2grid.display`, and they will then be available in the callback.\n",
"\n",
"### Displaying the 3D structure with 3Dmol.js\n",
"\n",
"In the following example, we query PubChem using the SMILES of the molecule (and Cactus as a fallback, but you can also provide another custom REST API), then fetch the 3D structure in SDF format and display it with 3Dmol.js:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols2grid.display(\n",
" df,\n",
" callback=mols2grid.callbacks.show_3d(),\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Opening an external link\n",
"\n",
"There is also a function to open a link based on the data in the molecule: `mols2grid.callbacks.external_link`.\n",
"\n",
"By default, it opens the search window of Leruli using the SMILES string, but the URL and data field used can be configured."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols2grid.display(\n",
" df,\n",
" callback=mols2grid.callbacks.external_link(),\n",
")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
| Unknown |
2D | cbouy/mols2grid | docs/notebooks/quickstart.ipynb | .ipynb | 4,711 | 175 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Quickstart\n",
"\n",
"[](https://colab.research.google.com/github/cbouy/mols2grid/blob/master/docs/notebooks/quickstart.ipynb)\n",
"\n",
"The easiest way to use mols2grid is through the `mols2grid.display` function. The input can be a DataFrame, a list of RDKit molecules, or an SDFile."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# uncomment and run if you're on Google Colab\n",
"# !pip install mols2grid\n",
"\n",
"# for development purposes only\n",
"# %load_ext autoreload\n",
"# %autoreload 2\n",
"# %env ANYWIDGET_HMR=1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import mols2grid"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's start with an SDFile (`.sdf` and `.sdf.gz` are both supported):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols2grid.display(mols2grid.datafiles.SOLUBILITY_SDF)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From this interface, you can:\n",
"\n",
"- Make simple text searches using the searchbar on the top right.\n",
"- Make substructure queries by clicking on `SMARTS` instead of `Text` and typing in the searchbar.\n",
"- Sort molecules by clicking on `Sort` and selecting a field (click the arrows on the right side of the `Sort` dropdown to reverse the order).\n",
"- View metadata by hovering your mouse over the *`i`* button of a cell, you can also press that button to anchor the information.\n",
"- Select a couple of molecules (click on a cell or on a checkbox, or navigate using your keyboard arrows and press the `ENTER` key).\n",
"- Export the selection to a SMILES or CSV file, or directly to the clipboard (this last functionality might be blocked depending on how you are running the notebook). If no selection was made, the entire grid is exported."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also use a pandas DataFrame as input, containing a column of RDKit molecules (specified using `mol_col=...`) or SMILES strings (specified using `smiles_col=...`):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)\n",
"subset_df = df.sample(50, random_state=0xAC1D1C)\n",
"mols2grid.display(subset_df, mol_col=\"mol\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, we can also use a list of RDKit molecules:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols = subset_df[\"mol\"].to_list()\n",
"mols2grid.display(mols)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"But the main point of mols2grid is that the widget let's you access your selections from Python afterwards:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols2grid.get_selection()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you were using a DataFrame, you can get the subset corresponding to your selection with:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df.iloc[list(mols2grid.get_selection().keys())]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, you can save the grid as a standalone HTML document. Simply replace `display` by `save` and add the path to the output file with `output=\"path/to/molecules.html\"`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"mols2grid.save(mols, output=\"quickstart-grid.html\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| Unknown |
2D | cbouy/mols2grid | docs/notebooks/filtering.ipynb | .ipynb | 3,481 | 121 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Filtering\n",
"\n",
"[](https://colab.research.google.com/github/cbouy/mols2grid/blob/master/docs/notebooks/filtering.ipynb)\n",
"\n",
"It's possible to integrate the grid with other widgets to complement the searchbar."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# uncomment and run if you're on Google Colab\n",
"# !pip install mols2grid\n",
"\n",
"# for development purposes only\n",
"# %load_ext autoreload\n",
"# %autoreload 2\n",
"# %env ANYWIDGET_HMR=1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from ipywidgets import interact, widgets\n",
"from rdkit.Chem import Descriptors\n",
"\n",
"import mols2grid"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We'll use ipywidgets to add sliders for the molecular weight and the other molecular descriptors, and define a function that queries the internal dataframe using the values in the sliders.\n",
"\n",
"Everytime the sliders are moved, the function is called to filter our grid."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)\n",
"# compute some descriptors\n",
"df[\"MolWt\"] = df[\"mol\"].apply(Descriptors.ExactMolWt)\n",
"df[\"LogP\"] = df[\"mol\"].apply(Descriptors.MolLogP)\n",
"df[\"NumHDonors\"] = df[\"mol\"].apply(Descriptors.NumHDonors)\n",
"df[\"NumHAcceptors\"] = df[\"mol\"].apply(Descriptors.NumHAcceptors)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"grid = mols2grid.MolGrid(\n",
" df,\n",
" size=(120, 100),\n",
" name=\"filters\",\n",
")\n",
"view = grid.display(n_items_per_page=12)\n",
"\n",
"\n",
"@interact(\n",
" MolWt=widgets.IntRangeSlider(value=[0, 600], min=0, max=600, step=10),\n",
" LogP=widgets.IntRangeSlider(value=[-10, 10], min=-10, max=10, step=1),\n",
" NumHDonors=widgets.IntRangeSlider(value=[0, 20], min=0, max=20, step=1),\n",
" NumHAcceptors=widgets.IntRangeSlider(value=[0, 20], min=0, max=20, step=1),\n",
")\n",
"def filter_grid(MolWt, LogP, NumHDonors, NumHAcceptors):\n",
" results = grid.dataframe.query(\n",
" \"@MolWt[0] <= MolWt <= @MolWt[1] and \"\n",
" \"@LogP[0] <= LogP <= @LogP[1] and \"\n",
" \"@NumHDonors[0] <= NumHDonors <= @NumHDonors[1] and \"\n",
" \"@NumHAcceptors[0] <= NumHAcceptors <= @NumHAcceptors[1]\"\n",
" )\n",
" return grid.filter_by_index(results.index)\n",
"\n",
"\n",
"view"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.11"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
| Unknown |
2D | cbouy/mols2grid | scripts/marimo_example.py | .py | 2,983 | 104 | import marimo
__generated_with = "0.18.4"
app = marimo.App(width="medium")
@app.cell
def import_libraries():
import marimo as mo
import mols2grid
from mols2grid.datafiles import SOLUBILITY_SDF
return SOLUBILITY_SDF, mo, mols2grid
@app.cell
def prepare(mo):
from rdkit.Chem.Draw import rdMolDraw2D
def mol_to_svg(mol, width=130, height=90, opts=None):
if mol is None:
return mo.Html("")
drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
if opts is not None:
drawer.SetDrawOptions(opts)
drawer.DrawMolecule(mol)
drawer.FinishDrawing()
return mo.Html(drawer.GetDrawingText())
solubility_range = mo.ui.range_slider(
-10,
2,
0.5,
debounce=True,
show_value=True,
full_width=True,
label="Solubility",
)
return mol_to_svg, solubility_range
@app.cell
def create_grid(SOLUBILITY_SDF, mols2grid):
# NOTE:
# This cell is intentionally kept independent from the sliders.
# In marimo, cells are re-executed whenever any of their dependencies change.
# Keeping grid creation here prevents MolGrid.from_sdf(...) from being
# re-run on every slider update, which would reset the widget state.
grid = mols2grid.MolGrid.from_sdf(SOLUBILITY_SDF, size=(120, 100))
get_selection_ids = grid.get_marimo_selection()
view = grid.display(n_items_per_page=12, selection=True)
return get_selection_ids, grid, view
@app.cell
def filter_and_display(grid, mo, solubility_range, view):
mask = grid.dataframe["SOL"].between(*solubility_range.value)
results = grid.dataframe.loc[mask]
# Same as:
# grid.dataframe["SOL"] >= solubility_range.value[0]) & \
# (grid.dataframe["SOL"] <= solubility_range.value[1])
grid.filter_by_index(results.index)
mo.vstack([solubility_range, view])
return (results,)
@app.cell(hide_code=True)
def display_selection(get_selection_ids, mo, mol_to_svg, results):
# This cell displays the selected molecules in a Marimo table.
# The `mol_to_svg` function is used to render the molecule images
# directly in the table.
# We filter the dataframe based on the selection state (`get_selection_ids`)
# from the grid above.
selected = results[results["mols2grid-id"].isin(get_selection_ids())]
# # If you want to use custom drawing options:
# opts = rdMolDraw2D.MolDrawOptions()
# opts.explicitMethyl = True
table = mo.ui.table(
selected.reset_index(drop=True).drop(columns="img"),
format_mapping={
"mol": mol_to_svg
# "mol": lambda mol: mol_to_svg(mol, opts=opts)
# If you want to use custom drawing options
},
freeze_columns_left=["mols2grid-id", "mol"],
freeze_columns_right=["SOL"],
label="Try selecting molecules from the grid above!!",
)
table # noqa: B018
if __name__ == "__main__":
app.run()
| Python |
2D | cbouy/mols2grid | tests/webdriver_utils.py | .py | 5,453 | 137 | from ast import literal_eval
from base64 import b64decode
from io import BytesIO
import imagehash
from cairosvg import svg2png
from PIL import Image
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class selection_available:
def __init__(self, is_empty=False):
self.empty = is_empty
def __call__(self, driver):
sel = driver.execute_script("return SELECTION.to_dict();")
sel = literal_eval(sel)
if sel == {} and self.empty:
return True
if sel != {} and not self.empty:
return sel
return False
class CustomDriver(webdriver.Chrome):
def wait_for_img_load(
self, max_delay=30, selector="#mols2grid .m2g-cell .data-img svg"
):
return WebDriverWait(self, max_delay).until(
EC.presence_of_element_located((By.CSS_SELECTOR, selector))
)
def wait_for_selection(self, is_empty=False, max_delay=3):
return WebDriverWait(self, max_delay).until(selection_available(is_empty))
def wait(self, condition, max_delay=5):
return WebDriverWait(
self, max_delay, ignored_exceptions=[StaleElementReferenceException]
).until(condition)
def find_by_id(self, element_id, **kwargs):
condition = EC.presence_of_element_located((By.ID, element_id))
return self.wait(condition, **kwargs)
def find_clickable(self, by, selector, **kwargs):
condition = EC.element_to_be_clickable((by, selector))
return self.wait(condition, **kwargs)
def find_by_css_selector(self, css_selector, **kwargs):
condition = EC.presence_of_element_located((By.CSS_SELECTOR, css_selector))
return self.wait(condition, **kwargs)
def find_by_class_name(self, name, **kwargs):
condition = EC.presence_of_element_located((By.CLASS_NAME, name))
return self.wait(condition, **kwargs)
def find_all_by_class_name(self, name, **kwargs):
condition = EC.presence_of_all_elements_located((By.CLASS_NAME, name))
return self.wait(condition, **kwargs)
def get_svg_hash(self, *args, **kwargs):
im = next(self.get_imgs_from_svgs(*args, **kwargs))
return imagehash.average_hash(im, hash_size=16)
def get_imgs_from_svgs(self, selector="#mols2grid .m2g-cell .data-img"):
condition = EC.presence_of_all_elements_located((By.CSS_SELECTOR, selector))
svgs = self.wait(condition)
for svg in svgs:
im = svg2png(bytestring=(svg.get_attribute("innerHTML")))
yield Image.open(BytesIO(im))
def get_png_hash(self, selector="#mols2grid .m2g-cell .data-img *"):
img = self.find_by_css_selector(selector)
im = Image.open(BytesIO(b64decode(img.get_attribute("src")[22:])))
return imagehash.average_hash(im, hash_size=16)
def substructure_query(self, smarts):
self.find_clickable(By.CSS_SELECTOR, "#mols2grid .m2g-search-smarts").click()
self.find_by_css_selector("#mols2grid .m2g-searchbar").send_keys(smarts)
self.wait_for_img_load()
def text_search(self, txt):
self.find_clickable(By.CSS_SELECTOR, "#mols2grid .m2g-search-text").click()
self.find_by_css_selector("#mols2grid .m2g-searchbar").send_keys(txt)
self.wait_for_img_load()
def clear_search(self):
self.find_by_css_selector("#mols2grid .m2g-searchbar").clear()
self.find_by_css_selector("#mols2grid .m2g-searchbar").send_keys(Keys.BACKSPACE)
self.wait_for_img_load()
def sort_grid(self, field):
self.find_clickable(By.CSS_SELECTOR, "#mols2grid .m2g-sort").click()
self.find_clickable(
By.CSS_SELECTOR, f'#mols2grid .m2g-sort option[value="data-{field}"]'
).click()
self.wait_for_img_load()
def invert_sort(self):
self.find_clickable(By.CSS_SELECTOR, "#mols2grid .m2g-sort .m2g-order").click()
self.wait_for_img_load()
def grid_action(self, action, pause=0):
self.find_clickable(By.CSS_SELECTOR, "#mols2grid .m2g-actions").click()
self.find_clickable(
By.CSS_SELECTOR, f'#mols2grid .m2g-actions option[value="{action}"]'
).click()
ActionChains(self).pause(pause).perform()
def get_tooltip_content(self, pause=0, selector=".m2g-cell .m2g-info"):
(
ActionChains(self)
.move_to_element(self.find_by_css_selector(f"#mols2grid {selector}"))
.pause(pause)
.perform()
)
tooltip = self.find_by_css_selector('div.popover[role="tooltip"]')
el = tooltip.find_element(By.CLASS_NAME, "popover-body")
return el.get_attribute("innerHTML")
def trigger_callback(
self, selector="#mols2grid .m2g-cell .m2g-callback", pause=0.2
):
self.wait_for_img_load()
el = self.find_clickable(By.CSS_SELECTOR, selector)
(ActionChains(self).move_to_element(el).pause(pause).click().perform())
def click_checkbox(self, is_empty=False):
self.find_clickable(By.CSS_SELECTOR, ".m2g-cb").click()
return self.wait_for_selection(is_empty=is_empty)
| Python |
2D | cbouy/mols2grid | tests/test_select.py | .py | 1,528 | 59 | from types import SimpleNamespace
import pytest
import mols2grid as mg
from mols2grid.select import register
@pytest.fixture(autouse=True)
def clear_register_between_tests():
register._clear()
register._init_grid("foo")
yield
register._clear()
def test_clear_register():
register._clear()
assert not hasattr(register, "current_selection")
assert register.SELECTIONS == {}
def test_update_current_grid(smiles_records):
mg.MolGrid(smiles_records, name="bar")
assert register.current_selection == "bar"
def test_init_grid():
assert "foo" in register.SELECTIONS
assert register.current_selection == "foo"
def test_overwrite_warning():
event = SimpleNamespace(new='{0: "C"}')
register.selection_updated("foo", event)
with pytest.warns(
UserWarning, match="Overwriting non-empty 'foo' grid selection: {0: 'C'}"
):
register._init_grid("foo")
assert register.get_selection() == {}
def test_update_and_get_selection():
assert register.get_selection() == {}
event = SimpleNamespace(new='{0: "CCO"}')
register.selection_updated("foo", event)
assert register.get_selection() == {0: "CCO"}
event.new = "{}"
register.selection_updated("foo", event)
assert register.get_selection() == {}
def test_list_grids():
assert register.list_grids() == ["foo"]
register._init_grid("bar")
assert register.list_grids() == ["foo", "bar"]
register._init_grid("foo")
assert register.list_grids() == ["foo", "bar"]
| Python |
2D | cbouy/mols2grid | tests/test_marimo_integration.py | .py | 4,250 | 137 | import sys
from unittest.mock import MagicMock, patch
import pandas as pd
import pytest
from mols2grid import MolGrid
from mols2grid.utils import is_running_within_marimo
@pytest.fixture
def mock_marimo_module():
with patch.dict(sys.modules, {"marimo": MagicMock()}):
yield
@pytest.mark.usefixtures("mock_marimo_module")
def test_is_running_within_marimo_true():
assert is_running_within_marimo() is True
def test_is_running_within_marimo_false():
# Ensure marimo is not in sys.modules for this test
with patch.dict(sys.modules):
if "marimo" in sys.modules:
del sys.modules["marimo"]
assert is_running_within_marimo() is False
@pytest.fixture
def grid_fixture():
df = pd.DataFrame({"SMILES": ["C"]})
return df, MolGrid(df, smiles_col="SMILES")
@pytest.mark.usefixtures("mock_marimo_module")
def test_init_in_marimo_does_not_display():
df = pd.DataFrame({"SMILES": ["C"]})
# Mock IPython.display.display which is imported as display in molgrid.py
# We need to patch it where it is used, i.e., in mols2grid.molgrid
with patch("mols2grid.molgrid.display") as mock_display:
_ = MolGrid(df, smiles_col="SMILES")
mock_display.assert_not_called()
@pytest.mark.usefixtures("mock_marimo_module")
def test_display_in_marimo(grid_fixture):
_, mg = grid_fixture
# Mock marimo.Html and marimo.vstack
with patch("marimo.Html") as mock_html, patch("marimo.vstack") as mock_vstack:
result = mg.display()
# Verify that an iframe is being rendered inside Html
mock_html.assert_called_once()
args, _ = mock_html.call_args
html_content = args[0]
assert "<iframe" in html_content
assert 'class="mols2grid-iframe"' in html_content
# Verify vstack was called with [widget, html]
mock_vstack.assert_called_once()
vstack_args = mock_vstack.call_args[0][0]
assert len(vstack_args) == 2
assert vstack_args[0] == mg.widget
assert vstack_args[1] == mock_html.return_value
# Ensure the result is the return value of marimo.vstack
assert result == mock_vstack.return_value
@pytest.mark.usefixtures("mock_marimo_module")
def test_get_selection_state_inside_marimo(grid_fixture):
_, mg = grid_fixture
# Mock marimo.state
mock_get_state = MagicMock()
mock_set_state = MagicMock()
with patch(
"marimo.state", return_value=(mock_get_state, mock_set_state)
) as mock_state:
# Call get_marimo_selection
state_getter = mg.get_marimo_selection()
# Check if marimo.state was called with empty list
mock_state.assert_called_once_with([])
# Check if _marimo_hooked is set
assert getattr(mg.widget, "_marimo_hooked", False) is True
# Verify return value
assert state_getter == mock_get_state
def test_get_selection_state_outside_marimo(grid_fixture):
_, mg = grid_fixture
# Ensure marimo is not in sys.modules
with patch.dict(sys.modules):
if "marimo" in sys.modules:
del sys.modules["marimo"]
with pytest.raises(RuntimeError, match="only available in a marimo notebook"):
mg.get_marimo_selection()
@pytest.mark.usefixtures("mock_marimo_module")
def test_selection_state_update_logic(grid_fixture):
_, mg = grid_fixture
mock_set_state = MagicMock()
with (
patch("marimo.state", return_value=(MagicMock(), mock_set_state)),
patch.object(mg.widget, "observe") as mock_observe,
):
# Inspect the observe call to capture the callback
mg.get_marimo_selection()
# Verify observe was called
mock_observe.assert_called()
args, _ = mock_observe.call_args
callback = args[0]
# Simulate event with valid selection
# The widget returns a string representation of a dict
new_selection = {1: "C", 2: "CC"}
event = {"new": str(new_selection)}
callback(event)
mock_set_state.assert_called_with([1, 2])
# Test invalid input (should pass silently)
mock_set_state.reset_mock()
callback({"new": "invalid json"})
mock_set_state.assert_not_called()
| Python |
2D | cbouy/mols2grid | tests/__init__.py | .py | 0 | 0 | null | Python |
2D | cbouy/mols2grid | tests/test_callbacks.py | .py | 921 | 34 | import pytest
from mols2grid import callbacks
def test_make_popup_callback():
popup = callbacks.make_popup_callback(
title="${title}",
subtitle="${title}",
svg="<svg><rect width='10' height='10'/></svg>",
html='<span id="foo">${title}</span>',
js='var title = "FOOBAR";',
style="max-width: 42%;",
)
assert "<h2>${title}</h2>" in popup
assert "<p>${title}</p>" in popup
assert '<span id="foo">${title}</span>' in popup
assert (
'// Prerequisite JavaScript code.\n// prettier-ignore\nvar title = "FOOBAR";'
in popup
)
assert '<div id="m2g-modal" tabindex="-1" style="max-width: 42%;">' in popup
@pytest.mark.parametrize(
("title", "expected"),
[
("SMILES", "${data['SMILES']}"),
(None, None),
],
)
def test_title_field(title, expected):
assert callbacks._get_title_field(title) == expected
| Python |
2D | cbouy/mols2grid | tests/test_molgrid.py | .py | 10,533 | 345 | from types import SimpleNamespace
import pytest
from numpy.testing import assert_equal
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem.rdDepictor import Compute2DCoords
from mols2grid import MolGrid
from mols2grid.select import register
def get_grid(df, **kwargs):
kwargs.setdefault("mol_col", "mol")
return MolGrid(df, **kwargs)
def test_no_input_specified(small_df):
with pytest.raises(
ValueError, match="One of `smiles_col` or `mol_col` must be set"
):
get_grid(small_df, smiles_col=None, mol_col=None)
def test_name_not_str(small_df):
with pytest.raises(
TypeError, match=r"`name` must be a string\. Currently of type int"
):
get_grid(small_df, name=0)
def test_uses_svg(grid_prerendered):
assert grid_prerendered.useSVG is True
data = grid_prerendered.dataframe.loc[0, "img"]
assert "<svg " in data[:100]
def test_uses_png(small_df):
grid = get_grid(small_df, useSVG=False, prerender=True)
assert grid.useSVG is False
data = grid.dataframe.loc[0, "img"]
assert data.startswith('<img src="data:image/png;base64')
def test_copy_df(df):
grid = MolGrid(df, mol_col="mol")
assert grid.dataframe is not df
def test_records_as_input(smiles_records):
MolGrid(smiles_records)
def test_rename(small_df):
grid = get_grid(small_df, rename={"SOL": "Solubility"})
assert "Solubility" in grid.dataframe.columns
def test_smi_only_makes_mol_temporary(small_df):
df = small_df.copy()
df["SMILES"] = df["mol"].apply(Chem.MolToSmiles)
df = df.drop(columns=["mol"])
grid = MolGrid(df)
assert "mol" not in grid._extra_columns
assert "mol" not in grid.dataframe.columns
def test_keep_mol_col_if_input(grid_prerendered):
assert "mol" not in grid_prerendered._extra_columns
assert "mol" in grid_prerendered.dataframe.columns
def test_remove_hydrogens():
mol = Chem.MolFromSmiles("C")
mol = Chem.AddHs(mol)
data = [{"mol": mol, "ID": 0}]
grid = MolGrid(data, mol_col="mol", removeHs=True, prerender=True)
new = grid.dataframe.loc[0, "mol"]
assert new.GetNumAtoms() == 1
def test_remove_coordinates():
mol = Chem.MolFromSmiles("C")
mol = Chem.AddHs(mol)
Compute2DCoords(mol)
data = [{"mol": mol, "ID": 0}]
grid = MolGrid(data, mol_col="mol", use_coords=False, prerender=True)
new = grid.dataframe.loc[0, "mol"]
with pytest.raises(ValueError, match="Bad Conformer Id"):
new.GetConformer()
def test_generate_smi_from_mol_col(small_df):
df = small_df.drop(columns=["SMILES"])
grid = MolGrid(df, mol_col="mol", prerender=True)
assert "SMILES" in grid.dataframe.columns
def test_index_when_none_molecules(small_df):
df = small_df.copy()
df.loc[1, "mol"] = None
grid = MolGrid(df, mol_col="mol", prerender=True)
assert len(grid.dataframe) == len(df) - 1
assert_equal(grid.dataframe["mols2grid-id"].values, [0, 2, 3, 4])
def test_custom_moldrawoptions(small_df):
opts = Draw.MolDrawOptions()
opts.fixedBondLength = 42
grid = get_grid(small_df, MolDrawOptions=opts, prerender=True)
assert grid.MolDrawOptions.fixedBondLength == 42
def test_moldrawoptions_as_kwargs(small_df):
grid = get_grid(small_df, fixedBondLength=42, prerender=True)
assert grid.MolDrawOptions.fixedBondLength == 42
def test_update_current_grid_on_init(small_df):
get_grid(small_df, name="foo")
assert register.current_selection == "foo"
assert register.get_selection("foo") is register.get_selection()
assert register.get_selection() == {}
def test_from_mols(mols):
grid = MolGrid.from_mols(mols)
assert "mol" in grid.dataframe.columns
def test_from_mols_custom_mol_col(mols):
grid = MolGrid.from_mols(mols, mol_col="rdmol")
assert "rdmol" in grid.dataframe.columns
assert "mol" not in grid.dataframe.columns
@pytest.mark.parametrize(
("param", "attr", "value"),
[
("name", "_grid_id", "foobar"),
("coordGen", "prefer_coordGen", False),
("removeHs", "removeHs", True),
("useSVG", "useSVG", False),
("use_coords", "use_coords", False),
("size", "img_size", (42, 42)),
("prerender", "prerender", True),
("smiles_col", "smiles_col", "smi"),
("mol_col", "mol_col", "rdmol"),
],
)
def test_from_mols_kwargs(mols, param, attr, value):
if param == "useSVG":
grid = MolGrid.from_mols(mols, prerender=True, **{param: value})
else:
grid = MolGrid.from_mols(mols, **{param: value})
assert getattr(grid, attr) == value
@pytest.mark.parametrize("sdf_source", ["sdf_path", "sdf_file"])
def test_from_sdf(sdf_source, request):
sdf = request.getfixturevalue(sdf_source)
grid = MolGrid.from_sdf(sdf)
assert "mol" in grid.dataframe.columns
def test_from_sdf_custom_mol_col(sdf_path):
grid = MolGrid.from_sdf(sdf_path, mol_col="rdmol", prerender=True)
assert "rdmol" in grid.dataframe.columns
assert "mol" not in grid.dataframe.columns
@pytest.mark.parametrize(
("param", "attr", "value"),
[
("name", "_grid_id", "foobar"),
("coordGen", "prefer_coordGen", False),
("removeHs", "removeHs", True),
("useSVG", "useSVG", False),
("use_coords", "use_coords", False),
("size", "img_size", (42, 42)),
("prerender", "prerender", True),
("smiles_col", "smiles_col", "smi"),
("mol_col", "mol_col", "rdmol"),
],
)
def test_from_sdf_kwargs(sdf_path, param, attr, value):
if param == "useSVG":
grid = MolGrid.from_sdf(sdf_path, prerender=True, **{param: value})
else:
grid = MolGrid.from_sdf(sdf_path, **{param: value})
assert getattr(grid, attr) == value
def test_template(grid_prerendered):
grid_prerendered.template = "interactive"
assert grid_prerendered._template is grid_prerendered.template
def test_template_setter(grid_prerendered):
with pytest.raises(ValueError, match="template='foo' not supported"):
grid_prerendered.template = "foo"
def test_substruct_highlight():
mol = Chem.MolFromSmiles("C")
mol.__sssAtoms = [0]
grid = MolGrid.from_mols([mol], prerender=True)
svg = grid.dataframe.loc[0, "img"]
assert "<ellipse" in svg
def test_mol_to_img_svg():
mol = Chem.MolFromSmiles("C")
grid = MolGrid.from_mols([mol], prerender=True)
img = grid.mol_to_img(mol)
assert "<svg " in img[:100]
def test_mol_to_img_png():
mol = Chem.MolFromSmiles("C")
grid = MolGrid.from_mols([mol], prerender=True)
grid.useSVG = False
grid._MolDraw2D = Draw.MolDraw2DCairo
img = grid.mol_to_img(mol)
assert img.startswith('<img src="data:image/png;base64')
def test_get_selection(small_df):
grid = MolGrid(small_df, mol_col="mol", name="grid")
other = MolGrid(small_df, mol_col="mol", name="other")
event = SimpleNamespace(new='{0: ""}')
register.selection_updated("grid", event)
assert register.current_selection == "grid"
assert grid.get_selection().equals(small_df.head(1))
assert other.get_selection().equals(small_df.head(0)) # empty dataframe
register._clear()
def test_save(grid, tmp_path):
output = tmp_path / "output.html"
grid.save(output)
assert output.is_file()
def test_render_interactive(grid):
grid.render(template="interactive")
def test_render_static(grid_prerendered):
grid_prerendered.render(template="static")
def test_render_wrong_template(grid):
with pytest.raises(ValueError, match="template='foo' not supported"):
grid.render(template="foo")
@pytest.mark.parametrize(
"kwargs",
[
{},
{"subset": ["ID"]},
{"tooltip": ["ID"]},
{"gap": 5},
{"style": {"ID": lambda x: "color: red" if x == 1 else ""}},
{"transform": {"ID": lambda x: f"Id. #{x}"}},
],
)
def test_integration_static(grid_prerendered, kwargs):
grid_prerendered.to_static(**kwargs)
def test_python_callback(grid):
html = grid.to_interactive(subset=["img"], callback=lambda data: None) # noqa: ARG005
assert "// Trigger custom python callback" in html
assert "// No kernel detected for callback" in html
def test_cache_selection(small_df):
grid = get_grid(small_df, name="cache")
event = SimpleNamespace(new='{0: "CCO"}')
register.selection_updated("cache", event)
grid = get_grid(small_df, name="cache", cache_selection=True)
assert hasattr(grid, "_cached_selection")
assert register.get_selection("cache") == grid._cached_selection
def test_cache_no_init(small_df):
grid = get_grid(small_df, name="new_cache", cache_selection=True)
assert hasattr(grid, "_cached_selection")
assert grid._cached_selection == {}
assert "new_cache" in register.list_grids()
def test_no_cache_selection(small_df):
grid = get_grid(small_df, name="no_cache", cache_selection=False)
assert grid._cached_selection == {}
assert "no_cache" in register.list_grids()
def test_onthefly_render_png_error(df):
with pytest.raises(
ValueError, match="On-the-fly rendering of PNG images not supported"
):
MolGrid(df, prerender=False, useSVG=False)
def test_substruct_highlight_prerender_error(grid_prerendered):
with pytest.raises(
ValueError, match="Cannot highlight substructure search with prerendered images"
):
grid_prerendered.display(substruct_highlight=True)
# disables substruct highlight when prerendering by default
grid_prerendered.display()
def test_use_coords_onthefly_error(small_df):
with pytest.raises(
ValueError, match="Cannot use coordinates with on-the-fly rendering"
):
get_grid(small_df, use_coords=True, prerender=False)
def test_sort_by_not_in_subset_or_tooltip(grid):
with pytest.raises(ValueError, match="'_Name' is not an available field"):
grid.to_interactive(subset=["ID", "img"], sort_by="_Name")
def test_subset_without_img_no_error(grid):
grid.display(subset=["_Name"])
def test_static_no_prerender_error(grid):
with pytest.raises(
ValueError, match="Please set `prerender=True` when using the 'static' template"
):
grid.display(template="static")
def test_replace_non_serializable_from_default_output(small_df):
grid = get_grid(small_df)
grid.dataframe["non-serializable"] = grid.dataframe[grid.mol_col]
html = grid.render()
assert "\\ud83e\\udd37\\u200d\\u2642\\ufe0f" in html # 🤷♂️
| Python |
2D | cbouy/mols2grid | tests/test_interface.py | .py | 27,392 | 859 | import json
import os
import sys
from base64 import b64encode
from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import imagehash
import pytest
from rdkit import Chem
from rdkit.Chem import AllChem
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import mols2grid
from mols2grid.select import register
from mols2grid.utils import env
from .webdriver_utils import CustomDriver
try:
from rdkit.Chem.rdDepictor import IsCoordGenSupportAvailable
except ImportError:
COORDGEN_SUPPORT = not sys.platform.startswith("win")
else:
COORDGEN_SUPPORT = IsCoordGenSupportAvailable()
GITHUB_ACTIONS = bool(os.environ.get("GITHUB_ACTIONS"))
HEADLESS = GITHUB_ACTIONS or ("debugpy" not in sys.modules)
pytestmark = pytest.mark.webdriver
skip_no_coordgen = pytest.mark.skipif(
not COORDGEN_SUPPORT,
reason="CoordGen library not available in this RDKit build",
)
def get_grid(df, **kwargs):
kwargs.setdefault("mol_col", "mol")
return mols2grid.MolGrid(df, **kwargs)
def get_doc(grid, kwargs):
html = grid.render(**kwargs)
html = b64encode(html.encode()).decode()
return f"data:text/html;base64,{html}"
@pytest.fixture(scope="module")
def driver():
# note: change `browser-path` in se-config.toml if not using Brave browser
options = webdriver.ChromeOptions()
# Run headless on GitHub CI, and locally unless using VSCode debugger
if HEADLESS:
options.add_argument("--headless=new")
options.add_argument("--enable-automation")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--start-maximized")
driver = CustomDriver(options=options)
driver.set_page_load_timeout(10)
yield driver
driver.quit()
@pytest.fixture(scope="module")
def html_doc(grid):
return get_doc(
grid,
{
"n_items_per_page": 5,
"subset": ["_Name", "img"],
},
)
def test_no_subset_all_visible(driver: CustomDriver, grid):
doc = get_doc(grid, {"tooltip": [], "selection": False})
driver.get(doc)
columns = set(grid.dataframe.columns.drop(["mol", "mols2grid-id"]).to_list())
cell = driver.find_by_css_selector("#mols2grid .m2g-cell")
data_el = cell.find_elements(By.CLASS_NAME, "data")
classes = [
c.replace("data-", "").replace("-display", "")
for x in data_el
for c in x.get_attribute("class").split(" ")
if c.startswith("data-")
]
classes = set(classes)
assert classes == columns
def test_smiles_hidden(driver: CustomDriver, html_doc):
driver.get(html_doc)
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-SMILES")
assert not el.is_displayed()
@pytest.mark.parametrize("page", [1, 2, 3])
def test_page_click(driver: CustomDriver, grid, page):
doc = get_doc(grid, {"subset": ["img", "_Name"], "n_items_per_page": 9})
driver.get(doc)
for i in range(2, page + 1):
driver.wait_for_img_load()
next_page = driver.find_by_css_selector(f'a.page-link[data-i="{i}"]')
next_page.click()
first_cell = driver.find_by_class_name("m2g-cell")
mols2grid_id = 9 * (page - 1)
name = first_cell.find_element(By.CLASS_NAME, "data-_Name")
ref = grid.dataframe.iloc[mols2grid_id]
assert name.text == ref["_Name"]
@pytest.mark.parametrize(
("name", "css_prop", "value", "expected"),
[
("gap", "margin-top", 20, "20px"),
("border", "border-top-width", "3px solid", "3px"),
("border", "border-top-style", "1px dashed", "dashed"),
("border", "border-top-color", "1px solid blue", "rgb(0, 0, 255)"),
("fontsize", "font-size", "16pt", "21.3333px"),
("fontfamily", "font-family", "Consolas", "Consolas"),
("textalign", "text-align", "right", "right"),
(
"custom_css",
"background-color",
"#mols2grid .m2g-cell { background-color: black; }",
"rgb(0, 0, 0)",
),
],
)
def test_css_properties(driver: CustomDriver, grid, name, css_prop, value, expected):
doc = get_doc(grid, {name: value})
driver.get(doc)
computed = driver.execute_script(
f"""return getComputedStyle(
document.querySelector('#mols2grid .m2g-cell')
).getPropertyValue({css_prop!r});
"""
)
assert computed == expected
def test_text_search(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
driver.text_search("iodopropane")
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-SMILES")
assert el.get_attribute("innerHTML") == "CC(I)C"
def test_text_search_regex_chars(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
driver.text_search("1-pentene")
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-SMILES")
assert el.get_attribute("innerHTML") == "CCCC=C"
def test_smarts_search(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
driver.substructure_query("CC(I)C")
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.text == "2-iodopropane"
def test_selection_click(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
sel = driver.click_checkbox()
assert sel == {0: "CCC(C)CC"}
register._clear()
def test_export_csv(driver: CustomDriver, html_doc):
sep = ";"
driver.get(html_doc)
driver.wait_for_img_load()
driver.click_checkbox()
driver.sort_grid("_Name")
now = datetime.now(tz=timezone.utc)
driver.grid_action("save-csv", pause=0.5)
csv_files = sorted(
(Path.home() / "Downloads").glob("selection*.csv"),
key=lambda x: x.stat().st_mtime,
)
assert csv_files, "No output CSV file found in `~/Downloads`"
csv_file = csv_files[-1]
file_mtime = datetime.fromtimestamp(csv_file.stat().st_mtime, tz=timezone.utc)
assert (file_mtime - now).seconds < 1, "Could not find recent selection file"
content = csv_file.read_text()
expected = (
sep.join(("index", "_Name", "SMILES"))
+ "\n"
+ sep.join(("0", "3-methylpentane", "CCC(C)CC"))
+ "\n"
)
assert content == expected
csv_file.unlink()
register._clear()
def test_selection_with_cache_check_and_uncheck(driver: CustomDriver, df):
register._init_grid("cached_sel")
event = SimpleNamespace(new='{0: "CCC(C)CC"}')
register.selection_updated("cached_sel", event)
grid = get_grid(df, name="cached_sel", cache_selection=True)
doc = get_doc(grid, {})
driver.get(doc)
driver.wait_for_img_load()
sel = driver.wait_for_selection(is_empty=False)
assert sel == {0: "CCC(C)CC"}
empty_sel = driver.click_checkbox(is_empty=True)
assert empty_sel is True
register._clear()
def test_selection_check_uncheck_invert(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
# search
driver.text_search("iodopropane")
# check all
driver.grid_action("select-all")
sel = driver.wait_for_selection(is_empty=False)
assert len(sel) == 30
# uncheck all
driver.grid_action("unselect-all")
empty_sel = driver.wait_for_selection(is_empty=True)
assert empty_sel is True
# check matching
driver.grid_action("select-matching")
sel = driver.wait_for_selection(is_empty=False)
assert sel == {27: "CC(I)C"}
# invert
driver.grid_action("invert")
sel = driver.wait_for_selection(is_empty=False)
assert len(sel) == 29
register._clear()
@pytest.mark.parametrize("prerender", [True, False])
def test_image_size(driver: CustomDriver, df, prerender):
size = (200, 300)
grid = get_grid(df, size=size, prerender=prerender)
doc = get_doc(
grid,
{
"selection": False,
"border": "0",
"substruct_highlight": False,
"n_items_per_page": 1,
},
)
driver.get(doc)
if not prerender:
driver.wait_for_img_load()
img = driver.find_by_css_selector("#mols2grid .m2g-cell .data-img *")
assert img.size == {"width": size[0], "height": size[1]}
def test_image_use_coords(driver: CustomDriver, df):
mols = df["mol"][23:24].tolist()
AllChem.EmbedMolecule(mols[0], randomSeed=0xF00D)
grid = mols2grid.MolGrid.from_mols(
mols,
use_coords=True,
prerender=True,
useSVG=False,
size=(160, 120),
)
doc = get_doc(grid, {"substruct_highlight": False})
driver.get(doc)
hash_ = driver.get_png_hash()
diff = hash_ - imagehash.hex_to_hash(
"ff3ffe3ffe3fff7fff7ffe7ffe7ffe7ffe7ff07fe03ff11f87cf8fe1cff1fffb"
)
assert diff <= 2
@pytest.mark.parametrize(
("coordGen", "prerender", "expected"),
[
pytest.param(
True,
True,
"fffffffffffffffffe7ffe7ffe7ffe7ffe7f3c3c8811c183f7efffffffffffff",
marks=skip_no_coordgen,
),
(
True,
False,
"fffffffffffffe7ffe7ffe7ffe7ffe7ffe7f3e7c8811c183e7e7ffffffffffff",
),
(
False,
True,
"ffffffff03fcf9fcfdf9fcf9fcfbfe03fe07fcfffcfffdfff9fffbffffffffff",
),
(
False,
False,
"ffffffff03fcf9fcfdf9fcf9fcfbfe03fe07fcfffcfffdfff9fffbffffffffff",
),
],
)
def test_coordgen(driver: CustomDriver, mols, coordGen, prerender, expected):
useSVG = not prerender
grid = mols2grid.MolGrid.from_mols(
mols,
coordGen=coordGen,
prerender=prerender,
useSVG=useSVG,
size=(160, 120),
use_coords=False,
)
doc = get_doc(grid, {"substruct_highlight": False})
driver.get(doc)
if not prerender:
driver.wait_for_img_load()
hash_ = driver.get_svg_hash() if useSVG else driver.get_png_hash()
assert str(hash_) == expected
@pytest.mark.parametrize(
("removeHs", "prerender", "expected"),
[
pytest.param(
True,
True,
"fffffffffffffffffe7ffe7ffe7ffe7ffe7f3c3c8811c183f7efffffffffffff",
marks=skip_no_coordgen,
),
pytest.param(
False,
True,
"fffffe1ff91ffd3ff01ff0cffcbff0bff00ff53fe1bff887f29ff30fff6fffff",
marks=skip_no_coordgen,
),
(
True,
False,
"fffffffffffffe7ffe7ffe7ffe7ffe7ffe7f3e7c8811c183e7e7ffffffffffff",
),
(
False,
False,
"ff7ffe1ff91ffd3ff00ff0cffcbff0bff00ffd3fe1bff887f29ff30fff6fff7f",
),
],
)
def test_removeHs(driver: CustomDriver, df, removeHs, prerender, expected):
useSVG = not prerender
mol = df["mol"][0]
mol.ClearProp("SMILES")
mols = [Chem.AddHs(mol)]
grid = mols2grid.MolGrid.from_mols(
mols,
removeHs=removeHs,
prerender=prerender,
useSVG=useSVG,
size=(160, 120),
use_coords=False,
)
doc = get_doc(grid, {"n_items_per_page": 5, "substruct_highlight": False})
driver.get(doc)
if not prerender:
driver.wait_for_img_load()
hash_ = driver.get_svg_hash() if useSVG else driver.get_png_hash()
if expected == "":
raise AssertionError(str(hash_))
diff = hash_ - imagehash.hex_to_hash(expected)
assert diff <= 1
@pytest.mark.parametrize(
("kwargs", "expected"),
[
(
{"addAtomIndices": True},
"ffffffffff7ffe3ffe7ffefffeff3e7f3e791830c184e7cfe7cff7cfffffffff",
),
(
{"fixedBondLength": 10},
"fffffffffffffffffffffffffe7ffe7ff81ffc3fffffffffffffffffffffffff",
),
(
{"atomColourPalette": {6: (0, 0.8, 0.8)}},
"fffffffffffffffffe7ffe7ffe7ffe7ffe7f3e7c8819c183e7e7ffffffffffff",
),
(
{"legend": "foo"},
"fffffffffffffe7ffe7ffe7ffe7ffe7f3e7c1818c183e7e7fffffffffe7ffe7f",
),
],
)
def test_moldrawoptions(driver: CustomDriver, df, kwargs, expected):
grid = get_grid(df, size=(160, 120), **kwargs)
doc = get_doc(grid, {"n_items_per_page": 1, "subset": ["img"]})
driver.get(doc)
driver.wait_for_img_load()
hash_ = driver.get_svg_hash()
assert str(hash_) == expected
@pytest.mark.xfail(HEADLESS, reason="only seem to pass without headless mode")
def test_hover_color(driver: CustomDriver, grid):
doc = get_doc(grid, {"hover_color": "rgba(255, 0, 0, 0.1)"})
driver.get(doc)
(
ActionChains(driver)
.move_to_element(driver.find_by_css_selector("#mols2grid .m2g-cell"))
.pause(0.2)
.perform()
)
color = driver.execute_script(
"""
return getComputedStyle(
document.querySelector('#mols2grid .m2g-cell:hover'), ":after"
).getPropertyValue('background-color');
"""
)
assert color == "rgba(255, 0, 0, 0.1)"
def test_tooltip(driver: CustomDriver, grid):
doc = get_doc(grid, {"tooltip": ["_Name"]})
driver.get(doc)
driver.wait_for_img_load()
tooltip = driver.get_tooltip_content()
assert (
tooltip
== '<strong>_Name</strong>: <span class="copy-me">3-methylpentane</span>'
)
def test_tooltip_fmt(driver: CustomDriver, grid):
doc = get_doc(grid, {"tooltip": ["_Name"], "tooltip_fmt": "<em>{value}</em>"})
driver.get(doc)
driver.wait_for_img_load()
tooltip = driver.get_tooltip_content()
assert tooltip == '<em><span class="copy-me">3-methylpentane</span></em>'
def test_tooltip_not_in_subset(driver: CustomDriver, grid):
doc = get_doc(grid, {"tooltip": ["_Name"], "subset": ["ID", "img"]})
driver.get(doc)
driver.wait_for_img_load()
tooltip = driver.get_tooltip_content()
assert (
tooltip
== '<strong>_Name</strong>: <span class="copy-me">3-methylpentane</span>'
)
def test_style(driver: CustomDriver, grid):
doc = get_doc(
grid,
{
"tooltip": ["_Name"],
"style": {
"__all__": lambda x: "color: red", # noqa: ARG005
"_Name": lambda x: "color: blue", # noqa: ARG005
},
},
)
driver.get(doc)
driver.wait_for_img_load()
el = driver.find_by_css_selector("#mols2grid .m2g-cell")
assert el.value_of_css_property("color") == "rgba(255, 0, 0, 1)"
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.value_of_css_property("color") == "rgba(0, 0, 255, 1)"
tooltip = driver.get_tooltip_content()
assert (
tooltip == '<strong>_Name</strong>: <span class="copy-me" '
'style="color: blue">3-methylpentane</span>'
)
def test_transform(driver: CustomDriver, grid):
doc = get_doc(
grid, {"tooltip": ["_Name"], "transform": {"_Name": lambda x: x.upper()}}
)
driver.get(doc)
name = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert name.text == "3-METHYLPENTANE"
driver.wait_for_img_load()
tooltip = driver.get_tooltip_content(pause=0.5)
assert (
tooltip
== '<strong>_Name</strong>: <span class="copy-me">3-METHYLPENTANE</span>'
)
def test_transform_style_tooltip(driver: CustomDriver, grid):
doc = get_doc(
grid,
{
"tooltip": ["_Name"],
"transform": {"_Name": lambda x: "foo"}, # noqa: ARG005
"style": {
"__all__": lambda x: "background-color: red", # noqa: ARG005
"_Name": lambda x: "color: green" if x == "foo" else "color: blue",
},
},
)
driver.get(doc)
driver.wait_for_img_load()
cell = driver.find_by_css_selector("#mols2grid .m2g-cell")
assert cell.value_of_css_property("background-color") == "rgba(255, 0, 0, 1)"
name = cell.find_element(By.CLASS_NAME, "data-_Name")
assert name.text == "foo"
tooltip = driver.get_tooltip_content(pause=0.5)
assert (
tooltip == '<strong>_Name</strong>: <span class="copy-me" style="color: blue">'
"foo</span>"
)
@pytest.mark.parametrize("selection", [True, False])
def test_callback_js(driver: CustomDriver, grid, selection):
doc = get_doc(
grid,
{
"subset": ["img", "_Name"],
"callback": "$('#mols2grid .m2g-cell .data-_Name').html('foo')",
"selection": selection,
},
)
driver.get(doc)
driver.wait_for_img_load()
driver.trigger_callback()
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.text == "foo"
def test_sort_by(driver: CustomDriver, grid):
doc = get_doc(grid, {"subset": ["img", "_Name"], "sort_by": "_Name"})
driver.get(doc)
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.text == "1,1,2,2-tetrachloroethane"
def test_sort_button(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
driver.sort_grid("_Name")
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.text == "1,1,2,2-tetrachloroethane"
driver.invert_sort()
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.text == "tetrachloromethane"
@pytest.mark.parametrize(
("substruct_highlight", "expected"),
[
(True, "fffffe7ffc3ffc3ffe7ffe7ffe7ffe7ffe7ffc3ff81fc003c3c3c7e3c7e3eff7"),
(False, "fe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffc3ff99fe3c7c7e3cff3"),
],
)
def test_substruct_highlight(driver: CustomDriver, grid, substruct_highlight, expected):
doc = get_doc(
grid, {"n_items_per_page": 5, "substruct_highlight": substruct_highlight}
)
driver.get(doc)
driver.wait_for_img_load()
driver.substructure_query("CC(I)C")
hash_ = driver.get_svg_hash()
assert str(hash_) == expected
def test_substruct_clear_removes_highlight(driver: CustomDriver, grid):
doc = get_doc(
grid,
{
"n_items_per_page": 5,
"substruct_highlight": True,
},
)
driver.get(doc)
driver.wait_for_img_load()
driver.substructure_query("C")
hash_hl = driver.get_svg_hash()
driver.clear_search()
hash_ = driver.get_svg_hash()
assert hash_ != hash_hl
assert (
str(hash_) == "fffffffffffffe7ffe7ffe7ffe7ffe7ffe7f3e7c8811c183e7e7ffffffffffff"
)
def test_smarts_to_text_search_removes_highlight(driver: CustomDriver, grid):
doc = get_doc(
grid,
{
"n_items_per_page": 5,
"substruct_highlight": True,
},
)
driver.get(doc)
driver.wait_for_img_load()
driver.substructure_query("I")
hash_hl = driver.get_svg_hash()
driver.text_search("odopropane")
hash_ = driver.get_svg_hash()
assert hash_ != hash_hl
assert (
str(hash_) == "fe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffe7ffc3ff99fe3c7c7e3cff3"
)
def test_filter(driver: CustomDriver, grid):
doc = get_doc(
grid,
{
"subset": ["img", "_Name"],
},
)
driver.get(doc)
mask = grid.dataframe["_Name"].str.contains("iodopropane")
filter_code = env.get_template("js/filter.js").render(
grid_id=grid._grid_id, mask=json.dumps(mask.tolist())
)
driver.wait_for_img_load()
driver.execute_script(filter_code)
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-_Name")
assert el.text == "2-iodopropane"
def test_subset_gives_rows_order(driver: CustomDriver, grid):
subset = ["_Name", "ID"]
doc = get_doc(grid, {"subset": subset, "n_items_per_page": 5})
driver.get(doc)
driver.wait_for_img_load()
cell = driver.find_by_css_selector("#mols2grid .m2g-cell")
elements = cell.find_elements(By.CLASS_NAME, "data")
i = 0
for el in elements:
class_list = el.get_attribute("class").split()
name = next(x.replace("data-", "") for x in class_list if x.startswith("data-"))
if name in {"img", "SMILES"}:
continue
assert name == subset[i]
i += 1
# smiles should always be there, and last
assert name == "SMILES"
assert el.value_of_css_property("display") == "none"
def test_colname_with_spaces(driver: CustomDriver, df):
df = df.rename(columns={"SMILES": "Molecule", "_Name": "Molecule name"}).drop(
columns="mol"
)
grid = mols2grid.MolGrid(df, smiles_col="Molecule")
doc = get_doc(
grid,
{
"subset": ["Molecule name", "img"],
"tooltip": ["Molecule"],
"n_items_per_page": 5,
},
)
driver.get(doc)
driver.wait_for_img_load()
el = driver.find_by_css_selector("#mols2grid .m2g-cell .data-Molecule-name")
assert el.text == "3-methylpentane"
def test_custom_header(driver: CustomDriver, grid):
doc = get_doc(
grid,
{
"subset": ["img"],
"custom_header": '<script src="https://unpkg.com/@rdkit/rdkit@2021.9.2/Code/MinimalLib/dist/RDKit_minimal.js"></script>',
"n_items_per_page": 5,
},
)
driver.get(doc)
driver.wait_for_img_load()
val = driver.execute_script("return RDKit.version();")
assert val == "2021.09.2"
def test_static_template(driver: CustomDriver, sdf_path):
df = mols2grid.sdf_to_dataframe(sdf_path)[:15]
grid = mols2grid.MolGrid(df, mol_col="mol", prerender=True, size=(160, 120))
doc = get_doc(
grid,
{
"template": "static",
"subset": ["mols2grid-id", "img"],
"tooltip": ["_Name"],
"sort_by": "_Name",
"tooltip_trigger": "hover",
},
)
driver.get(doc)
el = driver.find_by_css_selector("#mols2grid td.col-0")
assert el.find_element(By.CLASS_NAME, "data-mols2grid-id").text == "8"
tooltip = driver.get_tooltip_content(selector=".m2g-cell-0")
assert (
tooltip
== '<strong>_Name</strong>: <span class="copy-me">1,3,5-trimethylbenzene</span>'
)
if COORDGEN_SUPPORT:
hash_ = driver.get_svg_hash("#mols2grid td .data-img")
diff = hash_ - imagehash.hex_to_hash(
"fffffe7ffe7ffe7ffe7ffe7ffc3ff10ff3cff3cff3cff3cff38fe1078c319e79"
)
assert diff <= 1
def test_default_subset_tooltip(driver: CustomDriver, grid):
doc = get_doc(grid, {"n_items_per_page": 5})
driver.get(doc)
driver.wait_for_img_load()
expected_subset = ["img"]
expected_tooltip = [
x
for x in grid.dataframe.columns.drop(["mol", "mols2grid-id"]).to_list()
if x not in expected_subset
]
cell = driver.find_by_css_selector("#mols2grid .m2g-cell")
data_elements = cell.find_elements(By.CLASS_NAME, "data")
subset = [
c.replace("data-", "").replace("-display", "")
for x in data_elements
for c in x.get_attribute("class").split(" ")
if c.startswith("data-") and not x.get_attribute("style")
]
assert subset == expected_subset
tooltip = [
c.replace("data-", "").replace("-display", "")
for x in data_elements
for c in x.get_attribute("class").split(" ")
if c.startswith("data-") and x.get_attribute("style") == "display: none;"
]
assert tooltip == expected_tooltip
def test_multi_highlight(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
driver.substructure_query("Br")
hash_ = driver.get_svg_hash()
assert (
str(hash_) == "ffffffff8fff87ff003f079f8fdfffcfffefffe1ffe1ffe0ffe1fff1ffffffff"
)
def test_single_highlight(driver: CustomDriver, grid):
doc = get_doc(grid, {"single_highlight": True})
driver.get(doc)
driver.wait_for_img_load()
driver.substructure_query("Br")
hash_ = driver.get_svg_hash()
assert (
str(hash_) == "ffffffff8fff87ff003f001f87cfcfcfffefffe7fff3fff0fff1fff1ffffffff"
)
def test_mol_depiction_aligned_to_query(driver: CustomDriver, html_doc):
driver.get(html_doc)
driver.wait_for_img_load()
driver.substructure_query("CCCBr")
images = list(driver.get_imgs_from_svgs())
for img, expected in zip(
images,
[
"fffffffffcf9f8f8f0708001070f0f8f9f9fffdfffdfff9fff8fff8fffffffff",
"fffffffffffffff9fff9fff9fff9f8f9f8f0d0018003078f8f8fffffffffffff",
],
strict=False,
):
hash_ = imagehash.average_hash(img, hash_size=16)
assert str(hash_) == expected
def test_highlight_with_hydrogens(driver: CustomDriver, df):
mols = []
for mol in df["mol"][25:]:
m = Chem.AddHs(mol)
m.ClearProp("SMILES")
mols.append(m)
grid = mols2grid.MolGrid.from_mols(
mols,
removeHs=False,
size=(160, 120),
)
doc = get_doc(grid, {"substruct_highlight": True, "single_highlight": False})
driver.get(doc)
driver.wait_for_img_load()
driver.substructure_query("Cl")
hash_ = driver.get_svg_hash()
assert (
str(hash_) == "fdfffcfff8fffcfffdc7cdc780cf885bd901fb81f3b3f3bfff9fff1fff9fffbf"
)
def test_callbacks_info(driver: CustomDriver, grid):
doc = get_doc(grid, {"callback": mols2grid.callbacks.info()})
driver.get(doc)
driver.trigger_callback()
modal = driver.find_by_css_selector("#m2g-modal")
assert (
modal.find_element(By.CSS_SELECTOR, ".m2g-modal-header h2").get_attribute(
"innerHTML"
)
== "CCC(C)CC"
)
content = modal.find_element(By.CSS_SELECTOR, ".m2g-modal-body").get_attribute(
"innerHTML"
)
assert "PFEOZHBOMNWTJB-UHFFFAOYSA-N" in content
def test_callbacks_3D(driver: CustomDriver, grid):
doc = get_doc(grid, {"callback": mols2grid.callbacks.show_3d()})
driver.get(doc)
driver.trigger_callback(pause=2.0)
modal = driver.find_by_css_selector("#m2g-modal")
assert (
modal.find_element(By.CSS_SELECTOR, ".m2g-modal-header h2").get_attribute(
"innerHTML"
)
== "CCC(C)CC"
)
content = modal.find_element(By.CSS_SELECTOR, ".m2g-modal-body").get_attribute(
"innerHTML"
)
assert '<div id="molviewer' in content
# only works when testing locally...
assert "<canvas" in content
# cannot test for actual rendering as there's no GL available
assert driver.execute_script("return typeof($3Dmol)") != "undefined"
def test_callbacks_external_link(driver: CustomDriver, grid):
doc = get_doc(grid, {"callback": mols2grid.callbacks.external_link()})
driver.get(doc)
driver.trigger_callback()
# check if new tab was opened
assert len(driver.window_handles) > 1
urls = []
for handle in driver.window_handles[1:]:
driver.switch_to.window(handle)
driver.wait(EC.url_contains("https://"))
url = driver.current_url
if url == "https://leruli.com/search/Q0NDKEMpQ0M=/home":
break
urls.append(url)
else:
raise AssertionError("Corresponding URL not found", urls)
| Python |
2D | cbouy/mols2grid | tests/test_utils.py | .py | 5,656 | 205 | import gzip
from types import SimpleNamespace
from unittest.mock import Mock, patch
import pandas as pd
import pytest
from rdkit import Chem
from rdkit.Chem.rdDepictor import Compute2DCoords
from mols2grid import utils
def test_requires():
@utils.requires("_not_a_module")
def func():
pass
with pytest.raises(
ModuleNotFoundError, match="The module '_not_a_module' is required"
):
func()
@pytest.mark.parametrize(
("subset", "fmt", "style", "transform", "exp"),
[
(
["SMILES", "ID"],
"<strong>{key}</strong>: {value}",
{},
{},
'<strong>SMILES</strong>: <span class="copy-me">CCO</span><br>'
'<strong>ID</strong>: <span class="copy-me">0</span>',
),
(["ID"], "foo-{value}", {}, {}, 'foo-<span class="copy-me">0</span>'),
(
["ID"],
"{value}",
{"ID": lambda x: "color: red"}, # noqa: ARG005
{},
'<span class="copy-me" style="color: red">0</span>',
),
(
["Activity"],
"{value}",
{},
{"Activity": lambda x: f"{x:.2f}"},
'<span class="copy-me">42.01</span>',
),
(
["Activity"],
"{key}: {value}",
{"Activity": lambda x: "color: red" if x > 40 else ""},
{"Activity": lambda x: f"{x:.2f}"},
'Activity: <span class="copy-me" style="color: red">42.01</span>',
),
],
)
def test_tooltip_formatter(subset, fmt, style, transform, exp):
row = pd.Series(
{
"ID": 0,
"SMILES": "CCO",
"Activity": 42.012345,
}
)
tooltip = utils.tooltip_formatter(row, subset, fmt, style, transform)
assert tooltip == exp
@pytest.mark.parametrize(
("smi", "exp"), [("CCO", "CCO"), ("blabla", None), (None, None)]
)
def test_mol_to_smiles(smi, exp):
mol = Chem.MolFromSmiles(smi) if smi else smi
assert utils.mol_to_smiles(mol) == exp
def test_mol_to_record():
mol = Chem.MolFromSmiles("CCO")
props = {
"NAME": "ethanol",
"foo": 42,
"_bar": 42.01,
"__baz": 0,
}
for prop, value in props.items():
if isinstance(value, int):
mol.SetIntProp(prop, value)
elif isinstance(value, float):
mol.SetDoubleProp(prop, value)
else:
mol.SetProp(prop, value)
new = utils.mol_to_record(mol)
assert "mol" in new
new.pop("mol")
assert new == props
def test_mol_to_record_none():
new = utils.mol_to_record(None)
assert new == {}
def test_mol_to_record_overwrite_smiles():
mol = Chem.MolFromSmiles("CCO")
mol.SetProp("SMILES", "foo")
new = utils.mol_to_record(mol)
assert new["SMILES"] == "foo"
def test_mol_to_record_custom_mol_col():
mol = Chem.MolFromSmiles("CCO")
new = utils.mol_to_record(mol, mol_col="foo")
assert new["foo"] is mol
@pytest.mark.parametrize("sdf_source", ["sdf_path", "sdf_file"])
def test_sdf_to_dataframe(sdf_source, request):
sdf = request.getfixturevalue(sdf_source)
df = utils.sdf_to_dataframe(sdf)
exp = {
"ID": 5,
"NAME": "3-methylpentane",
"SMILES": "CCC(C)CC",
"SOL": -3.68,
"SOL_classification": "(A) low",
"_MolFileComments": "",
"_MolFileInfo": "SciTegic05121109362D",
"_MolFileChiralFlag": 0,
"_Name": "3-methylpentane",
}
new = df.iloc[0].drop(["mol"]).to_dict()
new["_MolFileInfo"] = new["_MolFileInfo"].strip()
assert new == exp
def test_sdf_to_dataframe_custom_mol_col(sdf_path):
df = utils.sdf_to_dataframe(sdf_path, mol_col="foo")
assert "mol" not in df.columns
assert "foo" in df.columns
def test_sdf_to_df_gz(sdf_path, tmp_path):
tmp_file = tmp_path / "mols.sdf.gz"
with open(tmp_file, "wb") as tf:
gz = gzip.compress(sdf_path.read_bytes(), compresslevel=1)
tf.write(gz)
tf.flush()
df = utils.sdf_to_dataframe(tmp_file).drop(columns=["mol"])
ref = utils.sdf_to_dataframe(sdf_path).drop(columns=["mol"])
assert (df == ref).to_numpy().all()
def test_remove_coordinates():
mol = Chem.MolFromSmiles("CCO")
Compute2DCoords(mol)
mol.GetConformer()
new = utils.remove_coordinates(mol)
assert new is mol
with pytest.raises(ValueError, match="Bad Conformer Id"):
new.GetConformer()
@pytest.mark.parametrize(
("string", "expected"),
[
("Mol", "Mol"),
("mol name", "mol-name"),
("mol name", "mol-name"),
("mol-name", "mol-name"),
("mol- name", "mol--name"),
("mol\tname", "mol-name"),
("mol\nname", "mol-name"),
("mol \t\n name", "mol-name"),
],
)
def test_slugify(string, expected):
assert utils.slugify(string) == expected
@pytest.mark.parametrize("value", [1, 2])
def test_callback_handler(value):
def callback(x):
return x + 1
mock = Mock(side_effect=callback)
event = SimpleNamespace(new=str(value))
utils.callback_handler(mock, event)
mock.assert_called_once_with(value)
def test_is_running_within_streamlit():
assert utils.is_running_within_streamlit() is False
with patch(
"mols2grid.utils._get_streamlit_script_run_ctx",
create=True,
new=object,
):
assert utils.is_running_within_streamlit() is True
with patch(
"mols2grid.utils._get_streamlit_script_run_ctx", create=True, new=lambda: None
):
assert utils.is_running_within_streamlit() is False
| Python |
2D | cbouy/mols2grid | tests/conftest.py | .py | 890 | 46 | from pathlib import Path
import pytest
from mols2grid import MolGrid, datafiles, sdf_to_dataframe
@pytest.fixture(scope="module")
def sdf_path():
return Path(datafiles.SOLUBILITY_SDF)
@pytest.fixture(scope="module")
def sdf_file(sdf_path):
return str(sdf_path)
@pytest.fixture(scope="module")
def smiles_records():
return [{"SMILES": "C" * i, "ID": i} for i in range(1, 5)]
@pytest.fixture(scope="module")
def df(sdf_path):
return sdf_to_dataframe(sdf_path).head(30)
@pytest.fixture(scope="module")
def small_df(df):
return df.head(5)
@pytest.fixture(scope="module")
def grid_prerendered(df):
return MolGrid(df, mol_col="mol", prerender=True)
@pytest.fixture(scope="module")
def grid(df):
return MolGrid(df, mol_col="mol", size=(160, 120))
@pytest.fixture(scope="module")
def mols(small_df): # noqa: FURB118, RUF100
return small_df["mol"]
| Python |
2D | thesourcerer8/OpenSourceTCAD | install-ubuntu.sh | .sh | 220 | 17 | echo Installation routine for Ubuntu:
sudo apt-get install docker.io
cd Charon
sudo bash build.sh
cd ..
cd Genius
sudo bash build.sh
cd ..
cd DevSim
sudo bash build.sh
cd ..
echo "All Docker images have been built."
| Shell |
2D | thesourcerer8/OpenSourceTCAD | DevSim/DockerUsage.md | .md | 1,028 | 34 | # DevSim TCAD Docker Usage
DevSim-TCAD uses a number of old versions of libraries, this makes it increasingly difficult to compile and run on the latest Linux distributions. To work around this a Docker image of an older Ubuntu 20.04 distribution is used.
## Installation
### Docker Installation
Search for instructions on how to install Docker on your distribution.
### Container Installation
To install the Docker container navigate to the folder containing this document and execute the following command:
./build.sh
The software will be automatically downloaded and installed - this will take some time.
## Usage
To interact with the installed container execute the following command:
./bash.sh
Which will allow you to navigate and execute software within the container.
To move files to and from the container use the Docker command (from a host terminal):
docker cp INST_NAME:/container/file/location /host/file/location
Use the ``docker ps`` to file the instance name of running containers.
| Markdown |
2D | thesourcerer8/OpenSourceTCAD | DevSim/build.sh | .sh | 30 | 2 | docker build -t devsim-tcad .
| Shell |
2D | thesourcerer8/OpenSourceTCAD | DevSim/bash.sh | .sh | 37 | 2 | docker run -it devsim-tcad /bin/bash
| Shell |
2D | thesourcerer8/OpenSourceTCAD | Genius/DockerUsage.md | .md | 1,028 | 34 | # Genius TCAD Docker Usage
Genius-TCAD uses a number of old versions of libraries, this makes it increasingly difficult to compile and run on the latest Linux distributions. To work around this a Docker image of an older Ubuntu 14.04 distribution is used.
## Installation
### Docker Installation
Search for instructions on how to install Docker on your distribution.
### Container Installation
To install the Docker container navigate to the folder containing this document and execute the following command:
./build.sh
The software will be automatically downloaded and installed - this will take some time.
## Usage
To interact with the installed container execute the following command:
./bash.sh
Which will allow you to navigate and execute software within the container.
To move files to and from the container use the Docker command (from a host terminal):
docker cp INST_NAME:/container/file/location /host/file/location
Use the ``docker ps`` to file the instance name of running containers.
| Markdown |
2D | thesourcerer8/OpenSourceTCAD | Genius/build.sh | .sh | 30 | 2 | docker build -t genius-tcad .
| Shell |
2D | thesourcerer8/OpenSourceTCAD | Genius/bash.sh | .sh | 160 | 7 | xhost +local:
docker run -it \
--env="DISPLAY" \
--env="QT_X11_NO_MITSHM=1" \
--volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
genius-tcad /bin/bash
| Shell |
2D | thesourcerer8/OpenSourceTCAD | Charon/DockerUsage.md | .md | 1,028 | 34 | # Charon TCAD Docker Usage
Charon-TCAD uses a number of old versions of libraries, this makes it increasingly difficult to compile and run on the latest Linux distributions. To work around this a Docker image of an older Ubuntu 18.04 distribution is used.
## Installation
### Docker Installation
Search for instructions on how to install Docker on your distribution.
### Container Installation
To install the Docker container navigate to the folder containing this document and execute the following command:
./build.sh
The software will be automatically downloaded and installed - this will take some time.
## Usage
To interact with the installed container execute the following command:
./bash.sh
Which will allow you to navigate and execute software within the container.
To move files to and from the container use the Docker command (from a host terminal):
docker cp INST_NAME:/container/file/location /host/file/location
Use the ``docker ps`` to file the instance name of running containers.
| Markdown |
2D | thesourcerer8/OpenSourceTCAD | Charon/build.sh | .sh | 30 | 2 | docker build -t charon-tcad .
| Shell |
2D | thesourcerer8/OpenSourceTCAD | Charon/bash.sh | .sh | 37 | 2 | docker run -it charon-tcad /bin/bash
| Shell |
2D | thesourcerer8/OpenSourceTCAD | Vienna/DockerUsage.md | .md | 1,025 | 34 | # Vienna TCAD Docker Usage
Vienna-* uses a number of old versions of libraries, this makes it increasingly difficult to compile and run on the latest Linux distributions. To work around this a Docker image of an older Ubuntu 18.04 distribution is used.
## Installation
### Docker Installation
Search for instructions on how to install Docker on your distribution.
### Container Installation
To install the Docker container navigate to the folder containing this document and execute the following command:
./build.sh
The software will be automatically downloaded and installed - this will take some time.
## Usage
To interact with the installed container execute the following command:
./bash.sh
Which will allow you to navigate and execute software within the container.
To move files to and from the container use the Docker command (from a host terminal):
docker cp INST_NAME:/container/file/location /host/file/location
Use the ``docker ps`` to file the instance name of running containers.
| Markdown |
2D | thesourcerer8/OpenSourceTCAD | Vienna/build.sh | .sh | 30 | 2 | docker build -t vienna-tcad .
| Shell |
2D | thesourcerer8/OpenSourceTCAD | Vienna/bash.sh | .sh | 37 | 2 | docker run -it vienna-tcad /bin/bash
| Shell |
2D | brownjm/gpe | spectral.py | .py | 3,694 | 137 | """Spectral method for evolving GPE for BEC's"""
from numpy import exp, pi, arange, meshgrid, sqrt, linspace
from numpy.fft import fft2, ifft2, fftshift
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
matplotlib.rcParams['figure.dpi'] = 200
from timestep2d import QHO
class Simulation:
"""Simulation to step wavefunction forward in time from the given parameters
xmax : maximum extent of boundary
N : number of spatial points
init : initial wavefunction
nonlinearity : factor in front of |psi^2| term
"""
def __init__(self, parameters):
self.parameters = parameters
# set up spatial dimensions
xmax = parameters['xmax']
self.xmax = xmax
N = parameters['N']
v = linspace(-xmax, xmax, N)
self.dx = v[1] - v[0]
self.x, self.y = meshgrid(v, v)
# spectral space
kmax = 2*pi / self.dx
dk = kmax / N
self.k = fftshift((arange(N)-N/2) * dk)
kx, ky = meshgrid(self.k, self.k)
# time
self.steps = 0
self.time = 0
self.dt = self.dx**2 / 4
# wavefunction
init_func = parameters['initial']
self.wf = init_func(self.x, self.y, 0)
self.wf /= sqrt(self.norm().sum() * self.dx**2) # normalize
# Hamiltonian operators
self.loss = 1 - 1j*parameters['loss']
self.T = exp(-1j * self.loss * (kx**2 + ky**2) * self.dt / 2)
self.V = exp(-1j * self.loss * (self.x**2 + self.y**2) * self.dt / 2)
self.eta = parameters['nonlinearity']
def evolve(self, time):
"""Evolve the wavefunction to the given time in the future"""
steps = int(time / self.dt)
if steps == 0:
steps = 1 # guarantee at least 1 step
for _ in range(steps):
#self.linear_step()
self.nonlinear_step()
if self.loss:
N = self.norm().sum()*self.dx**2
self.wf /= N
self.update_time(steps)
def linear_step(self):
"""Make one linear step dt forward in time"""
# kinetic
self.wf[:] = fft2(ifft2(self.wf) * self.T)
# potential
self.wf *= self.V
def nonlinear_step(self):
"""Make one nonlinear step dt forward in time"""
# linear step
self.linear_step()
# nonlinear
self.wf *= exp(-1j * self.loss * self.eta * abs(self.wf)**2 * self.dt)
def update_time(self, steps):
"""Increment time by steps taken"""
self.steps += steps
self.time = self.steps * self.dt
def norm(self):
return abs(self.wf)**2
def show(self):
"""Show the current norm of the wavefunction"""
fig, ax = plt.subplots()
ax.imshow(self.norm(), cmap=plt.cm.hot)
plt.show()
def animate(simulation, time, interval=100):
"""Display an animation of the simulation"""
fig, ax = plt.subplots()
L = simulation.xmax
norm = ax.imshow(simulation.norm(), extent=(-L, L, -L, L), cmap=plt.cm.hot)
def update(i):
simulation.evolve(time / interval)
N = simulation.norm()
norm.set_data(N)
ax.set_title('T = {:3.2f}, N = {:1.6f}'.format(simulation.time, N.sum()*simulation.dx**2))
anim = animation.FuncAnimation(fig, update, interval=10)
plt.show()
if __name__ == '__main__':
params = {'N': 800,
'xmax': 7,
'nonlinearity': 4,
'initial': QHO(n=0, xshift=0), # GaussianWavepacket(1, 5, -4),
'loss': 0.0,
}
sim = Simulation(params)
#animate(sim, 1)
#sim.evolve()
#sim.wf.dump('wf')
| Python |
2D | brownjm/gpe | timestep2d.py | .py | 10,691 | 374 | """Modified Visscher's method for Gross-Pitaevskii equation for BEC's
Original paper:
A fast explicit algorithm for the time-dependent Schroedinger equation
P. B. Visscher
Computers in Physics 5, 596 (1991)
doi: 10.1063/1.168415
"""
from math import factorial
from numpy import pi, sqrt, exp, linspace, meshgrid, zeros, empty, random, cosh, arctan2
import numpy
from scipy.ndimage.filters import laplace
from scipy.special import hermite
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
# higher resolution plots
matplotlib.rcParams['figure.dpi'] = 200
class Simulation:
"""Simulator steps a wavefunction forward in time from the given parameters
xmax : maximum extent of boundary
N : number of spatial points
BC : boundary conditions, e.g. reflect, wrap
init : initial wavefunction
potential : potential name V(x), e.g. linear, harmonic
nonlinearity : factor in front of |psi^2| term
"""
def __init__(self, parameters):
self.parameters = parameters
# set up spatial dimensions
xmax = parameters['xmax']
self.xmax = xmax
N = parameters['N']
self.v = linspace(-xmax, xmax, N)
self.dx = self.v[1] - self.v[0]
print("dx = {}".format(self.dx))
self.x, self.y = meshgrid(self.v, -self.v)
# time
self.steps = 0
self.time = 0
self.dt = self.dx**2 / 4 # good choice for stability
print("dt = {}".format(self.dt))
# wavefunction
init_func = parameters['initial']
self.wf = Wavefunction(init_func, self.x, self.y, self.dt)
# Hamiltonian operators
BC = parameters['BC']
self.T = Kinetic(self.dx, BC)
self.V = Potential(parameters['potential'])
# nonlinearity
self.eta = parameters['nonlinearity']
# observers
self.observers = []
def reset(self):
"""Reinitializes wavefunction and sets time = 0"""
self.steps = 0
self.time = 0
init_func = self.parameters['initial']
self.wf = Wavefunction(init_func, self.x, self.y, self.dt)
def add_observer(self, observer):
"""Add an observer that will be given the wavefunction after each call of evolve"""
self.observers.append(observer)
def evolve(self, time):
"""Evolve the wavefunction to the given time in the future"""
steps = int(time / self.dt)
#print("n = {}".format(steps))
if steps == 0:
steps = 1 # guarantee at least 1 step
for _ in range(steps):
#self.linear_step()
self.nonlinear_step()
self.update_time(steps)
for ob in self.observers:
ob.notify(self.time, self.wf)
def linear_step(self):
"""Make one linear step dt forward in time"""
# shorten the names of variables
x = self.x
y = self.y
t = self.time
dt = self.dt
real = self.wf.real
imag = self.wf.imag
prev = self.wf.prev
T = self.T
V = self.V
# update wavefunctions
real += dt * (T.fast(imag) + V(x, y, t) * imag)
prev[:] = imag[:] # need to explicitly copy values, assignment doesn't work
imag -= dt * (T.fast(real) + V(x, y, t+dt/2) * real)
def nonlinear_step(self):
"""Make one nonlinear step dt forward in time"""
# shorten the names of variables
x = self.x
y = self.y
t = self.time
dt = self.dt
eta = self.eta
real = self.wf.real
imag = self.wf.imag
prev = self.wf.prev
T = self.T
V = self.V
# update wavefunctions
real[:] = (real + dt*(T.fast(imag) + V(x, y, t)*imag + eta*imag*imag*imag)) / (1 - dt*eta*real*imag)
prev[:] = imag # need to explicitly copy values, assignment doesn't work
imag[:] = (imag - dt*(T.fast(real) + V(x, y, t+dt/2)*real + eta*real*real*real)) / (1 + dt*eta*real*imag)
def update_time(self, steps):
"""Increment time by steps taken"""
self.steps += steps
self.time = self.steps * self.dt
def show(self):
L = self.xmax
plt.imshow(self.wf.norm(), plt.cm.hot, extent=(-L, L, -L, L))
plt.colorbar()
plt.show()
class Kinetic:
"""Kinetic energy term in Hamiltonian"""
def __init__(self, dx, BC='reflect'):
self.coef = -0.5 / dx**2
self.BC = BC
def __call__(self, wf):
return self.coef * laplace(wf, mode=self.BC)
def fast(self, wf):
new = empty(wf.shape)
new[1:-1, 1:-1] = self.coef * (wf[:-2, 1:-1] + wf[2:, 1:-1]
+ wf[1:-1, :-2] + wf[1:-1, 2:]
- 4*wf[1:-1, 1:-1])
new[:,0] = new[:,-1] = new[0,:] = new[-1,:] = 0.0
return new
class Potential(object):
"""Potential V in Hamiltonian"""
def __init__(self, potential_name):
self.func = self.__getattribute__(potential_name)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def free(self, x, y, t):
return zeros(x.shape)
def linear(self, x, y, t):
return -x
def harmonic(self, x, y, t):
return 0.5*(x*x + y*y)
def barrier(self, x, y, t):
potential = zeros(x.shape, dtype=float)
inside = abs(x) < 0.1
potential[inside] = 10
potential[~inside] = 0
return potential
def laser_swipe(self, x, y, t):
harmonic = 0.5 * (x*x + y*y)
w = 0.1
v = 20
xs = x - v*t + 5
laser = 100*exp(-(xs*xs + y*y) / w**2)
return harmonic + laser
class Wavefunction:
"""Complex valued wavefunction where real and imaginary values live at different times"""
def __init__(self, init_func, x, y, dt):
# real R(x,0) and imaginary I(x,dt/2) part of wavefunction
self.real = init_func(x, y, 0).real
self.imag = init_func(x, y, dt/2).imag
# stores previous imaginary part
self.prev = init_func(x, y, -dt/2).imag
# normalize wavefunction
dx = x[0,1] - x[0,0]
N = sqrt(abs(self.norm()).sum() * dx**2)
self.real /= N
self.imag /= N
self.prev /= N
def norm(self):
"""|psi|^2 at integer t/dt times"""
return self.real**2 + self.imag*self.prev
class GaussianWavepacket:
"""Gaussian wavepacket"""
def __init__(self, width, k, xshift=0, yshift=0):
self.w = width
self.k = k
self.xshift = xshift
self.yshift = yshift
def __call__(self, x, y, t):
xs = x - self.xshift
ys = y - self.yshift
k = self.k
w = self.w
wf = exp(-(xs**2 + ys**2) / w**2 + 1j*(k*x - k**2 * t / 2))
return wf
class Sech:
"""Sech solution for harmonic trap"""
def __init__(self, mu=-0.5):
self.mu = mu
def __call__(self, x, y, t):
return 1/sqrt(2) * exp(-1j*self.mu*t) / cosh(x*x + y*y)
class QHO:
"""Quantum harmonic oscillator wavefunctions"""
def __init__(self, n, xshift=0, yshift=0):
self.n = n
self.xshift = xshift
self.yshift = yshift
self.E = n + 0.5
self.coef = 1 / sqrt(2**n * factorial(n)) * (1 / pi)**(1/4)
self.hermite = hermite(n)
def __call__(self, x, y, t):
xs = x - self.xshift
ys = y - self.yshift
return self.coef * exp(-(xs**2 + ys**2) / 2 - 1j*self.E*t) * self.hermite(x) * self.hermite(y)
class Noise:
"""Random floating point noise that falls between 0 and 1"""
def __call__(self, x, y, t):
return random.ranf(x.shape) + 1j*random.ranf(x.shape)
class File:
"""Load a wavefunction from file"""
def __init__(self, filename):
self.filename = filename
self.wf = numpy.load(filename)
def __call__(self, x, y, t):
return self.wf
class Vortex:
"""Load a wavefunction from file and add vortex"""
def __init__(self, filename):
self.filename = filename
self.wf = numpy.load(filename)
def __call__(self, x, y, t):
a = 20
shift = 0.3
xs = x - shift
rho = sqrt(xs*xs + y*y)
f = (rho / a) / sqrt(1 + (rho/a)**2)
theta = arctan2(y, xs)
return self.wf * f * exp(1j*theta)
class Observer:
def notify(self, time, wf):
raise NotImplementedError("Overload this method in the derived observer")
class WavefunctionObserver(Observer):
def __init__(self):
self.time = []
self.wavefunction = []
def notify(self, time, wf):
self.time.append(time)
self.wavefunction.append(wf)
def animate(simulation, time, interval=100):
"""Display an animation of the simulation"""
wf = simulation.wf
fig, ax = plt.subplots()
L = simulation.xmax
norm = ax.imshow(wf.norm(), extent=(-L, L, -L, L), cmap=plt.cm.hot)
#V = ax.imshow(simulation.V(simulation.x, simulation.y, simulation.time))
def update(i):
simulation.evolve(time / interval)
N = wf.norm()
norm.set_data(N)
ax.set_title('T = {:3.2f}, N = {:1.6f}'.format(simulation.time, N.sum() * simulation.dx**2))
# V.set_data(simulation.V(simulation.x, simulation.y, simulation.time))
# ax.set_title('T = {:3.2f}'.format(simulation.time))
anim = animation.FuncAnimation(fig, update, interval=10)
plt.show()
def make_movie(simulation, time):
FFMpegWriter = animation.writers['ffmpeg']
metadata = dict(title='GPE 2D', artist='matplotlib',
comment="Adapted Visscher's taggered time step method")
writer = FFMpegWriter(fps=15, metadata=metadata)
fig, ax = plt.subplots()
wf = simulation.wf
L = sim.xmax
norm = ax.imshow(wf.norm(), extent=(-L, L, -L, L), cmap=plt.cm.hot)
steps = int(time/sim.dt)
with writer.saving(fig, "test.mp4", 100):
for _ in range(int(steps/100)):
simulation.evolve(steps*sim.dt/100)
N = wf.norm()
norm.set_data(N)
writer.grab_frame()
if __name__ == '__main__':
params = {'N': 128,
'xmax': 7,
'BC': 'reflect',
'nonlinearity': 4,
'initial': Vortex('wf.dat'),
'potential': 'harmonic',
}
sim = Simulation(params)
#wfob = WavefunctionObserver()
#sim.add_observer(wfob)
#sim.evolve(0.1)
#sim.show()
animate(sim, 5)
#make_movie(sim, 40)
| Python |
2D | brownjm/gpe | timestep.py | .py | 7,844 | 287 | """Modified Visscher's method for Gross-Pitaevskii equation for BEC's
Original paper:
A fast explicit algorithm for the time-dependent Schroedinger equation
P. B. Visscher
Computers in Physics 5, 596 (1991)
doi: 10.1063/1.168415
"""
from math import factorial
from numpy import pi, sqrt, exp, linspace, zeros, empty, cosh
from scipy.ndimage.filters import laplace
from scipy.special import hermite
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import animation
# higher resolution plots
matplotlib.rcParams['figure.dpi'] = 200
class Simulation:
"""Simulator steps a wavefunction forward in time from the given parameters
xmax : maximum extent of boundary
N : number of spatial points
BC : boundary conditions, e.g. reflect, wrap
init : initial wavefunction
potential : potential name V(x), e.g. linear, harmonic
nonlinearity : factor in front of |psi^2| term
"""
def __init__(self, parameters):
self.parameters = parameters
# set up spatial dimensions
xmax = parameters['xmax']
N = parameters['N']
self.x = linspace(-xmax, xmax, N)
self.dx = self.x[1] - self.x[0]
# time
self.steps = 0
self.time = 0
self.dt = self.dx**2 / 4 # good choice for stability
# wavefunction
init_func = parameters['initial']
self.wf = Wavefunction(init_func, self.x, self.dt)
# Hamiltonian operators
BC = parameters['BC']
self.T = Kinetic(self.dx, BC)
self.V = Potential(parameters['potential'])
# nonlinearity
self.eta = parameters['nonlinearity']
# observers
self.observers = []
def reset(self):
"""Reinitializes wavefunction and sets time = 0"""
self.steps = 0
self.time = 0
init_func = self.parameters['initial']
self.wf = Wavefunction(init_func, self.x, self.dt)
def add_observer(self, observer):
"""Add an observer that will be given the wavefunction after each call of evolve"""
self.observers.append(observer)
def evolve(self, time):
"""Evolve the wavefunction to the given time in the future"""
steps = int(time / self.dt)
if steps == 0:
steps = 1 # guarantee at least 1 step
for _ in range(steps):
#self.linear_step()
self.nonlinear_step()
self.update_time(steps)
for ob in self.observers:
ob.notify(self.wf)
def linear_step(self):
"""Make one linear step dt forward in time"""
# shorten the names of variables
x = self.x
dt = self.dt
real = self.wf.real
imag = self.wf.imag
prev = self.wf.prev
T = self.T
V = self.V
# update wavefunctions
real += dt * (T.fast(imag) + V(x) * imag)
prev[:] = imag # need to explicitly copy values, assignment doesn't work
imag -= dt * (T.fast(real) + V(x) * real)
def nonlinear_step(self):
"""Make one nonlinear step dt forward in time"""
# shorten the names of variables
x = self.x
dt = self.dt
eta = self.eta
real = self.wf.real
imag = self.wf.imag
prev = self.wf.prev
T = self.T
V = self.V
# update wavefunctions
real[:] = (real + dt*(T.fast(imag) + V(x)*imag + eta*imag*imag*imag)) / (1 - dt*eta*real*imag)
prev[:] = imag # need to explicitly copy values, assignment doesn't work
imag[:] = (imag - dt*(T.fast(real) + V(x)*real + eta*real*real*real)) / (1 + dt*eta*real*imag)
def update_time(self, steps):
"""Increment time by one step in dt"""
self.steps += steps
self.time = self.steps * self.dt
def plot(self):
plt.plot(self.wf.real, label='real')
plt.plot(self.wf.real, label='imag')
plt.plot(self.wf.norm(), label='norm')
plt.legend()
plt.show()
class Kinetic:
"""Kinetic energy term in Hamiltonian"""
def __init__(self, dx, BC='reflect'):
self.coef = -0.5 / dx**2
self.BC = BC
def __call__(self, wf):
return self.coef * laplace(wf, mode=self.BC)
def fast(self, wf):
new = empty(wf.shape)
new[1:-1] = self.coef * (wf[:-2] + wf[2:] - 2*wf[1:-1])
new[0] = new[-1] = 0.0
return new
class Potential(object):
"""Potential V in Hamiltonian"""
def __init__(self, potential_name):
self.func = self.__getattribute__(potential_name)
self.past = None
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def free(self, x):
return zeros(x.shape)
def linear(self, x):
return -x
def harmonic(self, x):
return 0.5*x**2
def barrier(self, x):
potential = zeros(x.shape, dtype=float)
inside = abs(x) < 3
potential[inside] = -100
potential[~inside] = 0
return potential
class Wavefunction:
"""Complex valued wavefunction where real and imaginary values live at different times"""
def __init__(self, init_func, x, dt):
# real R(x,0) and imaginary I(x,dt/2) part of wavefunction
self.real = init_func(x, 0).real
self.imag = init_func(x, dt/2).imag
# stores previous imaginary part
self.prev = init_func(x, -dt/2).imag
# normalize wavefunction
dx = x[1] - x[0]
N = sqrt(sum(abs(self.norm()))*dx)
self.real /= N
self.imag /= N
self.prev /= N
def norm(self):
"""|psi|^2 at integer t/dt times"""
return self.real**2 + self.imag*self.prev
class Sech:
"""Sech(x) solution"""
def __init__(self, mu=-0.5):
self.mu = mu
def __call__(self, x, t):
return 1/sqrt(2) * exp(-1j*self.mu*t) / cosh(x)
class GaussianWavepacket:
"""Gaussian wavepacket"""
def __init__(self, width, k, shift=0):
self.w = width
self.k = k
self.shift = shift
def __call__(self, x, t):
xs = x - self.shift
k = self.k
w = self.w
wf = exp(-xs**2 / w**2 + 1j*(k*x - k**2 * t / 2))
return wf
class QHO:
"""Quantum harmonic oscillator wavefunctions"""
def __init__(self, n, shift=0):
self.n = n
self.shift = shift
self.E = n + 0.5
self.coef = 1 / sqrt(2**n * factorial(n)) * (1 / pi)**(1/4)
self.hermite = hermite(n)
def __call__(self, x, t):
xs = x - self.shift
return self.coef * exp(-xs**2 / 2 - 1j*self.E*t) * self.hermite(x)
def animate(simulation, time, interval=100):
"""Display an animation of the simulation"""
x = simulation.x
V = simulation.V
wf = simulation.wf
fig, ax = plt.subplots()
# plot scaled potential
potential = V(x)
if max(abs(potential)) != 0.0:
potential /= max(abs(potential))
ax.plot(x, potential, 'k')
# real, = ax.plot(x, wf.real, label='real')
# imag, = ax.plot(x, wf.imag, label='imag')
norm, = ax.plot(x, wf.norm(), label='norm')
def update(i):
simulation.evolve(time / interval)
# real.set_ydata(wf.real)
# imag.set_ydata(wf.imag)
N = wf.norm()
norm.set_ydata(N)
ax.set_title('T = {:3.2f}, N = {:1.6f}'.format(sim.time, sum(N)*sim.dx))
anim = animation.FuncAnimation(fig, update, interval=10)
plt.show()
if __name__ == '__main__':
params = {'N': 2001,
'xmax': 25,
'BC': 'reflect',
'nonlinearity': 0,
'initial': GaussianWavepacket(1, 5, -4),
'potential': 'barrier',
}
sim = Simulation(params)
animate(sim, 1)
| Python |
2D | ma-compbio/SNIPER | sniper_train.py | .py | 438 | 23 | """
Main training file
Calls helper functions from utilities
"""
import numpy as np
import sys
from scipy.io import loadmat
from utilities.input import get_params
from pipeline.training import train_with_hic, train_with_mat
if __name__ == '__main__':
params = get_params()
rowMap = params['cropMap']['rowMap']
colMap = params['cropMap']['colMap']
if not params['usemat']:
train_with_hic(params)
else:
train_with_mat(params) | Python |
2D | ma-compbio/SNIPER | sniper.py | .py | 378 | 20 | """
Application file
Calls helper functions from utilities
"""
import numpy as np
import sys
from scipy.io import loadmat
from utilities.input import get_application_params
from pipeline.application import apply_on_hic, apply_on_mat
if __name__ == '__main__':
params = get_application_params()
if not params['usemat']:
apply_on_hic(params)
else:
apply_on_mat(params) | Python |
2D | ma-compbio/SNIPER | utilities/interchromosome_matrix.py | .py | 1,608 | 69 | import os
import numpy as np
import pandas as pd
import pickle as pkl
from scipy.sparse import coo_matrix, hstack, vstack
from scipy.io import savemat
from utilities.data_processing import chrom_sizes
def construct(hic_dir='.',prefix='hic',hic_res=100000,sizes_file='data/hg19.chrom.sizes',verbose=False):
fullSM = None
chromosome_lengths = chrom_sizes(sizes_file)
"""Span chrms 1, 3, 5, 7... 21"""
for i in range(1,23,2):
# sparse matrix
rowSM = None
"""Interactions with even chromosomes"""
for j in range(2,23,2):
if verbose:
print('Compiling interactions between chr{0} and chr{1}...'.format(i,j))
filepath = os.path.join(hic_dir, '{2}_chrm{0}_chrm{1}.txt'.format(i,j,prefix))
# file = open(filepath,'r')
txt_data = pd.read_csv(filepath, sep='\t', header=None).values
nrow = int(chromosome_lengths['chr' + str(i)] / hic_res + 1)
ncol = int(chromosome_lengths['chr' + str(j)] / hic_res + 1)
SM = np.zeros((nrow,ncol))
rows = txt_data[:,0] / hic_res
cols = txt_data[:,1] / hic_res
if i > j:
rows = txt_data[:,1] / hic_res
cols = txt_data[:,0] / hic_res
data = txt_data[:,2]
rows = rows.astype(int)
cols = cols.astype(int)
try:
SM[rows,cols]=data
except IndexError:
temp = rows.copy()
rows = cols
cols = temp
del temp
SM[rows,cols] = data
if rowSM is None:
rowSM = SM
else:
rowSM = np.hstack((rowSM, SM))
if fullSM is None:
fullSM = rowSM
else:
fullSM = vstack([fullSM, rowSM])
return fullSM.toarray()
| Python |
2D | ma-compbio/SNIPER | utilities/input.py | .py | 3,474 | 138 | import sys
from scipy.io import loadmat
def get_params():
# set defaults
if len(sys.argv) < 4:
raise Exception('Must specify input and target .hic or .mat files and a label file')
params = {
'usemat' : False,
'input_file': sys.argv[1],
'target_file': sys.argv[2],
'label_file': sys.argv[3],
}
if params['input_file'].endswith('.mat'):
params['usemat'] = True
"""
Specify a path to juicer_tools.jar
"""
if '-jt' in sys.argv:
jtIdx = sys.argv.index('-jt') + 1
params['juicer_tools_path'] = sys.argv[jtIdx]
"""
Check if using custom crop folder including cropMap and cropIndices.
Recommended to set this if not running SNIPER from its root directory.
"""
if '-c' in sys.argv:
cIdx = sys.argv.index('-c') + 1
try:
params['cropMap'] = loadmat(os.path.join(sys.argv[cIdx],'cropMap.mat'))
params['cropIndices'] = loadmat(os.path.join(sys.argv[cIdx],'cropIndices.mat'))
except:
raise Exception('No custom crop folder specified')
sys.exit()
else:
params['cropMap'] = loadmat('crop_map/cropMap.mat')
params['cropIndices'] = loadmat('crop_map/cropIndices.mat')
"""
Set dump location for hic text outputs, which are erased after converting
to a matrix file if -ar is set.
Strongly recommended if SNIPER is installed on a solid state drive.
"""
params['dump_dir'] = '.'
if '-dd' in sys.argv:
ddIdx = sys.argv.index('-dd') + 1
try:
params['dump_dir'] = sys.argv[ddIdx]
except:
raise Exception('No dump directory specified')
sys.exit()
"""
Set -sm to save matrix to .mat file to a specified path
"""
params['save_matrix'] = False
if '-sm' in sys.argv:
params['save_matrix'] = True
"""Set -ar to autoremove hic text files"""
params['autoremove'] = False
if '-ar' in sys.argv:
params['autoremove'] = True
"""Set -ow to overwrite existing hic text files"""
params['overwrite'] = False
if '-ow' in sys.argv:
params['overwrite'] = True
return params
def get_application_params():
params = {
'usemat' : False,
'input_file': sys.argv[1],
'output_path': sys.argv[2],
'odd_encoder': sys.argv[3],
'odd_classifier': sys.argv[4],
'even_encoder': sys.argv[5],
'even_classifier': sys.argv[6],
}
if params['input_file'].endswith('.mat'):
params['usemat'] = True
params['dump_dir'] = '.'
if '-dd' in sys.argv:
ddIdx = sys.argv.index('-dd') + 1
try:
params['dump_dir'] = sys.argv[ddIdx]
except:
raise Exception('No dump directory specified')
sys.exit()
params['save_matrix'] = False
""" Set -sm to save matrix to .mat file to a specified path """
if '-sm' in sys.argv:
params['save_matrix'] = True
"""Set -ar to autoremove hic text files"""
params['autoremove'] = False
if '-ar' in sys.argv:
params['autoremove'] = True
"""Set -ow to overwrite existing hic text files"""
params['overwrite'] = False
if '-ow' in sys.argv:
params['overwrite'] = True
if '-c' in sys.argv:
cIdx = sys.argv.index('-c') + 1
try:
params['cropMap'] = loadmat(os.path.join(sys.argv[cIdx],'cropMap.mat'))
params['cropIndices'] = loadmat(os.path.join(sys.argv[cIdx],'cropIndices.mat'))
except:
raise Exception('No custom crop folder specified')
sys.exit()
else:
params['cropMap'] = loadmat('crop_map/cropMap.mat')
params['cropIndices'] = loadmat('crop_map/cropIndices.mat')
"""
Specify a path to juicer_tools.jar
"""
if '-jt' in sys.argv:
jtIdx = sys.argv.index('-jt') + 1
params['juicer_tools_path'] = sys.argv[jtIdx]
return params | Python |
2D | ma-compbio/SNIPER | utilities/data_processing.py | .py | 4,488 | 158 | import os
import numpy as np
from subprocess import call
from scipy.io import loadmat, savemat
def chrom_sizes(f,length=np.inf):
data = open(f,'r')
sizes = {}
for line in data:
ldata = line.split()
if len(ldata[0]) > length:
continue
sizes[ldata[0]] = int(ldata[1])
return sizes
from utilities.interchromosome_matrix import construct
def constructAndSave(tmp_dir,prefix):
M = construct(tmp_dir, prefix=prefix)
savemat(os.path.join(tmp_dir,'%s_matrix.mat' % prefix),{'inter_matrix' : M})
return M
def hicToMat(h,juicer_path,tmp_dir='.',prefix='hic',autoremove=False,overwrite=False,save_matrix=False,verbose=False):
try:
os.stat(tmp_dir)
except:
os.mkdir(tmp_dir)
""" Calls juicer_tools to extract hic data into txt files """
for chrm1 in range(1,23,2):
for chrm2 in range(2,23,2):
output_path = os.path.join(tmp_dir,'{2}_chrm{0}_chrm{1}.txt'.format(chrm1,chrm2,prefix))
if os.path.isfile(output_path) and not overwrite:
continue
cmd = 'java -jar {0} dump observed KR {1} {2} {3} BP 100000 {4} > tmp_juicer_log'.format(juicer_path,h,chrm1,chrm2,output_path)
call([cmd],shell=True)
""" File path of the inter-chromosomal matrix """
M_filepath = os.path.join(tmp_dir,'%s_matrix.mat' % prefix)
""" If overwrite flag is set, reconstruct matrix and check save flag """
if overwrite:
M = constructAndSave(tmp_dir,prefix)
else:
""" If overwrite unset, check if filepath exists and either load mat or construct new """
if os.path.isfile(M_filepath):
M = loadmat(M_filepath)['inter_matrix']
else:
M = constructAndSave(tmp_dir,prefix)
""" If autoremove is set, remove hic .txt files """
if autoremove:
for chrm1 in range(1,23,2):
for chrm2 in range(2,23,2):
file_path = os.path.join(tmp_dir,'{2}_chrm{0}_chrm{1}.txt'.format(chrm1,chrm2,prefix))
try:
os.remove(file_path)
except:
continue
return M
""" Trims sparse, NA, and B4 regions """
def trimMat(M,indices):
row_indices = indices['odd_indices'].flatten()
col_indices = indices['even_indices'].flatten()
M = M[row_indices,:]
M = M[:,col_indices]
return M
"""Set delta to avoid dividing by zero"""
def contactProbabilities(M,delta=1e-10):
coeff = np.nan_to_num(1 / (M+delta))
PM = np.power(1/np.exp(1),coeff)
return PM
def RandomSample(data):
N = len(data)
return data[np.random.randint(N)]
def bootstrap(data,labels,samplesPerClass=None):
Nsamples = samplesPerClass
classes = np.unique(labels)
maxSamples = np.max(np.bincount(labels))
if samplesPerClass is None or samplesPerClass < maxSamples:
Nsamples = maxSamples
bootstrapSamples = []
bootstrapClasses = []
for i, c in enumerate(classes):
classLabel = c
classData = data[labels == c]
nBootstrap = Nsamples
for n in range(nBootstrap):
sample = RandomSample(classData)
bootstrapSamples.append(sample)
bootstrapClasses.append(c)
bootstrapSamples = np.asarray(bootstrapSamples)
bootstrapClasses = np.asarray(bootstrapClasses)
bootstrapData = np.hstack((bootstrapSamples,np.array([bootstrapClasses]).T))
np.random.shuffle(bootstrapData)
return (bootstrapData[:,:-1], bootstrapData[:,-1])
def Sigmoid(data):
return 1 / (1 + np.exp(-data))
def getColorString(n):
subcColors = ['34,139,34','152,251,152','220,20,60','255,255,0','112,128,144']
return subcColors[n]
def getSubcName(n):
order = ['A1','A2','B1','B2','B3']
return order[n]
def predictionsToBed(path, odds, evens, cropMap, res=100000, sizes_file='data/hg19.chrom.sizes'):
rowMap = cropMap['rowMap'].astype(np.int)
colMap = cropMap['colMap'].astype(np.int)
sizes = chrom_sizes(sizes_file)
file = open(path,'w')
for i,p in enumerate(np.argmax(odds,axis=1)):
m = rowMap
chrm, start = 'chr'+str(m[i,1]), m[i,2] * res
end = np.min([start + res, sizes[chrm]])
line = '{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(chrm, start, end, getSubcName(p), 0, '.' , start, end, getColorString(p))
file.write(line)
for i,p in enumerate(np.argmax(evens,axis=1)):
m = colMap
chrm, start = 'chr'+str(m[i,1]), m[i,2] * res
end = np.min([start + res, sizes[chrm]])
line = '{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(chrm, start, end, getSubcName(p), 0, '.' , start, end, getColorString(p))
file.write(line)
file.close() | Python |
2D | ma-compbio/SNIPER | pipeline/training.py | .py | 4,102 | 112 | import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from scipy.io import loadmat
from utilities.data_processing import hicToMat, trimMat, contactProbabilities, bootstrap, Sigmoid
from pipeline.models import DenoisingAutoencoder, Classifier
from keras.utils import to_categorical
def trainNN(inputM,targetM,params):
odd_labels = loadmat(params['label_file'])['rows'].flatten()
even_labels = loadmat(params['label_file'])['cols'].flatten()
print('Training autoencoders...')
odd_dae_model, odd_encoder, _ = DenoisingAutoencoder(inputM, targetM)
even_dae_model, even_encoder, _ = DenoisingAutoencoder(inputM.T, targetM.T)
odd_dae_model.fit(inputM[:7000],targetM[:7000],epochs=10,batch_size=32,
validation_data=[inputM[7000:],targetM[7000:]])
even_dae_model.fit(inputM.T[:7000],targetM.T[:7000],epochs=10,batch_size=32,
validation_data=[inputM.T[7000:],targetM.T[7000:]])
odd_encodings = Sigmoid(odd_encoder.predict(inputM))
even_encodings = Sigmoid(even_encoder.predict(inputM.T))
odd_clf = Classifier(odd_encodings)
even_clf = Classifier(even_encodings)
odd_X,odd_y = bootstrap(odd_encodings[:7000],odd_labels[:7000],samplesPerClass=2000)
even_X,even_y = bootstrap(even_encodings[:7000],even_labels[:7000],samplesPerClass=2000)
print('Training classifiers...')
odd_clf.fit(odd_X,to_categorical(odd_y), epochs=25, batch_size=32, verbose=0,
validation_data=[odd_encodings[7000:],to_categorical(odd_labels[7000:])])
even_clf.fit(even_X,to_categorical(even_y), epochs=25, batch_size=32, verbose=0,
validation_data=[even_encodings[7000:],to_categorical(even_labels[7000:])])
odd_dae_model.save(os.path.join(params['dump_dir'],'odd_chrm_autoencoder.h5'))
odd_encoder.save(os.path.join(params['dump_dir'],'odd_chrm_encoder.h5'))
odd_clf.save(os.path.join(params['dump_dir'],'odd_chrm_classifier.h5'))
even_dae_model.save(os.path.join(params['dump_dir'],'even_chrm_autoencoder.h5'))
even_encoder.save(os.path.join(params['dump_dir'],'even_chrm_encoder.h5'))
even_clf.save(os.path.join(params['dump_dir'],'even_chrm_classifier.h5'))
def train_with_hic(params):
print('Constructing input matrix')
if 'juicer_tools_path' not in params:
raise Exception('No juicer_tools path specified.')
sys.exit()
inputM = hicToMat(params['input_file'],
params['juicer_tools_path'],
tmp_dir=params['dump_dir'],
prefix='input',
autoremove=params['autoremove'],
overwrite=params['overwrite'],
save_matrix=params['save_matrix']
)
print('Trimming sparse regions...')
inputM = trimMat(inputM,params['cropIndices'])
print('Computing contact probabilities')
inputM = contactProbabilities(inputM)
print('Constructing target matrix')
targetM = hicToMat(params['target_file'],
params['juicer_tools_path'],
tmp_dir=params['dump_dir'],
prefix='target',
autoremove=params['autoremove'],
overwrite=params['overwrite'],
save_matrix=params['save_matrix']
)
print('Trimming sparse regions...')
targetM = trimMat(targetM,params['cropIndices'])
print('Computing contact probabilities')
targetM = contactProbabilities(targetM)
trainNN(inputM, targetM, params)
"""
This function will bypass the need to reconstruct .mat files of the inter-chromosomal Hi-C matrix
from a raw .hic file.
Use train_with_hic when training SNIPER for the first time. Turn on the -sm flag to save the
matrix as a .mat file, which will save the Hi-C matrix to the output directory specified by the
-dd flag.
"""
def train_with_mat(params):
print ('Using pre-computed .mat files, skipping hic-to-mat')
inputM = loadmat(params['input_file'])['inter_matrix']
targetM = loadmat(params['target_file'])['inter_matrix']
print('Trimming sparse regions from input matrix...')
inputM = trimMat(inputM,params['cropIndices'])
print('Computing contact probabilities')
inputM = contactProbabilities(inputM)
print('Trimming sparse regions from target matrix...')
targetM = trimMat(targetM,params['cropIndices'])
print('Computing contact probabilities')
targetM = contactProbabilities(targetM)
trainNN(inputM, targetM, params) | Python |
2D | ma-compbio/SNIPER | pipeline/models.py | .py | 1,563 | 51 | import keras.backend as K
from keras.layers import Dense, Input, Dropout
from keras.models import Sequential, Model
def DenoisingAutoencoder(input,target):
Ninput = input.shape[1]
Noutput = target.shape[1]
hidden_dims = [1024,512,256]
latent_dim = 128
encodeInput = Input(shape=(Ninput,))
encodeModel = Sequential([Dense(hidden_dims[0],activation='relu',input_dim=Ninput)])
encodeModel.add(Dropout(0.25))
[encodeModel.add(Dense(d,activation='relu')) for d in hidden_dims[1:]]
encodeModel.add(Dropout(0.25))
encodeModel.add(Dense(latent_dim))
decodeInput = Input(shape=(latent_dim,))
decodeModel = Sequential([Dense(hidden_dims[-1],activation='relu',input_dim=latent_dim)])
encodeModel.add(Dropout(0.25))
[decodeModel.add(Dense(d,activation='relu')) for d in reversed(hidden_dims[:-1])]
encodeModel.add(Dropout(0.25))
decodeModel.add(Dense(Noutput,activation='sigmoid'))
encoded = encodeModel(encodeInput)
decoded = decodeModel(decodeInput)
encoder = Model(encodeInput,encoded)
decoder = Model(decodeInput,decoded)
aeOut = decoder(encoder(encodeInput))
autoencoder = Model(encodeInput,aeOut)
autoencoder.compile(loss='binary_crossentropy',optimizer='rmsprop')
return autoencoder, encoder, decoder
def Classifier(X):
input_dim = X.shape[1]
clf = Sequential([
Dense(64,activation='relu',input_dim=input_dim),
Dropout(0.25),
Dense(16,activation='relu'),
Dropout(0.25),
Dense(5,activation='softmax')
])
clf.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
return clf | Python |
2D | ma-compbio/SNIPER | pipeline/application.py | .py | 2,092 | 61 | import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from scipy.io import loadmat, savemat
from keras.models import load_model
from utilities.data_processing import hicToMat, trimMat, contactProbabilities, Sigmoid, predictionsToBed
def apply_on_hic(params):
inputM = hicToMat(params['input_file'], params['juicer_tools_path'],
tmp_dir=params['dump_dir'],
prefix='input',
autoremove=params['autoremove'],
overwrite=params['overwrite'],
save_matrix=params['save_matrix']
)
print('Trimming sparse, NA, and B4 regions...')
inputM = trimMat(inputM,params['cropIndices'])
print('Computing contact probabilities')
inputM = contactProbabilities(inputM)
odd_encoder = load_model(params['odd_encoder'])
odd_clf = load_model(params['odd_classifier'])
even_encoder = load_model(params['even_encoder'])
even_clf = load_model(params['even_classifier'])
odd_enc = Sigmoid(odd_encoder.predict(inputM))
odd_predictions = odd_clf.predict(odd_enc)
even_enc = Sigmoid(even_encoder.predict(inputM.T))
even_predictions = even_clf.predict(even_enc)
savemat(params['output_path'],{
'odd_predictions' : odd_predictions,
'even_predictions' : even_predictions,
})
predictionsToBed(os.path.splitext(params['output_path'])[0] + '.bed', odd_predictions, even_predictions, params['cropMap'])
def apply_on_mat(params):
inputM = loadmat(params['input_file'])['inter_matrix']
print('Trimming sparse, NA, and B4 regions...')
inputM = trimMat(inputM,params['cropIndices'])
print('Computing contact probabilities')
inputM = contactProbabilities(inputM)
odd_encoder = load_model(params['odd_encoder'])
odd_clf = load_model(params['odd_classifier'])
even_encoder = load_model(params['even_encoder'])
even_clf = load_model(params['even_classifier'])
odd_enc = Sigmoid(odd_encoder.predict(inputM))
odd_predictions = odd_clf.predict(odd_enc)
even_enc = Sigmoid(even_encoder.predict(inputM.T))
even_predictions = even_clf.predict(even_enc)
savemat(params['output_path'],{
'odd_predictions' : odd_predictions,
'even_predictions' : even_predictions,
}) | Python |
2D | ITV-Stuttgart/loadBalancedChemistryModel | PrepareOpenFOAM.sh | .sh | 731 | 18 | #!/bin/bash
cd ${0%/*} || exit 1 # run from this directory
cat << EOF
The TDACChemistryModel of OpenFOAM uses a private scope for the variables
and member functions. This however prevents other classes, such as the
LoadBalancedTDACChemistryModel to derive from this class without replicating
all functionality. Further, the tabulation methods require a TDACChemistryModel.
Therefore, this script will add the protected keyword, making the private
member variables protected in the TDACChemistryModel
EOF
sed -i '88i protected:' ${WM_PROJECT_DIR}/src/thermophysicalModels/chemistryModel/chemistryModel/TDACChemistryModel/TDACChemistryModel.H
# ----------------------------------------------------------------- end-of-file
| Shell |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistrySolver/makeLoadBalancedChemistrySolvers.C | .C | 5,418 | 227 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "makeLoadBalancedChemistrySolverTypes.H"
#include "thermoPhysicsTypes.H"
#include "psiReactionThermo.H"
#include "rhoReactionThermo.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Chemistry solvers based on sensibleEnthalpy
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constGasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
gasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constIncompressibleGasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
incompressibleGasHThermoPhysics
)
;
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
icoPoly8HThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constFluidHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constAdiabaticFluidHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constGasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
gasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constIncompressibleGasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
incompressibleGasHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
icoPoly8HThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constFluidHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constAdiabaticFluidHThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constHThermoPhysics
);
// Chemistry solvers based on sensibleInternalEnergy
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constGasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
gasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constIncompressibleGasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
incompressibleGasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
icoPoly8EThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constFluidEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constAdiabaticFluidEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
psiReactionThermo,
constEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constGasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
gasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constIncompressibleGasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
incompressibleGasEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
icoPoly8EThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constFluidEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constAdiabaticFluidEThermoPhysics
);
makeLoadBalancedChemistrySolverTypes
(
rhoReactionThermo,
constEThermoPhysics
);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistrySolver/makeLoadBalancedChemistrySolverTypes.H | .H | 6,270 | 107 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#ifndef makeLoadBalancedChemistrySolverTypes_H
#define makeLoadBalancedChemistrySolverTypes_H
#include "chemistrySolver.H"
#include "LoadBalancedChemistryModel.H"
#include "LoadBalancedTDACChemistryModel.H"
#include "noChemistrySolver.H"
#include "EulerImplicit.H"
#include "ode.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#define makeLoadBalancedChemistrySolverType(SS, Comp, Thermo) \
\
typedef SS<LoadBalancedChemistryModel<Comp, Thermo>> SS##Comp##Thermo; \
\
defineTemplateTypeNameAndDebugWithName \
( \
SS##Comp##Thermo, \
(#SS"<" + word(LoadBalancedChemistryModel<Comp, Thermo>::typeName_()) \
+ "<" + word(Comp::typeName_()) + "," + Thermo::typeName() \
+ ">>").c_str(), \
0 \
); \
\
BasicChemistryModel<Comp>:: \
add##thermo##ConstructorToTable<SS##Comp##Thermo> \
add##SS##Comp##Thermo##thermo##ConstructorTo##BasicChemistryModel##Comp\
##Table_; \
\
typedef SS<LoadBalancedTDACChemistryModel<Comp, Thermo>> \
TDAC##SS##Comp##Thermo; \
\
defineTemplateTypeNameAndDebugWithName \
( \
TDAC##SS##Comp##Thermo, \
(#SS"<" \
+ word(LoadBalancedTDACChemistryModel<Comp, Thermo>::typeName_()) + "<"\
+ word(Comp::typeName_()) + "," + Thermo::typeName() + ">>").c_str(), \
0 \
); \
\
BasicChemistryModel<Comp>:: \
add##thermo##ConstructorToTable<TDAC##SS##Comp##Thermo> \
add##TDAC##SS##Comp##Thermo##thermo##ConstructorTo##BasicChemistryModel\
##Comp##Table_;
#define makeLoadBalancedChemistrySolverTypes(Comp, Thermo) \
\
makeLoadBalancedChemistrySolverType \
( \
noChemistrySolver, \
Comp, \
Thermo \
); \
\
makeLoadBalancedChemistrySolverType \
( \
EulerImplicit, \
Comp, \
Thermo \
); \
\
makeLoadBalancedChemistrySolverType \
( \
ode, \
Comp, \
Thermo \
); \
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Unknown |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistryModel/LoadBalancedTDACChemistryModel/LoadBalancedTDACChemistryModel.C | .C | 31,732 | 1,081 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "LoadBalancedTDACChemistryModel.H"
#include "UniformField.H"
#include "localEulerDdtScheme.H"
template<class ReactionThermo, class ThermoType>
Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::LoadBalancedTDACChemistryModel
(
ReactionThermo& thermo
)
:
TDACChemistryModel<ReactionThermo, ThermoType>(thermo)
{
// Create the table for the remote cell computation
tabulationRemote_ =
chemistryTabulationMethod<ReactionThermo, ThermoType>::New
(
*this,
*this
);
auto dict = this->subDictOrAdd("LoadBalancedTDACCoeffs");
maxIterUpdate_ = dict.template getOrDefault<label>("updateIter",0);
Info << "updateIter: "<<maxIterUpdate_<<endl;
// Set iter to maxIterUpdate to force update in the first iteration
iter_ = maxIterUpdate_;
// Initialize cell list
tmp<volScalarField> trho(this->thermo().rho());
const scalarField& rho = trho();
cellDataField_.reserve(rho.size());
// Number of additional properties stored in phiq.
// Default is pressure and temperatur, if variableTimeStep is active
// deltaT is added as well
label nAdditions = 2;
if (this->tabulation_->variableTimeStep())
nAdditions = 3;
forAll(rho,celli)
{
TDACDataContainer cData(this->nSpecie_,nAdditions);
cellDataField_.append(cData);
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>::addCell
(
DynamicList<TDACDataContainer*>& cellList,
const scalarField& phiq,
const scalar& T,
const scalar& p,
const scalar& rho,
const scalar& deltaT,
const label& celli
)
{
label MyProcNo = Pstream::myProcNo();
// Checkout the cData container from the field
TDACDataContainer& cData = cellDataField_[celli];
cData.phiq() = phiq;
cData.T() = T;
cData.p() = p;
cData.rho() = rho;
cData.deltaT() = deltaT;
cData.deltaTChem() = this->deltaTChem_[celli];
cData.proc() = MyProcNo;
cData.cellID() = celli;
cellList.append(&cData);
cellsToSolve_++;
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::cellsToSend
(
const DynamicList<TDACDataContainer*>& cellList,
const scalar cpuTimeToSend,
const label& start,
label& end
)
{
end = cellList.size();
scalar cpuTime = 0;
// go from start index and add as many particles until the cpuTimeToSend
// is reached
for (label i=start; i < cellList.size(); i++)
{
if (cpuTime >= cpuTimeToSend)
{
end = i;
break;
}
cpuTime += cellList[i]->cpuTime()+cellList[i]->addToTableCpuTime();
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::updateProcessorBalancing()
{
// Number of processors
const scalar numProcs = Pstream::nProcs();
auto sortedCpuTimeOnProcessors = getSortedCPUTimesOnProcessor();
// calculate average time spent on each cpu
scalar averageCpuTime = 0;
forAll(sortedCpuTimeOnProcessors,i)
{
averageCpuTime += sortedCpuTimeOnProcessors[i].first;
}
averageCpuTime /= numProcs;
// list of the distributed load for all processors
List<DynamicList<sendDataStruct>> distributedLoadAllProcs(numProcs);
// list of processors to receive data from
List<DynamicList<label>> receiveDataFromProc(numProcs);
// balance the load by calculating the percentages to be send
forAll(sortedCpuTimeOnProcessors,i)
{
const label procI = sortedCpuTimeOnProcessors[i].second[0];
// List of processors to send information to
DynamicList<sendDataStruct>& sendLoadList =
distributedLoadAllProcs[procI];
// Reserve space
sendLoadList.reserve
(
std::floor(0.5*(numProcs-i))
);
// Total time cpu time on procI -- including time to solve ODE and
// adding to the table
const scalar cpuTimeProcI = sortedCpuTimeOnProcessors[i].first;
scalar cpuTimeOverhead = cpuTimeProcI - averageCpuTime;
if (cpuTimeOverhead < 0)
continue;
// Loop over the other processors and distribute the load
// in reverse order
for (label k=numProcs-1; k > 0; k--)
{
const label procK = sortedCpuTimeOnProcessors[k].second[0];
const scalar cpuTimeProcK = sortedCpuTimeOnProcessors[k].first;
const scalar capacityOfProcK = averageCpuTime - cpuTimeProcK;
if (capacityOfProcK <= 0)
continue;
const scalar newCapacity = capacityOfProcK - cpuTimeOverhead;
// Only send information to procK if it is larger than 2% of the
// total average cell time
if ((std::min(capacityOfProcK,cpuTimeOverhead)/cpuTimeProcI) < 0.02)
continue;
if (newCapacity > 0)
{
// add the cpuTimeOverhead to the load of this processor
sortedCpuTimeOnProcessors[k].first += cpuTimeOverhead;
sortedCpuTimeOnProcessors[i].first -= cpuTimeOverhead;
// Processor procI sends information to procK
// Therefore the receive data list of procK has to be updated
receiveDataFromProc[procK].reserve(0.5*numProcs);
receiveDataFromProc[procK].append(procI);
sendLoadList.append
(
sendDataStruct
(
cpuTimeOverhead,
procK
)
);
cpuTimeOverhead = 0;
break;
}
else
{
sortedCpuTimeOnProcessors[k].first += capacityOfProcK;
sortedCpuTimeOnProcessors[i].first -= capacityOfProcK;
cpuTimeOverhead -= capacityOfProcK;
// Processor procI sends information to procK
// Therefore the receive data list of procK has to be updated
receiveDataFromProc[procK].reserve(0.5*numProcs);
receiveDataFromProc[procK].append(procI);
sendLoadList.append
(
sendDataStruct
(
capacityOfProcK,
sortedCpuTimeOnProcessors[k].second[0]
)
);
}
}
}
sendAndReceiveData_.first() = distributedLoadAllProcs[Pstream::myProcNo()];
sendAndReceiveData_.second() = receiveDataFromProc[Pstream::myProcNo()];
// Create send and receive lists
sendToProcessor_.resize(Pstream::nProcs());
receiveFromProcessor_.resize(Pstream::nProcs());
// Set all to false
forAll(sendToProcessor_,i)
{
sendToProcessor_[i] = false;
receiveFromProcessor_[i] = false;
}
for (auto& sendInfoData : sendAndReceiveData_.first())
{
sendToProcessor_[sendInfoData.toProc] = true;
}
for (label procID : sendAndReceiveData_.second())
{
receiveFromProcessor_[procID] = true;
}
}
template<class ReactionThermo, class ThermoType>
Foam::List<std::pair<scalar,Foam::List<scalar>>>
Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::getSortedCPUTimesOnProcessor() const
{
// Number of processors
const scalar numProcs = Pstream::nProcs();
// Gather the data from all processors
List<List<scalar>> cpuTimeOnProcessors(numProcs);
cpuTimeOnProcessors[Pstream::myProcNo()].resize(4);
cpuTimeOnProcessors[Pstream::myProcNo()][0] = totalCpuTime_;
cpuTimeOnProcessors[Pstream::myProcNo()][1] = cellsToSolve_;
cpuTimeOnProcessors[Pstream::myProcNo()][2] = addToTableCpuTime_;
cpuTimeOnProcessors[Pstream::myProcNo()][3] = searchISATCpuTime_;
Pstream::gatherList(cpuTimeOnProcessors);
Pstream::scatterList(cpuTimeOnProcessors);
// use std::pair for std::sort algorithm
// Data structure is:
// List[index].first: CPU time required for last time step
// List[index].second: Returns a List<scalar> with:
// List[0]: processor ID
// List[1]: Number of cells to compute
// List[2]: Time to add cells to table
List<std::pair<scalar,List<scalar>>> sortedCpuTimeOnProcessors(numProcs);
forAll(sortedCpuTimeOnProcessors,i)
{
sortedCpuTimeOnProcessors[i].first = cpuTimeOnProcessors[i][0];
sortedCpuTimeOnProcessors[i].second.resize(4);
sortedCpuTimeOnProcessors[i].second[0] = i;
sortedCpuTimeOnProcessors[i].second[1] = cpuTimeOnProcessors[i][1];
sortedCpuTimeOnProcessors[i].second[2] = cpuTimeOnProcessors[i][2];
sortedCpuTimeOnProcessors[i].second[3] = cpuTimeOnProcessors[i][3];
}
// sort using std::sort()
// first entry has largest cpu time --> descending order
std::stable_sort
(
sortedCpuTimeOnProcessors.begin(),
sortedCpuTimeOnProcessors.end(),
std::greater<std::pair<scalar,List<scalar>>>()
);
return sortedCpuTimeOnProcessors;
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::updateTotalCpuTime
(
const DynamicList<TDACDataContainer*>& cellList
)
{
// Calculate the total time spent solving the particles on this processor
totalCpuTime_ = 0;
addToTableCpuTime_ = 0;
for (const auto& cDataPtr : cellList)
{
addToTableCpuTime_ += cDataPtr->addToTableCpuTime();
totalCpuTime_ += (cDataPtr->cpuTime()+cDataPtr->addToTableCpuTime());
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>::solveCell
(
TDACDataContainer& cData
)
{
// Store total time waiting to attribute to add or grow
scalar timeTmp = clockTime_.timeIncrement();
// Note: first nSpecie entries are the Yi values in phiq
Field<scalar>& c = cData.c();
Field<scalar>& c0 = cData.c0();
for (label i=0; i<this->nSpecie_; i++)
{
c[i] = cData.rho()*cData.phiq()[i]/this->specieThermo_[i].W();
c0[i] = c[i];
}
const bool reduced = this->mechRed()->active();
scalar timeLeft = cData.deltaT();
scalar reduceMechCpuTime_ = 0;
if (reduced)
{
// Reduce mechanism change the number of species (only active)
this->mechRed()->reduceMechanism(c, cData.T(), cData.p());
scalar timeIncr = clockTime_.timeIncrement();
reduceMechCpuTime_ += timeIncr;
timeTmp += timeIncr;
nSpecieReduced_ = this->nSpecie_;
}
// Calculate the chemical source terms
while (timeLeft > SMALL)
{
scalar dt = timeLeft;
if (reduced)
{
// completeC_ used in the overridden ODE methods
// to update only the active species
this->completeC_ = c;
// Solve the reduced set of ODE
this->solve
(
this->simplifiedC_, cData.T(), cData.T(), dt, cData.deltaTChem()
);
for (label i=0; i<this->NsDAC_; ++i)
{
c[this->simplifiedToCompleteIndex_[i]] = this->simplifiedC_[i];
}
}
else
{
this->solve(c, cData.T(), cData.p(), dt, cData.deltaTChem());
}
timeLeft -= dt;
}
{
scalar timeIncr = clockTime_.timeIncrement();
solveChemistryCpuTime_ += timeIncr;
}
// When operations are done and if mechanism reduction is active,
// the number of species (which also affects nEqns) is set back
// to the total number of species (stored in the this->mechRed object)
if (reduced)
{
this->nSpecie_ = this->mechRed()->nSpecie();
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::solveCellList
(
UList<TDACDataContainer*>& cellList,
const bool isLocal
)
{
for (TDACDataContainer* cDataPtr : cellList)
{
// Check if it now can be found in table
// this is possible if a previous cell computed this result
if (lookUpCellInTable(*cDataPtr,isLocal))
continue;
// We cannot use here cpuTimeIncrement() of OpenFOAM as this
// returns only measurements in 100Hz or 1000Hz intervals depending
// on the installed kernel
auto start = std::chrono::high_resolution_clock::now();
solveCell
(
*cDataPtr
);
auto end = std::chrono::high_resolution_clock::now();
auto duration =
(std::chrono::duration_cast<std::chrono::microseconds>(end-start));
// Add the time required to solve this particle to the list
// as seconds
cDataPtr->cpuTime() = duration.count()*1.0E-6;
// Add to table
// Does not recompute the reduced reaction mechanism as it was just
// computed for this cell in solveCell()
addCellToTable(*cDataPtr,isLocal,false);
}
}
template<class ReactionThermo, class ThermoType>
bool Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::lookUpCellInTable
(
TDACDataContainer& cData,
const bool isLocal
)
{
chemistryTabulationMethod<ReactionThermo, ThermoType>* tabPtr;
if (isLocal)
tabPtr = this->tabulation_.get();
else
tabPtr = this->tabulationRemote_.get();
if
(
tabPtr->active()
&& tabPtr->retrieve(cData.phiq(), Rphiq_)
)
{
// Note: first nSpecie entries are the Yi values in phiq
Field<scalar>& c = cData.c();
Field<scalar>& c0 = cData.c0();
for (label i=0; i<this->nSpecie_; i++)
{
c0[i] = cData.rho()*cData.phiq()[i]/this->specieThermo_[i].W();
}
// Retrieved solution stored in Rphiq_
for (label i=0; i<this->nSpecie(); ++i)
{
c[i] = cData.rho()*Rphiq_[i]/this->specieThermo_[i].W();
}
return true;
}
return false;
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::addCellToTable
(
const TDACDataContainer& cData,
const bool isLocal,
const bool requiresRecomputeReducedMech
)
{
chemistryTabulationMethod<ReactionThermo, ThermoType>* tabPtr;
if (isLocal)
tabPtr = this->tabulation_.get();
else
tabPtr = this->tabulationRemote_.get();
// We cannot use here cpuTimeIncrement() of OpenFOAM as this
// returns only measurements in 100Hz or 1000Hz intervals depending
// on the installed kernel
auto start = std::chrono::high_resolution_clock::now();
const auto& c = cData.c();
// Not sure if this is necessary
Rphiq_ = Zero;
forAll(c, i)
{
Rphiq_[i] = c[i]/cData.rho()*this->specieThermo_[i].W();
}
if (tabPtr->variableTimeStep())
{
Rphiq_[Rphiq_.size()-3] = cData.T();
Rphiq_[Rphiq_.size()-2] = cData.p();
Rphiq_[Rphiq_.size()-1] = cData.deltaT();
}
else
{
Rphiq_[Rphiq_.size()-2] = cData.T();
Rphiq_[Rphiq_.size()-1] = cData.p();
}
clockTime_.timeIncrement();
// If tabulation is used, we add the information computed here to
// the stored points (either expand or add)
if
(
tabPtr->active()
&& !tabPtr->retrieve(cData.phiq(), Rphiq_)
)
{
if (this->mechRed()->active())
{
if (requiresRecomputeReducedMech)
this->mechRed_->reduceMechanism(c, cData.T(), cData.p());
else
this->setNSpecie(nSpecieReduced_);
}
label growOrAdd =
tabPtr->add
(
cData.phiq(), Rphiq_, cData.rho(), cData.deltaT()
);
// Only collect information for local cells
if (isLocal)
{
const label celli = cData.cellID();
auto end = std::chrono::high_resolution_clock::now();
auto duration =
(
std::chrono::duration_cast<std::chrono::microseconds>
(end-start)
);
// Add the time to the cell data container
cData.setAddToTableCpuTime(duration.count()*1.0E-6);
if (growOrAdd)
{
this->setTabulationResultsAdd(celli);
addNewLeafCpuTime_ += clockTime_.timeIncrement();
}
else
{
this->setTabulationResultsGrow(celli);
growCpuTime_ += clockTime_.timeIncrement();
}
}
// When operations are done and if mechanism reduction is active,
// the number of species (which also affects nEqns) is set back
// to the total number of species (stored in the this->mechRed object)
if (this->mechRed()->active())
{
this->nSpecie_ = this->mechRed()->nSpecie();
}
}
}
template<class ReactionThermo, class ThermoType>
template<class DeltaTType>
Foam::scalar Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::solve
(
const DeltaTType& deltaT
)
{
// List of cells that need to be solved
DynamicList<TDACDataContainer*> cellList(cellDataField_.size());
cellsToSolve_ = 0;
// Increment counter of time-step
this->timeSteps_++;
const bool reduced = this->mechRed()->active();
label nAdditionalEqn = (this->tabulation_->variableTimeStep() ? 1 : 0);
basicSpecieMixture& composition = this->thermo().composition();
// CPU time analysis
clockTime_= clockTime();
clockTime_.timeIncrement();
reduceMechCpuTime_ = 0;
addNewLeafCpuTime_ = 0;
growCpuTime_ = 0;
solveChemistryCpuTime_ = 0;
searchISATCpuTime_ = 0;
this->resetTabulationResults();
// Average number of active species
scalar nActiveSpecies = 0;
scalar nAvg = 0;
BasicChemistryModel<ReactionThermo>::correct();
scalar deltaTMin = GREAT;
if (!this->chemistry_)
{
return deltaTMin;
}
tmp<volScalarField> trho(this->thermo().rho());
const scalarField& rho = trho();
const scalarField& T = this->thermo().T();
const scalarField& p = this->thermo().p();
scalarField c(this->nSpecie_);
scalarField c0(this->nSpecie_);
// Composition vector (Yi, T, p)
scalarField phiq(this->nEqns() + nAdditionalEqn);
Rphiq_.resize(this->nEqns() + nAdditionalEqn);
forAll(rho, celli)
{
const scalar rhoi = rho[celli];
scalar pi = p[celli];
scalar Ti = T[celli];
for (label i=0; i<this->nSpecie_; i++)
{
const volScalarField& Yi = this->Y_[i];
c[i] = rhoi*Yi[celli]/this->specieThermo_[i].W();
c0[i] = c[i];
phiq[i] = Yi[celli];
}
phiq[this->nSpecie()] = Ti;
phiq[this->nSpecie() + 1] = pi;
if (this->tabulation_->variableTimeStep())
{
phiq[this->nSpecie() + 2] = deltaT[celli];
}
// Not sure if this is necessary
Rphiq_ = Zero;
clockTime_.timeIncrement();
// When tabulation is active (short-circuit evaluation for retrieve)
// It first tries to retrieve the solution of the system with the
// information stored through the tabulation method
if
(
this->tabulation_->active()
&& this->tabulation_->retrieve(phiq, Rphiq_)
)
{
// Retrieved solution stored in Rphiq_
for (label i=0; i<this->nSpecie(); ++i)
{
c[i] = rhoi*Rphiq_[i]/this->specieThermo_[i].W();
}
searchISATCpuTime_ += clockTime_.timeIncrement();
// Set the RR vector (used in the solver)
for (label i=0; i<this->nSpecie_; ++i)
{
this->RR_[i][celli] =
(c[i] - c0[i])*this->specieThermo_[i].W()/deltaT[celli];
}
}
// This position is reached when tabulation is not used OR
// if the solution is not retrieved.
// In the latter case, it adds the information for later compuation
// with the load balanced method
else
{
addCell(cellList,phiq,Ti,pi,rhoi,deltaT[celli],celli);
}
}
// Update total cpu time based on the current cell list
updateTotalCpuTime(cellList);
// ========================================================================
// Solve for cells that were not found in the table
// ========================================================================
// If it is solved the first time, computational statistics have to be
// gathered first
if (firstTime_)
{
solveCellList(cellList,true);
firstTime_ = false;
}
else
{
if (iter_++ >= maxIterUpdate_)
{
updateProcessorBalancing();
iter_ = 0;
}
const List<sendDataStruct>& sendDataInfo = sendAndReceiveData_.first();
const List<label>& recvProc = sendAndReceiveData_.second();
// indices of the reactCellList to create the sub lists to send
label start = 0;
// Send all particles
for (auto& sendDataInfoI : sendDataInfo)
{
const scalar cpuTimeToSend = sendDataInfoI.cpuTimeToSend;
const label toProc = sendDataInfoI.toProc;
label end = cellList.size();
cellsToSend
(
cellList,
cpuTimeToSend,
start,
end
);
// send particles
UOPstream toBuffer
(
pBufs_.commsType(),
toProc,
pBufs_.sendBuffer(toProc),
pBufs_.tag(),
pBufs_.comm(),
false
);
label dataSize = end - start;
toBuffer << dataSize;
for (label i=start; i < end; i++)
{
toBuffer << *(cellList[i]);
}
start = end;
}
// Set local to compute particle list
SubList<TDACDataContainer*> localToComputeCells
(
cellList,
cellList.size()-start,
start
);
pBufs_.finishedSends(sendToProcessor_,receiveFromProcessor_);
DynamicList<TDACDataContainer> processorCells;
List<label> receivedDataSizes(recvProc.size());
// Read the received information
forAll(recvProc,i)
{
label receiveBufferPosition=0;
label procI = recvProc[i];
UIPstream fromBuffer
(
pBufs_.commsType(),
procI,
pBufs_.recvBuffer(procI),
receiveBufferPosition,
pBufs_.tag(),
pBufs_.comm(),
false
);
label dataSize;
fromBuffer >> dataSize;
receivedDataSizes[i] = dataSize;
processorCells.reserve(processorCells.size()+dataSize);
for (label k=0; k < dataSize; k++)
{
TDACDataContainer p(fromBuffer);
processorCells.append(std::move(p));
}
}
// We need to create a pointer list for the solveCellList function
List<TDACDataContainer*> processorCellsPtr
(
processorCells.size(), nullptr
);
// We cannot create this pointer list in the for loop before, as each
// resize of the dynamic list will invalidate the pointers.
forAll(processorCells,i)
{
processorCellsPtr[i] = &processorCells[i];
}
// Solve the local cells first
solveCellList(localToComputeCells,true);
// Solve the chemistry on processor particles
solveCellList(processorCellsPtr,false);
// Send the information back
// Note: Now the processors to which we originally had send informations
// are the ones we receive from and vice versa
pBufs_.switchSendRecv();
label pI = 0;
forAll(recvProc,i)
{
label procI = recvProc[i];
UOPstream toBuffer
(
pBufs_.commsType(),
procI,
pBufs_.sendBuffer(procI),
pBufs_.tag(),
pBufs_.comm(),
false
);
toBuffer << receivedDataSizes[i];
for (label k=0; k < receivedDataSizes[i]; k++)
toBuffer << processorCells[pI++];
}
pBufs_.finishedSends();
start = 0;
label end = 0;
// Receive the particles
// --> now the sendDataInfo becomes the receive info
for (auto& sendDataInfoI : sendDataInfo)
{
const label fromProc = sendDataInfoI.toProc;
// send particles
label receiveBufferPosition=0;
label dataSize;
UIPstream fromBuffer
(
pBufs_.commsType(),
fromProc,
pBufs_.recvBuffer(fromProc),
receiveBufferPosition,
pBufs_.tag(),
pBufs_.comm(),
false
);
fromBuffer >> dataSize;
end = start + dataSize;
for (label i=start; i < end; i++)
fromBuffer >> *(cellList[i]);
start = end;
}
// Switch sendAndRecv back
pBufs_.switchSendRecv();
// =====================================================================
// Update Table for Remote cells
// =====================================================================
// Remote cells are all from start to end
SubList<TDACDataContainer*> remoteComputedCells
(
cellList,
0,
end
);
for (const auto& cDataPtr : remoteComputedCells)
{
// dereference pointer
const auto& cData = *cDataPtr;
// Add cell to ISAT table and log CPU time
addCellToTable(cData,true);
}
}
// ========================================================================
// Update Reaction Rate
// ========================================================================
for (const auto& cDataPtr : cellList)
{
// dereference pointer
const auto& cData = *cDataPtr;
const label celli = cData.cellID();
const auto& c = cData.c();
const auto& c0 = cData.c0();
deltaTMin = min(this->deltaTChem_[celli], deltaTMin);
this->deltaTChem_[celli] =
min(this->deltaTChem_[celli], this->deltaTChemMax_);
// Set the RR vector (used in the solver)
for (label i=0; i<this->nSpecie_; ++i)
{
this->RR_[i][celli] =
(c[i] - c0[i])*this->specieThermo_[i].W()/deltaT[celli];
}
}
if (this->mechRed_->log() || this->tabulation_->log())
{
this->cpuSolveFile_()
<< this->time().timeOutputValue()
<< " " << solveChemistryCpuTime_ << endl;
}
if (this->mechRed_->log())
{
this->cpuReduceFile_()
<< this->time().timeOutputValue()
<< " " << reduceMechCpuTime_ << endl;
}
if (this->tabulation_->active())
{
// Every time-step, look if the tabulation should be updated
this->tabulation_->update();
this->tabulationRemote_->update();
// Write the performance of the tabulation
this->tabulation_->writePerformance();
if (this->tabulation_->log())
{
this->cpuRetrieveFile_()
<< this->time().timeOutputValue()
<< " " << searchISATCpuTime_ << endl;
this->cpuGrowFile_()
<< this->time().timeOutputValue()
<< " " << growCpuTime_ << endl;
this->cpuAddFile_()
<< this->time().timeOutputValue()
<< " " << addNewLeafCpuTime_ << endl;
}
}
if (reduced && nAvg && this->mechRed_->log())
{
// Write average number of species
this->nActiveSpeciesFile_()
<< this->time().timeOutputValue()
<< " " << nActiveSpecies/nAvg << endl;
}
if (reduced && Pstream::parRun())
{
List<bool> active(composition.active());
Pstream::listCombineReduce(active, orEqOp<bool>());
forAll(active, i)
{
if (active[i])
{
composition.setActive(i);
}
}
}
forAll(this->Y(), i)
{
if (composition.active(i))
{
this->Y()[i].writeOpt(IOobject::AUTO_WRITE);
}
}
return deltaTMin;
}
template<class ReactionThermo, class ThermoType>
Foam::scalar Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::solve
(
const scalar deltaT
)
{
// Don't allow the time-step to change more than a factor of 2
return min
(
this->solve<UniformField<scalar>>(UniformField<scalar>(deltaT)),
2*deltaT
);
}
template<class ReactionThermo, class ThermoType>
Foam::scalar Foam::LoadBalancedTDACChemistryModel<ReactionThermo, ThermoType>
::solve
(
const scalarField& deltaT
)
{
return this->solve<scalarField>(deltaT);
}
// ************************************************************************* //
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistryModel/LoadBalancedTDACChemistryModel/LoadBalancedTDACChemistryModel.H | .H | 9,233 | 290 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::LoadBalancedTDACChemistryModel
Description
Extends the TDACChemistryModel with load balancing of the reation.
SourceFiles
LoadBalancedTDACChemistryModel.H
LoadBalancedTDACChemistryModel.C
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#ifndef LoadBalancedTDACChemistryModel_H
#define LoadBalancedTDACChemistryModel_H
#include "TDACChemistryModel.H"
#include "chemistryReductionMethod.H"
#include "chemistryTabulationMethod.H"
#include "TDACDataContainer.H"
#include "pointToPointBuffer.H"
#include "OFstream.H"
#include "clockTime.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class LoadBalancedTDACChemistryModel Declaration
\*---------------------------------------------------------------------------*/
template<class ReactionThermo, class ThermoType>
class LoadBalancedTDACChemistryModel
:
public TDACChemistryModel<ReactionThermo, ThermoType>
{
public:
// Struct to store the information required for sending cells to other
// processors
struct sendDataStruct
{
public:
// processor to send information to
label toProc=-1;
// CPU time to send to processor
scalar cpuTimeToSend=-1;
// Constructor
sendDataStruct() = default;
sendDataStruct(scalar cpuTimeToSend, label procId)
: toProc(procId),cpuTimeToSend(cpuTimeToSend)
{}
};
private:
// Private Memeber Variables for TDAC
//- Store for cpuStatistics
clockTime clockTime_;
scalar reduceMechCpuTime_;
scalar addNewLeafCpuTime_;
scalar growCpuTime_;
scalar solveChemistryCpuTime_;
scalar addToTableCpuTime_;
scalar searchISATCpuTime_;
scalar totalCpuTime_;
//- Variable to store the solution vector.
// Allocated here to avoid reallocation
scalarField Rphiq_;
// Private Member Variables for Load Balancing
//- List of TDACDataContainer for each cell of the field
// Always has the size of the field
DynamicList<TDACDataContainer> cellDataField_;
//- Switch to check if it is called the first time in the simulation
bool firstTime_{true};
//- Number of cells that were not found in the table and need to be
// solved
label cellsToSolve_;
//- Store the number of species of the reduced mechanism
label nSpecieReduced_;
//- Store processor balancing data, first entry is a list of sendData
// information, second entry is the recv processor ID
Tuple2
<
List<sendDataStruct>,
List<label>
>
sendAndReceiveData_;
//- Store remote computed cells in a separate table
autoPtr<chemistryTabulationMethod<ReactionThermo, ThermoType>>
tabulationRemote_;
//- List of size Pstream::nProcs() which is true if data is send to
List<bool> sendToProcessor_;
//- List of size Pstream::nProcs() which is true if data is received
//- from processor
List<bool> receiveFromProcessor_;
//- Needs to keep the buffer alive to not loose the information
// about send and receive sizes
pointToPointBuffer pBufs_;
//- Index of current iteration before the proc-tp-proc connection
// is recalculated for the load balancing
label iter_;
//- Maximum number of iterations before the proc-to-proc load balancing
// is updated
label maxIterUpdate_;
// Private Member Functions
//- Add cell to cellDataList for parallel processing
void addCell
(
DynamicList<TDACDataContainer*>& cellList,
const scalarField& phiq,
const scalar& T,
const scalar& p,
const scalar& rho,
const scalar& deltaT,
const label& celli
);
//- Calculate the cells to send/recv to/from other
//- processors
// Returns a list of sublists of cells to send to processor i
void cellsToSend
(
const DynamicList<TDACDataContainer*>& cellList,
const scalar cpuTimeToSend,
const label& start,
label& end
);
//- Get percentage of processor data to send to other processors
//- to balance the processor load
void updateProcessorBalancing();
//- Get cpu times of each processor in a descending order
// Format:
// List[index].first: CPU time required for last time step
// List[index].second: Returns a List<scalar> with:
// List[0]: processor ID
// List[1]: Number of cells to compute
// List[2]: Time to search ISAT table
List<std::pair<scalar,List<scalar>>>
getSortedCPUTimesOnProcessor() const;
//- Update the totalCpuTime_ variable
void updateTotalCpuTime
(
const DynamicList<TDACDataContainer*>& cellList
);
//- Add cell to ISAT table -- after solving
// Switch to set if local or remote cells are solved
// Switch if the reduced mechanism needs to be recomputed
// this is required if the cell was sent between processors
void addCellToTable
(
const TDACDataContainer& cData,
const bool isLocal,
const bool requiresRecomputeReducedMech=true
);
//- Lookup the cell data in the ISAT table
bool lookUpCellInTable
(
TDACDataContainer& cData,
const bool isLocal
);
//- Solve the reaction for all cells in the given list
// Flag sets if it is local or remote cell computation
void solveCellList
(
UList<TDACDataContainer*>& cellList,
const bool isLocal
);
//- Solve chemistry for once cell
void solveCell(TDACDataContainer& cellData);
//- Solve the reaction system for the given time step
// of given type and return the characteristic time
template<class DeltaTType>
scalar solve(const DeltaTType& deltaT);
public:
//- Runtime type information
TypeName("LoadBalancedTDAC");
// Constructors
//- No copy construct
LoadBalancedTDACChemistryModel
(
const LoadBalancedTDACChemistryModel&
) = delete;
//- No copy assignment
void operator=(const LoadBalancedTDACChemistryModel&) = delete;
//- Construct from thermo
LoadBalancedTDACChemistryModel(ReactionThermo& thermo);
//- Destructor
virtual ~LoadBalancedTDACChemistryModel() {};
//- Solve the reaction system for the given time step with load
// balancing and return the characteristic time
virtual scalar solve(const scalar deltaT);
//- Solve the reaction system for the given time step with load
// balancing and return the characteristic time
virtual scalar solve(const scalarField& deltaT);
// ODE functions (overriding functions in TDACChemistryModel to take
virtual void solve
(
scalarField& c,
scalar& T,
scalar& p,
scalar& deltaT,
scalar& subDeltaT
) const = 0;
};
} // End of namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
#include "LoadBalancedTDACChemistryModel.C"
#endif
#endif
| Unknown |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistryModel/LoadBalancedTDACChemistryModel/makeLoadBalancedTDACChemistryModels.C | .C | 6,255 | 276 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Generates the chemistry models
\*---------------------------------------------------------------------------*/
#include "makeChemistryModel.H"
#include "psiReactionThermo.H"
#include "rhoReactionThermo.H"
#include "LoadBalancedTDACChemistryModel.H"
#include "thermoPhysicsTypes.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Chemistry moldels based on sensibleEnthalpy
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
gasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constIncompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
incompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
icoPoly8HThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constAdiabaticFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
gasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constIncompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
incompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
icoPoly8HThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constAdiabaticFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constHThermoPhysics
);
// Chemistry moldels based on sensibleInternalEnergy
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
gasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constIncompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
incompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
icoPoly8EThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constAdiabaticFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
psiReactionThermo,
constEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
gasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constIncompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
incompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
icoPoly8EThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constAdiabaticFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedTDACChemistryModel,
rhoReactionThermo,
constEThermoPhysics
);
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistryModel/LoadBalancedChemistryModel/LoadBalancedChemistryModel.C | .C | 20,786 | 733 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "LoadBalancedChemistryModel.H"
template<class ReactionThermo, class ThermoType>
Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>
::LoadBalancedChemistryModel
(
ReactionThermo& thermo
)
:
StandardChemistryModel<ReactionThermo, ThermoType>(thermo)
{
auto dict = this->subDictOrAdd("LoadBalancedCoeffs");
minFractionOfCellsToSend_ =
dict.template getOrDefault<scalar>("minFractionOfCellsToSend",0.02);
maxIterUpdate_ = dict.template getOrDefault<label>("updateIter",0);
Info << "updateIter: "<<maxIterUpdate_<<endl;
cellsOnProcessors_.resize(Pstream::nProcs());
// Gather the number of particles on each processor
List<label> cellsOnProcessors(Pstream::nProcs());
cellsOnProcessors[Pstream::myProcNo()] = this->mesh().C().size();
Pstream::gatherList(cellsOnProcessors);
Pstream::scatterList(cellsOnProcessors);
cellsOnProcessors_ = cellsOnProcessors;
iter_ = maxIterUpdate_;
}
template<class ReactionThermo, class ThermoType>
template<class DeltaTType>
void Foam::LoadBalancedChemistryModel
<ReactionThermo, ThermoType>::buildCellDataList
(
const DeltaTType& deltaT
)
{
tmp<volScalarField> trho(this->thermo().rho());
const scalarField& rho = trho();
// Reserve at least enough space for all cells on the local mesh
cellDataList_.reserve(rho.size());
forAll(rho, celli)
{
// store the cell data in a container
baseDataContainer cData(this->nSpecie_);
cellDataList_.append(cData);
}
updateCellDataList(deltaT);
}
template<class ReactionThermo, class ThermoType>
template<class DeltaTType>
void Foam::LoadBalancedChemistryModel
<ReactionThermo, ThermoType>::updateCellDataList
(
const DeltaTType& deltaT
)
{
label MyProcNo = Pstream::myProcNo();
tmp<volScalarField> trho(this->thermo().rho());
const scalarField& rho = trho();
const scalarField& T = this->thermo().T();
const scalarField& p = this->thermo().p();
// Additional checks if FULLDEBUG is activated:
#ifdef FULLDEBUG
// Check that the number of cells has not changed
if (rho.size() != cellDataList().size())
FatalError
<< "updateCellDataList does not work if the mesh changes"
<< " -- mesh size: " << p.size() << " cellDataList size: "
<< cellDataList().size()
<< exit(FatalError);
#endif
scalarField c0(this->nSpecie_);
// Loop over all entries
forAll(cellDataList_,celli)
{
auto& cellData = cellDataList_[celli];
cellData.proc() = MyProcNo;
cellData.T() = T[celli];
cellData.p() = p[celli];
cellData.rho() = rho[celli];
cellData.deltaT() = deltaT[celli];
cellData.deltaTChem() = this->deltaTChem_[celli];
cellData.cellID() = celli;
// Set species
forAll(this->Y_,j)
{
cellData.Y()[j] = this->Y_[j][celli];
}
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>::cellsToSend
(
const DynamicList<baseDataContainer>& cellList,
const scalar cpuTimeToSend,
const label& start,
label& end
)
{
end = cellList.size();
scalar cpuTime = 0;
// go from start index and add as many particles until the cpuTimeToSend
// is reached
for (label i=start; i < cellList.size(); i++)
{
if (cpuTime >= cpuTimeToSend)
{
end = i;
break;
}
cpuTime += cellList[i].cpuTime();
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>
::updateProcessorBalancing()
{
// Number of processors
const scalar numProcs = Pstream::nProcs();
auto sortedCpuTimeOnProcessors = getSortedCPUTimesOnProcessor();
// calculate average time spent on each cpu
scalar averageCpuTime = 0;
forAll(sortedCpuTimeOnProcessors,i)
{
averageCpuTime += sortedCpuTimeOnProcessors[i].first;
}
averageCpuTime /= numProcs;
// list of the distributed load for all processors
List<DynamicList<sendDataStruct>> distributedLoadAllProcs(numProcs);
// list of processors to receive data from
List<DynamicList<label>> receiveDataFromProc(numProcs);
// balance the load by calculating the percentages to be send
forAll(sortedCpuTimeOnProcessors,i)
{
const label procI = sortedCpuTimeOnProcessors[i].second.first();
// List of processors to send information to
DynamicList<sendDataStruct>& sendLoadList =
distributedLoadAllProcs[procI];
// Reserve space
sendLoadList.reserve
(
std::floor(0.5*(numProcs-i))
);
const scalar cpuTimeProcI = sortedCpuTimeOnProcessors[i].first;
scalar cpuTimeOverhead = cpuTimeProcI - averageCpuTime;
// Loop over the other processors and distribute the load
// in reverse order
for (label k=numProcs-1; k > 0; k--)
{
const label procK = sortedCpuTimeOnProcessors[k].second.first();
const scalar cpuTimeProcK = sortedCpuTimeOnProcessors[k].first;
const scalar capacityOfProcK = averageCpuTime - cpuTimeProcK;
if (capacityOfProcK <= 0)
continue;
const scalar newCapacity = capacityOfProcK - cpuTimeOverhead;
// Only send information to procK if it is larger than 2% of the
// total average cell time
if
(
(std::min(capacityOfProcK,cpuTimeOverhead)/cpuTimeProcI)
< minFractionOfCellsToSend_
)
continue;
if (newCapacity > 0)
{
// add the cpuTimeOverhead to the load of this processor
sortedCpuTimeOnProcessors[k].first += cpuTimeOverhead;
sortedCpuTimeOnProcessors[i].first -= cpuTimeOverhead;
// Processor procI sends information to procK
// Therefore the receive data list of procK has to be updated
receiveDataFromProc[procK].reserve(0.5*numProcs);
receiveDataFromProc[procK].append(procI);
sendLoadList.append
(
sendDataStruct
(
cpuTimeOverhead/cpuTimeProcI,
procK
)
);
cpuTimeOverhead = 0;
break;
}
else
{
sortedCpuTimeOnProcessors[k].first += capacityOfProcK;
sortedCpuTimeOnProcessors[i].first -= capacityOfProcK;
cpuTimeOverhead -= capacityOfProcK;
// Processor procI sends information to procK
// Therefore the receive data list of procK has to be updated
receiveDataFromProc[procK].reserve(0.5*numProcs);
receiveDataFromProc[procK].append(procI);
sendLoadList.append
(
sendDataStruct
(
capacityOfProcK/cpuTimeProcI,
sortedCpuTimeOnProcessors[k].second.first()
)
);
}
}
}
sendAndReceiveData_.first() = distributedLoadAllProcs[Pstream::myProcNo()];
sendAndReceiveData_.second() = receiveDataFromProc[Pstream::myProcNo()];
// Create send and receive lists
sendToProcessor_.resize(Pstream::nProcs());
receiveFromProcessor_.resize(Pstream::nProcs());
// Set all to false
forAll(sendToProcessor_,i)
{
sendToProcessor_[i] = false;
receiveFromProcessor_[i] = false;
}
for (auto& sendInfoData : sendAndReceiveData_.first())
{
sendToProcessor_[sendInfoData.toProc] = true;
}
for (label procID : sendAndReceiveData_.second())
{
receiveFromProcessor_[procID] = true;
}
}
template<class ReactionThermo, class ThermoType>
Foam::List<std::pair<scalar,Foam::Pair<label>>>
Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>
::getSortedCPUTimesOnProcessor() const
{
// Number of processors
const scalar numProcs = Pstream::nProcs();
// Gather the data from all processors
List<scalar> cpuTimeOnProcessors(numProcs);
cpuTimeOnProcessors[Pstream::myProcNo()] = totalCpuTime_;
Pstream::gatherList(cpuTimeOnProcessors);
Pstream::scatterList(cpuTimeOnProcessors);
// use std::pair for std::sort algorithm
List<std::pair<scalar,Pair<label>>> sortedCpuTimeOnProcessors(numProcs);
forAll(sortedCpuTimeOnProcessors,i)
{
sortedCpuTimeOnProcessors[i].first = cpuTimeOnProcessors[i];
sortedCpuTimeOnProcessors[i].second.first() = i;
sortedCpuTimeOnProcessors[i].second.second() = cellsOnProcessors_[i];
}
// sort using std::sort()
// first entry has largest cpu time --> descending order
std::stable_sort
(
sortedCpuTimeOnProcessors.begin(),
sortedCpuTimeOnProcessors.end(),
std::greater<std::pair<scalar,Pair<label>>>()
);
return sortedCpuTimeOnProcessors;
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>
::updateTotalCpuTime
(
const DynamicList<baseDataContainer>& reactCellList
)
{
// Calculate the total time spent solving the particles on this processor
totalCpuTime_ = 0;
for (const auto& obj : reactCellList)
totalCpuTime_ += obj.cpuTime();
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>::solveCell
(
baseDataContainer& cellData
)
{
if (cellData.T() > this->Treact_)
{
// We can use here the specieThermo at any processor
// as the weight of a specie is static and the same on each processor
auto& Y = cellData.Y();
scalarField c0(this->nSpecie_);
for (label i=0; i<this->nSpecie_; i++)
{
this->c_[i] = cellData.rho()*Y[i]/this->specieThermo_[i].W();
c0[i] = this->c_[i];
}
// Initialise time progress
scalar timeLeft = cellData.deltaT();
// Calculate the chemical source terms
while (timeLeft > SMALL)
{
scalar dt = timeLeft;
this->solve
(
this->c_,
cellData.T(),
cellData.p(),
dt,
cellData.deltaTChem()
);
timeLeft -= dt;
}
cellData.deltaTChem() =
min(cellData.deltaTChem(), this->deltaTChemMax_);
for (label i=0; i<this->nSpecie_; i++)
{
cellData.RR()[i] =
(this->c_[i] - c0[i])
* this->specieThermo_[i].W()/cellData.deltaT();
}
}
else
{
for (label i=0; i<this->nSpecie_; i++)
{
cellData.RR()[i] = 0;
}
}
}
template<class ReactionThermo, class ThermoType>
void Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>::solveCellList
(
UList<baseDataContainer>& cellList
)
{
for(baseDataContainer& cellData : cellList)
{
// We cannot use here cpuTimeIncrement() of OpenFOAM as this
// returns only measurements in 100Hz or 1000Hz intervals depending
// on the installed kernel
auto start = std::chrono::high_resolution_clock::now();
solveCell
(
cellData
);
auto end = std::chrono::high_resolution_clock::now();
auto duration =
(std::chrono::duration_cast<std::chrono::microseconds>(end-start));
// Add the time required to solve this cell to the list
// as seconds
cellData.cpuTime() = duration.count()*1.0E-6;
}
}
template<class ReactionThermo, class ThermoType>
template<class DeltaTType>
Foam::scalar Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>::solve
(
const DeltaTType& deltaT
)
{
BasicChemistryModel<ReactionThermo>::correct();
scalar deltaTMin = GREAT;
if (!this->chemistry_)
{
return deltaTMin;
}
// In the first iteration the cpuTimePerParticle_ is not yet set and
// time statistics have to be gathered first
if (firstTime_)
{
// First create the local cell list
buildCellDataList(deltaT);
solveCellList(cellDataList_);
// Update the cell values
forAll(cellDataList_,celli)
{
#ifdef FULLDEBUG
if (cellDataList_[celli].cellID() != celli)
FatalError << "cellID of cellDataList is "
<< cellDataList_[celli].cellID() << " and does not "
<< "match " << celli << exit(FatalError);
#endif
auto& cellData = cellDataList_[celli];
this->deltaTChem_[celli] = cellData.deltaTChem();
// Copy over the results
deltaTMin = min(this->deltaTChem_[celli], deltaTMin);
this->deltaTChem_[celli] =
min(this->deltaTChem_[celli], this->deltaTChemMax_);
for (label i=0; i<this->nSpecie_; i++)
{
this->RR_[i][celli] = cellData.RR()[i];
}
}
updateTotalCpuTime(cellDataList_);
firstTime_=false;
return deltaTMin;
}
// If it is not the first time, the cellDataList has to be updated
updateCellDataList(deltaT);
// Get percentage of particles to send/receive from other processors
if (iter_++ >= maxIterUpdate_)
{
updateProcessorBalancing();
iter_ = 0;
}
List<sendDataStruct>& sendDataInfo = sendAndReceiveData_.first();
const List<label>& recvProc = sendAndReceiveData_.second();
// indices of the reactCellList to create the sub lists to send
label start = 0;
// Send all particles
for (auto& sendDataInfoI : sendDataInfo)
{
const scalar percToSend = sendDataInfoI.percToSend;
const label toProc = sendDataInfoI.toProc;
label end = cellDataList_.size();
cellsToSend
(
cellDataList_,
totalCpuTime_*percToSend,
start,
end
);
// send particles
UOPstream toBuffer
(
pBufs_.commsType(),
toProc,
pBufs_.sendBuffer(toProc),
pBufs_.tag(),
pBufs_.comm(),
false
);
label dataSize = end - start;
toBuffer << dataSize;
for (label i=start; i < end; i++)
{
toBuffer << cellDataList_[i];
}
start = end;
}
// Set local to compute particle list
SubList<baseDataContainer> localToComputeParticles
(
cellDataList_,
cellDataList_.size()-start,
start
);
// Exchange data and set send/recv relationship
pBufs_.finishedSends(sendToProcessor_,receiveFromProcessor_);
DynamicList<baseDataContainer> processorCells;
List<label> receivedDataSizes(recvProc.size());
// Read the received information
forAll(recvProc,i)
{
label receiveBufferPosition=0;
label procI = recvProc[i];
UIPstream fromBuffer
(
pBufs_.commsType(),
procI,
pBufs_.recvBuffer(procI),
receiveBufferPosition,
pBufs_.tag(),
pBufs_.comm(),
false
);
label dataSize;
fromBuffer >> dataSize;
receivedDataSizes[i] = dataSize;
processorCells.reserve(processorCells.size()+dataSize);
for (label k=0; k < dataSize; k++)
{
baseDataContainer p(fromBuffer);
processorCells.append(std::move(p));
}
}
// Start solving local to compute particles
solveCellList(localToComputeParticles);
// Solve the chemistry on processor particles
solveCellList(processorCells);
// Send the information back
// Note: Now the processors to which we originally had send informations
// are the ones we receive from and vice versa
pBufs_.switchSendRecv();
label pI = 0;
forAll(recvProc,i)
{
label procI = recvProc[i];
UOPstream toBuffer
(
pBufs_.commsType(),
procI,
pBufs_.sendBuffer(procI),
pBufs_.tag(),
pBufs_.comm(),
false
);
toBuffer << receivedDataSizes[i];
for (label k=0; k < receivedDataSizes[i]; k++)
toBuffer << processorCells[pI++];
}
pBufs_.finishedSends();
start = 0;
// Receive the particles --> now the sendDataInfo becomes the receive info
for (auto& sendDataInfoI : sendDataInfo)
{
const label fromProc = sendDataInfoI.toProc;
// send particles
label receiveBufferPosition=0;
label dataSize;
UIPstream fromBuffer
(
pBufs_.commsType(),
fromProc,
pBufs_.recvBuffer(fromProc),
receiveBufferPosition,
pBufs_.tag(),
pBufs_.comm(),
false
);
fromBuffer >> dataSize;
label end = start + dataSize;
for (label i=start; i < end; i++)
fromBuffer >> cellDataList_[i];
start = end;
}
// Switch sendAndRecv back
pBufs_.switchSendRecv();
// Update the cell values
forAll(cellDataList_,celli)
{
#ifdef FULLDEBUG
if (cellDataList_[celli].cellID() != celli)
FatalError << "cellID of cellDataList is "
<< cellDataList_[celli].cellID() << " and does not "
<< "match " << celli << exit(FatalError);
#endif
auto& cellData = cellDataList_[celli];
this->deltaTChem_[celli] = cellData.deltaTChem();
// Copy over the results
deltaTMin = min(this->deltaTChem_[celli], deltaTMin);
this->deltaTChem_[celli] =
min(this->deltaTChem_[celli], this->deltaTChemMax_);
for (label i=0; i<this->nSpecie_; i++)
{
this->RR_[i][celli] = cellData.RR()[i];
}
}
updateTotalCpuTime(cellDataList_);
return deltaTMin;
}
template<class ReactionThermo, class ThermoType>
Foam::scalar Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>::solve
(
const scalar deltaT
)
{
// Don't allow the time-step to change more than a factor of 2
return min
(
this->solve<UniformField<scalar>>(UniformField<scalar>(deltaT)),
2*deltaT
);
}
template<class ReactionThermo, class ThermoType>
Foam::scalar Foam::LoadBalancedChemistryModel<ReactionThermo, ThermoType>::solve
(
const scalarField& deltaT
)
{
return this->solve<scalarField>(deltaT);
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistryModel/LoadBalancedChemistryModel/makeLoadBalancedChemistryModels.C | .C | 6,123 | 276 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Generates the chemistry models
\*---------------------------------------------------------------------------*/
#include "makeChemistryModel.H"
#include "psiReactionThermo.H"
#include "rhoReactionThermo.H"
#include "LoadBalancedChemistryModel.H"
#include "thermoPhysicsTypes.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Chemistry moldels based on sensibleEnthalpy
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
gasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constIncompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
incompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
icoPoly8HThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constAdiabaticFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
gasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constIncompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
incompressibleGasHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
icoPoly8HThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constAdiabaticFluidHThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constHThermoPhysics
);
// Chemistry moldels based on sensibleInternalEnergy
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
gasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constIncompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
incompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
icoPoly8EThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constAdiabaticFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
psiReactionThermo,
constEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
gasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constIncompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
incompressibleGasEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
icoPoly8EThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constAdiabaticFluidEThermoPhysics
);
makeChemistryModelType
(
LoadBalancedChemistryModel,
rhoReactionThermo,
constEThermoPhysics
);
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/chemistryModel/LoadBalancedChemistryModel/LoadBalancedChemistryModel.H | .H | 8,189 | 259 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::LoadBalancedChemistryModel
Description
Extends the StandardChemistryModel with load balancing of the reation.
SourceFiles
LoadBalancedChemistryModel.H
LoadBalancedChemistryModel.C
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#ifndef LoadBalancedChemistryModel_H
#define LoadBalancedChemistryModel_H
#include "StandardChemistryModel.H"
#include "baseDataContainer.H"
#include "pointToPointBuffer.H"
#include "OFstream.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class LoadBalancedChemistryModel Declaration
\*---------------------------------------------------------------------------*/
template<class ReactionThermo, class ThermoType>
class LoadBalancedChemistryModel
:
public StandardChemistryModel<ReactionThermo, ThermoType>
{
public:
// Struct to store the information required for sending cells to other
// processors
struct sendDataStruct
{
public:
// processor to send information to
label toProc=-1;
// percent of own cells to send to processor toProc
scalar percToSend=-1;
// Constructor
sendDataStruct() = default;
sendDataStruct(scalar perc, label procId)
: toProc(procId),percToSend(perc)
{}
};
private:
// Private Member Variables
//- Minimum percent of cells to send to processors
// Only processors that would receive more the n-percent of cells
// are considered for load balancing
// --> Value is given as absolute fraction, not in percent!
// Default value is: 0.02
scalar minFractionOfCellsToSend_;
//- List to store the cell information in the baseDataContainer
DynamicList<baseDataContainer> cellDataList_;
//- Get list of cells on each processor
List<label> cellsOnProcessors_;
//- Switch to check if it is called the first time in the simulation
bool firstTime_{true};
//- Total cpu time on all processors
scalar totalCpuTime_;
//- Store processor balancing data, first entry is a list of sendData
// information, second entry is a list of processor IDs of which
// data is received
Tuple2
<
List<sendDataStruct>,
List<label>
>
sendAndReceiveData_;
//- List of size Pstream::nProcs() which is true if data is send to
List<bool> sendToProcessor_;
//- List of size Pstream::nProcs() which is true if data is received
//- from processor
List<bool> receiveFromProcessor_;
//- Needs to keep the buffer alive to not loose the information
// about send and receive sizes
pointToPointBuffer pBufs_;
//- Index of current iteration until the send/recv cell information
// is updated
label iter_;
//- Number of iterations till send/recv is updated
label maxIterUpdate_;
// Private Member Functions
//- Build the baseDataContainer list from the cells
template<class DeltaTType>
void buildCellDataList(const DeltaTType&);
//- Update teh cellDataList with new cell values
template<class DeltaTType>
void updateCellDataList(const DeltaTType&);
//- Calculate the cells to send/recv to/from other
//- processors
// Returns a list of sublists of cells to send to processor i
void cellsToSend
(
const DynamicList<baseDataContainer>& cellList,
const scalar cpuTimeToSend,
const label& start,
label& end
);
//- Get percentage of processor data to send to other processors
//- to balance the processor load
void updateProcessorBalancing();
//- Get cpu times of each processor in a descending order
// Format:
// List[index].first: CPU time required for last time step
// List[index].second: Returns an Foam::Pair<label> with
// Pair.first(): processor ID
// Pair.second(): Number of particles on
// that processor
List<std::pair<scalar,Pair<label>>>
getSortedCPUTimesOnProcessor() const;
//- Update the totalCpuTime_ variable
void updateTotalCpuTime
(
const DynamicList<baseDataContainer>& reactParList
);
//- solve the reaction for all cells in the given list
void solveCellList
(
UList<baseDataContainer>& cellList
);
//- Solve chemistry for once cell
void solveCell(baseDataContainer& cellData);
//- Solve the reaction system for the given time step
// of given type and return the characteristic time
template<class DeltaTType>
scalar solve(const DeltaTType& deltaT);
public:
//- Runtime type information
TypeName("LoadBalancedChemistryModel");
// Constructors
//- No copy construct
LoadBalancedChemistryModel(const LoadBalancedChemistryModel&) = delete;
//- No copy assignment
void operator=(const LoadBalancedChemistryModel&) = delete;
//- Construct from thermo
LoadBalancedChemistryModel(ReactionThermo& thermo);
//- Destructor
virtual ~LoadBalancedChemistryModel() {};
//- Solve the reaction system for the given time step with load
// balancing and return the characteristic time
virtual scalar solve(const scalar deltaT);
//- Solve the reaction system for the given time step with load
// balancing and return the characteristic time
virtual scalar solve(const scalarField& deltaT);
//- Access the stored cell data
DynamicList<baseDataContainer>& cellDataList()
{
return cellDataList_;
}
//- Const access the stored cell data
const DynamicList<baseDataContainer>& cellDataList() const
{
return cellDataList_;
}
// ODE functions (overriding abstract functions in ODE.H)
virtual void solve
(
scalarField &c,
scalar& T,
scalar& p,
scalar& deltaT,
scalar& subDeltaT
) const = 0;
};
} // End of namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
#include "LoadBalancedChemistryModel.C"
#endif
#endif
| Unknown |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/pointToPointBuffer/pointToPointBuffer.C | .C | 7,605 | 270 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#include "pointToPointBuffer.H"
void Foam::pointToPointBuffer::update()
{
forAll(sendBufferList_,procI)
{
sendBufferSize_[procI] = sendBufferList_[procI].byteSize();
}
recvBufferSize_.resize_nocopy(sendBufferSize_.size());
// Use UPstream::allToAll as it is used in exchangeSizes()
UPstream::allToAll(sendBufferSize_, recvBufferSize_, comm_);
// Update the receive buffer sizes
forAll(recvBufferList_,procI)
{
recvBufferList_[procI].resize(recvBufferSize_[procI]);
}
}
void Foam::pointToPointBuffer::switchSendRecv()
{
List<std::streamsize> recvBufferSizeCopy = recvBufferSize_;
forAll(sendBufferSize_,procI)
{
recvBufferSize_[procI] = sendBufferSize_[procI];
sendBufferSize_[procI] = recvBufferSizeCopy[procI];
}
// Update the receive buffer sizes
forAll(recvBufferList_,procI)
{
recvBufferList_[procI].resize(recvBufferSize_[procI]);
}
}
void Foam::pointToPointBuffer::finishedSends()
{
const label startOfRequests = UPstream::nRequests();
checkBufferSize();
forAll(sendBufferSize_,procI)
{
if (recvBufferSize_[procI] > 0 && procI != Pstream::myProcNo())
{
IPstream::read
(
commsType_,
procI,
recvBufferList_[procI].data(),
recvBufferSize_[procI],
UPstream::msgType(),
comm_
);
}
}
forAll(sendBufferSize_,procI)
{
if (sendBufferSize_[procI] > 0 && procI != Pstream::myProcNo())
{
OPstream::write
(
commsType_,
procI,
sendBufferList_[procI].cdata(),
sendBufferList_[procI].byteSize(),
UPstream::msgType(),
comm_
);
}
}
UPstream::waitRequests(startOfRequests);
// Clear the send buffer
forAll(sendBufferList_,procI)
{
sendBufferList_[procI].clear();
}
}
void Foam::pointToPointBuffer::finishedSends
(
const List<bool>& sendToProcessor,
const List<bool>& receiveFromProcessor
)
{
exchangeBufferSizes(sendToProcessor,receiveFromProcessor);
const label startOfRequests = UPstream::nRequests();
checkBufferSize();
forAll(sendBufferSize_,procI)
{
if (recvBufferSize_[procI] > 0 && procI != Pstream::myProcNo())
{
IPstream::read
(
commsType_,
procI,
recvBufferList_[procI].data(),
recvBufferSize_[procI],
UPstream::msgType(),
comm_
);
}
}
forAll(sendBufferSize_,procI)
{
if (sendBufferSize_[procI] > 0 && procI != Pstream::myProcNo())
{
OPstream::write
(
commsType_,
procI,
sendBufferList_[procI].cdata(),
sendBufferList_[procI].byteSize(),
UPstream::msgType(),
comm_
);
}
}
UPstream::waitRequests(startOfRequests);
// Clear the send buffer
forAll(sendBufferList_,procI)
{
sendBufferList_[procI].clear();
}
}
void Foam::pointToPointBuffer::checkBufferSize()
{
forAll(sendBufferSize_,procI)
{
if (sendBufferList_[procI].byteSize() != sendBufferSize_[procI])
FatalError
<< "sendBufferSize "<<sendBufferList_[procI].byteSize()
<< " for processor "<<procI
<< " does not match " << sendBufferSize_[procI] << ". Consider "
<< "calling update() to set the new buffer sizes"
<< exit(FatalError);
if (recvBufferList_[procI].byteSize() != recvBufferSize_[procI])
FatalError
<< "recvBufferSize "<<recvBufferList_[procI].byteSize()
<< " for processor "<<procI
<< " does not match " << recvBufferSize_[procI] << ". Consider "
<< "calling update() to set the new buffer sizes"
<< exit(FatalError);
}
}
void Foam::pointToPointBuffer::exchangeBufferSizes
(
const List<bool>& sendToProcessor,
const List<bool>& receiveFromProcessor
)
{
const label startOfRequests = UPstream::nRequests();
// Update the sendBufferSizes based on the current buffers
forAll(sendBufferSize_,procI)
{
sendBufferSize_[procI] = sendBufferList_[procI].byteSize();
}
recvBufferSize_.resize_nocopy(sendBufferSize_.size());
// Fill with zero
std::fill(recvBufferSize_.begin(),recvBufferSize_.end(),0);
// Create temporary receive buffer
List<List<char>> recvBuffer(Pstream::nProcs());
for (auto& e : recvBuffer)
e.resize(sizeof(std::streamsize));
forAll(recvBufferSize_,procI)
{
if (receiveFromProcessor[procI] && procI != Pstream::myProcNo())
{
IPstream::read
(
commsType_,
procI,
recvBuffer[procI].data(),
sizeof(std::streamsize),
UPstream::msgType(),
comm_
);
}
}
forAll(sendBufferSize_,procI)
{
if (sendToProcessor[procI] && procI != Pstream::myProcNo())
{
sendBufferSize_[procI] = sendBufferList_[procI].byteSize();
OPstream::write
(
commsType_,
procI,
reinterpret_cast<char*>(&sendBufferSize_[procI]),
sizeof(std::streamsize),
UPstream::msgType(),
comm_
);
}
}
UPstream::waitRequests(startOfRequests);
forAll(recvBufferSize_,procI)
{
if (receiveFromProcessor[procI] && procI != Pstream::myProcNo())
{
std::streamsize* ptr =
reinterpret_cast<std::streamsize*>(recvBuffer[procI].data());
recvBufferSize_[procI] = *ptr;
}
}
// Update the receive buffer sizes
forAll(recvBufferList_,procI)
{
recvBufferList_[procI].resize(recvBufferSize_[procI]);
}
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/pointToPointBuffer/pointToPointBuffer.H | .H | 4,877 | 158 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::pointToPointBuffer
Description
Provides a buffer for inter-processor communication which only exchanges
sizes if the update() function is called. Otherwise the buffer sizes are
fixed, and no MPI_allToAll is required. In the OpenFOAM PstreamBuffers the
sizes are exchanged for each finishedSends which requires an allToAll
communication. Especially for large scale operations this is expansive.
This is closer to the processorLduInterface class than PstreamBuffers.
SourceFiles
pointToPointBuffer.C
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#ifndef pointToPointBuffer_H
#define pointToPointBuffer_H
#include "fvCFD.H"
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class pointToPointBuffer
\*---------------------------------------------------------------------------*/
class pointToPointBuffer
{
protected:
// Protected Member Variables
//- Send buffer list
// Size of list is Pstream::nProcs()
List<DynamicList<char>> sendBufferList_;
//- Receive buffer list
List<DynamicList<char>> recvBufferList_;
//- Store the size of the buffer
List<std::streamsize> sendBufferSize_;
List<std::streamsize> recvBufferSize_;
//- Always non-blocking communication
const UPstream::commsTypes commsType_;
//- World communicator
const label comm_;
// Protected Member Functions
//- Check that the buffer is the expected size
void checkBufferSize();
//- Echange the send/recv buffer sizes based on the given send
// and receive lists
void exchangeBufferSizes
(
const List<bool>& sendToProcessor,
const List<bool>& receiveFromProcessor
);
public:
pointToPointBuffer()
:
sendBufferList_(Pstream::nProcs()),
recvBufferList_(Pstream::nProcs()),
sendBufferSize_(Pstream::nProcs()),
recvBufferSize_(Pstream::nProcs()),
commsType_(Pstream::commsTypes::nonBlocking),
comm_(UPstream::worldComm)
{};
// Modify
//- Update the send and receive buffers based on the current
// sendBufferList
void update();
//- Exchange all information
// Requires update() to be called if the buffer changed
void finishedSends();
//- Send the buffers to the processors defined by sendToProcessor
// and receiveFromProcessor
// Uses exchangeBufferSizes
void finishedSends
(
const List<bool>& sendToProcessor,
const List<bool>& receiveFromProcessor
);
//- Switch send and receive buffer sizes
// Helps for cases when data is send for computation and then received
// again
void switchSendRecv();
// Access
//- Return the recv buffer for procI
DynamicList<char>& recvBuffer(const label procI)
{return recvBufferList_[procI];}
// Return the send buffer for procI
DynamicList<char>& sendBuffer(const label procI)
{return sendBufferList_[procI];}
//- Return the communication type
const UPstream::commsTypes& commsType() {return commsType_;}
//- Return the tag
const int& tag() {return UPstream::msgType();}
//- Return communicator world
const label& comm() {return comm_;}
};
} // End of namespace Foam
#endif
| Unknown |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/dataContainer/baseDataContainer/baseDataContainer.H | .H | 6,280 | 220 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::baseDataContainer
Description
Data container to store the species, pressure, and temperature information
of cells for processor streaming with Pstream.
SourceFiles
baseDataContainer.C
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2022
\*---------------------------------------------------------------------------*/
#ifndef baseDataContainer_H
#define baseDataContainer_H
#include "fvCFD.H"
#include "Ostream.H"
#include "Istream.H"
namespace Foam
{
/*---------------------------------------------------------------------------*\
IO Functions required for Parallel Handling
\*---------------------------------------------------------------------------*/
class baseDataContainer;
// Read and write the eulerian fields data class
Istream& operator >> (Istream& is, baseDataContainer& eField);
Ostream& operator << (Ostream& os, const baseDataContainer& eField);
// When comparing baseDataContainer always return untrue as otherwise all
// fields have to be checked
// --> This operation is only needed to write out a list of baseDataContainer
// which checks for uniform list entries
inline bool operator==(const baseDataContainer& e1, const baseDataContainer& e2)
{
return false;
}
inline bool operator!=(const baseDataContainer& e1, const baseDataContainer& e2)
{
return true;
}
/*---------------------------------------------------------------------------*\
Class baseDataContainer
\*---------------------------------------------------------------------------*/
// Base struct to store the eulerian field properties for each particle
class baseDataContainer
{
protected:
//- List of species
List<scalar> Y_;
//- Store the computed reaction rate
List<scalar> RR_;
//- Temperature
scalar T_;
//- Pressure
scalar p_;
//- Density
scalar rho_;
//- Time deltaT
scalar deltaT_;
//- Chemical time scale
scalar deltaTChem_;
//- cpu time required for computation - default init to zero
scalar cpuTime_{0};
//- Store processor ID
label procID_;
//- Label of cellID
label cellID_;
//- Is it a local particle
// set to false if transferred
bool local_{true};
public:
baseDataContainer() = default;
//- Construct with given size for lists
baseDataContainer
(
const label nSpecies
)
:
Y_(nSpecies),
RR_(nSpecies)
{};
//- Construct from input stream
baseDataContainer(Istream& is);
// Functions for IO operations
//- Read baseDataContainer from stream
Istream& read(Istream& is);
//- Write baseDataContainer to stream
Ostream& write(Ostream& os) const;
// Modify
//- Return species
List<scalar>& Y() {return Y_;}
//- Return reaction rate
List<scalar>& RR() {return RR_;}
//- Access the temperature information
scalar& T() {return T_;}
//- Access the pressure information
scalar& p() {return p_;}
//- Access the density
scalar& rho() {return rho_;}
//- Access deltaT
scalar& deltaT() {return deltaT_;}
//- Access deltaTChem()
scalar& deltaTChem() {return deltaTChem_;}
//- Access processor ID
label& proc() {return procID_;}
//- Access cpu time
scalar& cpuTime() {return cpuTime_;}
//- Acess cellID
label& cellID() {return cellID_;}
// Const Access
//- Return species
const List<scalar>& Y() const {return Y_;}
//- Return reaction rate
const List<scalar>& RR() const {return RR_;}
//- Access the temperature information
const scalar& T() const {return T_;}
//- Access the pressure information
const scalar& p() const {return p_;}
//- Access the density
const scalar& rho() const {return rho_;}
//- Access deltaT
const scalar& deltaT() const {return deltaT_;}
//- Access deltaTChem()
const scalar& deltaTChem() const {return deltaTChem_;}
//- Access processor ID
const label& proc() const {return procID_;}
//- Access cpu time
const scalar& cpuTime() const {return cpuTime_;}
//- Acess cellID
const label& cellID() const {return cellID_;}
// Check if container had been streamed
//- check if the container is local
inline bool& local() {return local_;}
//- Const access if it is a local container
inline const bool& local() const {return local_;}
};
} // End of namespace Foam
#endif
| Unknown |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/dataContainer/baseDataContainer/baseDataContainer.C | .C | 2,683 | 100 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "baseDataContainer.H"
// * * * * * * * * * * * * * * * * Constructor * * * * * * * * * * * * * * * *
Foam::baseDataContainer::baseDataContainer(Istream& is)
{
read(is);
}
// * * * * * * * * * * * * * * * IO Functions * * * * * * * * * * * * * * * * *
Foam::Istream& Foam::baseDataContainer::read
(
Istream& is
)
{
Y_.clear();
RR_.clear();
// Read scalar lists
is >> Y_;
is >> RR_;
// Read scalars
is >> T_;
is >> p_;
is >> rho_;
is >> deltaT_;
is >> deltaTChem_;
is >> cpuTime_;
is >> procID_;
is >> cellID_;
is >> local_;
return is;
}
Foam::Ostream& Foam::baseDataContainer::write
(
Ostream& os
) const
{
// When the particle container is transferred or written it is no longer
// local
bool localParticle = false;
os << Y_ << token::SPACE
<< RR_ << token::SPACE
<< T_ << token::SPACE
<< p_ << token::SPACE
<< rho_ << token::SPACE
<< deltaT_ << token::SPACE
<< deltaTChem_ << token::SPACE
<< cpuTime_ << token::SPACE
<< procID_ << token::SPACE
<< cellID_ << token::SPACE
<< localParticle << endl;
return os;
}
Foam::Istream& Foam::operator >>(Istream& is, baseDataContainer& eField)
{
return eField.read(is);
}
Foam::Ostream& Foam::operator <<(Ostream& os, const baseDataContainer& eField)
{
return eField.write(os);
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/dataContainer/TDACDataContainer/TDACDataContainer.H | .H | 7,136 | 246 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::TDACDataContainer
Description
Data container to store the species, pressure, and temperature information
of cells for processor streaming with Pstream.
SourceFiles
TDACDataContainer.C
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#ifndef TDACDataContainer_H
#define TDACDataContainer_H
#include "fvCFD.H"
#include "Ostream.H"
#include "Istream.H"
namespace Foam
{
/*---------------------------------------------------------------------------*\
IO Functions required for Parallel Handling
\*---------------------------------------------------------------------------*/
class TDACDataContainer;
// Read and write the eulerian fields data class
Istream& operator >> (Istream& is, TDACDataContainer& eField);
Ostream& operator << (Ostream& os, const TDACDataContainer& eField);
// When comparing TDACDataContainer always return untrue as otherwise all
// fields have to be checked
// --> This operation is only needed to write out a list of TDACDataContainer
// which checks for uniform list entries
inline bool operator==(const TDACDataContainer& e1, const TDACDataContainer& e2)
{
return false;
}
inline bool operator!=(const TDACDataContainer& e1, const TDACDataContainer& e2)
{
return true;
}
/*---------------------------------------------------------------------------*\
Class TDACDataContainer
\*---------------------------------------------------------------------------*/
// Base struct to store the eulerian field properties for each particle
class TDACDataContainer
{
protected:
//- Composition vector (Y, T, p)
Field<scalar> phiq_;
//- Concentration
Field<scalar> c_;
//- Concentration prior solving
Field<scalar> c0_;
//- Temperature
scalar T_;
//- Pressure
scalar p_;
//- Density
scalar rho_;
//- Time deltaT
scalar deltaT_;
//- Chemical time scale
scalar deltaTChem_;
//- cpu time required for computation - default init to zero
scalar cpuTime_{0};
//- Store the time required to add the cell to the table
mutable scalar addToTableCpuTime_{0};
//- Store processor ID
label procID_;
//- Label of cellID
label cellID_;
//- Is it a local particle
// set to false if transferred
bool local_{true};
public:
TDACDataContainer() = default;
//- Construct with given size for lists
TDACDataContainer
(
const label nSpecies,
const label nAdditions
)
:
phiq_(nSpecies+nAdditions),
c_(nSpecies),
c0_(nSpecies)
{};
//- Construct from input stream
TDACDataContainer(Istream& is);
// Functions for IO operations
//- Read TDACDataContainer from stream
Istream& read(Istream& is);
//- Write TDACDataContainer to stream
Ostream& write(Ostream& os) const;
// Modify
//- Return species
Field<scalar>& phiq() {return phiq_;}
//- Return concentration
Field<scalar>& c() {return c_;}
//- Return old concentration
Field<scalar>& c0() {return c0_;}
//- Access the temperature information
scalar& T() {return T_;}
//- Access the pressure information
scalar& p() {return p_;}
//- Access the density
scalar& rho() {return rho_;}
//- Access deltaT
scalar& deltaT() {return deltaT_;}
//- Access deltaTChem()
scalar& deltaTChem() {return deltaTChem_;}
//- Access processor ID
label& proc() {return procID_;}
//- Access cpu time
scalar& cpuTime() {return cpuTime_;}
//- Add cell to table cpu time
scalar& addToTableCpuTime() {return addToTableCpuTime_;}
//- Acess cellID
label& cellID() {return cellID_;}
// Const Access
//- Return species
const Field<scalar>& phiq() const {return phiq_;}
//- Return concentration
const Field<scalar>& c() const {return c_;}
//- Return old concentration
const Field<scalar>& c0() const {return c0_;}
//- Access the temperature information
const scalar& T() const {return T_;}
//- Access the pressure information
const scalar& p() const {return p_;}
//- Access the density
const scalar& rho() const {return rho_;}
//- Access deltaT
const scalar& deltaT() const {return deltaT_;}
//- Access deltaTChem()
const scalar& deltaTChem() const {return deltaTChem_;}
//- Access processor ID
const label& proc() const {return procID_;}
//- Access cpu time
const scalar& cpuTime() const {return cpuTime_;}
//- Add cell to table cpu time
const scalar& addToTableCpuTime() const {return addToTableCpuTime_;}
//- Acess cellID
const label& cellID() const {return cellID_;}
//- Set CPU time
void setAddToTableCpuTime(const scalar time) const
{
addToTableCpuTime_ = time;
}
// Check if container had been streamed
//- check if the container is local
inline bool& local() {return local_;}
//- Const access if it is a local container
inline const bool& local() const {return local_;}
};
} // End of namespace Foam
#endif
| Unknown |
2D | ITV-Stuttgart/loadBalancedChemistryModel | src/dataContainer/TDACDataContainer/TDACDataContainer.C | .C | 2,826 | 105 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "TDACDataContainer.H"
// * * * * * * * * * * * * * * * * Constructor * * * * * * * * * * * * * * * *
Foam::TDACDataContainer::TDACDataContainer(Istream& is)
{
read(is);
}
// * * * * * * * * * * * * * * * IO Functions * * * * * * * * * * * * * * * * *
Foam::Istream& Foam::TDACDataContainer::read
(
Istream& is
)
{
phiq_.clear();
c_.clear();
c0_.clear();
// Read scalar lists
is >> phiq_;
is >> c_;
is >> c0_;
// Read scalars
is >> T_;
is >> p_;
is >> rho_;
is >> deltaT_;
is >> deltaTChem_;
is >> cpuTime_;
is >> addToTableCpuTime_;
is >> procID_;
is >> cellID_;
is >> local_;
return is;
}
Foam::Ostream& Foam::TDACDataContainer::write
(
Ostream& os
) const
{
// When the particle container is transferred or written it is no longer
// local
bool localParticle = false;
os << phiq_ << token::SPACE
<< c_ << token::SPACE
<< c0_ << token::SPACE
<< T_ << token::SPACE
<< p_ << token::SPACE
<< rho_ << token::SPACE
<< deltaT_ << token::SPACE
<< deltaTChem_ << token::SPACE
<< cpuTime_ << token::SPACE
<< addToTableCpuTime_ << token::SPACE
<< procID_ << token::SPACE
<< cellID_ << token::SPACE
<< localParticle << endl;
return os;
}
Foam::Istream& Foam::operator >>(Istream& is, TDACDataContainer& eField)
{
return eField.read(is);
}
Foam::Ostream& Foam::operator <<(Ostream& os, const TDACDataContainer& eField)
{
return eField.write(os);
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | tests/src/main.C | .C | 4,013 | 117 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Custom main function for Catch2 to provide serial and parallel runs
Switch between serial and parallel using the -p or --parallel flag
e.g:
# Run in serial
./unitTest
# Run in parallel
mpirun -np 8 ./unitTest -p
Originally written for the movingAverage library by Jan Gärtner 2022
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#include <catch2/catch_session.hpp>
#include <iostream>
#include "fvCFD.H"
#include "globalFoamArgs.H"
Foam::argList* argsPtr = nullptr;
int main(int argc, char* argv[])
{
Catch::Session session; // There must be exactly one instance
// Add the command line argument to switch between parallel mode
// Build a new parser on top of Catch2's
bool parallelRun = false;
std::string casePath;
using namespace Catch::Clara;
auto cli
= session.cli() // Get Catch2's command line parser
| Opt( parallelRun ) // bind variable to a new option, with
// a hint string the option
["-p"]["--parallel"] // names it will respond to
("parallel run") // description string for the help
| Opt( casePath, "casePath" ) // output bind variable to a new option,
["-case"]["--case"] // with a hint string
("provide OpenFOAM case path"); // description string for the help
// output
// Now pass the new composite back to Catch2 so it uses that
session.cli( cli );
// Let Catch2 (using Clara) parse the command line
int returnCode = session.applyCommandLine( argc, argv );
if( returnCode != 0 ) // Indicates a command line error
return returnCode;
// Create OpenFOAM arguments
// Has to be done here for MPI support
int argcOF = 1;
if (parallelRun)
argcOF++;
if (casePath.size()>0)
argcOF+=2;
//char **argvOF = static_cast<char**>(malloc(sizeof(char*)));
char* argvOF[argcOF];
char executable[] = {'p','a','r','a','l','l','e','l','T','e','s','t'};
char flags[] = "-parallel";
char caseFlag[] = "-case";
char* casePath_cStr = new char [casePath.length()+1];
std::strcpy (casePath_cStr, casePath.c_str());
argvOF[0] = executable;
if (parallelRun)
argvOF[1] = flags;
if (casePath.size()>0)
{
argvOF[argcOF-2] = caseFlag;
argvOF[argcOF-1] = casePath_cStr;
}
setFoamArgs(argcOF, argvOF);
// Start the session
const int result = session.run();
// Clean up MPI
clearFoamArgs();
return result;
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | tests/src/TDACChemistryModel-Test.C | .C | 3,508 | 105 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Test the load-balanced TDAC chemistry model by comparison to the
standard TDAC model.
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
// Includes for Catch2 unit testing framework
#include <catch2/catch_session.hpp>
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
// For global arguments
#include "globalFoamArgs.H"
// Standard C++ includes
#include <stdlib.h> /* srand, rand */
#include <vector>
#include <iostream>
// OpenFOAM includes
#include "fvCFD.H"
#include "thermoPhysicsTypes.H"
#include "psiReactionThermo.H"
#include "ode.H"
#include "LoadBalancedTDACChemistryModel.H"
TEST_CASE("TDACChemistryModel-Test","[chemistry]")
{
// =========================================================================
// Prepare Case
// =========================================================================
// Replace setRootCase.H for Catch2
Foam::argList& args = getFoamArgs();
#include "createTime.H" // create the time object
#include "createMesh.H"
// Create a thermo model
autoPtr<psiReactionThermo> pThermo(psiReactionThermo::New(mesh));
psiReactionThermo& thermo = pThermo();
thermo.validate(args.executable(), "h", "e");
// Create a typedef
using chemModelLB =
LoadBalancedTDACChemistryModel<psiReactionThermo,gasHThermoPhysics>;
using chemModelStd =
TDACChemistryModel<psiReactionThermo,gasHThermoPhysics>;
// Create the load-balanced and standard chemistry model
ode<chemModelLB> cModelLB(thermo);
ode<chemModelStd> cModelStd(thermo);
const scalar deltaT = 1E-6;
cModelLB.chemModelLB::solve(deltaT);
cModelStd.chemModelStd::solve(deltaT);
// Compare the computed reaction rate
for (label specieI=0; specieI < cModelLB.nSpecie(); specieI++)
{
auto RRLB = cModelLB.RR(specieI);
auto RRStd = cModelStd.RR(specieI);
forAll(RRLB,celli)
{
REQUIRE_THAT
(
RRLB[celli],
Catch::Matchers::WithinRel(RRStd[celli],1E-6)
);
}
}
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | tests/src/pointToPointBuffer-Test.C | .C | 7,551 | 293 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Test the pointToPointBuffer
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
// Includes for Catch2 unit testing framework
#include <catch2/catch_session.hpp>
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
// For global arguments
#include "globalFoamArgs.H"
// Standard C++ includes
#include <stdlib.h> /* srand, rand */
#include <vector>
#include <iostream>
// OpenFOAM includes
#include "fvCFD.H"
#include "pointToPointBuffer.H"
TEST_CASE("pointToPointBuffer-Test","[Pstream]")
{
// =========================================================================
// Prepare Case
// =========================================================================
// Replace setRootCase.H for Catch2
Foam::argList& args = getFoamArgs();
#include "createTime.H" // create the time object
#include "createMesh.H"
Info << "Create buffer"<<endl;
// Create a pointToPointBuffer
pointToPointBuffer pBuf;
// Test matrix requires execution with 4 cores!
// Processor 0 sends a list to processor 3 with 10 label entries
// And Processor 3 sends processor 0 a list with 5 label entries
labelList myData;
if (Pstream::myProcNo() == 0)
{
myData.resize(10);
forAll(myData,i)
{
myData[i] = 10;
}
}
else if (Pstream::myProcNo() == 3)
{
myData.resize(5);
forAll(myData,i)
{
myData[i] = 5;
}
}
// Create the UOPstream object
if (Pstream::myProcNo() == 0)
{
label toProc = 3;
UOPstream toBuffer
(
pBuf.commsType(),
toProc,
pBuf.sendBuffer(toProc),
pBuf.tag(),
pBuf.comm(),
false
);
toBuffer << myData;
}
else if (Pstream::myProcNo() == 3)
{
label toProc = 0;
UOPstream toBuffer
(
pBuf.commsType(),
toProc,
pBuf.sendBuffer(toProc),
pBuf.tag(),
pBuf.comm(),
false
);
toBuffer << myData;
}
// Update the send and receive buffers
pBuf.update();
pBuf.finishedSends();
// Now read data
// Create the UOPstream object
labelList recvData;
if (Pstream::myProcNo() == 0)
{
label fromProc = 3;
label receiveBufferPosition=0;
UIPstream fromBuffer
(
pBuf.commsType(),
fromProc,
pBuf.recvBuffer(fromProc),
receiveBufferPosition,
pBuf.tag(),
pBuf.comm(),
false
);
fromBuffer >> recvData;
REQUIRE(recvData.size() == 5);
forAll(recvData,i)
{
REQUIRE(recvData[i] == 5);
}
}
else if (Pstream::myProcNo() == 3)
{
label fromProc = 0;
label receiveBufferPosition=0;
UIPstream fromBuffer
(
pBuf.commsType(),
fromProc,
pBuf.recvBuffer(fromProc),
receiveBufferPosition,
pBuf.tag(),
pBuf.comm(),
false
);
fromBuffer >> recvData;
REQUIRE(recvData.size() == 10);
forAll(recvData,i)
{
REQUIRE(recvData[i] == 10);
}
}
// =========================================================================
// Now send again from processor 0 to 3 and 3 to 0
// But this time use double the number of entries
Info << "*** Test with exchange sizes only ***"<<endl;
if (Pstream::myProcNo() == 0)
{
myData.resize(15);
forAll(myData,i)
{
myData[i] = 15;
}
}
else if (Pstream::myProcNo() == 3)
{
myData.resize(8);
forAll(myData,i)
{
myData[i] = 8;
}
}
// Use send/recv Lists
List<bool> sendToProcessor(Pstream::nProcs(),false);
List<bool> receiveFromProcessor(Pstream::nProcs(),false);
// Create the UOPstream object
if (Pstream::myProcNo() == 0)
{
label toProc = 3;
UOPstream toBuffer
(
pBuf.commsType(),
toProc,
pBuf.sendBuffer(toProc),
pBuf.tag(),
pBuf.comm(),
false
);
toBuffer << myData;
sendToProcessor[toProc] = true;
// Here we receive from the processor we send to
receiveFromProcessor[toProc] = true;
}
else if (Pstream::myProcNo() == 3)
{
label toProc = 0;
UOPstream toBuffer
(
pBuf.commsType(),
toProc,
pBuf.sendBuffer(toProc),
pBuf.tag(),
pBuf.comm(),
false
);
toBuffer << myData;
sendToProcessor[toProc] = true;
// Here we receive from the processor we send to
receiveFromProcessor[toProc] = true;
}
pBuf.finishedSends(sendToProcessor,receiveFromProcessor);
// Now read data
// Create the UOPstream object
recvData.clear();
if (Pstream::myProcNo() == 0)
{
label fromProc = 3;
label receiveBufferPosition=0;
UIPstream fromBuffer
(
pBuf.commsType(),
fromProc,
pBuf.recvBuffer(fromProc),
receiveBufferPosition,
pBuf.tag(),
pBuf.comm(),
false
);
fromBuffer >> recvData;
REQUIRE(recvData.size() == 8);
forAll(recvData,i)
{
REQUIRE(recvData[i] == 8);
}
}
else if (Pstream::myProcNo() == 3)
{
label fromProc = 0;
label receiveBufferPosition=0;
UIPstream fromBuffer
(
pBuf.commsType(),
fromProc,
pBuf.recvBuffer(fromProc),
receiveBufferPosition,
pBuf.tag(),
pBuf.comm(),
false
);
fromBuffer >> recvData;
REQUIRE(recvData.size() == 15);
forAll(recvData,i)
{
REQUIRE(recvData[i] == 15);
}
}
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | tests/src/standardChemistryModel-Test.C | .C | 3,507 | 105 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Test the load-balanced standard chemistry model by comparison to the
standard model.
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
// Includes for Catch2 unit testing framework
#include <catch2/catch_session.hpp>
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
// For global arguments
#include "globalFoamArgs.H"
// Standard C++ includes
#include <stdlib.h> /* srand, rand */
#include <vector>
#include <iostream>
// OpenFOAM includes
#include "fvCFD.H"
#include "thermoPhysicsTypes.H"
#include "psiReactionThermo.H"
#include "ode.H"
#include "LoadBalancedChemistryModel.H"
TEST_CASE("standardChemistryModel-Test","[chemistry]")
{
// =========================================================================
// Prepare Case
// =========================================================================
// Replace setRootCase.H for Catch2
Foam::argList& args = getFoamArgs();
#include "createTime.H" // create the time object
#include "createMesh.H"
// Create a thermo model
autoPtr<psiReactionThermo> pThermo(psiReactionThermo::New(mesh));
psiReactionThermo& thermo = pThermo();
thermo.validate(args.executable(), "h", "e");
// Create a typedef
using chemModelLB =
LoadBalancedChemistryModel<psiReactionThermo,gasHThermoPhysics>;
using chemModelStd =
StandardChemistryModel<psiReactionThermo,gasHThermoPhysics>;
// Create the load-balanced and standard chemistry model
ode<chemModelLB> cModelLB(thermo);
ode<chemModelStd> cModelStd(thermo);
const scalar deltaT = 1E-6;
cModelLB.chemModelLB::solve(deltaT);
cModelStd.chemModelStd::solve(deltaT);
// Compare the computed reaction rate
for (label specieI=0; specieI < cModelLB.nSpecie(); specieI++)
{
auto RRLB = cModelLB.RR(specieI);
auto RRStd = cModelStd.RR(specieI);
forAll(RRLB,celli)
{
REQUIRE_THAT
(
RRLB[celli],
Catch::Matchers::WithinRel(RRStd[celli],1E-6)
);
}
}
}
| C |
2D | ITV-Stuttgart/loadBalancedChemistryModel | tests/src/globalFoamArgs.H | .H | 1,757 | 58 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | www.openfoam.com
\\/ M anipulation |
-------------------------------------------------------------------------------
Copyright (C) 2011-2017 OpenFOAM Foundation
Copyright (C) 2020-2021,2023 OpenCFD Ltd.
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Description
Create the global Foam args variable
Author
Jan Wilhelm Gärtner <jan.gaertner@outlook.de> Copyright (C) 2024
\*---------------------------------------------------------------------------*/
#ifndef GLOBALARGFOAM_H
#define GLOBALARGFOAM_H
#include "fvCFD.H"
extern Foam::argList* argsPtr;
inline Foam::argList& getFoamArgs()
{
return *argsPtr;
}
inline void setFoamArgs(int argc, char* argv[])
{
argsPtr = new Foam::argList(argc,argv);
}
inline void clearFoamArgs()
{
delete argsPtr;
}
#endif
| Unknown |
2D | abhinavroy1999/grain-growth-phase-field-code | GrainGrowth.m | .m | 12,068 | 256 | function GrainGrowth(Nx, Ny, dx, dy, end_time, time_step)
% Phase-field simulation code for grain growth in 2D, using the Allen-Cahn
% equation (for non-conserved order parameters).
%
% The model is developed by Fan & Chen (http://www.mmm.psu.edu/DNFan1997Actamater_Graingrowth1phase2D.pdf)
%
% Function call: GrainGrowth(Nx, Ny, dx, dy, end_time, time_step)
%
% The current simulation uses 10 order parameters for 10 different grain
% orientations.
%
% Output: PNG snapshot of the microstructures at 'time_step' intervals
% Nx : Grid dimension in x direction
% Ny : Grid dimension in y direction
% dx : Grid spacing in x direction
% dy : Grid spacing in y direction
% end_time : End time of the simulation run
% time_step : the time interval for output of simulation data
%
% Copyright (C) 2021 Abhinav Roy
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% any later version.
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <https://www.gnu.org/licenses/>.
tic
if nargin < 6
error("Please enter the required number of arguments. For more information on function call, use help GrainGrowth2D");
end
disp('The code execution has commenced');
axis("square");
more off;
%--------------------------------------------------------------------------------------------------
% SIMULATION PARAMETERS
halfNx = Nx/2;
halfNy = Ny/2;
start_time = 1;
%--------------------------------------------------------------------------------------------------
% Defining the initial profile of the order parameters
phi = unidrnd(10,Nx,Ny);
% Defining the ten order parameters
eta1 = zeros(Nx,Ny);
eta2 = zeros(Nx,Ny);
eta3 = zeros(Nx,Ny);
eta4 = zeros(Nx,Ny);
eta5 = zeros(Nx,Ny);
eta6 = zeros(Nx,Ny);
eta7 = zeros(Nx,Ny);
eta8 = zeros(Nx,Ny);
eta9 = zeros(Nx,Ny);
eta10 = zeros(Nx,Ny);
%--------------------------------------------------------------------------------------------------
% Defining the variables for the derivative of free energy density function
geta1 = zeros(Nx,Ny);
geta2 = zeros(Nx,Ny);
geta3 = zeros(Nx,Ny);
geta4 = zeros(Nx,Ny);
geta5 = zeros(Nx,Ny);
geta6 = zeros(Nx,Ny);
geta7 = zeros(Nx,Ny);
geta8 = zeros(Nx,Ny);
geta9 = zeros(Nx,Ny);
geta10 = zeros(Nx,Ny);
%--------------------------------------------------------------------------------------------------
% Assigning the order parameters value for ten different grain orientation
for i = 1:Nx
for j = 1:Ny
if (phi(i,j) == 1)
eta1(i,j) = 1;
end
if (phi(i,j) == 2)
eta2(i,j) = 1;
end
if (phi(i,j) == 3)
eta3(i,j) = 1;
end
if (phi(i,j) == 4)
eta4(i,j) = 1;
end
if (phi(i,j) == 5)
eta5(i,j) = 1;
end
if (phi(i,j) == 6)
eta6(i,j) = 1;
end
if (phi(i,j) == 7)
eta7(i,j) = 1;
end
if (phi(i,j) == 8)
eta8(i,j) = 1;
end
if (phi(i,j) == 9)
eta9(i,j) = 1;
end
if (phi(i,j) == 10)
eta10(i,j) = 1;
end
end
end
b = zeros(Nx,Ny);
for i = 1:Nx
for j = 1:Ny
b(i,j) = eta1(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta2(i,j)*(eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta3(i,j)*(eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta4(i,j)*(eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta5(i,j)*(eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta6(i,j)*(eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta7(i,j)*(eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta8(i,j)*(eta9(i,j) + eta10(i,j)) ...
+ eta9(i,j)*eta10(i,j);
end
end
%--------------------------------------------------------------------------------------------------
dt = 1.0; %The time step
delkx = 2*pi/(Nx*dx); %condition for fourier transform
delky = 2*pi/(Ny*dy); %condition for fourier transform
A = 1.0; %setting the value of A
L = 1.0; %Setting the value of relaxation coefficient
kappa = 1.0; %Setting the value of kappa (considered non-dimensional here)
%--------------------------------------------------------------------------------------------------
% TEMPORAL EVOLUTION LOOP
%--------------------------------------------------------------------------------------------------
for temp = start_time : end_time
for i = 1 : Nx
for j = 1 : Ny
geta1(i,j) = -eta1(i,j) + eta1(i,j)*eta1(i,j)*eta1(i,j) ...
+ 2*eta1(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta2(i,j) = -eta2(i,j) + eta2(i,j)*eta2(i,j)*eta2(i,j) ...
+ 2*eta2(i,j)*(eta1(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta3(i,j) = -eta3(i,j) + eta3(i,j)*eta3(i,j)*eta3(i,j) ...
+ 2*eta3(i,j)*(eta2(i,j) + eta1(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta4(i,j) = -eta4(i,j) + eta4(i,j)*eta4(i,j)*eta4(i,j) ...
+ 2*eta4(i,j)*(eta2(i,j) + eta3(i,j) + eta1(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta5(i,j) = -eta5(i,j) + eta5(i,j)*eta5(i,j)*eta5(i,j) ...
+ 2*eta5(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta1(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta6(i,j) = -eta6(i,j) + eta6(i,j)*eta6(i,j)*eta6(i,j) ...
+ 2*eta6(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta1(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta7(i,j) = -eta7(i,j) + eta7(i,j)*eta7(i,j)*eta7(i,j) ...
+ 2*eta7(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta1(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j));
geta8(i,j) = -eta8(i,j) + eta8(i,j)*eta8(i,j)*eta8(i,j) ...
+ 2*eta8(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta1(i,j) + eta9(i,j) + eta10(i,j));
geta9(i,j) = -eta9(i,j) + eta9(i,j)*eta9(i,j)*eta9(i,j) ...
+ 2*eta9(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta1(i,j) + eta10(i,j));
geta10(i,j) = -eta10(i,j) + eta10(i,j)*eta10(i,j)*eta10(i,j) ...
+ 2*eta10(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta1(i,j));
end
end
eta1hat = fft2(eta1);
eta2hat = fft2(eta2);
eta3hat = fft2(eta3);
eta4hat = fft2(eta4);
eta5hat = fft2(eta5);
eta6hat = fft2(eta6);
eta7hat = fft2(eta7);
eta8hat = fft2(eta8);
eta9hat = fft2(eta9);
eta10hat = fft2(eta10);
geta1hat = fft2(geta1);
geta2hat = fft2(geta2);
geta3hat = fft2(geta3);
geta4hat = fft2(geta4);
geta5hat = fft2(geta5);
geta6hat = fft2(geta6);
geta7hat = fft2(geta7);
geta8hat = fft2(geta8);
geta9hat = fft2(geta9);
geta10hat = fft2(geta10);
%--------------------------------------------------------------------------------------------------
% EVOLUTION EQUATION
%--------------------------------------------------------------------------------------------------
for i = 1:Nx
if ((i-1) <= halfNx) % Implementing the Periodic Boundary Condition for the x direction
kx = (i-1)*delkx;
else
kx = (i-1-Nx)*delkx;
end
for j = 1:Ny
if ((j-1) <= halfNy) % Implementing the Periodic Boundary Condition for the y direction
ky = (j-1)*delky;
else
ky = (j-1-Ny)*delky;
end
k2 = kx*kx + ky*ky;
eta1hat(i,j) = (eta1hat(i,j) - L*dt*geta1hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta2hat(i,j) = (eta2hat(i,j) - L*dt*geta2hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta3hat(i,j) = (eta3hat(i,j) - L*dt*geta3hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta4hat(i,j) = (eta4hat(i,j) - L*dt*geta4hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta5hat(i,j) = (eta5hat(i,j) - L*dt*geta5hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta6hat(i,j) = (eta6hat(i,j) - L*dt*geta6hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta7hat(i,j) = (eta7hat(i,j) - L*dt*geta7hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta8hat(i,j) = (eta8hat(i,j) - L*dt*geta8hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta9hat(i,j) = (eta9hat(i,j) - L*dt*geta9hat(i,j))/(1 + 2*L*kappa*k2*dt);
eta10hat(i,j) = (eta10hat(i,j) - L*dt*geta10hat(i,j))/(1 + 2*L*kappa*k2*dt);
end % Ending the j loop
end % Ending the i loop
%--------------------------------------------------------------------------------------------------
eta1 = real(ifft2(eta1hat));
eta2 = real(ifft2(eta2hat));
eta3 = real(ifft2(eta3hat));
eta4 = real(ifft2(eta4hat));
eta5 = real(ifft2(eta5hat));
eta6 = real(ifft2(eta6hat));
eta7 = real(ifft2(eta7hat));
eta8 = real(ifft2(eta8hat));
eta9 = real(ifft2(eta9hat));
eta10 = real(ifft2(eta10hat));
%--------------------------------------------------------------------------------------------------
if (rem(temp, time_step) == 0)
for i = 1:Nx
for j = 1:Ny
b(i,j) = eta1(i,j)*(eta2(i,j) + eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta2(i,j)*(eta3(i,j) + eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta3(i,j)*(eta4(i,j) + eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta4(i,j)*(eta5(i,j) + eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta5(i,j)*(eta6(i,j) + eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta6(i,j)*(eta7(i,j) + eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta7(i,j)*(eta8(i,j) + eta9(i,j) + eta10(i,j)) ...
+ eta8(i,j)*(eta9(i,j) + eta10(i,j)) ...
+ eta9(i,j)*eta10(i,j);
end
end
mesh(b);
colorbar;
colormap("jet");
title(sprintf("time %d", temp));
xlim([1 Nx]);
ylim([1 Ny]);
xticks([]);
yticks([]);
xticklabels([]);
yticklabels([]);
view(2);
box on;
ax = gca;
ax.LineWidth = 2;
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 4 3]);
OutputFileName = sprintf("image%d.png", temp);
print(OutputFileName, '-dpng', '-r256');
end
end
toc
disp('The code execution has finished');
%--------------------------------------------------------------------------------------------------
% END OF CODE
%--------------------------------------------------------------------------------------------------
| MATLAB |
2D | pyNLSE/bpm | 1D.py | .py | 4,478 | 155 | import numpy as np
import matplotlib.pyplot as plt
import os
from matplotlib import cm
import shutil
import platform
def grid(Nx,Ny,xmax,ymax):
x = np.linspace(-xmax, xmax-2*xmax/Nx, Nx) # x variable
y = 0 # not used, but a value must be given
return x,y;
# Builds the Laplacian in Fourier space
def L(Nx,Ny,xmax,ymax):
kx = np.linspace(-Nx/4/xmax, Nx/4/xmax-1/2/xmax, Nx) # x variable
return (2*np.pi*1.j*kx)**2
# Introduces an absorbing shell at the border of the computational window
def absorb(x,y,xmax,ymax,dt,absorb_coeff):
wx = xmax/20
return np.exp(-absorb_coeff*(2-np.tanh((x+xmax)/wx)+np.tanh((x-xmax)/wx))*dt);
# Saves the data of abs(psi)**2 at different values of t
def savepsi(Ny,psi):
return abs(psi)**2
# Defines graphic output: |psi|^2 is depicted
def output(x,y,psi,n,t,folder,output_choice,fixmaximum):
# Number of figure
if (output_choice==2) or (output_choice==3):
num =str(int(n))
if n < 100:
num ='0'+str(int(n))
if n < 10:
num ='00'+str(int(n))
## The plot
fig = plt.figure("1D plot") # figure
plt.clf() # clears the figure
if platform.system() == 'Windows':
fig.set_size_inches(8,6)
plt.plot(x, abs(psi)**2) # makes the plot
plt.xlabel('$x$') # format LaTeX if installed (choose axes labels,
plt.ylabel('$|\psi|^2$') # title of the plot and axes range
plt.title('$t=$ %f'%(t)) # title of the plot
if fixmaximum>0: # choose maximum |psi|^2 to be depicted in the vertical axis
plt.axis([min(x),max(x),0,fixmaximum])
# Saves figure
if (output_choice==2) or (output_choice==3):
figname = folder+'/fig'+num+'.png'
plt.savefig(figname)
# Displays on screen
if (output_choice==1) or (output_choice==3):
plt.show(block=False)
fig.canvas.flush_events()
return;
# Some operations after the computation is finished: save the final value of psi, generate videos and builds
# the final plot: a contour map of the y=0 cut as a function of x and t
def final_output(folder,x,Deltat,psi,savepsi,output_choice,images,fixmaximum):
np.save(folder,psi) # saves final wavefunction
if (output_choice==2) or (output_choice==3):
movie(folder) # creates video
# Now we make a plot of the evolution depicting the 1D cut at y=0
tvec=np.linspace(0,Deltat*images,images+1)
tt,xx=np.meshgrid(tvec,x)
figtx = plt.figure("Evolution of |psi(x)|^2") # figure
plt.clf() # clears the figure
figtx.set_size_inches(8,6)
# Generates the plot
toplot=savepsi
if fixmaximum>0:
toplot[toplot>fixmaximum]=fixmaximum
plt.contourf(xx, tt, toplot, 100, cmap=cm.jet, linewidth=0, antialiased=False)
cbar=plt.colorbar() # colorbar
plt.xlabel('$x$') # axes labels, title, plot and axes range
plt.ylabel('$t$')
cbar.set_label('$|\psi|^2$',fontsize=14)
figname = folder+'/sectx.png'
plt.savefig(figname) # Saves the figure
plt.show() # Displays figure on screen
# Generates video from the saved figures. This function is called by final_output
def movie(folder):
folder.replace('.','')
examplename=folder[13:]
video_options='vbitrate=4320000:mbd=2:keyint=132:v4mv:vqmin=3:lumi_mask=0.07:dark_mask=0.2:mpeg_quant:scplx_mask=0.1:tcplx_mask=0.1:naq'
if platform.system() == 'Windows':
try:
shutil.copyfile('mencoder.exe', folder+'/mencoder.exe')
os.chdir(folder)
command ='mencoder "mf://fig*.png" -mf w=800:h=600:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o movie_'+examplename+'.avi'
os.system(command)
try:
os.remove('mencoder.exe')
except:
print("Could not delete mencoder.exe in examlpe directory")
os.chdir('../../')
except:
print("Error making movie with mencoder in windows")
else:
try:
command1 ='mencoder "mf://'+folder+'/fig*.png" -mf fps=25 -o /dev/null -ovc lavc -lavcopts vcodec=mpeg4:vpass=1:'+video_options
command2 ='mencoder "mf://'+folder+'/fig*.png" -mf fps=25 -o ./'+folder+'/movie_'+examplename+'.avi -ovc lavc -lavcopts vcodec=mpeg4:vpass=2:'+video_options
os.system(command1)
os.system(command2)
except:
print("Error making movie with mencoder in Linux")
## delete temporary files:
try:
os.remove('divx2pass.log')
except:
pass
try:
shutil.rmtree('__pycache__')
except:
pass
try:
shutil.rmtree('examples1D/__pycache__/')
except:
pass
| Python |
2D | pyNLSE/bpm | bpm.py | .py | 3,154 | 71 | # Integrating a 1+1D or 1+2D NLSE with different initial conditions and for different potentials.
# To run this code type the command:
# python3 bpm.py example 1D for a 1D example (1D.py file needed)
# python3 bpm.py example 2D for a 2D example (2D.py file needed)
# where example.py contains the details for the particular example and should be placed in
# the directory ./examples1D or ./examples2D
import numpy as np
import sys
import os
import importlib
import glob
# Preliminaries (handling directories and files)
sys.path.insert(0, './examples'+sys.argv[2]) # adds to path the directory with examples
output_folder = './examples'+sys.argv[2]+'/'+sys.argv[1] # directory for images and video output
if not os.path.exists(output_folder): # creates folder if it does not exist
os.makedirs(output_folder)
try: # Erase all image files (if exist) before starting computation and generating new output
for filename in glob.glob(output_folder+'/*.png') :
os.remove( filename )
except:
pass
my = importlib.__import__(sys.argv[1]) # imports the file with the details for the computation
build = importlib.__import__(sys.argv[2]) # selects 1D or 2D
# Initialization of the computation
x, y = build.grid(my.Nx,my.Ny,my.xmax,my.ymax) # builds spatial grid
psi = my.psi_0(x,y) # loads initial condition
L = build.L(my.Nx,my.Ny,my.xmax,my.ymax) # Laplacian in Fourier space
linear_phase = np.fft.fftshift(np.exp(1.j*L*my.dt/2)) # linear phase in Fourier space (including point swap)
border = build.absorb(x,y,my.xmax,my.ymax,my.dt,my.absorb_coeff) # Absorbing shell at the border of the computational window
savepsi=np.zeros((my.Nx,my.images+1)) # Creates a vector to save the data of |psi|^2 for the final plot
steps_image=int(my.tmax/my.dt/my.images) # Number of computational steps between consecutive graphic outputs
# Main computational loop
print("calculating", end="", flush=True)
for j in range(steps_image*my.images+1): # propagation loop
if j%steps_image == 0: # Generates image output
build.output(x,y,psi,int(j/steps_image),j*my.dt,output_folder,my.output_choice,my.fixmaximum)
savepsi[:,int(j/steps_image)]=build.savepsi(my.Ny,psi)
print(".", end="", flush=True)
V = my.V(x,y,j*my.dt,psi) # potential operator
psi *= np.exp(-1.j*my.dt*V) # potential phase
if sys.argv[2] == "1D":
psi = np.fft.fft(psi) # 1D Fourier transform
psi *=linear_phase # linear phase from the Laplacian term
psi = border*np.fft.ifft(psi) # inverse Fourier transform and damping by the absorbing shell
elif sys.argv[2] == "2D":
psi = np.fft.fft2(psi) # 2D Fourier transform
psi *=linear_phase # linear phase from the Laplacian term
psi = border*np.fft.ifft2(psi) # inverse Fourier transform and damping by the absorbing shell
else:
print("Not implemented")
# Final operations
# Generates some extra output after the computation is finished and save the final value of psi:
build.final_output(output_folder,x,steps_image*my.dt,psi,savepsi,my.output_choice,my.images,my.fixmaximum)
print()
| Python |
2D | pyNLSE/bpm | 2D.py | .py | 6,458 | 211 | import numpy as np
import matplotlib.pyplot as plt
import os
from matplotlib import cm
import shutil
import platform
# Builds the (x,y) grid
def grid(Nx,Ny,xmax,ymax):
x = np.linspace(-xmax, xmax-2*xmax/Nx, Nx) # x variable
y = np.linspace(-ymax, ymax-2*ymax/Ny, Ny) # y variable
y,x=np.meshgrid(y, x)
return x,y;
# Builds the Laplacian in Fourier space
def L(Nx,Ny,xmax,ymax):
kx = np.linspace(-Nx/4/xmax, Nx/4/xmax-1/2/xmax, Nx) # x variable
ky = np.linspace(-Ny/4/ymax, Ny/4/ymax-1/2/ymax, Ny) # y variable
ky, kx = np.meshgrid(ky, kx)
return (2*np.pi*1.j*kx)**2 + (2*np.pi*1.j*ky)**2 ;
# Introduces an absorbing shell at the border of the computational window
def absorb(x,y,xmax,ymax,dt,absorb_coeff):
wx = xmax/40
wy = ymax/40
return np.exp(-absorb_coeff*(4-np.tanh((x+xmax)/wx)+np.tanh((x-xmax)/wx)-np.tanh((y+ymax)/wy)+np.tanh((y-ymax)/wy))*dt);
# Saves the 1D cut at y=0 at different values of t
def savepsi(Ny,psi):
return abs(psi[:,int(Ny/2)+1])**2
# Defines graphic output: a contour plot two-dimensional figure and the y=0 1d cut.
# For both figures, |psi|^2 is depicted
def output(x,y,psi,n,t,folder,output_choice,fixmaximum):
# Number of figure
if (output_choice==2) or (output_choice==3):
num =str(int(n))
if n < 100:
num ='0'+str(int(n))
if n < 10:
num ='00'+str(int(n))
#Two-dimensional countour map
fig = plt.figure("Contour map") # figure
plt.clf() # clears the figure
if platform.system() == 'Windows':
fig.set_size_inches(8,6)
plt.axes().set_aspect('equal') # Axes aspect ratio
plt.xlabel('$x$') # choose axes labels
plt.ylabel('$y$')
# Makes the contour plot:
toplot=abs(psi)**2
if fixmaximum>0: # This fixes the minimum and maximum of the color code and
# the color bar, ensuring that it is [0,fixmaximum]
toplot[toplot>fixmaximum]=fixmaximum
toplot[0,0]=0
toplot[0,1]=fixmaximum
plt.contourf(x, y, toplot, 100, cmap=cm.jet, linewidth=0, antialiased=False)
cbar=plt.colorbar() # colorbar
cbar.set_label('$|\psi|^2$',fontsize=14)
plt.title('$t=$ %f'%(t)) # Title of the plot
#Saves figure
if (output_choice==2) or (output_choice==3):
figname = folder+'/fig'+num+'.png'
plt.savefig(figname)
#Displays on screen
if (output_choice==1) or (output_choice==3):
plt.show(block=False)
fig.canvas.flush_events()
#One dimensional cut y=0
fig = plt.figure("1D-cut for y=0") # figure
plt.clf() # clears the figure
if platform.system() == 'Windows':
fig.set_size_inches(8,6)
Ny=len(y[1,:])
plt.plot(x[:,1], toplot[:,int(Ny/2)+1]) # makes the plot
plt.xlabel('$x$') # choose axes labels, title of the plot and axes range
plt.ylabel('$|\psi|^2$')
plt.title('$t=$ %f'%(t)) # title of the plot
if fixmaximum>0: # choose maximum |psi|^2 to be depicted in the vertical axis
plt.axis([min(x[:,1]),max(x[:,1]),0,fixmaximum])
#Saves figure
if (output_choice==2) or (output_choice==3):
figname = folder+'/cut'+num+'.png'
plt.savefig(figname)
#Displays on screen
if (output_choice==1) or (output_choice==3):
plt.show(block=False)
fig.canvas.flush_events()
return
# Some operations after the computation is finished: save the final value of psi, generate videos and builds
# the final plot: a contour map of the y=0 cut as a function of x and t
def final_output(folder,x,Deltat,psi,savepsi,output_choice,images,fixmaximum):
np.save(folder,psi) # saves final wavefunction
if (output_choice==2) or (output_choice==3):
movie(folder) # creates video
# Now we make a plot of the evolution depicting the 1D cut at y=0
x=x[:,1]
tvec=np.linspace(0,Deltat*images,images+1)
tt,xx=np.meshgrid(tvec,x)
plt.figure("Evolution of 1D cut at y=0") # figure
plt.clf() # clears the figure
# Generates the plot
toplot=savepsi
if fixmaximum>0:
toplot[toplot>fixmaximum]=fixmaximum
plt.contourf(xx, tt, toplot, 100, cmap=cm.jet, linewidth=0, antialiased=False)
cbar=plt.colorbar() # colorbar
plt.xlabel('$x$') # choose axes labels, title of the plot and axes range
plt.ylabel('$t$')
cbar.set_label('$|\psi|^2$',fontsize=14)
if fixmaximum>0: # chooses the maximum for the color scale
plt.clim(0,fixmaximum)
figname = folder+'/sectx.png'
plt.savefig(figname) # Saves the figure
plt.show() # Displays figure on screen
# Generates two videos from the saved figures. This function is called by final_output
def movie(folder):
folder.replace('.','')
examplename=folder[13:]
video_options='vbitrate=4320000:mbd=2:keyint=132:v4mv:vqmin=3:lumi_mask=0.07:dark_mask=0.2:mpeg_quant:scplx_mask=0.1:tcplx_mask=0.1:naq'
if platform.system() == 'Windows':
try:
shutil.copyfile('mencoder.exe', folder+'/mencoder.exe')
os.chdir(folder)
command ='mencoder "mf://fig*.png" -mf w=800:h=600:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o movie_'+examplename+'.avi'
os.system(command)
command ='mencoder "mf://cut*.png" -mf w=800:h=600:fps=25:type=png -ovc lavc -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o moviecut_'+examplename+'.avi'
os.system(command)
try:
os.remove('mencoder.exe')
except:
print("Could not delete mencoder.exe in examlpe directory")
os.chdir('../../')
except:
print("Error making movie with mencoder in windows")
else:
try:
command1 ='mencoder "mf://'+folder+'/fig*.png" -mf fps=25 -o /dev/null -ovc lavc -lavcopts vcodec=mpeg4:vpass=1:'+video_options
command2 ='mencoder "mf://'+folder+'/fig*.png" -mf fps=25 -o ./'+folder+'/movie_'+examplename+'.avi -ovc lavc -lavcopts vcodec=mpeg4:vpass=2:'+video_options
os.system(command1)
os.system(command2)
command1 ='mencoder "mf://'+folder+'/cut*.png" -mf fps=25 -o /dev/null -ovc lavc -lavcopts vcodec=mpeg4:vpass=1:'+video_options
command2 ='mencoder "mf://'+folder+'/cut*.png" -mf fps=25 -o ./'+folder+'/moviecut_'+examplename+'.avi -ovc lavc -lavcopts vcodec=mpeg4:vpass=2:'+video_options
os.system(command1)
os.system(command2)
except:
print("Error making movie with mencoder in Linux")
try:
os.remove('divx2pass.log')
except:
pass
try:
shutil.rmtree('__pycache__')
except:
pass
try:
shutil.rmtree('examples2D/__pycache__/')
except:
pass
| Python |
2D | pyNLSE/bpm | examples2D/Diffraction_Circle_2D.py | .py | 926 | 36 | # File: ./examples2D/Diffraction_Circle_2D.py
# Run as python3 bpm.py Diffraction_Circle_2D 2D
# Diffraction by a circular aperture
import numpy as np
Nx = 500 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 60 # End of propagation
xmax = 100 # x-window size
ymax = xmax # y-window size
images = 6 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0.04 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y):
# A step-like function with radial symmetry
rhole=10
r=np.sqrt(x**2+y**2)
f=0.j+(np.tanh((rhole-r)/.01)+1)/2
return f;
def V(x,y,t,psi): # Free propagation
V=0
return V; | Python |
2D | pyNLSE/bpm | examples2D/Vortex_Precession_2D.py | .py | 1,012 | 36 | # File: ./examples2D/Vortex_Precession_2D.py
# Run as python3 bpm.py Vortex_Precession_2D 2D
# Vortex precession within a harmonic potential
import numpy as np
Nx = 300 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 80 # End of propagation
xmax = 8 # x-window size
ymax = xmax # y-window size
images = 800 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 2 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y):
# Initial wavefunction: a vortex configuration
z=x+1.j*y
absz2=x**2+y**2
f = (1-1.2*z)*np.exp(z)*np.exp(-absz2/2)
return f;
def V(x,y,t,psi): # A harmonic trap and a repulsive cubic potential
V = (x**2+y**2)/2 + abs(psi)**2
return V;
| Python |
2D | pyNLSE/bpm | examples2D/Vortices_Pattern_2D.py | .py | 1,678 | 51 | # File: ./examples2D/Vortices_Pattern_2D.py
# Run as python3 bpm.py Vortices_Pattern_2D 2D
# A Gaussian beam impinges on a mask that generates a diffaction pattern with
# vortices of different topological charges.
# NOTICE: This example uses a fine computational grid, it uses a lot of memory
# and takes some time to run. It is possible to reduce Nx, Ny and take a larger dt
# in order to obtain approximate results with less computational resources.
import numpy as np
Nx = 1500 # Grid points
Ny = 450
dt = 0.0005 # Evolution step
tmax = 800 # End of propagation
xmax = 1000 # x-window size
ymax = 300 # y-window size
images = 800 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 2 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction: a Gaussian
zR = 5000 # Rayleigh range
zini = 0 # initial position, with respect to focus
qini = -zini+1.j*zR # Complex parameter of the beam
f = np.sqrt(zR/np.pi)/qini*np.exp(-1.j*(x**2+y**2)/(2*qini))
return f;
def V(x,y,t,psi):
# Between tini and tfin, there is an imaginary potential that absorbs part of
# the energy. It acts as a spatial filter. After tfin, there is free propagation
tini=1
tfin=1.1
k=.5
m=1
mask=2*(1+np.cos(k*x-m*np.arctan2(y,x)))
if (t>=tini) and (t<tfin):
V=-20*1.j*mask
else:
V=0
return V;
| Python |
2D | pyNLSE/bpm | examples2D/Vortex_2D.py | .py | 1,146 | 37 | # File: ./examples2D/Vortex_2D.py
# Run as python3 bpm.py Vortex_2D 2D
# A vortex beam propagating in free space
import numpy as np
Nx = 300 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 10 # End of propagation
xmax = 20 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 2/(4*np.pi*np.exp(1)) # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction: a vortex
zR = 2 # Rayleigh range
zini = -5 # initial position, with respect to focus
qini = -zini+1.j*zR # Complex parameter of the beam
r=np.sqrt(x**2+y**2)
phase=np.exp(1.j*np.arctan2(y,x))
f = zR/np.sqrt(np.pi)/(qini**2)*r*np.exp(-1.j*r**2/(2*qini))*phase
return f;
def V(x,y,t,psi): # Free propagation
V=0
return V; | Python |
2D | pyNLSE/bpm | examples2D/Vortex_Breaking_2D.py | .py | 1,182 | 37 | # File: ./examples2D/Vortex_Breaking_2D.py
# Run as python3 bpm.py Vortex_Breaking_2D 2D
# Azimuthal instability of a vortex because of an attractive nonlinearity
import numpy as np
Nx = 300 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 500 # End of propagation
xmax = 120 # x-window size
ymax = xmax # y-window size
images = 200 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0.02 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction: a vortex
zR = 200 # Rayleigh range
zini = 0 # initial position, with respect to focus
qini = -zini+1.j*zR # Complex parameter of the beam
r=np.sqrt(x**2+y**2)
phase=np.exp(1.j*2*np.arctan2(y,x))
f = 0.0009*r**2*np.exp(-1.j*r**2/(2*qini))*phase
return f;
def V(x,y,t,psi): # Focusing Kerr (cubic) nonlinearity
V=-abs(psi)**2
return V; | Python |
2D | pyNLSE/bpm | examples2D/Collapse_2D.py | .py | 1,527 | 52 | # File: ./examples2D/Collapse_2D.py
# Run as python3 bpm.py Collapse_2D 2D
# Self-similar collapse of the Townes' profile
import numpy as np
Nx = 500 # Grid points
Ny = 500
dt = 0.005 # Evolution step
tmax = 7 # End of propagation
xmax = 20 # x-window size
ymax = xmax # y-window size
images = 70 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 2 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y):
# Initial wavefunction: the Townes' profile (computed elsewhere) is loaded
# as initial data. With it, we build the initial condition for self-similar
# collapse. The singularity should form at t=ts
my_data = np.genfromtxt('./examples2D/townes_profile.csv', delimiter=',')
r=my_data[0,:]
f=my_data[1,:]
dr=r[1]-r[0]
ts=8
Nx=len(x[:,1])
Ny=len(y[1,:])
psi0=np.zeros((Nx,Ny))+0.j
maxr=r[len(r)-1]
for ix in range(Nx):
for iy in range(Ny):
rhere=np.sqrt(x[ix,1]**2+y[1,iy]**2)/ts
if rhere<maxr:
ii=int(rhere/dr);
psi0[ix,iy]=f[ii]+(f[ii+1]-f[ii])/dr*(rhere-r[ii])
psi0[ix,iy]=1/ts*np.exp(1.j/ts)*psi0[ix,iy]*np.exp(-1.j*(x[ix,1]**2+y[1,iy]**2)/(2*ts))
return psi0;
def V(x,y,t,psi): # Kerr (cubic) focusing nonlinearity
V = - abs(psi)**2
return V; | Python |
2D | pyNLSE/bpm | examples2D/Liquid_Droplet_2D.py | .py | 1,370 | 50 | # File: ./examples2D/Liquid_Droplet_2D.py
# Run as python3 bpm.py Liquid_Droplet_2D 2D
# A droplet of "liquid light" collides with a barrier
import numpy as np
Nx = 400 # Grid points
Ny = 240
dt = 0.001 # Evolution step
tmax = 140 # End of propagation
xmax = 160 # x-window size
ymax = 100 # y-window size
images = 300 # number of .png images
absorb_coeff = 10 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0.8 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y):
# Initial wavefunction: We introduce an analytic function that is an approximation
# to a flat-top eigenstate of the cubic-quintic nonlinear Schrodinger equaiton.
rsoliton=60
Nx=len(x[:,1])
Ny=len(y[1,:])
psi0=np.zeros((Nx,Ny))+0.j
x0=0
y0=10
vx=0
vy=-1
for ix in range(Nx):
for iy in range(Ny):
rhere=np.sqrt((x[ix,1]-x0)**2+(y[1,iy]-y0)**2)
psi0[ix,iy]=np.sqrt(3/4/(np.exp(rhere-rsoliton)+1))
psi0*=np.exp(1.j*(vx*x+vy*y))
return psi0;
def V(x,y,t,psi): # Cubic-quintic nonlineariry and a steep barrier
V = - abs(psi)**2 + abs(psi)**4 + 20*(np.tanh(y+80)-1)
return V; | Python |
2D | pyNLSE/bpm | examples2D/Gaussian_Vortex_interf_2D.py | .py | 1,608 | 57 | # File: ./examples2D/Gaussian_Vortex_interf_2D.py
# Run as python3 bpm.py Gaussian_Vortex_interf_2D 2D
# A Gaussian beam and a vortex cross each other generating the typical fork-like
# pattern
import numpy as np
Nx = 600 # Grid points
Ny = 300
dt = 0.001 # Evolution step
tmax = 7 # End of propagation
xmax = 30 # x-window size
ymax = 20 # y-window size
images = 140 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0.07 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# gaussian beam moving rightwarks
x1=-10
y1=0
r1=np.sqrt((x-x1)**2+(y-y1)**2)
zR1=7
zini1=-5
qini1 = -zini1+1.j*zR1 # Complex parameter of the beam
vx1=2.5
vy1=0
vel_phase1=np.exp(1.j*(vx1*x+vy1*y))
f1 = np.sqrt(zR1/np.pi)/qini1*np.exp(-1.j*r1**2/(2*qini1))*vel_phase1
# vortex moving leftwards
x2=8
y2=0
zR2 = 5 # Rayleigh range
zini2 = -5 # initial position, with respect to focus
qini2 = -zini2+1.j*zR2 # Complex parameter of the beam
r2=np.sqrt((x-x2)**2+(y-y2)**2)
phase=np.exp(1.j*np.arctan2(y-y2,x-x2))
vx2=-2.5
vy2=0
vel_phase2=np.exp(1.j*(vx2*x+vy2*y))
f2 = zR2/np.sqrt(np.pi)/(qini2**2)*r2*np.exp(-1.j*r2**2/(2*qini2))*phase*vel_phase2
return f1+f2;
def V(x,y,t,psi): # Free propagation
V=0
return V; | Python |
2D | pyNLSE/bpm | examples2D/Gaussian_Beam_2D.py | .py | 1,082 | 34 | # File: ./examples2D/Gaussian_Beam_2D.py
# Run as python3 bpm.py Gaussian_Beam_2D 2D
# A Gaussian beam propagating in free space
import numpy as np
Nx = 300 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 10 # End of propagation
xmax = 20 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 2/(4*np.pi) # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction: a Gaussian beam
zR = 2 # Rayleigh range
zini = -5 # initial position, with respect to focus
qini = -zini+1.j*zR # Complex parameter of the beam
f = np.sqrt(zR/np.pi)/qini*np.exp(-1.j*(x**2+y**2)/(2*qini))
return f;
def V(x,y,t,psi): # Free propagation
V=0
return V; | Python |
2D | pyNLSE/bpm | examples2D/Filamentation_2D.py | .py | 1,319 | 39 | # File: ./examples2D/Filamentation.py
# Run as python3 bpm.py Filamentation 2D
# Filamentation: an initially constant energy distribution results in the
# formation of filaments. The nonlinearities drive the evolution.
import numpy as np
Nx = 400 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 20 # End of propagation
xmax = 50 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 5 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y):
# Initial wavefunction: a flat distribution, perturbed by a small quantity of random noise
f = np.ones((len(x[:,1]),len(y[1,:])))+0.j
f = f + 0.001*np.random.randn(len(x[:,1]),len(y[1,:]))+1.j*0.001*np.random.randn(len(x[:,1]),len(y[1,:]))
return f;
def V(x,y,t,psi):
# An attractive cubic nonlinearity that induces modulation instability.
# A repulsive quintic term is included in order to avoid collapse (singularity formation).
V= -abs(psi)**2 + 0.1* abs(psi)**4
return V; | Python |
2D | pyNLSE/bpm | examples1D/Thomas_Fermi_1D.py | .py | 1,428 | 49 | # File: ./examples1D/Thomas_Fermi_1D.py
# Run as python3 bpm.py Thomas_Fermi_1D 1D
# Initially, a nonlinear wave packet is confined within a harmonic well, and
# it is well approximated by a Thomas-Fermi profile (in which the Laplacian
# is neglected). At t=5, the strength of the nonlinearity is changed and an
# oscillation starts
import numpy as np
Nx = 1000 # Grid points
Ny = Nx
dt = 0.0005 # Evolution step
tmax = 15 # End of propagation
xmax = 30 # x-window size
ymax = xmax # y-window size
images = 300 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 2 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 250 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# The initial |psi|^2 is an inverted parabola that solves the equation in the
# absence of the derivative term.
x0=12
f=0.j+np.zeros(len(x))
for l in range(len(x)-1):
if abs(x[l])<x0:
f[l]=0.j+np.sqrt(x0**2-x[l]**2)
return f;
def V(x,y,t,psi):
# A harmonic trap and a cubic attractive (focusing) nonlinearity, whose strength
# changes at t=5
if t<5:
V = x**2 + (abs(psi))**2
else:
V = x**2 +0.6* (abs(psi))**2
return V; | Python |
2D | pyNLSE/bpm | examples1D/Diffraction_Slit_1D.py | .py | 1,139 | 34 | # File: ./examples1D/Diffraction_Slit_1D.py
# Run as python3 bpm.py Diffraction_Slit_1D 1D
# Diffraction by a slit
# The initial condition is a flat function within a finite domain, modeling
# the passage of a wide wave through a slit. The evolution generates the typical
# diffraction pattern
import numpy as np
Nx = 1000 # Grid points
Ny = Nx
dt = 0.0001 # Evolution step
tmax = .4 # End of propagation
xmax = 30 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# A step function, modelling the passage of a plane wave through a slit
f = 0.j+np.piecewise(x, [abs(x)<.5, abs(x)>=.5],[1,0])
return f;
def V(x,y,t,psi): # Free propagation
V = 0
return V; | Python |
2D | pyNLSE/bpm | examples1D/Solitons_phase_opp_1D.py | .py | 1,276 | 42 | # File: ./examples1D/Solitons_phase_opp_1D.py
# Run as python3 bpm.py Solitons_phase_opp_1D 1D
# Encounter of two solitons in phase opposition. The process can be interpreted
# as two robust wave packets that bounce back from each other.
import numpy as np
Nx = 500 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 5 # End of propagation
xmax = 10 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 1.2 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# Two solitons heading each other in phase opposition
x01=-5
x02=-x01
v1=2
v2=-v1
fase1=0
fase2=np.pi # Phase difference of pi
f1 = (0.j+1/np.cosh(x-x01))*np.exp(v1*1.j*x+1.j*fase1) # Soliton 1
f2 = (0.j+1/np.cosh(x-x02))*np.exp(v2*1.j*x+1.j*fase2) # Soliton 2
f = f1+f2
return f;
def V(x,y,t,psi): # A cubic attractive (focusing) nonlinearity
V = - (abs(psi))**2
return V; | Python |
2D | pyNLSE/bpm | examples1D/Soliton_Emission_B_1D.py | .py | 1,656 | 48 | # File: ./examples1D/Soliton_Emission_B_1D.py
# Run as python3 bpm.py Soliton_Emission_B_1D 1D
# Initially, a Gaussian wave packet is confined within a shallow trap. At a given
# time, a repulsive interaction is turned on and the wave starts expanding. Then,
# the sign of the nonlinear term is changed and the interaction becomes attractive.
# This results in the formation of a bunch of solitons that escape from the trap.
import numpy as np
Nx = 1200 # Grid points
Ny = Nx
dt = 0.0002 # Evolution step
tmax = 10 # End of propagation
xmax = 60 # x-window size
ymax = xmax # y-window size
images = 400 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0.8 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction: a Gaussian
f=0.j+np.exp(-((x)**2)/np.sqrt(2)/4)
return f;
def V(x,y,t,psi):
# The linear part of the potential is a shallow trap modeled by an inverted Gaussian
# The nonlinear part is a cubic term whose sign and strength change abruptly in time.
a0=0; # initial (vanishing) nonlinear coefficient
a1=25; # repulsive nonlinear coefficient for 3<t<8
a2=-35; # attractive nonlinear coefficient for t>8
if t<1:
V= -np.exp(-((x)/4)**2) + a0*abs(psi)**2
elif t<3:
V= -np.exp(-((x)/4)**2) + a1*abs(psi)**2
else:
V= -np.exp(-((x)/4)**2) + a2*abs(psi)**2
return V; | Python |
2D | pyNLSE/bpm | examples1D/Interference_Gaussians_1D.py | .py | 1,243 | 35 | # File: ./examples1D/Interference_Gaussians_1D.py
# Run as python3 bpm.py Interference_Gaussians_1D 1D
# Interference of two Gaussian wave packets.
# The initial condition consists of two separate Gaussians. Each of them grows
# wider because of diffraction due to the Laplacian term. Eventually, they are
# wide enough to overlap in space and generate an interference pattern.
import numpy as np
Nx = 1000 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 4 # End of propagation
xmax = 25 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 20 # Introduces an absorbing boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 0 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# Two Gaussians with the same width, centered at different points,
f = (0.j+np.exp(-((x-3)/.5)**2))+(0.j+np.exp(-((x+3)/.5)**2))
return f;
def V(x,y,t,psi): # Free propagation
V = 0
return V; | Python |
2D | pyNLSE/bpm | examples1D/Double_Well_1D.py | .py | 1,132 | 34 | # File: ./examples1D/Double_Well_1D.py
# Run as python3 bpm.py Double_Well_1D 1D
# Beating in a double well potential
# A double well potential is defined. The initial condition concentrates the
# wavefunction around one of the minima. The simulation shows that, periodically, the
# energy tunnels between the two wells.
import numpy as np
Nx = 600 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 30 # End of propagation
xmax = 5 # x-window size
ymax = xmax # y-window size
images = 300 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 1.25 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
f = 0.j+np.exp(-((x-1)**2)/2) # A Gaussian centered at one of the wells
return f;
def V(x,y,t,psi): # A double well potential
V = (x**2-1)**2/8
return V;
| Python |
2D | pyNLSE/bpm | examples1D/Solitons_in_phase_1D.py | .py | 1,237 | 41 | # File: ./examples1D/Solitons_in_phase_1D.py
# Run as python3 bpm.py Solitons_in_phase_1D 1D
# Encounter of two solitons in phase, which traverse each other unaffected.
# During the collision, an interference pattern is generated.
import numpy as np
Nx = 500 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 5 # End of propagation
xmax = 10 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 1.2 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# Two solitons heading each other in phase coincidence
x01=-5
x02=-x01
v1=2
v2=-v1
fase1=0
fase2=0
f1 = (0.j+1/np.cosh(x-x01))*np.exp(v1*1.j*x+1.j*fase1) # Soliton 1
f2 = (0.j+1/np.cosh(x-x02))*np.exp(v2*1.j*x+1.j*fase2) # Soliton 2
f = f1+f2
return f;
def V(x,y,t,psi): # A cubic attractive (focusing) nonlinearity
V = - (abs(psi))**2
return V; | Python |
2D | pyNLSE/bpm | examples1D/Sech2_Pot_1D.py | .py | 1,372 | 37 | # File: ./examples1D/Sech2_Pot_1D.py
# Run as python3 bpm.py Sech2_Pot_1D 1D
# A Gaussian wave packet traverses a reflectionless potential. The simulation
# non-trivially shows that there is no reflected energy. Try changing the value
# of s to different (integer and non-integer) values
import numpy as np
Nx = 2000 # Grid points
Ny = Nx
dt = 0.001 # Evolution step
tmax = 200 # End of propagation
xmax = 100 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 1.6 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
vx=.4 # initial velocity
cx=-.005 # initial curvature of the beam
f=0.j+np.exp(-((x+30)/15)**2) # A Gaussian profile
f*=np.exp(1.j*(vx*x+cx*(x+30)**2)) # Include velocity and curvature
return f;
def V(x,y,t,psi): # A reflectionless potential
s=10 # The potential is reflectionless if s is a positive integer
V=-1/2*s*(s+1)/(np.cosh(x))**2 # The reflectionless potential
return V; | Python |
2D | pyNLSE/bpm | examples1D/Soliton_Emission_A_1D.py | .py | 1,300 | 38 | # File: ./examples1D/Soliton_Emission_A_1D.py
# Run as python3 bpm.py Soliton_Emission_A_1D 1D
# Initially, there is a Gaussian wavefunction within a shallow trap.
# Due to a space-dependent attractive nonlineary, the energy moves rightwards
# and it turns out that a train of solitons is emitted.
import numpy as np
Nx = 1200 # Grid points
Ny = Nx
dt = 0.0001 # Evolution step
tmax = 15 # End of propagation
xmax = 20 # x-window size
ymax = xmax # y-window size
images = 300 # number of .png images
absorb_coeff = 0 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 1.6 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction: a Gaussian
f=0.j+np.exp(-((x+8)**2)/np.sqrt(2)/4)
return f;
def V(x,y,t,psi):
# The linear part of the potential is a shallow trap modeled by an inverted
# Gaussian. The nonlinear part is an attractive cubic term whose coefficient
# depends on x in a step-like form
V= -np.exp(-((x+8)/4)**2) - 5*(np.tanh((x+6)/.5)+1)*abs(psi)**2
return V; | Python |
2D | pyNLSE/bpm | examples1D/Rectangular_Barrier_1D.py | .py | 1,234 | 36 | # File: ./examples1D/Rectangular_Barrier_1D.py
# Run as python3 bpm.py Rectangular_Barrier_1D 1D
# A Gaussian wave packet impinges on a rectangular barrier. Part of the wave
# is reflected, part of the wave is transmitted.
import numpy as np
Nx = 1600 # Grid points
Ny = Nx
dt = 0.0001 # Evolution step
tmax = 6 # Propagation end
xmax = 50 # x-window size
ymax = xmax # y-window size
images = 100 # number of .png images
absorb_coeff = 20 # 0 = periodic boundary
output_choice = 3 # If 1, it plots on the screen but does not save the images
# If 2, it saves the images but does not plot on the screen
# If 3, it saves the images and plots on the screen
fixmaximum= 1.05 # Fixes a maximum scale of |psi|**2 for the plots. If 0, it does not fix it.
def psi_0(x,y): # Initial wavefunction
# A Gaussian wave packet moving rightwards
vx=10 # value of the initial velocity
f=0.j+np.exp(-((x+15)/4)**2) # Gaussian profile
f*=np.exp(1.j*vx*x) # Multiply by an x-dependent phase to introduce velocity
return f;
def V(x,y,t,psi): # A barrier modeled by V=0 for |x|>5 and V=40 for |x|<5
V = np.piecewise(x, [abs(x-5)<2.5, abs(x-5)>=2.5],[40,0])
return V; | Python |
2D | pillowlab/GLMspiketools | setpaths_GLMspiketools.m | .m | 600 | 19 | % SETPATHS.m - GLMspiketools code repository
%
% This simple script sets the path to include relevant directories for the
% GLMspiketools code package. You must 'cd' into this directory in order
% to evaluate it.
%
% More info: http://pillowlab.princeton.edu/code_GLM.html
% Github page: https://github.com/pillowlab/GLMspiketools
basedir = pwd; % The directory where this script lives
% Add a bunch sub-directories (with absoluate path names)
addpath([basedir '/glmtools_fitting/']);
addpath([basedir '/glmtools_misc/']);
addpath([basedir '/nlfuns/']);
addpath([basedir '/glmtools_spline/']);
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/mksplineDesignMat.m | .m | 2,179 | 71 | function [Xdesign,Ysrt,Mspline] = mksplineDesignMat(X,Y,ss,sortflag,dcflag)
% [Xdesign,Ysrt,Mspline] = mksplineDesignMat(X,Y,ss,sortflag)
%
% Computes design matrix for least-squares fitting cubic splines, so that
% the problem can be written:
% argmin_w ||Ysrt - Xdesign*w||^2
%
% "Standard" spline coefficients can be recovered via
% splinecoeffs = reshape(Mspline*w,4,[])';
%
% Inputs:
% X - input (indep variable)
% Y - output (dep variable)
% ss - spline structure with fields: "breaks", "smoothness", "extrapDeg"
% sortflag - set to zero to obtain *unsorted* output (default=1)
% dcflag - set to zero to constrain f at first knot to zero (default=1)
%
% Outputs:
% Xdesign - design matrix (spline matrix projected onto X monomials)
% Ysrt - sorted Y so rows of Ysrt correspond to rows of Xdesign
% Mspline - spline parametrization matrix
if nargin<4
sortflag=1;
end
if nargin<5
dcflag = 1; % set to zero to have no DC component
end
breaks = ss.breaks; % number of knots
nsegs = length(breaks)-1; % number of segments
nx = size(X,1); % # elements in X and Y
% Make spline parametrization matrix
Mspline = mksplineParamMtx(ss,dcflag);
% for each data point, compute its breakpoint interval
[xsrt,isrt] = sort(X); % sort X values
[~,index] = sort([breaks(1:nsegs) xsrt']);
index = max([find(index>nsegs)-(1:nx);ones(1,nx)])'; % segment for each datapoint
% convert to local coordinates
xsrt = xsrt-breaks(index)';
% Insert data into design matrix
% - Use this version if no memory problems (much faster!)
AA = zeros(nx,nsegs*4);
% - Use this version if memory limitations occur
%AA = sparse([],[],[],nx,nsegs(ispl)*4,nx*4);
% Loop through each segment, inserting points into design matrix
for j = 1:nsegs
ii = [index==j]; % points with this index
ni = sum(ii); % number of such points
if ni > 0
AA(ii,((j-1)*4+1:j*4)) = ...
repmat(xsrt(ii),1,4).^repmat([3:-1:0],ni,1);
end
end
Xdesign = AA*Mspline;
if (sortflag==0)
% Pass back unsorted Design matrix
Xdesign(isrt,:) = Xdesign;
Ysrt = Y;
elseif nargout>1
% Sort Y values to match X values
Ysrt = Y(isrt);
end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/mksplineParamMtx.m | .m | 3,300 | 85 | function Mspline = mksplineParamMtx(ss,dcflag)
% Mspline = mksplineParamMtx(ss,dcflag)
%
% Computes matrix parametrizing a cubic spline (3rd order piecewise
% polynomial) with given smoothness and end-point conditions
%
% Inputs:
% ss - spline struct with fields "breaks", "smoothness", and "extrapDeg"
% fields:
% .breaks - x values where polynomials are spliced together
% .smoothness - number of derivs of continuity. (optional; default=3)
% 0 - not smooth (discontinuous)
% 1 - continuous (but not differentiable)
% 2 - differentiable (continuous 1st derivatives)
% 3 - twice differentiable (continuous 2nd derivs)
% (3 is the standard condition for cubic splines)
% .extrapDeg - degree of polynomials used in edge segments in [0,3]
% 0 - constant
% 1 - straight line
% 2 - quadratic final polynomials
% 3 - 3rd order polynomials (standard in cubic splines)
% Note: use a 2-vector to specify diff polynomial degrees on left
% and right segments. (optional; default=3)
% dcflag = [0 or 1]. Set to 0 to constrain avg function value at knots to 0.
%
% Output: Mspline = matrix parametrizing the given class of splines
% This matrix is given by the null space of a matrix enforcing boundary
% constraints on the piecewise polynomials.
% See also: fitSpline.m, makeSplineFun.m, convrtSplinePrs.m
if nargin==1
dcflag=1; % default: no constraint on DC of first segment
end
breaks = ss.breaks(:)'; % Convert to row vector;
nbreaks = length(breaks);
if nbreaks<3
error('Must use at least 3 breaks. (2 breaks => single polynomial)');
end
nsegs = nbreaks-1; % # of polynomial segments
ncoeffs = nsegs*4;
smoothness = ss.smoothness;
extrapDeg = ss.extrapDeg;
dd = diff(breaks(1:end-1))'; % spacing beteen breaks
v0 = zeros(nsegs-1,1); % vectors of zeros and ones
v1 = ones(nsegs-1,1);
% Generate row vectors needed to enforce smoothness constraints
dffs = [];
dffs(:,:,1) = [dd.^3 dd.^2 dd v1, v0 v0 v0 -v1]; % continuity
dffs(:,:,2) = [3*dd.^2 2*dd v1 v0, v0 v0 -v1 v0]; % differentiability
dffs(:,:,3) = [3*dd v1 v0 v0, v0 -v1 v0 v0]; % twice differentiability
ConstrMat = zeros(smoothness*(nsegs-1), 4*nsegs); % Constraint matrix
% Generate constraints for smoothness
for i = 1:smoothness
nrow = (i-1)*(nsegs-1)+1;
for j = 1:nsegs-1
ncol = (j-1)*4;
ConstrMat(nrow,ncol+[1:8]) = dffs(j,:,i);
nrow=nrow+1;
end
end
% Generate extra constraints for degree of last polynomial
meye = eye(4);
nleftC = 3-extrapDeg(1); % # additional constr on left side
nrightC = 3-extrapDeg(end); % # additional constr on right side
epMat1 = [meye(1:nleftC,:) zeros(nleftC,ncoeffs-4)];
epMat2 = [zeros(nrightC,ncoeffs-4), meye(1:nrightC,:)];
ConstrMat = [ConstrMat; epMat1; epMat2];
% Generate constraint on DC component of first segment (if desired)
if dcflag==0
%dcconstr = [0 0 0 1, zeros(1,ncoeffs-4)];
dcconstr = repmat([0 0 0 1],1,nsegs);
ConstrMat = [ConstrMat; dcconstr];
end
% size(ConstrMat,1) = total # of constraints
% Param Matrix is given by the null space of the constraint matrix
Mspline = null(ConstrMat);
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/ppfun.m | .m | 1,481 | 59 | function [f,df,ddf]=ppfun(pp,xx)
% [f,df,ddf]=ppfun(pp,xx)
%
% Evaluate piecewise polynomial 'pp' at values 'xx'. Optionally returns first and
% second derivs at these points.
%
% Inputs:
% pp = piecewise polynomial structure, given (eg) by makepp or spline
% xx = vector of values at which to evaluate
if isstruct(xx) % flip input args if ppval(xx,pp) was called
temp = xx; xx = pp; pp = temp;
end
% make into row vector
sz = size(xx);
lx = numel(xx);
xs = reshape(xx,1,lx);
% if necessary, sort xs
if any(diff(xs)<0), [xs,ix] = sort(xs); end
% take apart PP
[breaks,coefs,l,k,dd]=unmkpp(pp);
% for each data point, compute its breakpoint interval
[~,index] = sort([breaks(1:l) xs]);
index = max([find(index>l)-(1:lx);ones(1,lx)]);
% now go to local coordinates
xs = xs-breaks(index);
% Recursively compute polynomial and its derivs
f = coefs(index,1);
for i=2:k
f = xs(:).*f + coefs(index,i);
end
if nargout > 1
df = (k-1)*coefs(index,1);
for i = 2:k-1
df = xs(:).*df + (k-i)*coefs(index,i);
end
end
if nargout > 2
ddf = (k-2)*(k-1)*coefs(index,1);
for i = 2:k-2
ddf = xs(:).*ddf + (k-i)*(k-i-1)*coefs(index,i);
end
end
if exist('ix'),
f(ix) = f;
if (nargout > 1), df(ix) = df; end
if (nargout > 2), ddf(ix) = ddf; end
end
f = reshape(f,sz);
if nargout > 1, df = reshape(df,sz); end
if nargout > 2, ddf = reshape(ddf,sz); end
| MATLAB |
2D | pillowlab/GLMspiketools | glmtools_spline/MLfit_GLMwithspline.m | .m | 1,684 | 55 | function [gg,neglogli,H] = MLfit_GLMwithspline(gg,Stim,optimargs,npasses)
% [gg,neglogli,H] = MLfit_GLMwithspline(gg,Stim,optimargs,npasses)
%
% Fit GLM filters and spline nonlinearity using alternating
% ascent of filter and spline parameters
%
% Inputs:
% gg = glm param structure
% Stim = stimulus
% optimargs = optimization params
% npasses (OPTIONAL) = # of passes of filter and nonlinear param fitting
%
% Outputs:
% gg = GLM struct;
% fval = negative log-likelihood at maximum
% H = Hessian (for filter params) at max
if nargin <= 3
npasses = 3;
end
% Select which GLM fitting function to use
if isfield(gg, 'kxbas')
fitFun = @MLfit_GLMbi;
else
fitFun = @MLfit_GLM;
end
neglogliPrev = 0;
neglogli = neglogli_GLM(gg,Stim);
for j = 1:npasses
% Fit filters
fprintf('\n--- Pass %d: fitting filters (dLoss=%.3f)----\n', j,neglogliPrev-neglogli);
[gg,neglogli] = fitFun(gg,Stim,optimargs);
neglogliPrev = neglogli;
% Fit spline nonlinearity
fprintf('--- Pass %d: Fitting spline nlin -------\n', j);
[gg,neglogli] = MLfit_splineNlin(gg,Stim);
end
% Filters one last time and return Hessian for filters (if desired)
fprintf('--- Final step: fitting filters (dLoss=%.3f)----',neglogliPrev-neglogli);
[gg,neglogli,H] = fitFun(gg,Stim,optimargs);
% %----------------------------------------------------
% Debugging code
% %----------------------------------------------------
%
% % ------ Check analytic gradients and Hessians -------
% HessCheck(fitFun,prs0,opts);
% HessCheck_Elts(@Loss_GLM_logli, [1 12],prs0,opts);
% tic; [lival,J,H]=lfunc(prs0); toc;
| MATLAB |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.