1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#![doc = include_str!("../README.md")]

extern crate form_urlencoded;
extern crate quick_xml;
extern crate thiserror;
extern crate ureq;

#[macro_use]
mod parser;
#[macro_use]
mod utils;

pub mod error;
pub mod model;

use std::borrow::Cow;

use self::error::Error;
use self::model::rest;
use self::parser::FromApiResponse;
use self::utils::Join;

named_enum! {
    #[derive(Debug, PartialEq, Eq)]
    /// A single property that can be retrieved from a compound.
    pub enum CompoundProperty {
        /// Molecular formula.
        MolecularFormula,
        /// The molecular weight is the sum of all atomic weights of the constituent atoms in a compound, measured in g/mol. In the absence of explicit isotope labelling, averaged natural abundance is assumed. If an atom bears an explicit isotope label, 100% isotopic purity is assumed at this location.
        MolecularWeight,
        /// Canonical SMILES (Simplified Molecular Input Line Entry System) string.  It is a unique SMILES string of a compound, generated by a “canonicalization” algorithm.
        CanonicalSMILES,
        /// Isomeric SMILES string.  It is a SMILES string with stereochemical and isotopic specifications.
        IsomericSMILES,
        /// Standard IUPAC International Chemical Identifier (InChI).  It does not allow for user selectable options in dealing with the stereochemistry and tautomer layers of the InChI string.
        InChI,
        /// Hashed version of the full standard InChI, consisting of 27 characters.
        InChIKey,
        /// Chemical name systematically determined according to the IUPAC nomenclatures.
        IUPACName,
        /// The title used for the compound summary page.
        Title,
        /// Computationally generated octanol-water partition coefficient or distribution coefficient. XLogP is used as a measure of hydrophilicity or hydrophobicity of a molecule.
        XLogP,
        /// The mass of the most likely isotopic composition for a single molecule, corresponding to the most intense ion/molecule peak in a mass spectrum.
        ExactMass,
        /// The mass of a molecule, calculated using the mass of the most abundant isotope of each element.
        MonoisotopicMass,
        /// Topological polar surface area, computed by the algorithm described in the paper by Ertl et al.
        TPSA,
        /// The molecular complexity rating of a compound, computed using the Bertz/Hendrickson/Ihlenfeldt formula.
        Complexity,
        /// The total (or net) charge of a molecule.
        Charge,
        /// Number of hydrogen-bond donors in the structure.
        HBondDonorCount,
        /// Number of hydrogen-bond acceptors in the structure.
        HBondAcceptorCount,
        /// Number of rotatable bonds.
        RotatableBondCount,
        /// Number of non-hydrogen atoms.
        HeavyAtomCount,
        /// Number of atoms with enriched isotope(s)
        IsotopeAtomCount,
        /// Total number of atoms with tetrahedral (sp3) stereo [e.g., (R)- or (S)-configuration]
        AtomStereoCount,
        /// Number of atoms with defined tetrahedral (sp3) stereo.
        DefinedAtomStereoCount,
        /// Number of atoms with undefined tetrahedral (sp3) stereo.
        UndefinedAtomStereoCount,
        /// Total number of bonds with planar (sp2) stereo [e.g., (E)- or (Z)-configuration].
        BondStereoCount,
        /// Number of atoms with defined planar (sp2) stereo.
        DefinedBondStereoCount,
        /// Number of atoms with undefined planar (sp2) stereo.
        UndefinedBondStereoCount,
        /// Number of covalently bound units.
        CovalentUnitCount,
        /// Analytic volume of the first diverse conformer (default conformer) for a compound.
        Volume3D,
        /// The x component of the quadrupole moment (Qx) of the first diverse conformer (default conformer) for a compound.
        XStericQuadrupole3D,
        /// The y component of the quadrupole moment (Qy) of the first diverse conformer (default conformer) for a compound.
        YStericQuadrupole3D,
        /// The z component of the quadrupole moment (Qz) of the first diverse conformer (default conformer) for a compound.
        ZStericQuadrupole3D,
        /// Total number of 3D features (the sum of FeatureAcceptorCount3D, FeatureDonorCount3D, FeatureAnionCount3D, FeatureCationCount3D, FeatureRingCount3D and FeatureHydrophobeCount3D)
        FeatureCount3D,
        /// Number of hydrogen-bond acceptors of a conformer.
        FeatureAcceptorCount3D,
        /// Number of hydrogen-bond donors of a conformer.
        FeatureDonorCount3D,
        /// Number of anionic centers (at pH 7) of a conformer.
        FeatureAnionCount3D,
        /// Number of cationic centers (at pH 7) of a conformer.
        FeatureCationCount3D,
        /// Number of rings of a conformer.
        FeatureRingCount3D,
        /// Number of hydrophobes of a conformer.
        FeatureHydrophobeCount3D,
        /// Conformer sampling RMSD in Å.
        ConformerModelRMSD3D,
        /// Total number of 3D features (the sum of FeatureAcceptorCount3D, FeatureDonorCount3D, FeatureAnionCount3D, FeatureCationCount3D, FeatureRingCount3D and FeatureHydrophobeCount3D)
        EffectiveRotorCount3D,
        /// The number of conformers in the conformer model for a compound.
        ConformerCount3D,
        /// Base64-encoded PubChem Substructure Fingerprint of a molecule.
        Fingerprint2D,
    }
}

