Enrich a citation model with the information from PubMed.

    :param pybel.manager.Manager manager:
    :param Citation citation: A citation model
    :param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid]
186742
def enrich_citation_model(manager, citation, p) -> bool:
    
    if 'error' in p:
        log.warning('Error downloading PubMed')
        return False

    citation.name = p['fulljournalname']
    citation.title = p['title']
    citation.volume = p['volume']
    citation.issue = p['issue']
    citation.pages = p['pages']
    citation.first = manager.get_or_create_author(p['sortfirstauthor'])
    citation.last = manager.get_or_create_author(p['lastauthor'])

    if 'authors' in p:
        for author in p['authors']:
            author_model = manager.get_or_create_author(author['name'])
            if author_model not in citation.authors:
                citation.authors.append(author_model)

    publication_date = p['pubdate']

    sanitized_publication_date = sanitize_date(publication_date)
    if sanitized_publication_date:
        citation.date = datetime.strptime(sanitized_publication_date, '%Y-%m-%d')
    else:
        log.info('result had date with strange format: %s', publication_date)

    return True
1247646
def parse_pubmed_url(pubmed_url):
        """"""
        parse_result = urlparse(pubmed_url)
        pattern = re.compile(r'^/pubmed/(\d+)$')
        pmid = pattern.match(parse_result.path).group(1)
        return pmid
1119175
def publication_info(self, key, value):
    """"""
    def _get_cnum(value):
        w_value = force_single_element(value.get('w', ''))
        normalized_w_value = w_value.replace('/', '-').upper()

        return normalized_w_value

    def _get_material(value):
        schema = load_schema('elements/material')
        valid_materials = schema['enum']

        m_value = force_single_element(value.get('m', ''))
        normalized_m_value = m_value.lower()

        if normalized_m_value in valid_materials:
            return normalized_m_value

    def _get_parent_isbn(value):
        z_value = force_single_element(value.get('z', ''))
        if z_value:
            return normalize_isbn(z_value)

    def _get_pubinfo_freetext(value):
        x_value = force_single_element(value.get('x', ''))
        if not x_value.startswith('#DONE'):
            return x_value

    page_start, page_end, artid = split_page_artid(value.get('c'))

    parent_recid = maybe_int(force_single_element(value.get('0')))
    parent_record = get_record_ref(parent_recid, 'literature')

    journal_recid = maybe_int(force_single_element(value.get('1')))
    journal_record = get_record_ref(journal_recid, 'journals')

    conference_recid = maybe_int(force_single_element(value.get('2')))
    conference_record = get_record_ref(conference_recid, 'conferences')

    return {
        'artid': artid,
        'cnum': _get_cnum(value),
        'conf_acronym': force_single_element(value.get('q')),
        'conference_record': conference_record,
        'hidden': key.startswith('7731') or None,
        'journal_issue': force_single_element(value.get('n')),
        'journal_record': journal_record,
        'journal_title': force_single_element(value.get('p')),
        'journal_volume': force_single_element(value.get('v')),
        'material': _get_material(value),
        'page_end': page_end,
        'page_start': page_start,
        'parent_isbn': _get_parent_isbn(value),
        'parent_record': parent_record,
        'parent_report_number': force_single_element(value.get('r')),
        'pubinfo_freetext': _get_pubinfo_freetext(value),
        'year': maybe_int(force_single_element(value.get('y'))),
    }
392934
def citation_director(**kwargs):
    """"""
    qualifier = kwargs.get('qualifier', '')
    content = kwargs.get('content', '')
    if qualifier == 'publicationTitle':
        return CitationJournalTitle(content=content)
    elif qualifier == 'volume':
        return CitationVolume(content=content)
    elif qualifier == 'issue':
        return CitationIssue(content=content)
    elif qualifier == 'pageStart':
        return CitationFirstpage(content=content)
    elif qualifier == 'pageEnd':
        return CitationLastpage(content=content)
    else:
        return None
