recordheppubli.py 16.7 KB
Newer Older
1 2 3
""" store_tools.recordheppubli

"""
4
import logging
5
import pprint
6

7 8 9 10 11
from .authorsmixin import AuthorsMixin, MSG_NO_MY_AUTHOR
from .base import (search_synonym,
                   MSG_UNKNOWN_COLLABORATION,
                   MSG_WELL_FORMED_DATE,
                   REG_DATE_YYYYMM,
12
                   T4, T6)
13
from .exception import CheckException
14 15
from filters import CLEAN_COLLABORATION
from pandas import DataFrame
16
from .publicationinfomixin import PublicationInfoMixin
17
from plugin_dbui import UNDEF_ID
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
def pages(row):
    """Help function to build the pages argument

    Args:
        row (pandas.Series):
            * artid (str)
            * page_start (int)
            * page_end (int)

    Return
        str:
            * either 23 or 23-45
            * empty string when information is missing

    """
    artid = row.get("artid", None)
    pstart = row.get("page_start", None)
    pend = row.get("page_end", None)

    if pstart is None and pend is None and artid is None:
        return ""

    elif pstart is None and pend is None:
        return artid

    elif pend is None:
        return f"{pstart}"

    return f"{pstart}-{pend}"


51
class RecordHepPubli(dict, AuthorsMixin, PublicationInfoMixin):
52 53
    """Article, preprint and proceeding from inspirehep.net version 2.

54
    Schema for publication is documented here:
55 56 57 58 59 60 61 62
    https://inspire-schemas.readthedocs.io/en/latest/schemas/

    """

    def __init__(self, recjson):

        super().__init__(recjson)

63 64
        self.logger = logging.getLogger("web2py.app.limbra")

65 66 67 68
        self._last_fmt_author = "Last, First"
        self._process_authors()
        self._process_publication_info()

69 70
        # the authors of my institutes signing the record
        # string containing a list of name separated by a comma
LE GAC Renaud's avatar
LE GAC Renaud committed
71
        self.my_authors = None
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    def _process_authors(self):
        """Convert authors information into DataFrame:

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

            +---------------+--------------------------------+
            | column        |                                |
            +===============+================================+
            | affiliation   | value separated by "|"         |
            +---------------+--------------------------------+
            | first_name    | first name                     |
            +---------------+--------------------------------+
            | fmt_name      | formated name                  |
            +---------------+--------------------------------+
            | full_name     | Last, First                    |
            +---------------+--------------------------------+
            | last_name     | family name                    |
            +---------------+--------------------------------+
92
            | role          | equal to dir. for phd director |
93 94 95
            +---------------+--------------------------------+

        Note:
96 97 98
            After running this method, the attribute ``df_authors`` is defined.
            It contains one entry with empty strings when the file ``authors``
            is not defined.
99 100

        """
101
        self.logger.debug(f"{T4}process authors")
102

103 104 105 106 107 108 109
        authors = self.get("authors", None)

        if authors is None:
            cols = ["affiliation",
                    "first_name",
                    "fmt_name",
                    "full_name",
110 111
                    "last_name",
                    "role"]
112
            self.df_authors = DataFrame([[""] * len(cols)], columns=cols)
113 114 115 116 117 118 119 120 121
            return

        data = []
        for author in authors:

            affiliations = []
            if "affiliations" in author:
                affiliations = [elt["value"] for elt in author["affiliations"]]

122 123 124
            role = \
                (author["inspire_roles"] if "inspire_roles" in author else [])

125
            full_name = author["full_name"]
126 127 128
            idx = full_name.find(",")
            last_name = full_name[:idx]
            first_name = full_name[idx + 1:].strip()
129 130 131 132 133

            dct = {"affiliation": "|".join(affiliations),
                   "first_name": first_name.strip(),
                   "fmt_name": full_name,
                   "full_name": full_name,
134 135
                   "last_name": last_name.strip(),
                   "role": ", ".join(role)}
136 137 138 139 140 141 142 143 144 145

            data.append(dct)

        df = DataFrame(data)

        # protection against duplicated entries, e.g. twice the first author
        if "full_name" in df.columns:
            df = df.drop_duplicates("full_name")

        # replace
146
        self.df_authors = df
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170

    def _process_publication_info(self):
        """Convert publication_info into DataFrame:

            Note:
                * the field is a list when there are erratum
                * in some case the subfield year is a list (cds 1951625)

        publication information are stored in DataFrame with the
        following structure:

            +------------+--------------------------------+
            | column     |                                |
            +============+================================+
            | title      | abbreviation of the publisher  |
            +------------+--------------------------------+
            | volume     | volume                         |
            +------------+--------------------------------+
            | year       | year of publication            |
            +------------+--------------------------------+
            | pagination | page number or ranges          |
            +------------+--------------------------------+

        Note:
171 172 173
            * After running this method, the attribute ``df_info``
              is defined. It contains one entry with empty strings
              when the ``publication_info`` field does not exist.
174 175 176 177 178

            * In order to deal with erratum entry are sorter by year
              and volume.

        """
179
        self.logger.debug(f"{T4}process publication info")
180 181 182 183 184 185

        cols = ["title",
                "volume",
                "year",
                "pagination"]

186 187 188
        data = self.get("publication_info", None)

        if data is None:
189
            self.df_info = DataFrame([[""] * len(cols)], columns=cols)
190 191
            return

