Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Features:
- Produce template based reactions and molecules
- Atom-to-atom mapping, checking and rule-based fixing
- Perform MCS search
- 2d coordinates generation (based on `SmilesDrawer <https://github.com/reymond-group/smilesDrawer>`_)
- 2d coordinates generation
- 2d/3d depiction with Jupyter support
- SMARTS parser with restrictions
- Protective groups remover
Expand Down
2,566 changes: 2,566 additions & 0 deletions chython/algorithms/calculate2d/Calculate2d.py

Large diffs are not rendered by default.

434 changes: 434 additions & 0 deletions chython/algorithms/calculate2d/KKLayout.py

Large diffs are not rendered by default.

498 changes: 498 additions & 0 deletions chython/algorithms/calculate2d/Properties.py

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion chython/algorithms/calculate2d/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# -*- coding: utf-8 -*-
#
# Copyright 2019-2025 Ramil Nugmanov <[email protected]>
# Copyright 2024, 2025 Denis Lipatov <[email protected]>
# Copyright 2024, 2025 Vyacheslav Grigorev <[email protected]>
# Copyright 2024, 2025 Timur Gimadiev <[email protected]>
# This file is part of chython.
#
# chython is free software; you can redistribute it and/or modify
Expand All @@ -19,5 +22,4 @@
from .molecule import *
from .reaction import *


__all__ = ['Calculate2DMolecule', 'Calculate2DReaction']
1 change: 0 additions & 1 deletion chython/algorithms/calculate2d/clean2d.js

This file was deleted.

45 changes: 16 additions & 29 deletions chython/algorithms/calculate2d/molecule.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
#
# Copyright 2019-2025 Ramil Nugmanov <[email protected]>
# Copyright 2019, 2020 Dinar Batyrshin <[email protected]>
# Copyright 2024, 2025 Denis Lipatov <[email protected]>
# Copyright 2024, 2025 Vyacheslav Grigorev <[email protected]>
# Copyright 2024, 2025 Timur Gimadiev <[email protected]>
# This file is part of chython.
#
# chython is free software; you can redistribute it and/or modify
Expand All @@ -17,12 +20,12 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, see <https://www.gnu.org/licenses/>.
#

from math import sqrt
from random import random
from typing import TYPE_CHECKING, Union, Dict
from ...exceptions import ImplementationError
from typing import TYPE_CHECKING, Union, Dict, TypeVar, List
from ...periodictable.base.vector import Vector

from .Calculate2d import calculate2d_coord

try:
from importlib.resources import files
Expand All @@ -31,17 +34,11 @@


if TYPE_CHECKING:
from chython import MoleculeContainer

try:
from py_mini_racer import MiniRacer, JSEvalException

ctx = MiniRacer()
ctx.eval('const self = this')
ctx.eval(files(__package__).joinpath('clean2d.js').read_text())
except RuntimeError:
ctx = None

from ...containers import MoleculeContainer
Element = TypeVar('Element')
Bond = TypeVar('Bond')
Coords = Vector[float, float]


class Calculate2DMolecule:
__slots__ = ()
Expand All @@ -52,20 +49,10 @@ def clean2d(self: Union['MoleculeContainer', 'Calculate2DMolecule']):
"""
Calculate 2d layout of graph. https://pubs.acs.org/doi/10.1021/acs.jcim.7b00425 JS implementation used.
"""
if ctx is None:
raise ImportError('py_mini_racer is not installed or broken')
plane = {}
entry = iter(sorted(self, key=lambda n: len(self._bonds[n])))
for _ in range(min(5, len(self))):
smiles, order = self.__clean2d_prepare(next(entry))
try:
xy = ctx.call('$.clean2d', smiles)
except JSEvalException:
continue
break
else:
raise ImplementationError

smiles, order = self.__clean2d_prepare(next(entry))
xy: List[Coords] = calculate2d_coord(order, self)
shift_x, shift_y = xy[0]
for n, (x, y) in zip(order, xy):
plane[n] = (x - shift_x, shift_y - y)
Expand Down Expand Up @@ -144,6 +131,6 @@ def __clean2d_prepare(self: 'MoleculeContainer', entry):
w[entry] = -1
smiles, order = self._smiles(w.__getitem__, random=True, charges=False, stereo=False, _return_order=True)
return ''.join(smiles).replace('~', '-'), order


__all__ = ['Calculate2DMolecule']
__all__ = ['Calculate2DMolecule']
124 changes: 124 additions & 0 deletions chython/algorithms/calculate2d/polygon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
#
# Copyright 2024, 2025 Denis Lipatov <[email protected]>
# Copyright 2024, 2025 Vyacheslav Grigorev <[email protected]>
# Copyright 2024, 2025 Timur Gimadiev <[email protected]>
# This file is part of chython.
#
# chython is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, see <https://www.gnu.org/licenses/>.
#

