recordcdspubli.py 30.7 KB
Newer Older
1
""" store_tools.recordcdspubli
2 3

"""
4
import logging
5
import numpy as np
6
import pprint
7 8 9 10 11 12 13 14 15 16 17
import re

from .authorsmixin import AuthorsMixin, MSG_NO_MY_AUTHOR
from .base import (ARXIV,
                   MSG_UNKNOWN_COLLABORATION,
                   MSG_NO_REF,
                   OAI,
                   OAI_URL,
                   search_synonym,
                   REG_DOI,
                   REG_OAI,
18
                   T4, T6)
19
from .exception import CheckException
20
from filters import CLEAN_COLLABORATION
21
from pandas import concat, DataFrame
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
from plugin_dbui import CLEAN_SPACES, UNDEF_ID
from .publicationinfomixin import PAPER_REFERENCE_KEYS, PublicationInfoMixin

DECODE_ARXIV = re.compile(r"arXiv:(\d{2})(\d{2})\.")

# Decode submitted date: DD MMM YYYY or DD MM YYY
DECODE_DD_MMM_YYYY = re.compile(r"(\d{1,2}) *([A-Za-z]{3}) *(\d{4})")
DECODE_DD_MM_YYYY = re.compile(r"(\d{1,2}) +(\d{1,2}) +(\d{4})")

MONTHS = {"Jan": "01",
          "Feb": "02",
          "Fev": "02",
          "Mar": "03",
          "Apr": "04",
          "Avr": "04",
          "May": "05",
          "Mai": "05",
          "Jun": "06",
          "Jul": "07",
          "Aug": "08",
          "Sep": "09",
          "Oct": "10",
          "Nov": "11",
          "Dec": "12"}

MSG_NO_DATE = "Reject no submission date"
MSG_WELL_FORMED_DATE = "Reject submission date is not well formed"
49

50

51 52 53 54
def to_str(x):
    return ("|".join(x) if isinstance(x, list) else x)


55
class RecordCdsPubli(dict, AuthorsMixin, PublicationInfoMixin):
56 57 58 59
    """Article, preprint, proceeding, report and talk from cds.cern.ch or
    old.inspirehep.net.

    The record is organised in ``field`` and ``subfield``:
LE GAC Renaud's avatar
LE GAC Renaud committed
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

        +---------------------------------+----------------------------------+
        | field                           | subfield                         |
        +=================================+==================================+
        | FIXME_OAI (inspire)             | id                               |
        +---------------------------------+----------------------------------+
        | abstract                        |                                  |
        +---------------------------------+----------------------------------+
        | accelerator_experiment          |                                  |
        +---------------------------------+----------------------------------+
        | agency_code (cds)               |                                  |
        +---------------------------------+----------------------------------+
        | authors                         | INSPIRE_number, affiliation,     |
        |                                 | control_number, first_name,      |
        |                                 | full_name, last_name,            |
        |                                 | relator_name (phd director)      |
        +---------------------------------+----------------------------------+
        | base (cds)                      |                                  |
        +---------------------------------+----------------------------------+
        | collection                      |                                  |
        +---------------------------------+----------------------------------+
        | comment                         |                                  |
        +---------------------------------+----------------------------------+
        | copyright_status (cds)          |                                  |
        +---------------------------------+----------------------------------+
        | corporate_name                  | collaboration                    |
        +---------------------------------+----------------------------------+
        | creation_date                   |                                  |
        +---------------------------------+----------------------------------+
        | doi                             |                                  |
        +---------------------------------+----------------------------------+
        | email_message (cds)             |                                  |
        +---------------------------------+----------------------------------+
        | filenames                       |                                  |
        +---------------------------------+----------------------------------+
        | files                           | comment, description, eformat,   |
        |                                 | full_name, full_path, magic,     |
        |                                 | name, path, size, status,        |
        |                                 | subformat, superformat, type,    |
        |                                 | url, version                     |
        +---------------------------------+----------------------------------+
        | filetypes                       |                                  |
        +---------------------------------+----------------------------------+
        | imprint                         |                                  |
        +---------------------------------+----------------------------------+
        | keywords                        |                                  |
        +---------------------------------+----------------------------------+
        | language (cds)                  |                                  |
        +---------------------------------+----------------------------------+
        | license                         |                                  |
        +---------------------------------+----------------------------------+
        | number_of_authors               |                                  |
        +---------------------------------+----------------------------------+
        | number_of_citations             |                                  |
        +---------------------------------+----------------------------------+
        | number_of_comments              |                                  |
        +---------------------------------+----------------------------------+
        | number_of_reviews               |                                  |
        +---------------------------------+----------------------------------+
        | oai (cds)                       | value                            |
        +---------------------------------+----------------------------------+
        | other_report_number (cds)       |                                  |
        +---------------------------------+----------------------------------+
        | persistent_identifiers_keys     |                                  |
        +---------------------------------+----------------------------------+
        | physical_description            |                                  |
        +---------------------------------+----------------------------------+
        | prepublication                  | date, publisher_name, place      |
        +---------------------------------+----------------------------------+
        | primary_report_number           |                                  |
        +---------------------------------+----------------------------------+
        | publication_info                | pagination, title, volume, year  |
        +---------------------------------+----------------------------------+
        | recid                           | none                             |
        +---------------------------------+----------------------------------+
        | reference (inspire)             |                                  |
        +---------------------------------+----------------------------------+
        | report_number (cds)             | internal, report_number          |
        +---------------------------------+----------------------------------+
        | source_of_acquisition (inspire) |                                  |
        +---------------------------------+----------------------------------+
        | status_week (cds)               |                                  |
        +---------------------------------+----------------------------------+
        | subject                         |                                  |
        +---------------------------------+----------------------------------+
        | system_control_number           | institute, value or canceled     |
        +---------------------------------+----------------------------------+
        | thesaurus_terms                 |                                  |
        +---------------------------------+----------------------------------+
        | title                           | title                            |
        +---------------------------------+----------------------------------+
        | title_additional (inspire)      |                                  |
        +---------------------------------+----------------------------------+
        | url (cds)                       | description, url                 |
        +---------------------------------+----------------------------------+
        | version_id                      |                                  |
        +---------------------------------+----------------------------------+
157 158

    """
