ssakg 0.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.
ssakg-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ include README_PYPI.md
ssakg-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.1
2
+ Name: ssakg
3
+ Version: 0.0.1
4
+ Summary: Sequential Structural Associative Knowledge Graph (ssakg)
5
+ Home-page: https://github.com/PrzemyslawStok/ssakg
6
+ Author: Przemysław Stokłosa
7
+ Author-email: przemyslaw.stoklosa@gmail.com
8
+ License: Apache 2.0
9
+ Keywords: semantic memory,structural graphs,graph density,sequence storage,sequence retrieval,context based memory,graph based memory
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy~=1.26.2
19
+ Requires-Dist: networkx~=3.2.1
20
+ Requires-Dist: matplotlib~=3.8.2
21
+ Requires-Dist: pandas~=2.2.0
22
+ Requires-Dist: tabulate~=0.9.0
23
+ Requires-Dist: PyPrind~=2.11.3
24
+ Requires-Dist: seaborn~=0.13.2
25
+
26
+ # SSAKG
27
+
28
+ Sequential Structural Associative Knowledge Graph (SSAKG) is a semantic memory.
29
+ It can memorize sequences and then read them using a context.
30
+ The context contains random sequence elements. The elements of the context are not ordered.
31
+ ## Requirements
32
+
33
+ - **Minimum Python Version:** 3.10
34
+ ## Installation
35
+
36
+ Use the package manager [pip](https://pip.pypa.io/en/stable/) to install ssakg.
37
+
38
+ ```bash
39
+ pip install ssakg
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ from ssakg import SSAKG
46
+
47
+ # This basic example creates very simple ssakg, and stores two sequences.
48
+ # The program shows how sequences are stored in Associative Knowledge Graph.
49
+
50
+ ssakg = SSAKG(number_of_symbols=10, sequence_length=3, graphs_to_drawing=True)
51
+ ssakg.insert([1, 2, 3])
52
+ ssakg.insert([2, 4, 5])
53
+ ssakg.show()
54
+ ```
55
+
56
+ ## Examples
57
+ Examples of the use of the program:
58
+
59
+ [Basics](https://github.com/PrzemyslawStok/ssakg/blob/main/examples/ssakg_basic.ipynb)\
60
+ [Reading sequences](https://github.com/PrzemyslawStok/ssakg/blob/main/examples/ssakg_reading.ipynb)
61
+ [SSAKG memory](https://github.com/PrzemyslawStok/ssakg/blob/main/examples/ssakg_tests.ipynb)
62
+
63
+ ## Requirements
64
+
65
+ - **Minimum Python Version:** 3.10
66
+
67
+ ## License
68
+
69
+ [Apache 2.0](LICENSE)
ssakg-0.0.1/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # SSAKG
2
+
3
+ Sequential Structural Associative Knowledge Graph (SSAKG) is a semantic memory.
4
+ It can memorize sequences and then read them using a context.
5
+ The context contains random sequence elements. The elements of the context are not ordered.
6
+ ## Requirements
7
+
8
+ - **Minimum Python Version:** 3.10
9
+ ## Installation
10
+
11
+ Use the package manager [pip](https://pip.pypa.io/en/stable/) to install ssakg.
12
+
13
+ ```bash
14
+ pip install ssakg
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from ssakg import SSAKG
21
+
22
+ # This basic example creates very simple ssakg, and stores two sequences.
23
+ # The program shows how sequences are stored in Associative Knowledge Graph.
24
+
25
+ ssakg = SSAKG(number_of_symbols=10, sequence_length=3, graphs_to_drawing=True)
26
+ ssakg.insert([1, 2, 3])
27
+ ssakg.insert([2, 4, 5])
28
+ ssakg.show()
29
+ ```
30
+
31
+ ## Examples
32
+ Examples of the use of the program:
33
+
34
+ [Basics](examples/ssakg_basic.ipynb)\
35
+ [Reading sequences](examples/ssakg_reading.ipynb)
36
+ [SSAKG memory](examples/ssakg_tests.ipynb)
37
+
38
+ ## License
39
+
40
+ [Apache 2.0](LICENSE)
@@ -0,0 +1,44 @@
1
+ # SSAKG
2
+
3
+ Sequential Structural Associative Knowledge Graph (SSAKG) is a semantic memory.
4
+ It can memorize sequences and then read them using a context.
5
+ The context contains random sequence elements. The elements of the context are not ordered.
6
+ ## Requirements
7
+
8
+ - **Minimum Python Version:** 3.10
9
+ ## Installation
10
+
11
+ Use the package manager [pip](https://pip.pypa.io/en/stable/) to install ssakg.
12
+
13
+ ```bash
14
+ pip install ssakg
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from ssakg import SSAKG
21
+
22
+ # This basic example creates very simple ssakg, and stores two sequences.
23
+ # The program shows how sequences are stored in Associative Knowledge Graph.
24
+
25
+ ssakg = SSAKG(number_of_symbols=10, sequence_length=3, graphs_to_drawing=True)
26
+ ssakg.insert([1, 2, 3])
27
+ ssakg.insert([2, 4, 5])
28
+ ssakg.show()
29
+ ```
30
+
31
+ ## Examples
32
+ Examples of the use of the program:
33
+
34
+ [Basics](https://github.com/PrzemyslawStok/ssakg/blob/main/examples/ssakg_basic.ipynb)\
35
+ [Reading sequences](https://github.com/PrzemyslawStok/ssakg/blob/main/examples/ssakg_reading.ipynb)
36
+ [SSAKG memory](https://github.com/PrzemyslawStok/ssakg/blob/main/examples/ssakg_tests.ipynb)
37
+
38
+ ## Requirements
39
+
40
+ - **Minimum Python Version:** 3.10
41
+
42
+ ## License
43
+
44
+ [Apache 2.0](LICENSE)
ssakg-0.0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
ssakg-0.0.1/setup.py ADDED
@@ -0,0 +1,31 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ VERSION = '0.0.1'
4
+ DESCRIPTION = 'Sequential Structural Associative Knowledge Graph (ssakg)'
5
+ LONG_DESCRIPTION = open('README_PYPI.md').read()
6
+
7
+ setup(
8
+ name='ssakg',
9
+ version=VERSION,
10
+ description=DESCRIPTION,
11
+ long_description=LONG_DESCRIPTION,
12
+ long_description_content_type='text/markdown',
13
+ packages=find_packages(),
14
+ include_package_data=True,
15
+ install_requires=['numpy~=1.26.2', "networkx~=3.2.1", "matplotlib~=3.8.2", "pandas~=2.2.0", "tabulate~=0.9.0",
16
+ "PyPrind~=2.11.3", "seaborn~=0.13.2"],
17
+ url='https://github.com/PrzemyslawStok/ssakg',
18
+ license='Apache 2.0',
19
+ author='Przemysław Stokłosa',
20
+ author_email='przemyslaw.stoklosa@gmail.com',
21
+ classifiers=[
22
+ "Development Status :: 4 - Beta",
23
+ "Intended Audience :: Science/Research",
24
+ "Programming Language :: Python :: 3",
25
+ "License :: OSI Approved :: Apache Software License",
26
+ "Operating System :: OS Independent",
27
+ ],
28
+ keywords=["semantic memory", "structural graphs", "graph density", "sequence storage", "sequence retrieval",
29
+ "context based memory", "graph based memory"],
30
+ python_requires='>=3.10',
31
+ )
@@ -0,0 +1,3 @@
1
+ from .ssakg import SSAKG
2
+ from .utils.sequence_generator import SequenceGenerator
3
+ from .utils.ssakg_tester import SSAKG_Tester
@@ -0,0 +1,283 @@
1
+ # Copyright 2024 The SSAKG Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ # Unless required by applicable law or agreed to in writing, software
8
+ # distributed under the License is distributed on an "AS IS" BASIS,
9
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ # See the License for the specific language governing permissions and
11
+ # limitations under the License.
12
+
13
+ import os
14
+
15
+ import numpy as np
16
+
17
+ import warnings
18
+
19
+ import pandas as pd
20
+ import seaborn as sns
21
+
22
+ import matplotlib.pyplot as plot
23
+
24
+ from ssakg.anakg_view import GraphView, create_dir
25
+ from ssakg.sequence_translator import SequenceTranslator
26
+
27
+ from tabulate import tabulate
28
+
29
+
30
+ class ANAKG:
31
+ def __init__(self, graph_dim: int = 10, subgraph_dim: int = 5, dtype=np.int16, graphs_to_drawing=False,
32
+ remove_diagonals=True, weighted_edges=True):
33
+
34
+ # The parameter graphs_to_drawing is only for draw colorfully graph to examples.
35
+ # Do not use it for other purposes.
36
+
37
+ self.graph_dim = graph_dim
38
+ self.subgraph_dim = subgraph_dim
39
+ self.dtype = dtype
40
+
41
+ self.sequence_translator = SequenceTranslator(sequence_matrix_dim=graph_dim, dtype=self.dtype)
42
+
43
+ self.subgraph_pattern = self.create_upper_triangular(self.graph_dim, remove_diagonals=remove_diagonals,
44
+ weighted_edges=weighted_edges, dtype=self.dtype)
45
+
46
+ self.graph = self.crate_graph()
47
+ self.sequences = []
48
+
49
+ self.graphs_to_drawing = graphs_to_drawing
50
+ self.graph_matrices = []
51
+
52
+ @staticmethod
53
+ def create_upper_triangular(dim: int, remove_diagonals=False, weighted_edges=True, dtype=np.int16) -> np.array:
54
+
55
+ array = np.ones([dim, dim], dtype=dtype)
56
+
57
+ if weighted_edges:
58
+ mul = np.arange(1, dim + 1, dtype=dtype)
59
+ else:
60
+ mul = np.ones(dim, dtype=dtype)
61
+
62
+ upper_triangular_matrix = (np.tril(array) * mul).transpose()
63
+
64
+ if remove_diagonals:
65
+ upper_triangular_matrix = upper_triangular_matrix - np.eye(dim, dtype=dtype) * mul
66
+
67
+ return upper_triangular_matrix
68
+
69
+ @staticmethod
70
+ def create_square(dim: int, remove_diagonals=False, weighted_edges=False, dtype=np.int16) -> np.array:
71
+ if weighted_edges:
72
+ mul = np.arange(1, dim + 1, dtype=dtype)
73
+ else:
74
+ mul = np.ones(dim, dtype=dtype)
75
+
76
+ square_matrix = (np.ones([dim, dim], dtype=dtype) * mul).transpose()
77
+
78
+ if remove_diagonals:
79
+ square_matrix = square_matrix - np.eye(dim, dtype=dtype) * mul
80
+
81
+ return square_matrix
82
+
83
+ def set_subgraph_pattern(self, subgraph_pattern: np.array):
84
+ self.subgraph_pattern = subgraph_pattern
85
+
86
+ def crate_graph(self):
87
+ dim = self.graph_dim
88
+
89
+ return np.zeros([dim, dim], dtype=self.dtype)
90
+
91
+ def add_subgraph(self, i: int, j: int):
92
+ subgraph = self.subgraph_pattern.copy()
93
+
94
+ temp_graph = np.zeros(self.graph.shape, dtype=self.dtype)
95
+ temp_graph[i:i + self.subgraph_dim, j:j + self.subgraph_dim] = subgraph
96
+ if self.graphs_to_drawing:
97
+ self.graph_matrices.append(temp_graph)
98
+
99
+ self.graph = self.graph + temp_graph
100
+
101
+ def add_random_subgraph(self):
102
+ rand_min = 0
103
+ rand_max = len(self.graph) - self.subgraph_dim + 1
104
+ i = np.random.randint(rand_min, rand_max)
105
+ j = np.random.randint(rand_min, rand_max)
106
+
107
+ self.add_subgraph(i, j)
108
+
109
+ def add_dim_to_graph(self, dim_to_add: int):
110
+ self.graph_dim += dim_to_add
111
+ self.graph = np.pad(self.graph, (0, dim_to_add), 'constant')
112
+
113
+ for i in range(len(self.graph_matrices)):
114
+ self.graph_matrices[i] = np.pad(self.graph_matrices[i], (0, dim_to_add), 'constant')
115
+
116
+ def sequence_to_subgraph(self, sequence: np.ndarray) -> np.ndarray:
117
+ temp_graph = np.zeros(self.graph.shape, dtype=self.dtype)
118
+
119
+ for i in range(self.subgraph_dim):
120
+ for j in range(self.subgraph_dim):
121
+ temp_graph[sequence[i], sequence[j]] = self.subgraph_pattern[i, j]
122
+
123
+ return temp_graph
124
+
125
+ def insert_sequence(self, sequence: np.ndarray) -> np.ndarray | None:
126
+ if len(sequence) != self.subgraph_dim:
127
+ warnings.warn(f"Sequence has incorrect length {len(sequence)}. Subgraph not inserted.")
128
+ return None
129
+
130
+ new_sequence, dims_to_add = self.sequence_translator.translate_sequence(sequence)
131
+
132
+ if dims_to_add > 0:
133
+ self.add_dim_to_graph(dims_to_add)
134
+
135
+ self.sequences.append(new_sequence)
136
+ temp_graph = self.sequence_to_subgraph(new_sequence)
137
+
138
+ if self.graphs_to_drawing:
139
+ self.graph_matrices.append(temp_graph)
140
+
141
+ self.graph = self.graph + temp_graph
142
+
143
+ return new_sequence
144
+
145
+ def insert(self, sequences: np.ndarray):
146
+ if np.ndim(sequences) == 1:
147
+ return self.insert_sequence(sequences)
148
+ else:
149
+ for sequence in sequences:
150
+ self.insert_sequence(sequence)
151
+
152
+ def get_subgraph_from_sequence(self, sequence: np.ndarray) -> np.ndarray | None:
153
+ if len(sequence) > self.subgraph_dim:
154
+ warn = f"Sequence has incorrect length {len(sequence)}. Subgraph not created."
155
+ warnings.warn(warn)
156
+ return None
157
+
158
+ temp_graph = np.zeros([len(sequence), len(sequence)], dtype=self.dtype)
159
+
160
+ for i in range(len(sequence)):
161
+ for j in range(len(sequence)):
162
+ temp_graph[i, j] = self.graph[sequence[i], sequence[j]]
163
+
164
+ return temp_graph
165
+
166
+ def __str__(self):
167
+ graph_size = self.graph.nbytes
168
+ sequences_no = len(self.graph_matrices)
169
+ sequences_size = 0
170
+ for sequence in self.graph_matrices:
171
+ sequences_size += sequence.nbytes
172
+
173
+ density = self.density()
174
+
175
+ return (f"graph_size: {graph_size} B\ngraph density: {density:.2f}\nstored sequences: "
176
+ f"{sequences_no}\nstored sequences size: {sequences_size}B\n")
177
+
178
+ def get_subgraph(self):
179
+ return self.subgraph_pattern
180
+
181
+ def get_graph(self):
182
+ return self.graph
183
+
184
+ def create_graph_view(self, to_print=False):
185
+ graph_view = GraphView()
186
+ graph_view.graph_from_matrix(np.zeros(self.graph.shape), color="gray", to_print=to_print)
187
+
188
+ last_matrix = np.zeros(self.graph.shape, dtype=self.dtype)
189
+
190
+ for graph_matrix in self.graph_matrices:
191
+ last_matrix += graph_matrix
192
+
193
+ graph_view.graph_from_matrix(last_matrix, add_empty_nodes=False, color="orange", to_print=to_print)
194
+
195
+ return graph_view
196
+
197
+ def density(self) -> float:
198
+ n = self.graph_dim
199
+ non_zeros = np.nonzero(self.graph)
200
+ m = len(non_zeros[0])
201
+
202
+ return m / n / (n - 1)
203
+
204
+ def show(self, to_print=False):
205
+ if not self.graphs_to_drawing:
206
+ warnings.warn("Sequences are not stored. Graph view is empty.")
207
+ return
208
+
209
+ graph_view = self.create_graph_view(to_print=to_print)
210
+ graph_view.draw(title=None, to_print=to_print)
211
+
212
+ def save_fig(self, title: (str, str), output_dir: str = None, output_file: str = None, to_print=True):
213
+ if not self.graphs_to_drawing:
214
+ warnings.warn("Sequences are not stored. Graph view is empty.")
215
+
216
+ graph_view = self.create_graph_view(to_print=to_print)
217
+ graph_view.draw(show=False, output_dir=output_dir, output_file=output_file, title=title, to_print=to_print)
218
+
219
+ def save_matrix(self, output_dir: str = None, output_file: str = None):
220
+ if not self.graphs_to_drawing:
221
+ warnings.warn("Sequences are not stored. Matrix is empty.")
222
+
223
+ if output_file is not None and output_dir is not None:
224
+ create_dir(output_dir)
225
+ file = open(os.path.join(output_dir, output_file), "w")
226
+ file.write(tabulate(self.graph, tablefmt="latex", floatfmt=".0f"))
227
+ file.close()
228
+
229
+ def translate_sequence(self, sequence: np.ndarray):
230
+ return self.sequence_translator.translate_sequence(sequence, add_to_dictionary=False)[0]
231
+
232
+ def decode_sequence(self, sequence: np.ndarray):
233
+ return self.sequence_translator.decode_sentence(sequence)
234
+
235
+ def check_context_correctness(self, context: np.ndarray):
236
+ pass
237
+
238
+ def sequence_from_placeholders(self, sequence: list[str]) -> np.ndarray:
239
+ return self.sequence_translator.sequence_from_placeholders(sequence)
240
+
241
+ def translate_context(self, context: np.ndarray):
242
+ return self.sequence_translator.translate_sequence(context, add_to_dictionary=False)[0]
243
+
244
+ def clear(self):
245
+ self.graph = self.crate_graph()
246
+ self.sequences = []
247
+ self.sequence_translator = SequenceTranslator(sequence_matrix_dim=self.graph_dim, dtype=self.dtype)
248
+ self.graph_matrices = []
249
+
250
+ def draw_density(self, title=None, x_label=None, y_label=None, circle_size: int = 2):
251
+ dim = self.graph_dim
252
+
253
+ graph_1d = self.graph.reshape(dim * dim)
254
+
255
+ non_zeros = np.nonzero(graph_1d)[0]
256
+ x = np.mod(non_zeros, dim)
257
+ y = np.floor_divide(non_zeros, dim)
258
+ non_zeros_values = graph_1d[non_zeros]
259
+
260
+ dataframe = pd.DataFrame({"x": x, "y": y, "z": non_zeros_values})
261
+
262
+ palette = sns.color_palette("dark:#5A9_r", as_cmap=True)
263
+ joint_grid = sns.JointGrid(data=dataframe, x="x", y="y", hue="z", palette=palette)
264
+ joint_grid.plot_joint(sns.scatterplot, s=circle_size)
265
+ joint_grid.plot_marginals(sns.histplot, kde=False, bins=100)
266
+ joint_grid.ax_joint.legend().remove()
267
+
268
+ if title is not None:
269
+ joint_grid.fig.suptitle("ssakg - local density")
270
+
271
+ if x_label is not None:
272
+ joint_grid.ax_joint.set_xlabel(x_label)
273
+ else:
274
+ joint_grid.ax_joint.set_xlabel("")
275
+
276
+ if y_label is not None:
277
+ joint_grid.ax_joint.set_ylabel(y_label)
278
+ else:
279
+ joint_grid.ax_joint.set_ylabel("")
280
+
281
+ joint_grid.fig.tight_layout()
282
+
283
+ plot.show()