"""
This module introduces the `Polygon` class, designed to perform mathematical
calculations relevant to two-dimensional Cartesian coordinate systems and regular polygons.

The `Polygon` class focuses on properties and calculations related to regular polygons, such as
finding the circumradius, calculating central angles, determining the apothem, and identifying
the type of polygon based on its number of sides. It also includes static methods for
calculating normals to lines defined by two points and for adding, averaging, and mirroring points.

This class provides a comprehensive toolkit for performing geometric computations
essential in fields such as computer graphics, physics simulations, and computational chemistry,
where precise manipulation and analysis of spatial relationships is required.
"""
import math

class Polygon:
"""
The `Polygon` class focuses on properties and calculations related to regular polygons, such as
finding the circumradius, calculating central angles, determining the apothem, and identifying
the type of polygon based on its number of sides. It also includes static methods for
calculating normals to lines defined by two vectors and for adding, averaging, and mirroring
vectors.
"""

def __init__(self, edge_number: float) -> None:
"""
Initializes a Polygon with a specified number of edges.

Parameters:
:param edge_number float:
The number of edges (sides) of the polygon.
"""
self.edge_number: float = edge_number


@staticmethod
def find_polygon_radius(edge_length: float, edge_number: float) -> float:
"""
Calculates the radius of the circumcircle of a regular polygon.

Parameters:
:param edge_length float:
The length of one edge of the polygon.
:param edge_number float:
The number of edges (sides) of the polygon.

Returns float:
The radius of the circumcircle.
"""
return edge_length / (2 * math.sin(math.pi / edge_number))


@staticmethod
def get_central_angle(edge_number: float) -> float:
"""
Calculates the central angle of a regular polygon.

Parameters:
:param edge_number float:
The number of edges (sides) of the polygon.

Returns float:
The central angle in radians.
"""
return math.radians(float(360) / edge_number)


@staticmethod
def get_apothem(radius: float, edge_number: float) -> float:
"""
Calculates the apothem of a regular polygon.

Parameters:
:param radius float:
The radius of the circumcircle of the polygon.
:param edge_number float:
The number of edges (sides) of the polygon.

Returns float:
The length of the apothem.
"""
return radius * math.cos(math.pi / edge_number)


@staticmethod
def get_apothem_from_side_length(length: float, edge_number: float) -> float:
"""
Calculates the apothem of a regular polygon given the side length.

Parameters:
:param length float:
The length of one edge of the polygon.
:param edge_number float:
The number of edges (sides) of the polygon.

Returns float:
The length of the apothem.
"""
radius: float = Polygon.find_polygon_radius(length, edge_number)
return Polygon.get_apothem(radius, edge_number)

__all__ = ['Polygon']

24 changes: 13 additions & 11 deletions chython/algorithms/calculate2d/reaction.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# -*- coding: utf-8 -*-
#
# Copyright 2019-2025 Ramil Nugmanov <[email protected]>
# Copyright 2024, 2025 Denis Lipatov <[email protected]>
# Copyright 2024, 2025 Vyacheslav Grigorev <[email protected]>
# Copyright 2024, 2025 Timur Gimadiev <[email protected]>
# This file is part of chython.
#
# chython is free software; you can redistribute it and/or modify
Expand All @@ -16,28 +19,27 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, see <https://www.gnu.org/licenses/>.
#

from typing import TYPE_CHECKING

try:
from importlib.resources import files
except ImportError: # python3.8
from importlib_resources import files

if TYPE_CHECKING:
from chython import ReactionContainer


from ...containers import ReactionContainer
class Calculate2DReaction:
__slots__ = ()

def clean2d(self: 'ReactionContainer'):
"""
Recalculate 2d coordinates
"""
for m in self.molecules():
m.clean2d()
self.fix_positions()

def fix_positions(self: 'ReactionContainer'):
"""
Fix coordinates of molecules in reaction
"""
shift_x = 0
reactants = self.reactants
amount = len(reactants) - 1
Expand Down Expand Up @@ -74,7 +76,7 @@ def fix_positions(self: 'ReactionContainer'):
shift_x = max_x + 1
self._arrow = (arrow_min, arrow_max)
self._signs = tuple(signs)
self.flush_cache(keep_molecule_cache=True)
self.flush_cache()


__all__ = ['Calculate2DReaction']
__all__ = ['Calculate2DReaction']
Loading