772831
def fetch_single_representation(self, item_xlink_href):
        
        #A dict of URLs for PLoS subjournals
        journal_urls = {'pgen': 'http://www.plosgenetics.org/article/{0}',
                        'pcbi': 'http://www.ploscompbiol.org/article/{0}',
                        'ppat': 'http://www.plospathogens.org/article/{0}',
                        'pntd': 'http://www.plosntds.org/article/{0}',
                        'pmed': 'http://www.plosmedicine.org/article/{0}',
                        'pbio': 'http://www.plosbiology.org/article/{0}',
                        'pone': 'http://www.plosone.org/article/{0}',
                        'pctr': 'http://clinicaltrials.ploshubs.org/article/{0}'}
        #Identify subjournal name for base URl
        subjournal_name = self.article.doi.split('.')[2]
        base_url = journal_urls[subjournal_name]
        #Compose the address for fetchSingleRepresentation
        resource = 'fetchSingleRepresentation.action?uri=' + item_xlink_href
        return base_url.format(resource)
783259
def handle_set_citation(self, line: str, position: int, tokens: ParseResults) -> ParseResults:
        """"""
        self.clear_citation()

        values = tokens['values']

        if len(values) < 2:
            raise CitationTooShortException(self.get_line_number(), line, position)

        citation_type = values[0]

        if citation_type not in CITATION_TYPES:
            raise InvalidCitationType(self.get_line_number(), line, position, citation_type)

        if 2 == len(values):
            return self.handle_set_citation_double(line, position, tokens)

        citation_reference = values[2]

        if citation_type == CITATION_TYPE_PUBMED and not is_int(citation_reference):
            raise InvalidPubMedIdentifierWarning(self.get_line_number(), line, position, citation_reference)

        if 4 <= len(values) and not valid_date(values[3]):
            log.debug('Invalid date: %s. Truncating entry.', values[3])
            self.citation = dict(zip(CITATION_ENTRIES, values[:3]))
            return tokens

        if 5 <= len(values):
            values[4] = [value.strip() for value in values[4].split('|')]

        if 6 < len(values):
            raise CitationTooLongException(self.get_line_number(), line, position)

        self.citation = dict(zip(CITATION_ENTRIES, values))

        return tokens
401730
def get_model(self, name):
        
        try:
            ret = self.es.get(index=self.index_name, doc_type=self.DOC_TYPE,
                              id=name, _source=self.PACKAGE_FIELDS)
            if ret['found']:
                return ret['_source']['model']
            raise KeyError(name)
        except NotFoundError:
            raise KeyError(name)
537611
def parse_doc(obj: dict) -> BioCDocument:
    """"""
    doc = BioCDocument()
    doc.id = obj['id']
    doc.infons = obj['infons']
    for passage in obj['passages']:
        doc.add_passage(parse_passage(passage))
    for annotation in obj['annotations']:
        doc.add_annotation(parse_annotation(annotation))
    for relation in obj['relations']:
        doc.add_relation(parse_relation(relation))
    return doc
63039
def citation(self):
        
        path = find_dataset_path(
            self.name, data_home=self.data_home, fname="meta.json", raises=False
        )
        if path is None:
            return None

        with open(path, 'r') as f:
            return f.read()
