pythonknot 0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: pythonknot
3
+ Version: 0.1
4
+ Summary: pythonknot for knot theory calculation
5
+ Home-page:
6
+ Author: yjianzhu
7
+ Author-email: yjianzhu@mail.ustc.edu.cn
8
+ License: UNKNOWN
9
+ Platform: UNKNOWN
10
+
11
+ Python Knot is a Python package for creating and manipulating knots and links, calculating knot invariants, and more.
12
+
@@ -0,0 +1,13 @@
1
+ # Python Knot package: pythonknot
2
+
3
+ Python Knot is a Python package for creating and manipulating knots and links. It is based on the [KnotTheory](https://knot.theory.org) package for Mathematica.
4
+
5
+ ## Installation
6
+
7
+ ## Features
8
+
9
+ 1. Create and manipulate knots and links.
10
+ 2. Compute invariants of knots and links.
11
+ 3. Visualize knots and links.
12
+
13
+ ## Usage
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,148 @@
1
+ import setuptools
2
+
3
+ import os
4
+ import re
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from setuptools import Extension, setup
10
+ from setuptools.command.build_ext import build_ext
11
+
12
+ # Convert distutils Windows platform specifiers to CMake -A arguments
13
+ PLAT_TO_CMAKE = {
14
+ "win32": "Win32",
15
+ "win-amd64": "x64",
16
+ "win-arm32": "ARM",
17
+ "win-arm64": "ARM64",
18
+ }
19
+
20
+
21
+ # A CMakeExtension needs a sourcedir instead of a file list.
22
+ # The name must be the _single_ output extension from the CMake build.
23
+ # If you need multiple extensions, see scikit-build.
24
+ class CMakeExtension(Extension):
25
+ def __init__(self, name: str, sourcedir: str = "") -> None:
26
+ super().__init__(name, sources=[])
27
+ self.sourcedir = os.fspath(Path(sourcedir).resolve())
28
+
29
+
30
+ class CMakeBuild(build_ext):
31
+ def build_extension(self, ext: CMakeExtension) -> None:
32
+ # Must be in this form due to bug in .resolve() only fixed in Python 3.10+
33
+ ext_fullpath = Path.cwd() / self.get_ext_fullpath(ext.name)
34
+ extdir = ext_fullpath.parent.resolve()
35
+
36
+ # Using this requires trailing slash for auto-detection & inclusion of
37
+ # auxiliary "native" libs
38
+
39
+ debug = int(os.environ.get("DEBUG", 0)) if self.debug is None else self.debug
40
+ cfg = "Debug" if debug else "Release"
41
+
42
+ # CMake lets you override the generator - we need to check this.
43
+ # Can be set with Conda-Build, for example.
44
+ cmake_generator = os.environ.get("CMAKE_GENERATOR", "")
45
+
46
+ # Set Python_EXECUTABLE instead if you use PYBIND11_FINDPYTHON
47
+ # EXAMPLE_VERSION_INFO shows you how to pass a value into the C++ code
48
+ # from Python.
49
+ cmake_args = [
50
+ f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}{os.sep}",
51
+ f"-DPYTHON_EXECUTABLE={sys.executable}",
52
+ f"-DCMAKE_BUILD_TYPE={cfg}", # not used on MSVC, but no harm
53
+ ]
54
+ build_args = []
55
+ # Adding CMake arguments set as environment variable
56
+ # (needed e.g. to build for ARM OSx on conda-forge)
57
+ if "CMAKE_ARGS" in os.environ:
58
+ cmake_args += [item for item in os.environ["CMAKE_ARGS"].split(" ") if item]
59
+
60
+ # In this example, we pass in the version to C++. You might not need to.
61
+ cmake_args += [f"-DEXAMPLE_VERSION_INFO={self.distribution.get_version()}"]
62
+
63
+ if self.compiler.compiler_type != "msvc":
64
+ # Using Ninja-build since it a) is available as a wheel and b)
65
+ # multithreads automatically. MSVC would require all variables be
66
+ # exported for Ninja to pick it up, which is a little tricky to do.
67
+ # Users can override the generator with CMAKE_GENERATOR in CMake
68
+ # 3.15+.
69
+ if not cmake_generator or cmake_generator == "Ninja":
70
+ try:
71
+ import ninja
72
+
73
+ ninja_executable_path = Path(ninja.BIN_DIR) / "ninja"
74
+ cmake_args += [
75
+ "-GNinja",
76
+ f"-DCMAKE_MAKE_PROGRAM:FILEPATH={ninja_executable_path}",
77
+ ]
78
+ except ImportError:
79
+ pass
80
+
81
+ else:
82
+ # Single config generators are handled "normally"
83
+ single_config = any(x in cmake_generator for x in {"NMake", "Ninja"})
84
+
85
+ # CMake allows an arch-in-generator style for backward compatibility
86
+ contains_arch = any(x in cmake_generator for x in {"ARM", "Win64"})
87
+
88
+ # Specify the arch if using MSVC generator, but only if it doesn't
89
+ # contain a backward-compatibility arch spec already in the
90
+ # generator name.
91
+ if not single_config and not contains_arch:
92
+ cmake_args += ["-A", PLAT_TO_CMAKE[self.plat_name]]
93
+
94
+ # Multi-config generators have a different way to specify configs
95
+ if not single_config:
96
+ cmake_args += [
97
+ f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{cfg.upper()}={extdir}"
98
+ ]
99
+ build_args += ["--config", cfg]
100
+
101
+ if sys.platform.startswith("darwin"):
102
+ # Cross-compile support for macOS - respect ARCHFLAGS if set
103
+ archs = re.findall(r"-arch (\S+)", os.environ.get("ARCHFLAGS", ""))
104
+ if archs:
105
+ cmake_args += ["-DCMAKE_OSX_ARCHITECTURES={}".format(";".join(archs))]
106
+
107
+ # Set CMAKE_BUILD_PARALLEL_LEVEL to control the parallel build level
108
+ # across all generators.
109
+ if "CMAKE_BUILD_PARALLEL_LEVEL" not in os.environ:
110
+ # self.parallel is a Python 3 only way to set parallel jobs by hand
111
+ # using -j in the build_ext call, not supported by pip or PyPA-build.
112
+ if hasattr(self, "parallel") and self.parallel:
113
+ # CMake 3.12+ only.
114
+ build_args += [f"-j{self.parallel}"]
115
+
116
+ build_temp = Path(self.build_temp) / ext.name
117
+ if not build_temp.exists():
118
+ build_temp.mkdir(parents=True)
119
+
120
+ subprocess.run(
121
+ ["cmake", ext.sourcedir, *cmake_args], cwd=build_temp, check=True
122
+ )
123
+ subprocess.run(
124
+ ["cmake", "--build", ".", *build_args], cwd=build_temp, check=True
125
+ )
126
+
127
+ setuptools.setup(
128
+ name="pythonknot",
129
+ version="0.1",
130
+ author="yjianzhu",
131
+ author_email="yjianzhu@mail.ustc.edu.cn",
132
+ description="pythonknot for knot theory calculation",
133
+ long_description="Python Knot is a Python package for creating and manipulating knots and links, calculating knot invariants, and more.",
134
+ #packages=setuptools.find_packages(),
135
+ url = "",
136
+ ext_modules=[CMakeExtension(name="pythonknot.alexander_poly", sourcedir="src/cpp_module/")],
137
+ cmdclass={"build_ext": CMakeBuild},
138
+
139
+ packages=setuptools.find_packages(where='src'),
140
+ package_dir={"": "src"},
141
+ zip_safe=False,
142
+ install_requires=[
143
+ 'numpy',
144
+ 'scipy',
145
+ 'pybind11',
146
+ 'rmsd',
147
+ ],
148
+ )
File without changes
@@ -0,0 +1,46 @@
1
+ import numpy as np
2
+
3
+ def bond_length(xyz:np.ndarray,type = "open"):
4
+ """计算轨迹的键长分布,输入应该为N_frames, N_atoms, 3的numpy array. type="open"表示开链,type="ring"表示闭链."""
5
+ #print("original shape:", xyz.shape)
6
+ temp = xyz.transpose(1,2,0)
7
+ #print("temp shape:", temp.shape)
8
+ if(type == "ring"):
9
+ bond_length = np.linalg.norm(temp[1:] - temp[:-1], axis=1)
10
+ # 闭链需要计算首尾原子的键长
11
+ end_to_start_bond = np.linalg.norm(temp[-1] - temp[0], axis=0)
12
+ #print("end_to_start_bond shape:", end_to_start_bond.shape)
13
+ # 从(N_frames) 变为 (1, N_frames)
14
+ end_to_start_bond = end_to_start_bond.reshape(1,-1)
15
+ bond_length = np.concatenate((bond_length, end_to_start_bond), axis=0)
16
+ elif(type == "open"):
17
+ bond_length = np.linalg.norm(temp[1:] - temp[:-1], axis=1)
18
+ print("bond_length shape:", bond_length.shape)
19
+ bond_length = bond_length.flatten()
20
+ return bond_length
21
+
22
+ def radius_of_gyration(trajectory:np.ndarray):
23
+ """计算轨迹的质心半径分布,输入应该为N_frames, N_atoms, 3的numpy array."""
24
+ # 计算每帧的质心
25
+ centroids = np.mean(trajectory, axis=1)
26
+
27
+ # 广播质心回到trajectory的形状,以便进行逐元素操作
28
+ # centroids[:, np.newaxis, :] 使得 centroids 从 (N_frames, 3) 扩展为 (N_frames, 1, 3)
29
+ # 这样可以与 trajectory (N_frames, N_atoms, 3) 对齐
30
+ displacement = trajectory - centroids[:, np.newaxis, :]
31
+
32
+ # 计算每个原子到质心的距离的平方
33
+ distances_squared = np.sum(displacement**2, axis=2)
34
+
35
+ # 计算每帧的回转半径
36
+ gyration_radius = np.sqrt(np.mean(distances_squared, axis=1))
37
+
38
+ return gyration_radius
39
+
40
+ def end_to_end_distance(trajectory:np.ndarray):
41
+ """计算轨迹的端到端距离分布,输入应该为N_frames, N_atoms, 3的numpy array."""
42
+ # 计算每帧的端到端距离
43
+ end_to_end = trajectory[:,-1] - trajectory[:,0]
44
+ end_to_end_distance = np.linalg.norm(end_to_end, axis=1)
45
+
46
+ return end_to_end_distance
@@ -0,0 +1,29 @@
1
+ import rmsd
2
+ import numpy
3
+
4
+ def rmsd_ref(coords,ref):
5
+ """
6
+ Calculate the rmsd of coords to ref, and rotate coords to minimize rmsd.
7
+ """
8
+
9
+ rmsd_all = numpy.zeros(coords.shape[0])
10
+
11
+ frames, atoms, _ = coords.shape
12
+ if(ref.shape != coords[0].shape):
13
+ raise ValueError("The shape of ref and coords should be the same.")
14
+
15
+ ref = ref - numpy.mean(ref, axis=0)
16
+
17
+ # main loop
18
+ for i in range(frames):
19
+ # recenter
20
+ coords[i] -= numpy.mean(coords[i], axis=0)
21
+
22
+ # calculate the rotation matrix
23
+ R = rmsd.kabsch(coords[i], ref)
24
+ # rotate the coords
25
+ coords[i] = numpy.dot(coords[i], R)
26
+ # calculate the rmsd
27
+ rmsd_all[i] = rmsd.rmsd(coords[i], ref)
28
+
29
+ return rmsd_all
@@ -0,0 +1,20 @@
1
+ import numpy as np
2
+
3
+ def read_xyz(file):
4
+ """Read xyz file and get all the conf in same file, so return N_frames*n_atoms*3 np array"""
5
+ with open(file) as f:
6
+ lines = f.readlines()
7
+ N_frames = int(len(lines)/(int(lines[0])+2))
8
+ N_atoms = int(lines[0])
9
+ print(N_frames, N_atoms)
10
+ coords = np.zeros((N_frames, N_atoms, 3))
11
+ for i in range(N_frames):
12
+ lines = lines[2:]
13
+ for j in range(N_atoms):
14
+ line = lines[j].split()
15
+ coords[i,j,0] = float(line[1])
16
+ coords[i,j,1] = float(line[2])
17
+ coords[i,j,2] = float(line[3])
18
+ lines = lines[N_atoms:]
19
+
20
+ return coords
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: pythonknot
3
+ Version: 0.1
4
+ Summary: pythonknot for knot theory calculation
5
+ Home-page:
6
+ Author: yjianzhu
7
+ Author-email: yjianzhu@mail.ustc.edu.cn
8
+ License: UNKNOWN
9
+ Platform: UNKNOWN
10
+
11
+ Python Knot is a Python package for creating and manipulating knots and links, calculating knot invariants, and more.
12
+
@@ -0,0 +1,14 @@
1
+ README.md
2
+ setup.py
3
+ src/pythonknot/__init__.py
4
+ src/pythonknot/polymer.py
5
+ src/pythonknot/rmsd.py
6
+ src/pythonknot/xyz.py
7
+ src/pythonknot.egg-info/PKG-INFO
8
+ src/pythonknot.egg-info/SOURCES.txt
9
+ src/pythonknot.egg-info/dependency_links.txt
10
+ src/pythonknot.egg-info/not-zip-safe
11
+ src/pythonknot.egg-info/requires.txt
12
+ src/pythonknot.egg-info/top_level.txt
13
+ test/test.py
14
+ test/test2.py
@@ -0,0 +1,4 @@
1
+ numpy
2
+ scipy
3
+ pybind11
4
+ rmsd
@@ -0,0 +1 @@
1
+ pythonknot
@@ -0,0 +1,7 @@
1
+ import pythonknot
2
+ print(dir(pythonknot))
3
+ import pythonknot.xyz as xyz
4
+ print(dir(xyz))
5
+
6
+ import pythonknot.alexander_poly as alexander_poly
7
+ print(dir(alexander_poly))
@@ -0,0 +1,5 @@
1
+ # 从.so 文件中导入模块
2
+ import importlib.util
3
+ import sys
4
+
5
+ spec = importlib.util.spec_from_file_location("pythonknot", "../dist/pythonknot.cpython-37m-x86_64-linux-gnu.so")