192 193 194
        # filter data to keep only row with year information
        data = [dct for dct in data if "year" in dct]

195 196 197 198
        if len(data) == 0:
            self.df_info = DataFrame([[""] * len(cols)], columns=cols)
            return

199
        # convert data to DataFrame with a well know structure
200 201
        df = (DataFrame(data)
              .astype({"year": str})
202 203 204
              .rename(columns={"journal_title": "title",
                               "journal_volume": "volume"},
                      errors="ignore"))
205

206 207
        # construction pagination columns
        df["pagination"] = df.apply(pages, axis="columns")
208 209

        # erratum -- sort by year and volume
210
        columns = df.columns
211 212 213 214 215 216 217
        if set(["year", "volume"]).issubset(columns):
            df = df.sort_values(["year", "volume"])

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

        # replace
218
        self.df_info = df
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
    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:
            self["collaborations"] = [{"value": 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_paper_reference is a dummy method to preserve interface

        """

    def check_submitted_date(self):
        """Check that submitted date as ``YYYY-MM`` or ``YYYY-MM-DD``.

        Raises:
            CheckException::
                * the date is not well formed

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

        xdate = self.submitted()
        if not REG_DATE_YYYYMM.match(xdate):
            raise CheckException(MSG_WELL_FORMED_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()

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    def collaboration(self):
        """The collaboration(s) signing the publication.

        Returns:
            str:
                * collaborations are separated by a comma.
                * The filter CLEAN_COLLABORATION is applied.
                * empty string when not defined

        """
        collaborations = self.get("collaborations", None)

        if collaborations is None:
            return ""

350
        lst = [elt["value"] for elt in collaborations]
351 352
        return CLEAN_COLLABORATION(", ".join(lst))

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
    def debug(self):
        """Print the record structure on the standard output.

        """
        pprint.pprint(self)

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

        Returns:
            str:

        """
        return "inspirehep.net"

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

        Returns:
            int:

        """
        return self["control_number"]

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

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

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

390 391 392 393 394 395 396 397 398 399 400 401 402
    def oai_url(self):
        """The Open Archive Initiative identifier URL(s).

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

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

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
    def paper_url(self):
        """The URL of the document.

        Returns:
            str:
                * the string is empty when no URLs are found.
                * first URL is selected when there is more than one

        """
        documents = self.get("documents", None)
        return ("" if documents is None else documents[0]["url"])

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

        Returns:
            str:
                * numbers are separated by a comma.
                * empty string when it is not defined.

        """
        lst = self.get("arxiv_eprints", None)

        if lst is None:
            return ""

        lst = [f"arXiv:{elt['value']}" for elt in lst]
        return ", ".join(lst)

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    def primary_oai(self):
        """The primary Open Archive Initiative identifier.

        The primary OAI identifier matches the record identifier.

        Returns:
            str:
                * the pattern  is ``oai:host:id``.
                * empty string when it is not defined

        """
        return f"oai:inspirehep.net:{self['control_number']}"

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

        Returns:
            str:
                * the pattern is ``http://inspirehep.net/record/id``

        """
        recid = self["control_number"]
        return f"http://inspirehep.net/record/{recid}"

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    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.

        """
        lst = self.get("report_numbers", None)

        if lst is None:
            return ""

        lst = [elt["value"] for elt in lst]
        return ", ".join(lst)

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
    def secondary_oai(self):
        """The secondary OAI identifier.

        the secondary OAI identifier corresponds to the record in the
        store, *cds.cern.ch*.

        Returns:
            str:
                * the pattern  is ``oai:host:id``.
                * empty string when it is not defined

        """
        if "external_system_identifiers" not in self:
            return ""

        for elt in self["external_system_identifiers"]:
            if elt["schema"] == "CDS":
                return f"oai:cds.cern.ch:{elt['value']}"

        return ""

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

        the secondary OAI URL corresponds to the record in the
        store, *cds.cern.ch*.

        Returns:
            str:
                * the pattern is ``http://cds.cern.ch/record/id``
                * empty string when it is not defined

        """
        if "external_system_identifiers" not in self:
            return ""

        for elt in self["external_system_identifiers"]:
            if elt["schema"] == "CDS":
                return f"http://cds.cern.ch/record/{elt['value']}"

        return ""

516 517 518 519 520 521 522 523 524 525 526 527
    def submitted(self):
        """The date of submission.

        Returns:
            str:
                * format are"YYYY-MM", "YYYY-MM-DD", "DD MMM YYYY", *etc.*
                * Empty string when not defined.

        """
        val = self.get("preprint_date", None)
        return ("" if val is None else val)

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    def subtype(self):
        """The subtype of the publication.

        Returns:
            str:
                * "articles", "preprint", "note" or "report"
                * empty string when it is not defined

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

        doctype = (doctype[0] if isinstance(doctype, list) else doctype)

        if doctype != "article":
            return doctype

        # separate article from preprint
        # in the latter case publication_info is missing
        pubinfo = self.get("publication_info", None)
        return ("preprint" if pubinfo is None else "article")

551 552 553 554 555 556 557 558 559 560 561 562
    def title(self):
        """The title of the publication.

        Returns:
            str:
                * Empty string when not defined.
                * The filter CLEAN_SPACES is applied.
                * First one is selectec when ther is more than one

        """
        titles = self.get("titles", None)
        return ("" if titles is None else titles[0]["title"])