Spaces:
Sleeping
Sleeping
Commit
·
ce48cf1
0
Parent(s):
Duplicate from AndySAnker/DeepStruc
Browse files- .gitattributes +34 -0
- DeepStruc.ipynb +0 -0
- LICENSE +201 -0
- README.md +12 -0
- app.py +94 -0
- models/DeepStruc/model_arch.yaml +33 -0
- models/DeepStruc/models/DeepStruc.ckpt +3 -0
- models/README.md +5 -0
- predict.py +22 -0
- requirements.txt +17 -0
- tools/data_loader.py +236 -0
- tools/ls_points.csv +0 -0
- tools/module.py +364 -0
- tools/utils.py +279 -0
.gitattributes
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
DeepStruc.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
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.
|
README.md
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: DeepStruc App
|
3 |
+
emoji: 🦀
|
4 |
+
colorFrom: green
|
5 |
+
colorTo: blue
|
6 |
+
sdk: streamlit
|
7 |
+
sdk_version: 1.10.0
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
license: apache-2.0
|
11 |
+
duplicated_from: AndySAnker/DeepStruc
|
12 |
+
---
|
app.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import io, os, argparse, torch, random
|
3 |
+
import pytorch_lightning as pl
|
4 |
+
import numpy as np
|
5 |
+
from predict import main
|
6 |
+
from tools.utils import plot_ls
|
7 |
+
|
8 |
+
seed = 37
|
9 |
+
torch.manual_seed(seed)
|
10 |
+
pl.seed_everything(seed)
|
11 |
+
torch.manual_seed(seed)
|
12 |
+
np.random.seed(seed)
|
13 |
+
random.seed(seed)
|
14 |
+
|
15 |
+
st.title('DeepStruc')
|
16 |
+
|
17 |
+
st.write('Welcome to DeepStruc that is a Deep Generative Model which has been trained to solve a mono-metallic structure (<200 atoms) based on a PDF!')
|
18 |
+
st.write('Upload a PDF to use DeepStruc to predict the structure.')
|
19 |
+
|
20 |
+
|
21 |
+
# Define the file upload widget
|
22 |
+
pdf_file = st.file_uploader("Upload PDF file in .gr format", type=["gr"])
|
23 |
+
|
24 |
+
# Define the form to get the other parameters
|
25 |
+
num_structures = st.number_input("Number of structures to generate", min_value=1, max_value=100, value=10)
|
26 |
+
structure_index = st.number_input("Index of structure to visualize", min_value=0, value=3)
|
27 |
+
sigma = st.number_input("Standard deviation for sampling", min_value=0.1, value=3.0)
|
28 |
+
|
29 |
+
# Define parser
|
30 |
+
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
31 |
+
args = parser.parse_args()
|
32 |
+
args.num_samples = num_structures
|
33 |
+
args.index_plot = structure_index
|
34 |
+
args.sigma = sigma
|
35 |
+
# Fixed for DeepStruc app
|
36 |
+
args.model = 'DeepStruc'
|
37 |
+
args.save_path = './'
|
38 |
+
|
39 |
+
# Define the predict button and its behavior
|
40 |
+
if st.button("Generate structures"):
|
41 |
+
if pdf_file is None:
|
42 |
+
st.warning("Please upload a PDF file.")
|
43 |
+
else:
|
44 |
+
# Get the contents of the file as bytes
|
45 |
+
file_bytes = pdf_file.read()
|
46 |
+
|
47 |
+
# Save the contents of the file to disk
|
48 |
+
with open("uploaded_file.gr", "wb") as f:
|
49 |
+
f.write(file_bytes)
|
50 |
+
|
51 |
+
df, index_highlight, these_cords = main(args)
|
52 |
+
|
53 |
+
# Plot the latent space
|
54 |
+
fig = plot_ls(df, index_highlight)
|
55 |
+
st.pyplot(fig)
|
56 |
+
st.write('**The two-dimensional latent space with location of the input.** The size of the points relates to the size of the embedded structure. Each point is coloured after its structure type, FCC (light blue), octahedral (dark grey), decahedral (orange), BCC (green), icosahedral (dark blue), HCP (pink) and SC (red). Each point in the latent space corresponds to a structure based on its simulated PDF. Test data point are plotted on top of the training and validation data, which is made semi-transparent. The latent space locations of the reconstructed structures from the input are shown with black markers and the specific reconstructed structure that is shown in the next box is shown with a black and white marker.')
|
57 |
+
|
58 |
+
# Define the save directory and file name
|
59 |
+
file_name = "DeepStruc_prediction.xyz"
|
60 |
+
|
61 |
+
# Define a download button to download the file
|
62 |
+
def download_button(file_name, button_text):
|
63 |
+
with open(file_name, "rb") as f:
|
64 |
+
bytes = f.read()
|
65 |
+
st.download_button(
|
66 |
+
label=button_text,
|
67 |
+
data=bytes,
|
68 |
+
file_name=file_name,
|
69 |
+
mime="text/xyz",)
|
70 |
+
|
71 |
+
# Save the coordinates to a file and display a download button
|
72 |
+
np.savetxt(file_name, these_cords, fmt="%s")
|
73 |
+
download_button(file_name, "Download XYZ file")
|
74 |
+
|
75 |
+
|
76 |
+
|
77 |
+
st.subheader('Cite')
|
78 |
+
|
79 |
+
st.write('If you use DeepStruc, our code or results, please consider citing our papers. Thanks in advance!')
|
80 |
+
|
81 |
+
st.write('DeepStruc: Towards structure solution from pair distribution function data using deep generative models **2023** (https://pubs.rsc.org/en/content/articlehtml/2022/dd/d2dd00086e)')
|
82 |
+
st.write('Characterising the atomic structure of mono-metallic nanoparticles from x-ray scattering data using conditional generative models **2020** (https://par.nsf.gov/biblio/10300745)')
|
83 |
+
|
84 |
+
st.subheader('LICENSE')
|
85 |
+
|
86 |
+
st.write('This project is licensed under the Apache License Version 2.0, January 2004 - see the LICENSE file at https://github.com/EmilSkaaning/DeepStruc/blob/main/LICENSE.md for details.')
|
87 |
+
st.write("")
|
88 |
+
|
89 |
+
st.subheader('Github')
|
90 |
+
st.write('https://github.com/EmilSkaaning/DeepStruc')
|
91 |
+
|
92 |
+
st.subheader('Questions')
|
93 |
+
st.write('andy@chem.ku.dk or etsk@chem.ku.dk')
|
94 |
+
|
models/DeepStruc/model_arch.yaml
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
PDF_len: 2800
|
2 |
+
decoder:
|
3 |
+
d0: 32
|
4 |
+
d1: 64
|
5 |
+
d2: 128
|
6 |
+
d3: 256
|
7 |
+
d4: 512
|
8 |
+
d5: 1024
|
9 |
+
out_dim: 200
|
10 |
+
encoder:
|
11 |
+
e0: 1024
|
12 |
+
e1: 512
|
13 |
+
e2: 256
|
14 |
+
e3: 128
|
15 |
+
e4: 64
|
16 |
+
latent_space: 2
|
17 |
+
mlps:
|
18 |
+
m0: 256
|
19 |
+
m1: 128
|
20 |
+
m2: 64
|
21 |
+
node_features: 3
|
22 |
+
norm_vals:
|
23 |
+
x: 25.92
|
24 |
+
y: 25.92
|
25 |
+
z: 50.2637
|
26 |
+
posterior:
|
27 |
+
prior_0: 384
|
28 |
+
prior_1: 192
|
29 |
+
prior_2: 24
|
30 |
+
prior:
|
31 |
+
prior_0: 384
|
32 |
+
prior_1: 192
|
33 |
+
prior_2: 24
|
models/DeepStruc/models/DeepStruc.ckpt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b272c760a1df8398b876ea62c52ed700997c00b0fa075e7fa6357ccad04655dd
|
3 |
+
size 82960030
|
models/README.md
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[ChemRxiv](https://chemrxiv.org/engage/chemrxiv/article-details/6221f17357a9d20c9a729ecb) | [Paper](https://pubs.rsc.org/en/content/articlelanding/2023/dd/d2dd00086e)
|
2 |
+
|
3 |
+
# Models
|
4 |
+
This folder contain the DeepStruc model and all other trained models will be save here with the folder name:
|
5 |
+
DeepStruc-year-month-day-time.
|
predict.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys, argparse
|
2 |
+
from tools.module import Net
|
3 |
+
import torch, random, time
|
4 |
+
import numpy as np
|
5 |
+
import pytorch_lightning as pl
|
6 |
+
from tools.utils import get_data, format_predictions, plot_ls, get_model, save_predictions
|
7 |
+
|
8 |
+
def main(args):
|
9 |
+
time_start = time.time()
|
10 |
+
data, data_name, project_name = get_data(args)
|
11 |
+
model_path, model_arch = get_model(args.model)
|
12 |
+
|
13 |
+
Net(model_arch=model_arch)
|
14 |
+
DeepStruc = Net.load_from_checkpoint(model_path,model_arch=model_arch)
|
15 |
+
xyz_pred, latent_space, kl, mu, sigma = DeepStruc(data, mode='prior', sigma_scale=args.sigma)
|
16 |
+
samling_pairs = format_predictions(latent_space, data_name, mu, sigma, args.sigma)
|
17 |
+
|
18 |
+
df, mk_dir, index_highlight = samling_pairs, project_name, args.index_plot
|
19 |
+
|
20 |
+
these_cords = save_predictions(xyz_pred, samling_pairs, project_name, model_arch, args)
|
21 |
+
|
22 |
+
return df, index_highlight, these_cords
|
requirements.txt
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
-f https://download.pytorch.org/whl/cpu/torch_stable.html
|
2 |
+
-f https://data.pyg.org/whl/torch-1.7.1+cpu.html
|
3 |
+
torch==1.7.1+cpu
|
4 |
+
torch-scatter==2.0.7
|
5 |
+
torch-sparse==0.6.9
|
6 |
+
streamlit
|
7 |
+
matplotlib==3.4.3
|
8 |
+
ase
|
9 |
+
pytorch-lightning
|
10 |
+
torch-geometric==1.7.2
|
11 |
+
h5py
|
12 |
+
|
13 |
+
#torch @ https://download.pytorch.org/whl/cu116/torch-1.13.1%2Bcu116-cp38-cp38-linux_x86_64.whl
|
14 |
+
#torch-geometric==1.7.2
|
15 |
+
#torch-scatter==2.1.0
|
16 |
+
#torch-sparse
|
17 |
+
#torch-sparse -f https://data.pyg.org/whl/torch-1.13.0+cpu.html
|
tools/data_loader.py
ADDED
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, torch, h5py, random, sys, shutil, yaml
|
2 |
+
from pytorch_lightning.callbacks import ModelCheckpoint
|
3 |
+
import numpy as np
|
4 |
+
from torch_geometric.data import Data, DataLoader
|
5 |
+
from tqdm import tqdm
|
6 |
+
import pytorch_lightning as pl
|
7 |
+
|
8 |
+
|
9 |
+
class graph_loader(pl.LightningDataModule):
|
10 |
+
def __init__(self, data_dir, cluster_size=None, num_files=None, batchsize=1, shuffle=True, num_workers=0):
|
11 |
+
super(graph_loader, self).__init__()
|
12 |
+
"""
|
13 |
+
|
14 |
+
Parameters
|
15 |
+
----------
|
16 |
+
data_dir
|
17 |
+
num_files
|
18 |
+
batchsize
|
19 |
+
shuffle
|
20 |
+
|
21 |
+
Returns
|
22 |
+
-------
|
23 |
+
|
24 |
+
"""
|
25 |
+
self.batchsize = int(batchsize)
|
26 |
+
self.num_workers = num_workers
|
27 |
+
self.files_sorted = sorted(os.listdir(data_dir))
|
28 |
+
self.cluster_size = cluster_size
|
29 |
+
files = self.files_sorted.copy()
|
30 |
+
# files = [file for file in files if 'FCC' in file]
|
31 |
+
|
32 |
+
if shuffle == True:
|
33 |
+
random.shuffle(files)
|
34 |
+
if files != None:
|
35 |
+
files = files[:num_files]
|
36 |
+
else:
|
37 |
+
pass
|
38 |
+
|
39 |
+
nTrain = int(0.6 * len(files))
|
40 |
+
nValid = int((len(files) - nTrain) / 2)
|
41 |
+
nTest = len(files) - (nTrain + nValid)
|
42 |
+
|
43 |
+
print('\nBatch size: {}'.format(batchsize))
|
44 |
+
print('Total number of graphs {}.'.format(len(files)))
|
45 |
+
print('\tTraining files:', nTrain)
|
46 |
+
print('\tValidation files:', nValid)
|
47 |
+
print('\tTest files:', nTest, '\n')
|
48 |
+
|
49 |
+
self.trSamples, self.vlSamples, self.teSamples = list(), list(), list()
|
50 |
+
print('Loading graphs:')
|
51 |
+
|
52 |
+
for idx in range(len(files)):
|
53 |
+
h5f = h5py.File(data_dir + '/' + files[idx], 'r')
|
54 |
+
b = h5f['Node Feature Matrix'][:]
|
55 |
+
h5f.close()
|
56 |
+
|
57 |
+
if self.cluster_size == None:
|
58 |
+
self.cluster_size = len(b)
|
59 |
+
elif len(b) > self.cluster_size:
|
60 |
+
self.cluster_size = len(b)
|
61 |
+
|
62 |
+
largest_x_dist, largest_y_dist, largest_z_dist, edge_f_max = 0, 0, 0, 0
|
63 |
+
for idx in range(nTrain):
|
64 |
+
h5f = h5py.File(data_dir + '/' + files[idx], 'r')
|
65 |
+
a = h5f['Edge Feature Matrix'][:]
|
66 |
+
b = h5f['Node Feature Matrix'][:]
|
67 |
+
|
68 |
+
h5f.close()
|
69 |
+
|
70 |
+
diff_ph = abs(np.amin(b, axis=0)) + np.amax(b, axis=0)
|
71 |
+
if largest_x_dist < diff_ph[0]:
|
72 |
+
largest_x_dist = diff_ph[0]
|
73 |
+
if largest_y_dist < diff_ph[1]:
|
74 |
+
largest_y_dist = diff_ph[1]
|
75 |
+
if largest_z_dist < diff_ph[2]:
|
76 |
+
largest_z_dist = diff_ph[2]
|
77 |
+
if np.amax(a) > edge_f_max:
|
78 |
+
edge_f_max = np.amax(a)
|
79 |
+
|
80 |
+
self.largest_x_dist = largest_x_dist
|
81 |
+
self.largest_y_dist = largest_y_dist
|
82 |
+
self.largest_z_dist = largest_z_dist
|
83 |
+
|
84 |
+
for idx in tqdm(range(len(files))):
|
85 |
+
h5f = h5py.File(data_dir + '/' + files[idx], 'r')
|
86 |
+
a = h5f['Edge Feature Matrix'][:] # todo: norm this
|
87 |
+
b = h5f['Node Feature Matrix'][:]
|
88 |
+
c = h5f['Edge Directions'][:]
|
89 |
+
d = h5f['PDF label'][:]
|
90 |
+
h5f.close()
|
91 |
+
|
92 |
+
a /= edge_f_max
|
93 |
+
min_vals = np.amin(b, axis=0)
|
94 |
+
if min_vals[0] < 0.0: # Make all coordinates positive
|
95 |
+
b[:, 0] -= min_vals[0]
|
96 |
+
if min_vals[1] < 0.0: # Make all coordinates positive
|
97 |
+
b[:, 1] -= min_vals[1]
|
98 |
+
if min_vals[2] < 0.0: # Make all coordinates positive
|
99 |
+
b[:, 2] -= min_vals[2]
|
100 |
+
|
101 |
+
b[:, 0] /= largest_x_dist
|
102 |
+
b[:, 1] /= largest_y_dist
|
103 |
+
b[:, 2] /= largest_z_dist
|
104 |
+
|
105 |
+
cord_ph = np.zeros((self.cluster_size, np.shape(b)[1])) - 1
|
106 |
+
cord_ph[:np.shape(b)[0]] = b
|
107 |
+
|
108 |
+
d /= np.amax(d) # Standardize PDF
|
109 |
+
|
110 |
+
pdf = torch.tensor([d], dtype=torch.float)
|
111 |
+
x = torch.tensor(b, dtype=torch.float)
|
112 |
+
y = torch.tensor([cord_ph], dtype=torch.float)
|
113 |
+
edge_index = torch.tensor(c, dtype=torch.long)
|
114 |
+
edge_attr = torch.tensor(a, dtype=torch.float)
|
115 |
+
name_idx = torch.tensor(self.files_sorted.index(files[idx]), dtype=torch.int16)
|
116 |
+
|
117 |
+
if idx < nTrain:
|
118 |
+
self.trSamples.append(
|
119 |
+
tuple((Data(x=x, y=y, edge_index=edge_index, edge_attr=edge_attr), pdf.T, name_idx)))
|
120 |
+
elif idx < nTrain + nValid:
|
121 |
+
self.vlSamples.append(
|
122 |
+
tuple((Data(x=x, y=y, edge_index=edge_index, edge_attr=edge_attr), pdf.T, name_idx)))
|
123 |
+
else:
|
124 |
+
self.teSamples.append(
|
125 |
+
tuple((Data(x=x, y=y, edge_index=edge_index, edge_attr=edge_attr), pdf.T, name_idx)))
|
126 |
+
|
127 |
+
def train_dataloader(self):
|
128 |
+
return DataLoader(self.trSamples, batch_size=self.batchsize, shuffle=True, num_workers=self.num_workers)
|
129 |
+
|
130 |
+
def val_dataloader(self):
|
131 |
+
return DataLoader(self.vlSamples, batch_size=self.batchsize, num_workers=self.num_workers)
|
132 |
+
|
133 |
+
def test_dataloader(self):
|
134 |
+
return DataLoader(self.teSamples, batch_size=self.batchsize, num_workers=self.num_workers)
|
135 |
+
|
136 |
+
|
137 |
+
def save_xyz_file(save_dir, cords, file_name, xyz_scale=[1,1,1]):
|
138 |
+
|
139 |
+
cords = [xyz for xyz in cords if np.mean(xyz) >= -0.2]
|
140 |
+
cords = np.array(cords)
|
141 |
+
cords[:,0] -= cords[:,0].mean()
|
142 |
+
cords[:,1] -= cords[:,1].mean()
|
143 |
+
cords[:,2] -= cords[:,2].mean()
|
144 |
+
these_cords = []
|
145 |
+
for count, xyz in enumerate(cords):
|
146 |
+
if count == 0:
|
147 |
+
these_cords.append(['{:d}'.format(len(cords))])
|
148 |
+
these_cords.append([''])
|
149 |
+
|
150 |
+
these_cords.append(['W {:.4f} {:.4f} {:.4f}'.format(xyz[0]*xyz_scale[0], xyz[1]*xyz_scale[1], xyz[2]*xyz_scale[2])])
|
151 |
+
|
152 |
+
np.savetxt(save_dir + '/{}.xyz'.format(file_name), these_cords, fmt='%s')
|
153 |
+
|
154 |
+
return these_cords
|
155 |
+
|
156 |
+
|
157 |
+
def folder_manager(input_dict, model_arch):
|
158 |
+
this_trainer = None
|
159 |
+
epoch = input_dict['epochs']
|
160 |
+
if not os.path.isdir(input_dict['save_dir']):
|
161 |
+
os.mkdir(input_dict['save_dir'])
|
162 |
+
os.mkdir(input_dict['save_dir'] + '/models')
|
163 |
+
shutil.copy2('train.py', input_dict['save_dir'] + '/train.py')
|
164 |
+
shutil.copy2('./tools/data_loader.py', input_dict['save_dir'] + '/data_loader.py')
|
165 |
+
shutil.copy2('./tools/module.py', input_dict['save_dir'] + '/module.py')
|
166 |
+
os.mkdir(input_dict['save_dir'] + '/prior')
|
167 |
+
os.mkdir(input_dict['save_dir'] + '/posterior')
|
168 |
+
else:
|
169 |
+
shutil.copy2('train.py', input_dict['save_dir'] + '/train.py')
|
170 |
+
shutil.copy2('./tools/data_loader.py', input_dict['save_dir'] + '/data_loader.py')
|
171 |
+
shutil.copy2('./tools/module.py', input_dict['save_dir'] + '/module.py')
|
172 |
+
|
173 |
+
if input_dict['load_trainer']:
|
174 |
+
best_model = sorted(os.listdir(input_dict['save_dir'] + '/models'))
|
175 |
+
print(f'\nUsing {best_model[0]} as starting model!\n')
|
176 |
+
this_trainer = input_dict['save_dir'] + '/models/' + best_model[0]
|
177 |
+
#input_dict = yaml.load(f'{input_dict["save_dir"]}/input_dict.yaml', Loader=yaml.FullLoader)
|
178 |
+
|
179 |
+
try:
|
180 |
+
with open(f'{input_dict["save_dir"]}/input_dict.yaml') as file:
|
181 |
+
input_dict = yaml.full_load(file)
|
182 |
+
input_dict['load_trainer'] = True
|
183 |
+
input_dict['epochs'] = epoch
|
184 |
+
with open(f'{input_dict["save_dir"]}/model_arch.yaml') as file:
|
185 |
+
model_arch = yaml.full_load(file)
|
186 |
+
except FileNotFoundError: # todo: transition - need to be deleted at some point
|
187 |
+
with open(f'{input_dict["save_dir"]}/input_dict.yaml', 'w') as outfile:
|
188 |
+
yaml.dump(input_dict, outfile, allow_unicode=True, default_flow_style=False)
|
189 |
+
|
190 |
+
with open(f'{input_dict["save_dir"]}/model_arch.yaml', 'w') as outfile:
|
191 |
+
yaml.dump(model_arch, outfile, allow_unicode=True, default_flow_style=False)
|
192 |
+
else:
|
193 |
+
with open(f'{input_dict["save_dir"]}/input_dict.yaml', 'w') as outfile:
|
194 |
+
yaml.dump(input_dict, outfile, allow_unicode=True, default_flow_style=False)
|
195 |
+
|
196 |
+
with open(f'{input_dict["save_dir"]}/model_arch.yaml', 'w') as outfile:
|
197 |
+
yaml.dump(model_arch, outfile, allow_unicode=True, default_flow_style=False)
|
198 |
+
return this_trainer, input_dict, model_arch
|
199 |
+
|
200 |
+
|
201 |
+
def get_callbacks(save_dir):
|
202 |
+
checkpoint_callback_tot = ModelCheckpoint(
|
203 |
+
monitor='vld_tot',
|
204 |
+
dirpath=save_dir + '/models',
|
205 |
+
filename='model-{vld_tot:.5f}-{beta:.3f}-{vld_rec_pdf:.5f}-{epoch:010d}',
|
206 |
+
save_top_k=5,
|
207 |
+
mode='min',
|
208 |
+
save_last=True,
|
209 |
+
)
|
210 |
+
|
211 |
+
checkpoint_callback_rec = ModelCheckpoint(
|
212 |
+
monitor='vld_rec',
|
213 |
+
dirpath=save_dir + '/models',
|
214 |
+
filename='model-{vld_rec:.5f}-{beta:.3f}-{vld_rec_pdf:.5f}-{vld_tot:.5f}-{epoch:010d}',
|
215 |
+
save_top_k=5,
|
216 |
+
mode='min',
|
217 |
+
)
|
218 |
+
|
219 |
+
checkpoint_callback_kld = ModelCheckpoint(
|
220 |
+
monitor='vld_kld',
|
221 |
+
dirpath=save_dir + '/models',
|
222 |
+
filename='model-{vld_kld:.5f}-{beta:.3f}-{vld_rec_pdf:.5f}-{vld_tot:.5f}-{epoch:010d}',
|
223 |
+
save_top_k=5,
|
224 |
+
mode='min',
|
225 |
+
)
|
226 |
+
|
227 |
+
checkpoint_callback_vld_rec_pdf = ModelCheckpoint(
|
228 |
+
monitor='vld_rec_pdf',
|
229 |
+
dirpath=save_dir + '/models',
|
230 |
+
filename='model-{vld_rec_pdf:.5f}-{beta:.3f}-{vld_tot:.5f}-{epoch:010d}',
|
231 |
+
save_top_k=5,
|
232 |
+
mode='min',
|
233 |
+
)
|
234 |
+
|
235 |
+
return [checkpoint_callback_tot, checkpoint_callback_rec, checkpoint_callback_kld,
|
236 |
+
checkpoint_callback_vld_rec_pdf]
|
tools/ls_points.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tools/module.py
ADDED
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch, sys
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import torch.nn
|
5 |
+
from torch_geometric.nn import GATConv
|
6 |
+
import pytorch_lightning as pl
|
7 |
+
from collections import OrderedDict
|
8 |
+
from torch_geometric.nn.glob import global_add_pool, GlobalAttention
|
9 |
+
from torch.distributions import Normal, Independent
|
10 |
+
from torch.distributions.kl import kl_divergence as KLD
|
11 |
+
|
12 |
+
class Net(pl.LightningModule):
|
13 |
+
def __init__(self, model_arch, lr=1e-4, beta=0, beta_inc=0.001, beta_max=1, rec_th=0.0001):
|
14 |
+
super(Net, self).__init__()
|
15 |
+
self.actFunc = nn.LeakyReLU()
|
16 |
+
self.actFunc_ReLU = nn.ReLU()
|
17 |
+
self.cluster_size = int(model_arch['decoder']['out_dim'])
|
18 |
+
self.latent_space = model_arch['latent_space']
|
19 |
+
self.beta = beta # starting val
|
20 |
+
self.beta_inc = beta_inc # beta increase
|
21 |
+
self.rec_th = rec_th # Update beta if loss_rec is =< this value
|
22 |
+
self.last_beta_update = 0
|
23 |
+
self.beta_max = beta_max
|
24 |
+
self.lr = lr
|
25 |
+
self.num_node_features = model_arch['node_features']
|
26 |
+
self.encoder_layers = self.Encoder(model_arch['node_features'], model_arch['encoder'], model_arch['mlps']['m0'])
|
27 |
+
self.decoder_layers = self.Decoder(model_arch['node_features'], model_arch['decoder'], model_arch['latent_space'])
|
28 |
+
self.mlp_layers = self.MLPs(model_arch['mlps'], model_arch['latent_space'])
|
29 |
+
|
30 |
+
self.prior_layers = self.conditioning_nw(model_arch['PDF_len'], model_arch['prior'], self.latent_space * 2)
|
31 |
+
self.posterior_layers = self.conditioning_nw(model_arch['PDF_len'], model_arch['posterior'], model_arch['mlps']['m0']) # Posterior
|
32 |
+
self.glob_at = GlobalAttention(torch.nn.Linear(model_arch['mlps']['m0'], 1), torch.nn.Linear(model_arch['mlps']['m0'], model_arch['mlps']['m0']))
|
33 |
+
|
34 |
+
|
35 |
+
def MLPs(self, model_arch, latent_dim):
|
36 |
+
layers = OrderedDict()
|
37 |
+
|
38 |
+
for idx, key in enumerate(model_arch.keys()):
|
39 |
+
if idx == 0:
|
40 |
+
layers[str(key)] = torch.nn.Linear(model_arch[key]*2, model_arch[key])
|
41 |
+
else:
|
42 |
+
layers[str(key)] = torch.nn.Linear(former_nhid, model_arch[key])
|
43 |
+
|
44 |
+
former_nhid = model_arch[key]
|
45 |
+
|
46 |
+
layers['-1'] = torch.nn.Linear(former_nhid, latent_dim*2)
|
47 |
+
|
48 |
+
|
49 |
+
return nn.Sequential(layers)
|
50 |
+
|
51 |
+
|
52 |
+
def Encoder(self, init_data, model_arch, out_dim):
|
53 |
+
layers = OrderedDict()
|
54 |
+
|
55 |
+
for idx, key in enumerate(model_arch.keys()):
|
56 |
+
if idx == 0:
|
57 |
+
layers[str(key)] = GATConv(init_data, model_arch[key])
|
58 |
+
else:
|
59 |
+
layers[str(key)] = GATConv(former_nhid, model_arch[key])
|
60 |
+
|
61 |
+
former_nhid = model_arch[key]
|
62 |
+
|
63 |
+
|
64 |
+
#layers['-1'] = GATConv(former_nhid, model_arch['m0'])
|
65 |
+
layers[str('e{}'.format(idx + 1))] = GATConv(former_nhid, out_dim)
|
66 |
+
|
67 |
+
return nn.Sequential(layers)
|
68 |
+
|
69 |
+
def Decoder(self, init_data, model_arch, latent_dim):
|
70 |
+
layers = OrderedDict()
|
71 |
+
|
72 |
+
for idx, key in enumerate(model_arch.keys()):
|
73 |
+
if idx == 0 :
|
74 |
+
layers[str(key)] = nn.Linear(latent_dim, model_arch[key])
|
75 |
+
elif key == 'out_dim':
|
76 |
+
continue
|
77 |
+
else:
|
78 |
+
layers[str(key)] = nn.Linear(former_nhid, model_arch[key])
|
79 |
+
|
80 |
+
former_nhid = model_arch[key]
|
81 |
+
|
82 |
+
|
83 |
+
layers[str('d{}'.format(idx+1))] = nn.Linear(former_nhid, model_arch['out_dim']*init_data)
|
84 |
+
|
85 |
+
return nn.Sequential(layers)
|
86 |
+
|
87 |
+
def conditioning_nw(self, pdf, model_arch, out):
|
88 |
+
### Conditioning network on prior for atom list
|
89 |
+
### Creates additional node features per node
|
90 |
+
### Assumes 1xself.atomRangex1 one hot encoding vector as input
|
91 |
+
### Output: 1x2*latent_dimx1
|
92 |
+
"""conditioning_layers = nn.Sequential(
|
93 |
+
GatedConv1d(pdf, 48, kernel_size=1, stride=1), nn.ReLU(),
|
94 |
+
GatedConv1d(48, 24, kernel_size=1, stride=1), nn.ReLU(),
|
95 |
+
GatedConv1d(24, out, kernel_size=1, stride=1))"""
|
96 |
+
|
97 |
+
|
98 |
+
conditioning_layers = torch.nn.Sequential()
|
99 |
+
for idx, key in enumerate(model_arch.keys()):
|
100 |
+
if idx == 0:
|
101 |
+
conditioning_layers.add_module(str(key), GatedConv1d(pdf, model_arch[key], kernel_size=1, stride=1))
|
102 |
+
else:
|
103 |
+
conditioning_layers.add_module(str(key), GatedConv1d(former_nhid, model_arch[key], kernel_size=1, stride=1))
|
104 |
+
|
105 |
+
former_nhid = model_arch[key]
|
106 |
+
conditioning_layers.add_module('-1', GatedConv1d(former_nhid, out, kernel_size=1, stride=1))
|
107 |
+
|
108 |
+
return conditioning_layers
|
109 |
+
|
110 |
+
|
111 |
+
def forward(self, data, mode='posterior', sigma_scale=1):
|
112 |
+
"""
|
113 |
+
|
114 |
+
Parameters
|
115 |
+
----------
|
116 |
+
data :
|
117 |
+
mode : str - posterior, prior or generate
|
118 |
+
|
119 |
+
Returns
|
120 |
+
-------
|
121 |
+
|
122 |
+
"""
|
123 |
+
self.sigma_scale = sigma_scale
|
124 |
+
if mode == 'posterior':
|
125 |
+
pdf_cond = data[1].to(self.device)
|
126 |
+
data = data[0].to(self.device)
|
127 |
+
try:
|
128 |
+
this_batch_size = len(data.batch.unique())
|
129 |
+
except:
|
130 |
+
this_batch_size = 1
|
131 |
+
|
132 |
+
# Prior
|
133 |
+
prior = self.get_prior_dist(pdf_cond)
|
134 |
+
|
135 |
+
# Posterior
|
136 |
+
posterior = self.get_posterior_dist(data, pdf_cond, this_batch_size)
|
137 |
+
|
138 |
+
# Divergence between posterior and prior
|
139 |
+
kl = KLD(posterior, prior) / this_batch_size
|
140 |
+
|
141 |
+
# Draw z from posterior distribution
|
142 |
+
z_sample = posterior.rsample()
|
143 |
+
z = z_sample.clone()
|
144 |
+
|
145 |
+
elif mode == 'prior':
|
146 |
+
try:
|
147 |
+
hej = data.clone()
|
148 |
+
pdf_cond = data.to(self.device)
|
149 |
+
this_batch_size = len(data)
|
150 |
+
except:
|
151 |
+
#print(data)
|
152 |
+
pdf_cond = data[1].to(self.device)
|
153 |
+
this_batch_size = 1
|
154 |
+
|
155 |
+
|
156 |
+
# Prior
|
157 |
+
prior = self.get_prior_dist(pdf_cond)
|
158 |
+
|
159 |
+
# Draw z from prior distribution
|
160 |
+
z_sample = prior.rsample()
|
161 |
+
z = z_sample.clone()
|
162 |
+
kl = torch.zeros(this_batch_size) -1
|
163 |
+
|
164 |
+
elif mode == 'generate':
|
165 |
+
# Set is given
|
166 |
+
z = data.clone()
|
167 |
+
z_sample = data.clone()
|
168 |
+
this_batch_size = 1
|
169 |
+
kl = torch.zeros(this_batch_size) -1
|
170 |
+
|
171 |
+
# Decoder
|
172 |
+
for idx, layer in enumerate(self.decoder_layers):
|
173 |
+
if idx == len(self.decoder_layers)-1:
|
174 |
+
z_sample = layer(z_sample)
|
175 |
+
else:
|
176 |
+
z_sample = self.actFunc(layer(z_sample))
|
177 |
+
|
178 |
+
z_sample = z_sample.view(this_batch_size, self.cluster_size, self.num_node_features) # Output
|
179 |
+
|
180 |
+
return z_sample, z, kl, self.mu, self.sigma#.mean()
|
181 |
+
|
182 |
+
|
183 |
+
def get_prior_dist(self, pdf_cond):
|
184 |
+
cond_prior = pdf_cond.clone()
|
185 |
+
|
186 |
+
for idx, layer in enumerate(self.prior_layers):
|
187 |
+
if idx == len(self.prior_layers) - 1:
|
188 |
+
cond_prior = layer(cond_prior)
|
189 |
+
else:
|
190 |
+
cond_prior = self.actFunc(layer(cond_prior))
|
191 |
+
|
192 |
+
cond_prior = cond_prior.squeeze(-1)
|
193 |
+
prior = self.get_distribution(cond_prior)
|
194 |
+
return prior
|
195 |
+
|
196 |
+
|
197 |
+
def get_posterior_dist(self, data, pdf_cond, this_batch_size):
|
198 |
+
cond_post = pdf_cond.clone()
|
199 |
+
|
200 |
+
# Posterior
|
201 |
+
for idx, layer in enumerate(self.posterior_layers):
|
202 |
+
if idx == len(self.posterior_layers) - 1:
|
203 |
+
cond_post = layer(cond_post)
|
204 |
+
else:
|
205 |
+
cond_post = self.actFunc(layer(cond_post))
|
206 |
+
|
207 |
+
# Encoder
|
208 |
+
z = data.x.clone()
|
209 |
+
for idx, layer in enumerate(self.encoder_layers):
|
210 |
+
if idx == len(self.encoder_layers) - 1:
|
211 |
+
z = layer(z, data.edge_index)
|
212 |
+
else:
|
213 |
+
edge_index = data.edge_index
|
214 |
+
|
215 |
+
z = self.actFunc(layer(z, edge_index))
|
216 |
+
test = z.clone()
|
217 |
+
|
218 |
+
#z = global_add_pool(z, data.batch, size=this_batch_size) # Sum note features
|
219 |
+
z = self.glob_at(test, data.batch, size=this_batch_size)
|
220 |
+
|
221 |
+
cond_post = cond_post.squeeze(-1)
|
222 |
+
|
223 |
+
z = torch.cat((z, cond_post), -1)
|
224 |
+
|
225 |
+
for idx, layer in enumerate(self.mlp_layers):
|
226 |
+
if idx == len(self.mlp_layers) - 1:
|
227 |
+
z = layer(z)
|
228 |
+
else:
|
229 |
+
z = self.actFunc(layer(z))
|
230 |
+
|
231 |
+
# Draw from distribution
|
232 |
+
posterior = self.get_distribution(z)
|
233 |
+
return posterior
|
234 |
+
|
235 |
+
|
236 |
+
def get_distribution(self, z):
|
237 |
+
mu, log_var = torch.chunk(z, 2, dim=-1)
|
238 |
+
log_var = nn.functional.softplus(log_var) # Sigma can't be negative
|
239 |
+
sigma = torch.exp(log_var / 2) * self.sigma_scale
|
240 |
+
self.sigma = sigma
|
241 |
+
self.mu = mu
|
242 |
+
distribution = Independent(Normal(loc=mu, scale=sigma), 2)
|
243 |
+
return distribution
|
244 |
+
|
245 |
+
|
246 |
+
def training_step(self, batch, batch_nb):
|
247 |
+
prediction, _, kl, _, _ = self.forward(batch)
|
248 |
+
|
249 |
+
loss = weighted_mse_loss(prediction, batch[0]['y'], self.device)
|
250 |
+
|
251 |
+
#loss = F.mse_loss(prediction, batch[0]['y'])
|
252 |
+
log_loss = loss#torch.log(loss)
|
253 |
+
|
254 |
+
tot_loss = log_loss + (self.beta * kl)
|
255 |
+
|
256 |
+
self.log('trn_tot', tot_loss, prog_bar=False, on_step=False, on_epoch=True)
|
257 |
+
self.log('trn_rec', loss, prog_bar=False, on_step=False, on_epoch=True)
|
258 |
+
self.log('trn_log_rec', log_loss, prog_bar=False, on_step=False, on_epoch=True)
|
259 |
+
self.log('trn_kld', kl, prog_bar=False, on_step=False, on_epoch=True)
|
260 |
+
|
261 |
+
return tot_loss
|
262 |
+
|
263 |
+
|
264 |
+
def validation_step(self, batch, batch_nb):
|
265 |
+
prediction, _, kl, _, _ = self.forward(batch)
|
266 |
+
prediction_pdf, _, _, _, _ = self.forward(batch[1], mode='prior')
|
267 |
+
|
268 |
+
#loss = weighted_mse_loss(prediction, batch[0]['y'], self.device, node_weight=5)
|
269 |
+
#loss_pdf = weighted_mse_loss(prediction_pdf, batch[0]['y'], self.device, node_weight=5)
|
270 |
+
|
271 |
+
loss = F.mse_loss(prediction, batch[0]['y'])
|
272 |
+
loss_pdf = F.mse_loss(prediction_pdf, batch[0]['y'])
|
273 |
+
|
274 |
+
log_loss = loss#torch.log(loss)
|
275 |
+
|
276 |
+
tot_loss = log_loss + (self.beta * kl)
|
277 |
+
|
278 |
+
if (self.last_beta_update != self.current_epoch and self.beta < self.beta_max) and loss <= self.rec_th:
|
279 |
+
self.beta += self.beta_inc
|
280 |
+
self.last_beta_update = self.current_epoch
|
281 |
+
|
282 |
+
beta = self.beta
|
283 |
+
self.log('vld_tot', tot_loss, prog_bar=True, on_epoch=True)
|
284 |
+
self.log('vld_rec', loss, prog_bar=True, on_epoch=True)
|
285 |
+
self.log('vld_log_rec', log_loss, prog_bar=True, on_epoch=True)
|
286 |
+
self.log('vld_rec_pdf', loss_pdf, prog_bar=True, on_epoch=True)
|
287 |
+
self.log('vld_kld', kl, prog_bar=True, on_epoch=True)
|
288 |
+
self.log('beta', beta, prog_bar=True, on_step=False, on_epoch=True)
|
289 |
+
|
290 |
+
return tot_loss
|
291 |
+
|
292 |
+
|
293 |
+
def test_step(self, batch, batch_nb):
|
294 |
+
prediction, _, kl, _, _ = self.forward(batch)
|
295 |
+
prediction_pdf, _, _, _, _ = self.forward(batch[1], mode='prior')
|
296 |
+
|
297 |
+
#loss = weighted_mse_loss(prediction, batch[0]['y'], self.device, node_weight=5)
|
298 |
+
#loss_pdf = weighted_mse_loss(prediction_pdf, batch[0]['y'], self.device, node_weight=5)
|
299 |
+
|
300 |
+
loss = F.mse_loss(prediction, batch[0]['y'])
|
301 |
+
loss_pdf = F.mse_loss(prediction_pdf, batch[0]['y'])
|
302 |
+
|
303 |
+
log_loss = loss#torch.log(loss)
|
304 |
+
|
305 |
+
tot_loss = log_loss + (self.beta * kl)
|
306 |
+
|
307 |
+
self.log('tst_tot', tot_loss, prog_bar=False, on_epoch=True)
|
308 |
+
self.log('tst_rec', loss, prog_bar=False, on_epoch=True)
|
309 |
+
self.log('tst_log_rec', log_loss, prog_bar=False, on_epoch=True)
|
310 |
+
self.log('tst_rec_pdf', loss_pdf, prog_bar=False, on_epoch=True)
|
311 |
+
self.log('tst_kld', kl, prog_bar=False, on_epoch=True)
|
312 |
+
|
313 |
+
return tot_loss
|
314 |
+
|
315 |
+
|
316 |
+
def configure_optimizers(self):
|
317 |
+
return torch.optim.Adam(self.parameters(), lr=self.lr)
|
318 |
+
|
319 |
+
|
320 |
+
class GatedConv1d(nn.Module):
|
321 |
+
def __init__(self, input_channels, output_channels,
|
322 |
+
kernel_size, stride, padding=0, dilation=1, activation=None):
|
323 |
+
super(GatedConv1d, self).__init__()
|
324 |
+
|
325 |
+
self.activation = activation
|
326 |
+
self.sigmoid = nn.Sigmoid()
|
327 |
+
|
328 |
+
self.h = nn.Conv1d(input_channels, output_channels, kernel_size,
|
329 |
+
stride, padding, dilation)
|
330 |
+
self.g = nn.Conv1d(input_channels, output_channels, kernel_size,
|
331 |
+
stride, padding, dilation)
|
332 |
+
|
333 |
+
def forward(self, x):
|
334 |
+
if self.activation is None:
|
335 |
+
h = self.h(x)
|
336 |
+
else:
|
337 |
+
h = self.activation(self.h(x))
|
338 |
+
g = self.sigmoid(self.g(x))
|
339 |
+
|
340 |
+
return h * g
|
341 |
+
|
342 |
+
|
343 |
+
def weighted_mse_loss(pred, label,device, dummy_weight=0.1, node_weight=1):
|
344 |
+
"""
|
345 |
+
|
346 |
+
Parameters
|
347 |
+
----------
|
348 |
+
pred : Predictions. (tensor)
|
349 |
+
label : True labels. (tensor)
|
350 |
+
dummy_weight : Weight of dummy nodes, default is 0.1. (float)
|
351 |
+
|
352 |
+
Returns
|
353 |
+
-------
|
354 |
+
this_loss : Computed loss. (tensor)
|
355 |
+
"""
|
356 |
+
mask = torch.ones(label.shape).to(device)
|
357 |
+
mask[label == -1.] = dummy_weight
|
358 |
+
mask[label >= -0] = node_weight
|
359 |
+
|
360 |
+
loss_func = nn.MSELoss(reduction='none')
|
361 |
+
this_loss = loss_func(pred, label)
|
362 |
+
this_loss = this_loss*mask
|
363 |
+
|
364 |
+
return this_loss.mean()
|
tools/utils.py
ADDED
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch, os, yaml, sys
|
2 |
+
import numpy as np
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import pandas as pd
|
5 |
+
from tqdm import tqdm
|
6 |
+
from matplotlib.patches import Ellipse
|
7 |
+
import matplotlib.lines as mlines
|
8 |
+
from matplotlib.gridspec import GridSpec
|
9 |
+
import datetime
|
10 |
+
from tools.data_loader import save_xyz_file
|
11 |
+
import streamlit as st
|
12 |
+
|
13 |
+
def get_data(args): # Todo: write your own dataloader.
|
14 |
+
ct = str(datetime.datetime.now()).replace(' ', '_').replace(':','-').replace('.','-')
|
15 |
+
project_name = f'{args.save_path}/DeepStruc_{ct}'
|
16 |
+
print(f'\nProject name is: {project_name}')
|
17 |
+
if not os.path.isdir(f'{project_name}'):
|
18 |
+
os.mkdir(f'{project_name}')
|
19 |
+
|
20 |
+
samples = args.num_samples
|
21 |
+
## Use the uploaded file. Does not support multiple files. Could be written smarter.
|
22 |
+
files = ['uploaded_file.gr']
|
23 |
+
this_path = '.'
|
24 |
+
#this_path = args.data
|
25 |
+
#if os.path.isdir(this_path):
|
26 |
+
# files = sorted(os.listdir(this_path))
|
27 |
+
#else:
|
28 |
+
# files = [this_path]
|
29 |
+
# this_path = '.'
|
30 |
+
|
31 |
+
x_list, y_list, name_list = [], [], []
|
32 |
+
idxx = 0
|
33 |
+
np_data = np.zeros((len(files)*samples, 2800))
|
34 |
+
for idx, file in enumerate(files):
|
35 |
+
for skip_row in range(100):
|
36 |
+
try:
|
37 |
+
data = np.loadtxt(f'{this_path}/{file}', skiprows=skip_row)
|
38 |
+
except ValueError:
|
39 |
+
continue
|
40 |
+
data = data.T
|
41 |
+
x_list.append(data[0])
|
42 |
+
y_list.append(data[1])
|
43 |
+
Gr_ph = data[1]
|
44 |
+
if round(data[0][1] - data[0][0],2) != 0.01:
|
45 |
+
raise ValueError("The PDF does not have an r-step of 0.01 Å")
|
46 |
+
try:
|
47 |
+
start_PDF = np.where((data[0] > 1.995) & (data[0] < 2.005))[0][0]
|
48 |
+
except:
|
49 |
+
Gr_ph = np.concatenate((np.zeros((int((data[0][0])/0.01))), Gr_ph))
|
50 |
+
print("The PDFs first value is above 2 Å. We have added 0's down to 2 Å as a quick fix.")
|
51 |
+
try:
|
52 |
+
end_PDF = np.where((data[0] > 29.995) & (data[0] < 30.005))[0][0]
|
53 |
+
except:
|
54 |
+
Gr_ph = np.concatenate((Gr_ph, np.zeros((3000-len(Gr_ph)))))
|
55 |
+
print("The PDFs last value is before 30 Å. We have added 0's up to 30 Å as a quick fix.")
|
56 |
+
Gr_ph = Gr_ph[200:3000]
|
57 |
+
|
58 |
+
for i in range(samples):
|
59 |
+
np_data[idxx] = Gr_ph
|
60 |
+
np_data[idxx] /= np.amax(np_data[idxx])
|
61 |
+
idxx += 1
|
62 |
+
name_list.append(file)
|
63 |
+
break
|
64 |
+
|
65 |
+
fig, ax = plt.subplots()
|
66 |
+
|
67 |
+
plt.plot(x_list[0], y_list[0], label="Input PDF")
|
68 |
+
plt.plot(np.arange(2, 30, 0.01), np_data[0], label="DeepStruc PDF")
|
69 |
+
ax.set_xlabel(r'r / $\mathtt{\AA}$')
|
70 |
+
ax.set_ylabel('G(r) / a.u.')
|
71 |
+
|
72 |
+
ax.set_xlim(0,30)
|
73 |
+
plt.legend()
|
74 |
+
plt.title(f'{files[0]}')
|
75 |
+
plt.tight_layout()
|
76 |
+
plt.savefig(f'{project_name}/PDFs.png', dpi=300)
|
77 |
+
|
78 |
+
np_data = np_data.reshape((len(files)*samples, 2800, 1))
|
79 |
+
np_data = torch.tensor(np_data, dtype=torch.float)
|
80 |
+
return np_data, name_list, project_name
|
81 |
+
|
82 |
+
|
83 |
+
def format_predictions(latent_space, data_names, mus, sigmas, sigma_inc):
|
84 |
+
df_preds = pd.DataFrame(columns=['x', 'y', 'file_name', 'mu', 'sigma', 'sigma_inc'])
|
85 |
+
for i,j, mu, sigma in zip(latent_space, data_names, mus, sigmas):
|
86 |
+
if '/' in j:
|
87 |
+
j = j.split('/')[-1]
|
88 |
+
|
89 |
+
if '.' in j:
|
90 |
+
j_idx = j.rindex('.')
|
91 |
+
j = j[:j_idx]
|
92 |
+
|
93 |
+
info_dict = {
|
94 |
+
'x': i[0].detach().cpu().numpy(),
|
95 |
+
'y': i[1].detach().cpu().numpy(),
|
96 |
+
'file_name': j,
|
97 |
+
'mu': mu.detach().cpu().numpy(),
|
98 |
+
'sigma': sigma.detach().cpu().numpy(),
|
99 |
+
'sigma_inc': sigma_inc,}
|
100 |
+
|
101 |
+
|
102 |
+
print ("info dict: ", info_dict)
|
103 |
+
print ("df_preds initial: ", df_preds.head())
|
104 |
+
|
105 |
+
# Append is deprecated and should use concat instead
|
106 |
+
df_preds = df_preds.append(info_dict, ignore_index=True)
|
107 |
+
|
108 |
+
return df_preds
|
109 |
+
|
110 |
+
|
111 |
+
def plot_ls(df, index_highlight):
|
112 |
+
ideal_ls = './tools/ls_points.csv'
|
113 |
+
color_dict = {
|
114 |
+
'FCC': '#19ADFF',
|
115 |
+
'BCC': '#4F8F00',
|
116 |
+
'SC': '#941100',
|
117 |
+
'Octahedron': '#212121',
|
118 |
+
'Icosahedron': '#005493',
|
119 |
+
'Decahedron': '#FF950E',
|
120 |
+
'HCP': '#FF8AD8',
|
121 |
+
}
|
122 |
+
df_ideal = pd.read_csv(ideal_ls, index_col=0) # Get latent space data
|
123 |
+
# Plotting inputs
|
124 |
+
## Training and validation data
|
125 |
+
MARKER_SIZE_TR = 60
|
126 |
+
EDGE_LINEWIDTH_TR = 0.0
|
127 |
+
ALPHA_TR = 0.3
|
128 |
+
|
129 |
+
## Figure
|
130 |
+
FIG_SIZE = (10, 4)
|
131 |
+
MARKER_SIZE_FG = 60
|
132 |
+
MARKER_FONT_SIZE = 10
|
133 |
+
MARKER_SCALE = 1.5
|
134 |
+
|
135 |
+
fig = plt.figure(figsize=FIG_SIZE)
|
136 |
+
gs = GridSpec(1, 5, figure=fig)
|
137 |
+
ax = fig.add_subplot(gs[0, :4])
|
138 |
+
ax_legend = fig.add_subplot(gs[0, 4])
|
139 |
+
|
140 |
+
if int(index_highlight) >= len(df):
|
141 |
+
print(f'\nIndex argument is to large! Need to be smaller than {len(df)} but was {index_highlight}')
|
142 |
+
raise IndexError
|
143 |
+
elif int(index_highlight) < -1:
|
144 |
+
print(f'\nIndex argument invalid! Must be integer from -1 to number of samples generated.')
|
145 |
+
raise ValueError
|
146 |
+
elif int(index_highlight)==-1:
|
147 |
+
pass
|
148 |
+
elif len(df['file_name'].unique()) > 1:
|
149 |
+
print(f'\nCan only show highlight index if --data is specific file but {len(df["file_name"].unique())} files were loaded.')
|
150 |
+
else:
|
151 |
+
print(f'\nHighlighting index {index_highlight} from the {df["file_name"].unique()[0]} sampling pool.')
|
152 |
+
ax.scatter(df.iloc[index_highlight]['x'], df.iloc[index_highlight]['y'], c='k', s=40,
|
153 |
+
linewidth=0.0, marker='o', zorder=3)
|
154 |
+
ax.scatter(df.iloc[index_highlight]['x'], df.iloc[index_highlight]['y'], c='w', s=25,
|
155 |
+
linewidth=0.0, marker='o', zorder=3)
|
156 |
+
ax.scatter(df.iloc[index_highlight]['x'], df.iloc[index_highlight]['y'], c='k', s=10,
|
157 |
+
linewidth=0.0, marker='o', zorder=3)
|
158 |
+
ax.scatter(df.iloc[index_highlight]['x'], df.iloc[index_highlight]['y'], c='w', s=1,
|
159 |
+
linewidth=0.0, marker='o', zorder=3)
|
160 |
+
|
161 |
+
print('\nPlotting DeepStruc training + validation data.')
|
162 |
+
ax.scatter(df_ideal.iloc[:]['x'].values, df_ideal.iloc[:]['y'].values,
|
163 |
+
c=[color_dict[str(s)] for s in df_ideal.iloc[:]['stru_type']],
|
164 |
+
s=MARKER_SIZE_TR * df_ideal.iloc[:]['size'].values,
|
165 |
+
edgecolors='k', linewidth=EDGE_LINEWIDTH_TR,
|
166 |
+
alpha=ALPHA_TR)
|
167 |
+
|
168 |
+
|
169 |
+
mlines_list = []
|
170 |
+
for key in color_dict.keys():
|
171 |
+
mlines_list.append(
|
172 |
+
mlines.Line2D([], [], MARKER_SIZE_FG, marker='o', c=color_dict[key], linestyle='None', label=key,
|
173 |
+
mew=1))
|
174 |
+
|
175 |
+
from matplotlib import cm
|
176 |
+
cm_subsection = np.linspace(0, 1, len(df.file_name.unique()))
|
177 |
+
data_color = [cm.magma(x) for x in cm_subsection]
|
178 |
+
|
179 |
+
print('\nPlotting DeepStruc structure sampling.')
|
180 |
+
pbar = tqdm(total=len(df.file_name.unique()))
|
181 |
+
for idx, file_name in enumerate(df.file_name.unique()):
|
182 |
+
this_c = np.array([data_color[idx]])
|
183 |
+
|
184 |
+
df_ph = df[df.file_name==file_name]
|
185 |
+
df_ph.reset_index(drop=True, inplace=True)
|
186 |
+
|
187 |
+
ax.scatter(df_ph['mu'][0][0],df_ph['mu'][0][1], c=this_c, s=10, edgecolors='k',
|
188 |
+
linewidth=0.5, marker='D',zorder=1)
|
189 |
+
ellipse = Ellipse((df_ph['mu'][0][0],df_ph['mu'][0][1]),df_ph['sigma'][0][0],df_ph['sigma'][0][1], ec='k', fc=this_c, alpha=0.5, fill=True, zorder=-1)
|
190 |
+
ax.add_patch(ellipse)
|
191 |
+
|
192 |
+
ellipse = Ellipse((df_ph['mu'][0][0],df_ph['mu'][0][1]),df_ph['x'].var(),df_ph['y'].var(), ec='k', fc=this_c, alpha=0.2, fill=True, zorder=-1)
|
193 |
+
ax.add_patch(ellipse)
|
194 |
+
|
195 |
+
mlines_list.append(
|
196 |
+
mlines.Line2D([], [], MARKER_SIZE_FG, marker='D', c=this_c, linestyle='None', label=file_name, mec='k',
|
197 |
+
mew=1))
|
198 |
+
|
199 |
+
for index, sample in df_ph.iterrows():
|
200 |
+
ax.scatter(sample['x'], sample['y'], c=this_c, s=10, edgecolors='k',
|
201 |
+
linewidth=0.8, marker='o', zorder=2)
|
202 |
+
pbar.update()
|
203 |
+
pbar.close()
|
204 |
+
|
205 |
+
ax_legend.legend(handles=mlines_list,fancybox=True, #ncol=2, #, bbox_to_anchor=(0.8, 0.5)
|
206 |
+
markerscale=MARKER_SCALE, fontsize=MARKER_FONT_SIZE, loc='upper right')
|
207 |
+
|
208 |
+
ax.set_xlabel('Latent space $\mathregular{z_0}$', size=10) # Latent Space Feature 1
|
209 |
+
ax.set_ylabel('Latent space $\mathregular{z_1}$', size=10)
|
210 |
+
|
211 |
+
ax_legend.spines['top'].set_visible(False)
|
212 |
+
ax_legend.spines['right'].set_visible(False)
|
213 |
+
ax_legend.spines['bottom'].set_visible(False)
|
214 |
+
ax_legend.spines['left'].set_visible(False)
|
215 |
+
ax_legend.get_xaxis().set_ticks([])
|
216 |
+
ax_legend.get_yaxis().set_ticks([])
|
217 |
+
ax.get_xaxis().set_ticks([])
|
218 |
+
ax.get_yaxis().set_ticks([])
|
219 |
+
|
220 |
+
plt.tight_layout()
|
221 |
+
|
222 |
+
return fig
|
223 |
+
|
224 |
+
def get_model(model_dir):
|
225 |
+
if model_dir == 'DeepStruc':
|
226 |
+
with open(f'./models/DeepStruc/model_arch.yaml') as file:
|
227 |
+
model_arch = yaml.full_load(file)
|
228 |
+
model_path = './models/DeepStruc/models/DeepStruc.ckpt'
|
229 |
+
return model_path, model_arch
|
230 |
+
if os.path.isdir(model_dir):
|
231 |
+
if 'models' in os.listdir(model_dir):
|
232 |
+
models = sorted(os.listdir(f'{model_dir}/models'))
|
233 |
+
models = [model for model in models if '.ckpt' in model]
|
234 |
+
print(f'No specific model was provided. {models[0]} was chosen.')
|
235 |
+
print('Dataloader might not be sufficient in loading dimensions.')
|
236 |
+
model_path = f'{model_dir}/models/{models[0]}'
|
237 |
+
with open(f'{model_dir}/model_arch.yaml') as file:
|
238 |
+
model_arch = yaml.full_load(file)
|
239 |
+
|
240 |
+
return model_path, model_arch
|
241 |
+
else:
|
242 |
+
print(f'Path not understood: {model_dir}')
|
243 |
+
else:
|
244 |
+
idx = model_dir.rindex('/')
|
245 |
+
with open(f'{model_dir[:idx-6]}model_arch.yaml') as file:
|
246 |
+
model_arch = yaml.full_load(file)
|
247 |
+
|
248 |
+
return model_dir, model_arch
|
249 |
+
|
250 |
+
|
251 |
+
def save_predictions(xyz_pred, df, project_name, model_arch, args):
|
252 |
+
print('\nSaving predicted structures as XYZ files.')
|
253 |
+
if not os.path.isdir(f'{project_name}'):
|
254 |
+
os.mkdir(f'{project_name}')
|
255 |
+
|
256 |
+
with open(f'{project_name}/args.yaml', 'w') as outfile:
|
257 |
+
yaml.dump(vars(args), outfile, allow_unicode=True, default_flow_style=False)
|
258 |
+
|
259 |
+
"""
|
260 |
+
pbar = tqdm(total=len(df))
|
261 |
+
for count, (idx, row) in enumerate(df.iterrows()):
|
262 |
+
if not os.path.isdir(f'{project_name}/{row["file_name"]}'):
|
263 |
+
os.mkdir(f'{project_name}/{row["file_name"]}')
|
264 |
+
x = f'{float(row["x"]):+.3f}'.replace('.', '-')
|
265 |
+
y = f'{float(row["y"]):+.3f}'.replace('.', '-')
|
266 |
+
|
267 |
+
these_cords = save_xyz_file('./',
|
268 |
+
xyz_pred[idx].detach().cpu().numpy(),
|
269 |
+
f'{count:05}',
|
270 |
+
[model_arch['norm_vals']['x'],model_arch['norm_vals']['y'],model_arch['norm_vals']['z']])
|
271 |
+
pbar.update()
|
272 |
+
pbar.close()
|
273 |
+
"""
|
274 |
+
# Does not support multiple structure saving
|
275 |
+
these_cords = save_xyz_file('./',
|
276 |
+
xyz_pred[args.index_plot].detach().cpu().numpy(),
|
277 |
+
'DummyName',
|
278 |
+
[model_arch['norm_vals']['x'],model_arch['norm_vals']['y'],model_arch['norm_vals']['z']])
|
279 |
+
return these_cords
|