159

160 161
    def __init__(self, *args):

162 163
        super().__init__(*args)

164 165 166
        self.logger = logging.getLogger("web2py.app.limbra")

        self._last_fmt_author = "Last, First"
167
        self._process_authors()
LE GAC Renaud's avatar
LE GAC Renaud committed
168
        self._process_publication_info()
169

170 171
        # the authors of my institutes signing the record
        # string containing a list of name separated by a comma
172
        self.my_authors = None
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

    def _get(self, field, subfield, force_list=False):
        """Get the value associated to the ``field`` and ``subfield``.

        Args:
            field (str):
                name of the field, *e.g.* ``authors``

            subfield (str):
                name of the subfield, *e.g.* ``full_name``

            force_list (bool):
                always return a *list* when ``True``.

        Returns:
            str:
                value or an empty string when not defined.

            list:
                list of values or an empty list when not defined
        """
        val = ""

        if field in self and subfield in self[field]:
            val = self[field][subfield]

        elif field in self and isinstance(self[field], list):
            val = []
            for el in self[field]:
                if subfield in el:
                    if isinstance(el[subfield], list):
                        val.extend(el[subfield])
                    else:
                        val.append(el[subfield])

        if force_list and not isinstance(val, list):
            val = ([val] if len(val) > 0 else [])

        return val