426199
function findPubMedArticle(title, callback) {
  var uri = 'http://www.ncbi.nlm.nih.gov/pubmed/?term=' + title.replace(/ /g, '+');
  utils.retrieve(uri, function(err, contents) {
     var $ = cheerio.load(contents);
     var absid = $('#absid');
     if (absid) {
       var id = $(absid).val();
       callback(null, id, 'http://www.ncbi.nlm.nih.gov/pubmed/' + id);
     } else {
       callback(null, null);
     }

  });
}
33924
def make_citation_dict(td):
    

    from datetime import datetime

    if isinstance(td, dict):
        d = td
        name = d['name_link']
    else:

        d = td.as_dict()
        d['_term'] = td

        try:
            d['name_link'] = td.name
        except AttributeError:
            d['name_link'] = td['name_link'].value

    if 'author' in d and isinstance(d['author'], str):
        authors = []
        for e in d['author'].split(';'):
            author_d = HumanName(e).as_dict(include_empty=False)
            if 'suffix' in author_d:
                author_d['lineage'] = author_d['suffix']
                del author_d['suffix']
            authors.append(author_d)
        d['author'] = authors

    if not 'type' in d:

        if '_term' in d:
            t = d['_term']

            if t.term_is('Root.Reference') or t.term_is('Root.Resource'):
                d['type'] = 'dataset'

            elif t.term_is('Root.Citation'):
                d['type'] = 'article'
            else:
                d['type'] = 'article'

    if d['type'] == 'dataset':

        if not 'editor' in d:
            d['editor'] = [HumanName('Missing Editor').as_dict(include_empty=False)]

        if not 'accessdate' in d:
            d['accessdate'] = datetime.now().strftime('%Y-%m-%d')

    if not 'author' in d:
        d['author'] = [HumanName('Missing Author').as_dict(include_empty=False)]

    if not 'title' in d:
        d['title'] = d.get('description', '<Missing Title>')

    if not 'journal' in d:
        d['journal'] = '<Missing Journal>'

    if not 'year' in d:
        d['year'] = '<Missing Year>'

    if '_term' in d:
        del d['_term']

    return d
566519
def add_reference(self, subj: Node, val: str) -> None:
        
        match = FHIR_RESOURCE_RE.match(val)
        ref_uri_str = res_type = None
        if match:
            ref_uri_str = val if match.group(FHIR_RE_BASE) else (self._base_uri + urllib.parse.quote(val))
            res_type = match.group(FHIR_RE_RESOURCE)
        elif '://' in val:
            ref_uri_str = val
            res_type = "Resource"
        elif self._base_uri and not val.startswith('#') and not val.startswith('/'):
            ref_uri_str = self._base_uri + urllib.parse.quote(val)
            res_type = val.split('/', 1)[0] if '/' in val else "Resource"
        if ref_uri_str:
            ref_uri = URIRef(ref_uri_str)
            self.add(subj, FHIR.link, ref_uri)
            self.add(ref_uri, RDF.type, FHIR[res_type])
1145498
def get_issns_for_journal(nlm_id):
    
    params = {'db': 'nlmcatalog',
              'retmode': 'xml',
              'id': nlm_id}
    tree = send_request(pubmed_fetch, params)
    if tree is None:
        return None
    issn_list = tree.findall('.//ISSN')
    issn_linking = tree.findall('.//ISSNLinking')
    issns = issn_list + issn_linking
    # No ISSNs found!
    if not issns:
        return None
    else:
        return [issn.text for issn in issns]
674578
def reference_id(self, index):
        """"""
        # TODO Include ISBN and ISSN?
        doi = self.reference_doi(index)
        if doi:
            return doi
        else:
            pmid = self.reference_pmid(index)
            if pmid:
                return "PMID_" + pmid
            else:
                unpublished_id = self.reference_unpublished_id(index)
                if unpublished_id:
                    return "UNPUBLISHED_" + unpublished_id
        return ""
150660
def _get_pdb_id(self, elem, **kwargs):
        ''''''
        id = elem.attrib['ID']
        if self.restrict_to_transmembrane_proteins:
            tmp = elem.attrib['TMP']
            assert(tmp == 'no' or tmp == 'yes' or tmp == 'not')
            if tmp == 'yes':
                self.ids[id] = PDBTM._get_tm_type(elem)
        else:
            self.ids[id] = self.ids.get(id, 0) + 1
144694
def save(self, *args, **kwargs):
        
        self.perform_bulk_pubmed_query()
        super().save(*args, **kwargs)
631189
def get_article_xml(pubmed_id):
    
    if pubmed_id.upper().startswith('PMID'):
        pubmed_id = pubmed_id[4:]
    params = {'db': 'pubmed',
              'retmode': 'xml',
              'id': pubmed_id}
    tree = send_request(pubmed_fetch, params)
    if tree is None:
        return None
    article = tree.find('PubmedArticle/MedlineCitation/Article')
    return article