#[derive(Debug)]
/// A client for retrieving information about a single PubChem compound.
pub struct Compound {
    namespace: Cow<'static, str>,
    identifier: Cow<'static, str>,
}

impl Compound {
    /// Create a new `Compound` from the given compound ID.
    pub fn new(id: u32) -> Self {
        Self {
            namespace: Cow::Borrowed("cid"),
            identifier: Cow::Owned(id.to_string()),
        }
    }

    /// Create a new `Compound` matching the given compound name.
    pub fn with_name(name: &str) -> Self {
        Self {
            namespace: Cow::Borrowed("name"),
            identifier: Cow::Owned(name.to_string()),
        }
    }

    /// Create a new `Compound` matching the given SMILES.
    pub fn with_smiles(smiles: &str) -> Self {
        Self {
            namespace: Cow::Borrowed("smiles"),
            identifier: Cow::Owned(smiles.to_string()),
        }
    }

    /// Create a new `Compound` matching the given InChI.
    pub fn with_inchi(inchi: &str) -> Self {
        Self {
            namespace: Cow::Borrowed("inchi"),
            identifier: Cow::Owned(inchi.to_string()),
        }
    }

    /// Create a new `Compound` matching the given InChIKey.
    pub fn with_inchikey(inchikey: &str) -> Self {
        Self {
            namespace: Cow::Borrowed("inchikey"),
            identifier: Cow::Owned(inchikey.to_string()),
        }
    }

    // pub fn with_sdf(sdf: &str) -> Self {
    //     Self {
    //         namespace: Cow::Borrowed("sdf"),
    //         identifiers: Cow::Owned(sdf.to_string())
    //     }
    // }

    /// Request the REST API for the given operation.
    ///
    /// The response is checked to see if the HTTP client or the API errored,
    /// otherwise the raw response is returned so that it can be parsed by
    /// the appropriate method.
    ///
    fn request(&self, operation: &str) -> Result<ureq::Response, Error> {
        let url = format!(
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/{dom}/{ns}/{op}/XML",
            dom = "compound",
            ns = &self.namespace,
            op = operation
        );
        let form_data = form_urlencoded::Serializer::new(String::new())
            .append_pair(&self.namespace, &self.identifier)
            .finish();
        match ureq::post(&url)
            .set("Accept", "application/xml")
            .set("Content-Type", "application/x-www-form-urlencoded")
            .send_string(&form_data)
        {
            Err(ureq::Error::Status(400 | 404 | 405 | 500 | 501 | 503 | 504, response)) => {
                let fault = rest::Fault::from_api_response(response)?;
                Err(Error::Api(fault.into()))
            }
            Err(e) => Err(Error::Request(e)),
            Ok(response) => Ok(response),
        }
    }

    /// Retrieve several properties at once for the compound.
    pub fn properties<'p, P>(&self, properties: P) -> Result<rest::Properties, Error>
    where
        P: IntoIterator<Item = &'p CompoundProperty>,
    {
        let mut path = String::from("/property/");
        path.push_str(&properties.into_iter().map(CompoundProperty::name).join(","));
        self.request(&path)
            .and_then(|response| rest::PropertyTable::from_api_response(response))
            .map(|mut table| table.properties.pop().unwrap())
    }