213 214 215
    def _process_authors(self):
        """Convert authors information into DataFrame:

216 217 218
        Authors and their affiliations are stored in DataFrame with the
        following structure:

LE GAC Renaud's avatar
LE GAC Renaud committed
219 220
            +---------------+--------------------------------+
            | column        |                                |
LE GAC Renaud's avatar
LE GAC Renaud committed
221
            +===============+================================+
LE GAC Renaud's avatar
LE GAC Renaud committed
222
            | affiliation   | value separated by "|"         |
LE GAC Renaud's avatar
LE GAC Renaud committed
223
            +---------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
224
            | first_name    | first name                     |
LE GAC Renaud's avatar
LE GAC Renaud committed
225
            +---------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
226
            | fmt_name      | formated name                  |
LE GAC Renaud's avatar
LE GAC Renaud committed
227
            +---------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
228
            | full_name     | Last, First                    |
LE GAC Renaud's avatar
LE GAC Renaud committed
229
            +---------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
230
            | last_name     | family name                    |
LE GAC Renaud's avatar
LE GAC Renaud committed
231
            +---------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
232 233
            | relator_name  | equal to dir. for phd director |
            +---------------+--------------------------------+
234

LE GAC Renaud's avatar
LE GAC Renaud committed
235
        Note:
236 237 238
            After running this method, the attribute ``df_authors`` is defined.
            It contains one entry with empty strings when the ``authors``
            field does not exist.
239

LE GAC Renaud's avatar
LE GAC Renaud committed
240
        """
241 242
        self.logger.debug(f"{T4}process authors")

243
        if "authors" not in self:
LE GAC Renaud's avatar
LE GAC Renaud committed
244 245 246 247 248
            cols = ["affiliation",
                    "first_name",
                    "fmt_name",
                    "full_name",
                    "last_name"]
249
            self.df_authors = DataFrame([[""] * len(cols)], columns=cols)
LE GAC Renaud's avatar
LE GAC Renaud committed
250
            return
251

252
        data = self["authors"]
LE GAC Renaud's avatar
LE GAC Renaud committed
253
        data = (data if isinstance(data, list) else [data])
254

LE GAC Renaud's avatar
LE GAC Renaud committed
255
        df = DataFrame(data)
256

LE GAC Renaud's avatar
LE GAC Renaud committed
257 258 259 260 261 262
        # drop useless columns
        refcols = ["affiliation",
                   "first_name",
                   "full_name",
                   "last_name",
                   "relator_name"]
263

LE GAC Renaud's avatar
LE GAC Renaud committed
264 265
        columns = df.columns
        df = df.drop(columns.difference(refcols), axis="columns")
266

LE GAC Renaud's avatar
LE GAC Renaud committed
267 268 269 270
        # protection against duplicated entries, e.g. twice the first author
        if set(["last_name", "first_name"]).issubset(df.columns):
            df = df.drop_duplicates(["last_name", "first_name"])

LE GAC Renaud's avatar
LE GAC Renaud committed
271 272
        # protection -- affiliation not defined
        if "affiliation" not in columns:
273
            dfa = DataFrame([""] * len(df), columns=["affiliation"])
LE GAC Renaud's avatar
LE GAC Renaud committed
274
            df = concat([df, dfa], axis="columns")
275

LE GAC Renaud's avatar
LE GAC Renaud committed
276 277 278 279
        # convert list of affiliation to string separated by |
        df.affiliation = (df.affiliation
                          .fillna("")
                          .apply(lambda x: to_str(x)))
280

LE GAC Renaud's avatar
LE GAC Renaud committed
281 282
        # add the column fmt_name
        df["fmt_name"] = df.full_name
283

LE GAC Renaud's avatar
LE GAC Renaud committed
284
        # replace
285
        self.df_authors = df
286

LE GAC Renaud's avatar
LE GAC Renaud committed
287 288
    def _process_publication_info(self):
        """Convert publication_info into DataFrame:
289

LE GAC Renaud's avatar
LE GAC Renaud committed
290
            Note:
291
                * the field is a list when there are erratum
LE GAC Renaud's avatar
LE GAC Renaud committed
292
                * in some case the subfield year is a list (cds 1951625)
293

LE GAC Renaud's avatar
LE GAC Renaud committed
294 295
        publication information are stored in DataFrame with the
        following structure:
296

LE GAC Renaud's avatar
LE GAC Renaud committed
297 298
            +------------+--------------------------------+
            | column     |                                |
LE GAC Renaud's avatar
LE GAC Renaud committed
299
            +============+================================+
LE GAC Renaud's avatar
LE GAC Renaud committed
300
            | title      | abbreviation of the publisher  |
LE GAC Renaud's avatar
LE GAC Renaud committed
301
            +------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
302
            | volume     | volume                         |
LE GAC Renaud's avatar
LE GAC Renaud committed
303
            +------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
304
            | year       | year of publication            |
LE GAC Renaud's avatar
LE GAC Renaud committed
305
            +------------+--------------------------------+
LE GAC Renaud's avatar
LE GAC Renaud committed
306 307
            | pagination | page number or ranges          |
            +------------+--------------------------------+
308

LE GAC Renaud's avatar
LE GAC Renaud committed
309
        Note:
310 311 312
            * After running this method, the attribute ``df_info`` is defined.
              It contains one entry with empty strings when the field
              ``publication_info`` does not exist.
313

LE GAC Renaud's avatar
LE GAC Renaud committed
314 315
            * In order to deal with erratum entry are sorter by year
              and volume.
316

LE GAC Renaud's avatar
LE GAC Renaud committed
317
        """
