citations.py 6.59 KB
Newer Older
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
""" NAME
        citations

    SYNOPSIS
        Produce a status report showing citations

    DESCRIPTION

    OPTIONS

        -h, --help
            Display the help and exit.

    EXAMPLE

        > cd ...limbra/scripts
        > run script test_limbra citations.py

    AUTHOR
        R. Le Gac -- Feb 2020

"""
import csv
import logging
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import re


from graph_tools import mplstyle
from invenio_tools import CdsException, InvenioStore
from matplotlib.backends.backend_pdf import PdfPages
from plugin_dbui import get_id

CSVFN = "/opt/web2py/applications/limbra/scripts/citations.csv"
PDFFN = "/opt/web2py/applications/limbra/scripts/citations.pdf"

REX_INS = re.compile(r"https?://inspirehep.net/")


def cli():

#     collect_citations()
    plot_citations()


def collect_citations():

    logger = logging.getLogger("web2py.app.limbra")

    logger.info("-"*79)
    logger.info("start collect citations...")

    publications = db.publications
    store = InvenioStore("inspirehep.net")

    # get the list of article stored in inspirehep
    id_acl = get_id(db.categories, code="ACL")

    query = (db.publications.id_categories == id_acl) & \
            (db.publications.origin.contains("inspirehep"))

    iterrow = db(query).iterselect(publications.id, publications.origin)

    # interrogate inspirehep to get the number of citations
    # save data into a local file
    with open(CSVFN, "w", newline="\n") as csvfile:
        writer = csv.writer(csvfile)

        for rowid, url in map(get_rowid_url, iterrow):
            logger.info(f"  {url}")
            try:
                citations = get_citations(store, url)
                writer.writerow((rowid, url, citations))
                logging.debug("FOO")

            except (CdsException, ValueError) as e:
                logging.info(f"  error {e}")
                pass

    logger.info("end of collect")
    logger.info("-"*79)


def get_citations(store, url):
    """
    Args:
        store (InvenioStore)
        url (str):

    Returns:
        int:
            number of citations
    """
    kwargs = dict(of="recjson", ot="number_of_citations")
98
    rep = store.interrogate(url, timeout=10, **kwargs)
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
    return rep.json()[0].get("number_of_citations")


def get_rowid_url(row):
    """
    Args:
        row (pyDAL.Row):
            row of the publications table with at least field id and origin

    Returns:
        tuple:
            (rowid (int), url (str))

    """
    url = [el for el in row.origin.split(", ") if REX_INS.match(el)][0]
    return (row.id, url)


def plot_citations():

    logger = logging.getLogger("web2py.app.limbra")

    logger.info("-"*79)
    logger.info("start plot citations...")

    mplstyle()
    pdf = PdfPages(PDFFN)

    df_publis = pd.read_csv(CSVFN, names=["id", "url", "citations"])

    # ........................................................................
    #
    # overview à la inspirehep (histogram of all citations)
    #
    citations = df_publis.citations
    bins = [-0.5, 0.5, 9.5, 49.5, 99.5, 249.5, 499.5, citations.max()+1]
    hist, dummy = np.histogram(citations, bins)
    ind = np.arange(len(hist))

    fig = plt.figure()
    ax = plt.subplot(211)

    ax.bar(ind, hist)
    ax.minorticks_on()

    xlabels = ("",
               "0",
               "1 à 9",
               "10 à 49",
               "50 à 99",
               "100 à 249",
               "250 à 499",
               "+500")

    ax.xaxis.set_ticklabels(xlabels)
    ax.grid(True)

    ax.set_xlabel("Number of citations", horizontalalignment='right', x=1.)
    ax.set_ylabel("Number of publications", horizontalalignment='right', y=1.)

    ax.xaxis.set_minor_locator(ticker.NullLocator())

    txt = [
        f"articles : {len(df_publis)}",
        f"citations: {citations.sum()}",
        f"citations/article (avg): {citations.mean():.1f}"]

    ax.text(
        0.72, 0.8, "\n".join(txt),
        bbox=dict(facecolor="white", alpha=0.5),
        family="monospace",
        fontsize=5,
        transform=ax.transAxes)

    pdf.savefig(fig)

    # ........................................................................
    #
    # per scientific domain
    #
    publications = db.publications

    # get (id_team, id_project) associate at each publication
    id_acl = get_id(db.categories, code="ACL")
    query = (db.publications.id_categories == id_acl) & \
            (db.publications.origin.contains("inspirehep"))

    rows = db(query).select(publications.id,
                            publications.id_teams,
                            publications.id_projects)

    df_publis_teams = (pd.DataFrame(rows.as_list())
                       .rename(columns={"id_teams": "id_team",
                                        "id_projects": "id_project"}))

    df_publis = pd.merge(df_publis, df_publis_teams,
                         how="inner",
                         on=["id", "id"])

    # expend id_team to domain and team
    df_teams = (pd.DataFrame(db(db.teams).select().as_list())
                .rename(columns={"id": "id_team"}))

    df_publis = (pd.merge(df_publis, df_teams,
                          how="inner",
                          on=["id_team", "id_team"])
                 .drop(["id_team"], axis="columns"))

    # expend id_project to project
    df_projects = (pd.DataFrame(db(db.projects).select().as_list())
                   .rename(columns={"id": "id_project"}))

    df_publis = (pd.merge(df_publis, df_projects,
                          how="inner",
                          on=["id_project", "id_project"])
                 .drop(["id_project", "agencies"], axis="columns"))

    fig = plt.figure()
    ax = plt.subplot(121)

    query = (df_publis.citations < 500) & (df_publis.domain != "Hors Equipe")
    df = df_publis[query]
    df.boxplot("citations", by="domain", ax=ax, grid=True, rot=20)

    ax.minorticks_on()
    ax.xaxis.set_minor_locator(ticker.NullLocator())

    ax.set_ylabel("Number of citations", horizontalalignment='right', x=1.)

    pdf.savefig(fig)

    # ........................................................................
    #
    # per team
    #
    fig = plt.figure()
    ax = plt.subplot(121)

    query = (df_publis.citations < 500) & (df_publis.domain != "Hors Equipe")
    df = df_publis[query]
    df.boxplot("citations", by="team", ax=ax, grid=True, rot=20)

    ax.minorticks_on()
    ax.xaxis.set_minor_locator(ticker.NullLocator())

    ax.set_ylabel("Number of citations", horizontalalignment='right', x=1.)

    pdf.savefig(fig)

    pdf.close()


if __name__ == "__main__":
    import sys

    cli()
255
    sys.exit(0)