    /// Retrieve the main PubChem designation for the compound.
    pub fn title(&self) -> Result<String, Error> {
        let properties = self.properties(&[CompoundProperty::Title])?;
        Ok(properties
            .title
            .expect("All PubChem compounds should have a title."))
    }

    /// Retrieve the molecular formula of the compound.
    ///
    /// # Example
    /// ```
    /// let compound = pubchem::Compound::with_name("aspirin");
    /// assert_eq!(compound.molecular_formula().unwrap(), "C9H8O4");
    /// ```
    pub fn molecular_formula(&self) -> Result<String, Error> {
        let properties = self.properties(&[CompoundProperty::MolecularFormula])?;
        Ok(properties
            .molecular_formula
            .expect("All PubChem compounds should have a formula."))
    }

    /// Retrieve the canonical SMILES string for the compound.
    pub fn canonical_smiles(&self) -> Result<String, Error> {
        let properties = self.properties(&[CompoundProperty::CanonicalSMILES])?;
        Ok(properties
            .canonical_smiles
            .expect("All PubChem compounds should have a SMILES."))
    }

    /// Retrieve the isomeric SMILES string for the compound.
    ///
    /// # Example
    /// ```
    /// let alanine = pubchem::Compound::with_name("alanine");
    /// assert_eq!(alanine.isomeric_smiles().unwrap(), "C[C@H](C(=O)O)N");
    /// ```
    pub fn isomeric_smiles(&self) -> Result<String, Error> {
        let properties = self.properties(&[CompoundProperty::IsomericSMILES])?;
        Ok(properties
            .isomeric_smiles
            .expect("All PubChem compounds should have a SMILES."))
    }

    // /// Retrieve the entire PubChem record for the compound.
    // pub fn record(&self) {
    //     unimplemented!()
    // }

    /// Retrieve synonym names for the compound.
    pub fn synonyms(&self) -> Result<Vec<String>, Error> {
        self.request("synonyms")
            .and_then(|response| rest::InformationList::from_api_response(response))
            .map(|mut list| list.informations.pop().unwrap().synonyms)
    }

    /// Retrieve the Compound IDs designating the compound.
    pub fn cids(&self) -> Result<Vec<i32>, Error> {
        self.request("cids")
            .and_then(|response| rest::IdentifierList::from_api_response(response))
            .map(|list| list.cids)
    }

    /// Retrieve the Substance IDs associated with the compound.
    pub fn sids(&self) -> Result<Vec<i32>, Error> {
        self.request("sids")
            .and_then(|response| rest::InformationList::from_api_response(response))
            .map(|mut list| list.informations.pop().unwrap().sids)
    }

    /// Retrieve the Assay IDs associated with the compound.
    pub fn aids(&self) -> Result<Vec<i32>, Error> {
        self.request("aids")
            .and_then(|response| rest::InformationList::from_api_response(response))
            .map(|mut list| list.informations.pop().unwrap().aids)
    }

    // pub fn assay_summary(&self) {
    //
    // }
    //
    // pub fn classification(&self) {
    //
    // }
    //
    // pub fn xref(&self) {
    //
    // }
    //
    // pub fn description(&self) {
    //
    // }
    //
    // pub fn conformers(&self) {
    //
    // }
}

#[derive(Debug)]
/// A client for retrieving information about multiple PubChem compoumds at once.
pub struct Compounds {
    namespace: Cow<'static, str>,
    identifiers: Cow<'static, str>,
}

impl Compounds {
    /// Query several compounds with the given compound IDs.
    pub fn new<I: IntoIterator<Item = u32>>(ids: I) -> Self {
        Self {
            namespace: Cow::Borrowed("cid"),
            identifiers: Cow::Owned(ids.into_iter().join(",")),
        }
    }