318 319
        self.logger.debug(f"{T4}process publication info")

320
        if "publication_info" not in self:
LE GAC Renaud's avatar
LE GAC Renaud committed
321 322 323 324
            cols = ["title",
                    "volume",
                    "year",
                    "pagination"]
325

326
            self.df_info = DataFrame([[""] * len(cols)], columns=cols)
327

LE GAC Renaud's avatar
LE GAC Renaud committed
328
            return
329

330
        data = self["publication_info"]
LE GAC Renaud's avatar
LE GAC Renaud committed
331
        data = (data if isinstance(data, list) else [data])
332

LE GAC Renaud's avatar
LE GAC Renaud committed
333
        df = DataFrame(data)
LE GAC Renaud's avatar
LE GAC Renaud committed
334
        columns = df.columns
335

LE GAC Renaud's avatar
LE GAC Renaud committed
336
        # protection -- list of year, e.g. [2014, 2014] (cds 1951625)
LE GAC Renaud's avatar
LE GAC Renaud committed
337 338 339 340 341
        if "year" in columns:
            df["year"] = \
                df.year.apply(
                    lambda x:
                        (", ".join(set(x)) if isinstance(x, list) else x))
342

LE GAC Renaud's avatar
LE GAC Renaud committed
343
        # erratum -- sort by year and volume
344 345 346 347 348
        if set(["year", "volume"]).issubset(columns):
            df = df.sort_values(["year", "volume"])

        elif "year" in columns:
            df = df.sort_values("year")
349

LE GAC Renaud's avatar
LE GAC Renaud committed
350
        # replace
