Debian Codegraph @

avogadro/qtplugins/importpqr/pqrrequest.cpp

raw
1 #include "pqrrequest.h"
2 #include "pqrwidget.h"
3
4 #include <avogadro/core/elements.h>
5
6 #include <nlohmann/json.hpp>
7
8 using json = nlohmann::json;
9
10 namespace Avogadro::QtPlugins {
11 /**
12 * @brief Constructor to initialize the NetworkAccessManager and set pointers to
13 * the widget's ui elements.
14 */
15 PQRRequest::PQRRequest(QTableWidget* tw, QLabel* gv, QLineEdit* nd, QLabel* fd,
16 PQRWidget* w)
17 {
18 // set pointers to ui elements now instead of in individual functions
19 table = tw; // pointer to ui table
20 pngPreview = gv; // png QLabel
21 nameDisplay = nd; // name
22 formulaDisplay = fd; // formula
23
24 // used to load molecule in Avogadro when downloaded
25 widget = w;
26 oNetworkAccessManager = new QNetworkAccessManager(this);
27 }
28
29 /**
30 * @brief Free the ui pointers
31 */
32 PQRRequest::~PQRRequest()
33 {
34 delete oNetworkAccessManager;
35 }
36
37 /**
38 * @brief Sends a network request to search for molecules from PQR;
39 * @param url The url to query
40 */
41 void PQRRequest::sendRequest(QString url)
42 {
43 reply = oNetworkAccessManager->get(QNetworkRequest(QUrl(url)));
44 connect(reply, SIGNAL(finished()), this, SLOT(parseJson()));
45 }
46
47 /**
48 * @brief Sends a network request to download a file from PQR
49 * @param url The url to send the request to
50 * @param mol2 The mol2 representation of the molecule to download
51 */
52 void PQRRequest::sendRequest(QString url, QString)
53 {
54 reply = oNetworkAccessManager->get(QNetworkRequest(QUrl(url)));
55 currentMolName = nameDisplay->text(); // needed to load mol into Avogadro
56 connect(reply, SIGNAL(finished()), this, SLOT(getFile()));
57 }
58
59 /**
60 * @brief Sends a network request to download a png form PQR
61 * @param url The url to send the request to
62 */
63 void PQRRequest::sendPNGRequest(QString url)
64 {
65 reply = oNetworkAccessManager->get(QNetworkRequest(QUrl(url)));
66 connect(reply, SIGNAL(finished()), this, SLOT(SetPNG()));
67 }
68
69 /**
70 * @brief Called when a molecule is selected to display information about the
71 * molecule and start grabbing the SVG preview.
72 * @param num The row number of the table result selected
73 * @returns The mol2 of the result for the widget to reference
74 */
75 QString PQRRequest::molSelected(int num)
76 {
77 if (results.empty() || num > static_cast<int>(results.size()))
78 return QString("N/A");
79
80 QString mol2 = results[num].mol2url;
81 QString url = "https://pqr.pitt.edu/static/data/png/" + mol2 + ".png";
82 sendPNGRequest(url);
83
84 formulaDisplay->setText(parseSubscripts(results[num].formula));
85 nameDisplay->setText(results[num].name);
86
87 return mol2;
88 }
89
90 /**
91 * @brief Parses the JSON response from querying PQR
92 */
93 void PQRRequest::parseJson()
94 {
95 if (reply->error() == QNetworkReply::NoError) {
96 // Reading the data from the response
97 QByteArray bytes = reply->readAll();
98
99 // parse the json
100 json root = json::parse(bytes.data());
101
102 int resultSize = root.size();
103
104 results.clear();
105 if (resultSize == 0) {
106 table->setRowCount(1);
107 table->setItem(0, 0, new QTableWidgetItem("No Results!"));
108 table->setCellWidget(0, 1, new QLabel());
109 table->setItem(0, 2, new QTableWidgetItem("N/A"));
110 } else {
111 table->setRowCount(resultSize);
112 for (int i = 0; i < resultSize; i++) {
113 results.emplace_back();
114
115 // Loop through the keys
116 for (auto it = root[i].cbegin(); it != root[i].cend(); ++it) {
117 if (it.key() == "formula" && it.value().is_string())
118 results[i].formula = it.value().get<std::string>().c_str();
119 else if (it.key() == "inchikey" && it.value().is_string())
120 results[i].inchikey = it.value().get<std::string>().c_str();
121 else if (it.key() == "mol2url" && it.value().is_string())
122 results[i].mol2url = it.value().get<std::string>().c_str();
123 else if (it.key() == "name" && it.value().is_string())
124 results[i].name = it.value().get<std::string>().c_str();
125 }
126 results[i].mass = getMolMass(results[i].formula);
127
128 table->setItem(i, 0, new QTableWidgetItem(results[i].name));
129
130 // clear possible QTableWidget if there were no results previously
131 table->setItem(i, 1, nullptr);
132 // use this to display subscripts, should automatically delete previous
133 // QLabel according to documentation
134 table->setCellWidget(i, 1,
135 new QLabel(parseSubscripts(results[i].formula)));
136
137 // table->setItem(i, 2, new
138 // QTableWidgetItem(QString::number(results[i].mass, 'f', 3) + QString("
139 // g/mol")));
140 auto* massItem = new QTableWidgetItem();
141 massItem->setData(Qt::DisplayRole, results[i].mass);
142 table->setItem(i, 2, massItem);
143 }
144 }
145 } else {
146 table->setRowCount(3);
147 table->setItem(0, 0, new QTableWidgetItem("Network Error!"));
148 table->setItem(0, 1, new QTableWidgetItem("N/A"));
149 table->setItem(0, 2, new QTableWidgetItem(reply->errorString()));
150 }
151 reply->deleteLater();
152 }
153
154 /**
155 * @brief Creates a file after requesting a file from PQR
156 */
157 void PQRRequest::getFile()
158 {
159 QByteArray molData = reply->readAll();
160 widget->loadMolecule(molData, currentMolName);
161 reply->deleteLater();
162 }
163
164 /**
165 * @brief Loads PNG data after sending a request
166 */
167 void PQRRequest::SetPNG()
168 {
169 QByteArray pngData = reply->readAll();
170 widget->loadPNG(pngData);
171 reply->deleteLater();
172 }
173
174 /**
175 * @brief Takes a formula string and returns a QString with subscript tags
176 * @param formula The formula string
177 */
178 QString PQRRequest::parseSubscripts(QString formula)
179 {
180 std::string str = formula.toStdString();
181 QString toReturn;
182 for (char i : str) {
183 if (isdigit(i)) {
184 toReturn.append("<sub>");
185 toReturn.append(i);
186 toReturn.append("</sub>");
187 } else {
188 toReturn.append(i);
189 }
190 }
191 return toReturn;
192 }
193
194 /**
195 * @brief Takes a formula string and returns the molecular mass of the molecule
196 * @param formula The formula string
197 */
198 float PQRRequest::getMolMass(QString formula)
199 {
200 std::string str = formula.toStdString();
201 float totalMass = 0.0;
202 int subscript = 1;
203 std::string element;
204 unsigned char atomicNum;
205 for (size_t i = 0; i < str.length(); i++) {
206 // each element will start with a capital letter
207 if (isupper(str[i])) {
208 // if next letter is a lower case then we know the whole element
209 if (islower(str[i + 1])) {
210 element = { str[i], str[i + 1] };
211 // this might be the last element of the formula
212 if (isdigit(str[i + 2])) {
213 subscript = (int)str[i + 2] - '0';
214 i += 2; // increment past lowercase and numeral
215 } else {
216 i += 1;
217 subscript = 1;
218 }
219 }
220 // get the subscript
221 else if (isdigit(str[i + 1])) {
222 if (isdigit(str[i + 2])) {
223 // might be 2 digit subscript
224 subscript = (int)str[i + 1] - '0';
225 subscript *= 10; // shift forward one decimal place
226 subscript += (int)str[i + 2] - '0';
227 element = { str[i] };
228 i += 2;
229 } else {
230 subscript = (int)str[i + 1] - '0';
231 element = { str[i] };
232 i += 1;
233 }
234 }
235 // if the next letter is another uppercase or null, the current subscript
236 // is 1
237 else if (isupper(str[i + 1]) || str[i + 1] == 0) {
238 subscript = 1;
239 element = { str[i] };
240 }
241 atomicNum = Core::Elements::atomicNumberFromSymbol(element);
242 totalMass += (subscript * Core::Elements::mass(atomicNum));
243 }
244 }
245 return totalMass;
246 }
247 } // namespace Avogadro::QtPlugins