    /// Request the REST API for the given operation.
    ///
    /// The response is checked to see if the HTTP client or the API errored,
    /// otherwise the raw response is returned so that it can be parsed by
    /// the appropriate method.
    ///
    fn request(&self, operation: &str) -> Result<ureq::Response, Error> {
        let url = format!(
            "https://pubchem.ncbi.nlm.nih.gov/rest/pug/{dom}/{ns}/{op}/XML",
            dom = "compound",
            ns = &self.namespace,
            op = operation
        );
        let form_data = form_urlencoded::Serializer::new(String::new())
            .append_pair(&self.namespace, &self.identifiers)
            .finish();
        match ureq::post(&url)
            .set("Accept", "application/xml")
            .set("Content-Type", "application/x-www-form-urlencoded")
            .send_string(&form_data)
        {
            Err(ureq::Error::Status(400 | 404 | 405 | 500 | 501 | 503 | 504, response)) => {
                let fault = rest::Fault::from_api_response(response)?;
                Err(Error::Api(fault.into()))
            }
            Err(e) => Err(Error::Request(e)),
            Ok(response) => Ok(response),
        }
    }

    /// Retrieve several properties at once for the compounds.
    pub fn properties<'p, P>(&self, properties: P) -> Result<rest::PropertyTable, Error>
    where
        P: IntoIterator<Item = &'p CompoundProperty>,
    {
        let mut path = String::from("/property/");
        path.push_str(&properties.into_iter().map(CompoundProperty::name).join(","));
        self.request(&path)
            .and_then(|response| rest::PropertyTable::from_api_response(response))
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::error::ApiError;

    #[test]
    fn compound_new() {
        let compound = Compound::new(2244);
        let properties = compound
            .properties(&[CompoundProperty::Title])
            .expect("compound property retrieval should not fail");
        assert_eq!(properties.title.as_ref().unwrap(), "Aspirin");
    }

    #[test]
    fn compound_with_name() {
        let compound = Compound::with_name("lyciumin A");
        let properties = compound
            .properties(&[CompoundProperty::Title])
            .expect("compound property retrieval should not fail");
        assert_eq!(properties.cid, 14430290);
    }

    #[test]
    fn compound_with_smiles() {
        let compound = Compound::with_smiles("CC(=O)OC1=CC=CC=C1C(=O)O");
        let properties = compound
            .properties(&[CompoundProperty::Title])
            .expect("compound property retrieval should not fail");
        assert_eq!(properties.cid, 2244);
    }

    #[test]
    fn compound_with_inchikey() {
        let compound = Compound::with_inchikey("AUJXLBOHYWTPFV-UHFFFAOYSA-N");
        assert_eq!(compound.title().unwrap(), "Echinomycin");
    }

    #[test]
    fn compound_with_inchi() {
        let compound = Compound::with_inchi("InChI=1S/C3H6O/c1-3(2)4/h1-2H3");
        assert_eq!(compound.title().unwrap(), "Acetone");
    }

    #[test]
    fn compound_cids() {
        let compound = Compound::new(2244);
        assert_eq!(compound.cids().unwrap(), vec![2244])
    }

    #[test]
    #[rustfmt::skip]
    fn compound_sids() {
        let compound = Compound::new(10444160);
        assert_eq!(
            compound.sids().unwrap(),
            vec![
                 15464793,  40571804,  50320706, 103261147,
                319343201, 383830942, 386266192, 459034771
            ]
        )
    }

    #[test]
    fn compound_synonyms() {
        let compound = Compound::new(180);
        let synonyms = compound.synonyms().unwrap();
        assert_eq!(synonyms.len(), 578);
        assert_eq!(&synonyms[0], "acetone");
        assert_eq!(&synonyms[1], "2-propanone");
    }

    #[test]
    fn compound_name_not_found() {
        let compound = Compound::with_name("none");
        match compound.cids() {
            Err(Error::Api(ApiError::NotFound(_))) => (),
            Err(e) => panic!("unexpected error {}", e),
            Ok(_) => panic!("unexpected success"),
        }
    }

    #[test]
    fn compounds_properties() {
        let compounds = Compounds::new([6140, 6057, 6305]);
        let property_table = compounds.properties(&[CompoundProperty::Title]).unwrap();
        assert_eq!(property_table.properties.len(), 3);
        for properties in property_table.properties {
            match properties.cid {
                6140 => assert_eq!(properties.title.unwrap(), "Phenylalanine"),
                6057 => assert_eq!(properties.title.unwrap(), "Tyrosine"),
                6305 => assert_eq!(properties.title.unwrap(), "Tryptophan"),
                _ => unreachable!(),
            }
        }
    }
}