351
        self.df_info = df
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 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    def _recover_submitted(self):
        """Recover submitted date using conference, preprint or thesis
        information.

        Args:
            record (RecordPubli):
                record describing a publication.

        Returns:
            str:
                target at least YYYY-MM
                empty when procedure failed

        """
        val = ""

        # try by using the preprint information
        report = self.preprint_number()
        if report:
            m_arxiv = DECODE_ARXIV.match(report)
            if m_arxiv:
                val = "20%s-%s" % (m_arxiv.group(1), m_arxiv.group(2))

        # last change use the creation date for the record
        if val == "" or len(val) < 7:
            val = self["creation_date"][0:7]

        return val

    def check_collaboration(self, db=None):
        """Check synonyms for collaboration by using by the proper value.

        Args:
            db (pydal.DAL):
                database connection

        Raises:
            CheckException:
                * the collaboration is unknown in the database
                * more than one synonym found.

        """
        if db is None:
            self.logger.debug(f"{T6}skip check collaboration -- db is None")
            return

        self.logger.debug(f"{T6}check collaboration")

        val = self.collaboration()
        if len(val) == 0:
            return

        dbid = search_synonym(db.collaborations, "collaboration", val)
        if dbid == UNDEF_ID:
            raise CheckException(MSG_UNKNOWN_COLLABORATION)

        collaboration = db.collaborations[dbid].collaboration

        if collaboration != val:
            if "corporate_name" in self:
                # one collaboration
                if isinstance(self["corporate_name"], dict):
                    self["corporate_name"]["collaboration"] = collaboration

                # several collaboration
                # replace the list of dictionary by a single one
                else:
                    self["corporate_name"] = {"collaboration": collaboration}

    def check_my_affiliation(self, rex_institute=None):
        """Check that authors of my institute are signatories.

        Args:
            rex_institute (str):
                regular expression defining my institute

        Raises:
            CheckException

        """
        if rex_institute is None:
            self.logger.debug(f"{T6}skip check my affiliation -- rex is None")
            return

        self.logger.debug(f"{T6}check my affiliation")
        value = self.find_affiliation(rex_institute)

        if len(value) == 0:
            raise CheckException(MSG_NO_MY_AUTHOR)

    def check_paper_reference(self):
        """Check that editor, page, volume and paper year are defined
        for a published paper. Repair it from doi when possible.

        Args:
            record (RecordCdsPubli):
                record describing a publication.

        Raises:
            CheckException:
                the paper reference is not well formed.

        """
        self.logger.debug(f"{T6}check paper reference")

        if self.is_published():
            return

        # paper reference can be incomplete or missing
        # is the paper published ? In that case the doi is defined
        if "doi" not in self:
            return

        # what information is missing ?
        # * df.columns are title, volume, year and pagination
        # * df can contains one or more rows due to erratum.
        # * assume that the first row is the oldest one and corresponds tp
        #   the first publication
        # * the row contains empty string when the record is not published.
        # * iloc[0] returns a serie where the index are the column's name
        #
        columns = (self.df_info.iloc[0]
                   .replace("", np.nan)
                   .dropna()
                   .index)

        missing = PAPER_REFERENCE_KEYS.difference(columns)

        # try to recover from the doi when it has the form
        # xx.yyyy/Publisher.Volume.Page
        m = REG_DOI.match(self["doi"])
        if not m:
            raise CheckException(MSG_NO_REF + str(list(missing)))

        for subfield in missing:
            if subfield == "title":

                # transform PhysRevD in Phys. Rev. D
                li = re.split(r"([A-Z][a-z]+)", m.group(1))
                title = ". ".join([el for el in li if len(el) > 0])
                self.df_info.loc[0, "title"] = title

            elif subfield == "volume":
                self.df_info.loc[0, "volume"] = m.group(2)

            elif subfield == "pagination":
                self.df_info.loc[0, "pagination"] = m.group(3)

            elif subfield == "year":
                raise CheckException(MSG_NO_REF + "[year]")

    def check_submitted_date(self):
        """Standardise the submitted date as ``YYYY-MM`` or ``YYYY-MM-DD``.
        Look for alternative when it is not defined.

        Note:
            After this check the year submitted contains one entry.

        Args:
            record (RecordCdsPubli):
                record describing a publication.

        Raises:
            CheckException::

                * the date is not well formed
                * more than one date are found.

        """
        self.logger.debug(f"{T6}check submitted")

        date = self.submitted()

        # recover missing date using conference, preprint, thesis information
        if len(date) < 7:
            date = self._recover_submitted()
            if len(date) == 0:
                raise CheckException(MSG_NO_DATE)

            elif len(date) < 7:
                raise CheckException(MSG_WELL_FORMED_DATE)

        # 22 Mar 2011
        m = DECODE_DD_MMM_YYYY.match(date)
        if m:
            data = (m.group(3), MONTHS[m.group(2)], int(m.group(1)))
            date = '%s-%s-%02i' % data

        # 22 03 2011
        m = DECODE_DD_MM_YYYY.match(date)
        if m:
            data = (m.group(3), int(m.group(2)), int(m.group(1)))
            date = '%s-%02i-%02i' % data

        # in some case we have to deal with a list (see cds 2234042)
        # in some case it is not defined (e.g. phd thesis)
        if "prepublication" in self:

            prepublication = self["prepublication"]
            if isinstance(prepublication, list):
                prepublication[0]["date"] = date
            else:
                prepublication["date"] = date

        else:
            self["prepublication"] = {"date": date}

    def check_and_fix_record(self,
                             db=None,
                             fmt_author=None,
                             rex_institute=None,
                             sep_author=", ",
                             sort_author=False):
        """Check record and fix non-conformities.

            * is with authors
            * is with authors form my institute
            * standardise name of collaboration
            * format authors according to my format
            * extract authors form my institute signing the publication

        Args:
            db (pydal.DAL):
                database connection

            fmt_author (str):
                define the format for author names.
                Possible values are ``First, Last``, ``F. Last``, ``Last``,
                ``Last, First`` and ``Last F.``

            rex_institute (str):
                regular expression defining my institute

            sep_author (str):
                string separating author names. The default is the comma.

            sort_author (bool):
                sort authors by family name when true otherwise use the
                order of authors at the creation of the record

        Raises:
            CheckException

        """
        self.check_authors()
        self.check_my_affiliation(rex_institute)
        self.check_collaboration(db)
        self.check_format_authors(fmt_author)
        self.extract_my_authors(rex_institute, sep_author, sort_author)
        self.check_submitted_date()

604 605 606
    def collaboration(self):
        """The collaboration(s) signing the publication.

607
        Returns:
608
            str:
609 610
                * names of collaboration are separated by a comma.
                * The filter CLEAN_COLLABORATION is applied.
611 612

        """
613
        li = self._get("corporate_name", "collaboration", force_list=True)
LE GAC Renaud's avatar
LE GAC Renaud committed
614
        return CLEAN_COLLABORATION(", ".join(li))
615

616 617 618 619 620 621 622 623 624 625 626 627 628
    def debug(self):
        """Print the record structure on the standard output.

        """
        pprint.pprint(self)

    def host(self):
        """The store housing the record.

        Returns:
            str:

        """
629
        return "cds.cern.ch"
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667

    def id(self):
        """The id of the record in the store.

        Returns:
            int:
                the unique id of the record in the store

        """
        return self["recid"]

    def oai(self):
        """The Open Archive Initiative identifier(s).

        Returns:
            str:
                the primary and secondary OAI identifier are separated
                by a comma. The pattern of the identifier is ``oai:host:id`` or
                an empty string when it is not defined.

        """
        lst = [self.primary_oai(), self.secondary_oai()]
        return ", ".join(lst).strip(", ")

    def oai_url(self):
        """The Open Archive Initiative identifier URL(s).

        Returns:
            str:
                the primary and secondary URLs are separated by a comma.
                The pattern of the URL is ``http://host/record/id`` or
                an empty string when it is not defined or when the OAI is
                not well formed.

        """
        lst = [self.primary_oai_url(), self.secondary_oai_url()]
        return ", ".join(lst).strip(", ")

668 669 670
    def paper_url(self):
        """The URL of the preprint.

671 672
        Note:
            Many others URL exists mainly those related to open access.
673

674
        Returns:
675
            str:
LE GAC Renaud's avatar
LE GAC Renaud committed
676
                the string is empty when no URLs are found.
677 678

        """
LE GAC Renaud's avatar
LE GAC Renaud committed
679 680
        # scan the list of files
        # work for both stores.
681 682
        pdf = f"{self.preprint_number()}.pdf"
        pdf = pdf.replace(ARXIV + ":", "")
683

684
        li = self._get("files", "url", force_list=True)
LE GAC Renaud's avatar
LE GAC Renaud committed
685
        li = [el for el in li if el.endswith(pdf)]
686

LE GAC Renaud's avatar
LE GAC Renaud committed
687 688
        if len(li) == 1:
            return li[0]
689

690
        return ""
691 692 693 694

    def preprint_number(self):
        """The ArXiv preprint number.

695
        Returns:
696
            str:
697
                empty string when it is not defined.
698 699

        """
700
        if "primary_report_number" not in self:
LE GAC Renaud's avatar
LE GAC Renaud committed
701 702
            return

703
        data = self["primary_report_number"]
LE GAC Renaud's avatar
LE GAC Renaud committed
704 705
        data = (data if isinstance(data, list) else [data])

706
        li = [el for el in data if el is not None and el.startswith(ARXIV)]
LE GAC Renaud's avatar
LE GAC Renaud committed
707 708 709
        if len(li) == 1:
                return li[0]

710
        return ""
711

712 713 714 715 716 717 718 719 720 721 722
    def primary_oai(self):
        """The primary Open Archive Initiative identifier.

        The primary OAI identifier matches the record identifier.

        Returns:
            str:
                the pattern of the string is ``oai:host:id``.
                It is an empty string when not defined

        """
723
        return f"oai:cds.cern.ch:{self['recid']}"
724 725 726 727 728 729 730 731 732

    def primary_oai_url(self):
        """The Open Archive Initiative URL for the primary OAI.

        Returns:
            str:
                the pattern of the string is ``http://host/record/id``.

        """
733 734
        recid = self["recid"]
        return f"http://cds.cern.ch/record/{recid}"
735

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    def report_number(self):
        """The report number(s) associated to the publication.

        Returns:
            str:
                - Numbers are separated by a comma
                - Number are sorted in alphabetic order.
                - Empty string when not defined.

        """
        # CDS
        if "report_number" in self:

            data = self["report_number"]
            data = (data if isinstance(data, list) else [data])

            li = []
            [li.extend(di.values()) for di in data]

            return ", ".join(sorted(li))

        # OLD.INSPIRE
        if "primary_report_number" in self:

            data = self["primary_report_number"]
            data = (data if isinstance(data, list) else [data])

            li = [el for el in data
                  if el is not None and not el.startswith(ARXIV)]

            return ", ".join(sorted(li))

        return ""

770 771 772 773 774 775 776 777
    def secondary_oai(self):
        """The secondary OAI identifier.

        If the current store is *cds.cern.ch*, the secondary OAI identifier
        corresponds to the record in the other store, *inspirehep.net*.

        Returns:
            str:
778
                the pattern is ``oai:inspirehep.net:id``.
779 780 781 782 783 784 785 786 787 788 789 790 791
                It is an empty string when not defined

        """
        if "system_control_number" not in self:
            return ""

        data = self["system_control_number"]
        data = (data if isinstance(data, list) else [data])

        # data is a list of dictionary
        # keys are `institute`, `value` or `cancelled`
        for di in data:
            institute = di.get("institute")
792
            if institute == "Inspire":
793 794 795 796 797 798 799 800 801 802
                if "value" in di:
                    return OAI % ("inspirehep.net", di["value"])

        return ""

    def secondary_oai_url(self):
        """The Open Archive Initiative URL for the secondary OAI.

        Returns:
            str:
803 804
                * the pattern is ``http://inspirehep.net/record/id``.
                * The string is empty when it is not defined
805 806

        """
807 808 809 810 811 812 813 814 815
        value = self.secondary_oai()
        if len(value) == 0:
            return ""

        match = REG_OAI.match(value)
        if match:
            return OAI_URL % (match.group(1), match.group(2))

        return ""
816

817 818 819
    def submitted(self):
        """The date of submission.

820
        Returns:
821
            str:
LE GAC Renaud's avatar
LE GAC Renaud committed
822
                * format are"YYYY-MM", "YYYY-MM-DD", "DD MMM YYYY", *etc.*
823
                * Empty string when not defined.
824 825

        """
LE GAC Renaud's avatar
LE GAC Renaud committed
826 827
        # in some case there is more than one date (see cds 2234042)
        # select the oldest one which should be the first one
828
        val = self._get("prepublication", "date")
LE GAC Renaud's avatar
LE GAC Renaud committed
829
        return (val[0] if isinstance(val, list) else val)
830

831 832 833 834 835
    def subtype(self):
        """The subtype of the publication.

        Returns:
            str:
836
                * articles, preprint, proceeding, note, report ot thesis
837 838 839 840 841 842 843
                * empty string when it is not defined

        """
        collection = self.get("collection", None)
        if collection is None:
            return ""

844 845 846
        if not isinstance(collection, list):
            collection = [collection]

847 848
        lst = [dct.get("primary", "").lower() for dct in collection]

849 850 851 852
        if "conferencepaper" in lst:
            return "proceeding"

        # order matter since we have (preprint+note)
853
        for val in ("article", "note", "report", "thesis", "preprint"):
854 855 856 857 858
            if val in lst:
                return val

        return ""

859 860 861
    def title(self):
        """The title of the publication.

862
        Returns:
863
            str:
864 865
                * Empty string when not defined.
                * The filter CLEAN_SPACES is applied.
866 867

        """
868
        return CLEAN_SPACES(self._get("title", "title"))