{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pyscisci.all as pyscisci\n",
    "\n",
    "import os\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pylab as plt\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# set this path to where the APS database will be stored\n",
    "path2aps = '/home/ajgates/APS'\n",
    "path2aps = '/users/hgt6rn/Documents/DataSets/APS2019'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "myaps = pyscisci.APS(path2aps, database_extension='csv.gz', keep_in_memory=False) \n",
    "\n",
    "# set keep_in_memory=False if you want to load the database each time its needed - good for when you \n",
    "# cant keep more than one DataFrame in memory at a time\n",
    "\n",
    "# otherwise keep_in_memory=True will keep each DataFrame in memory after its loaded"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# You need to request access to the APS dataset\n",
    "# Follow this link and fill out their form, they should email you\n",
    "# links to download two files.  (usually takes about 1 week.)\n",
    "\n",
    "myaps.download_from_source(files_to_download='orig')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "32a3db37fed74fed9bdab0a8c59675bd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "aps-metadata:   0%|          | 0/656622 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parsing Complete\n",
      "Saving Publication DataFrames\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "02529bbcc49943ea95562941a74ea7d8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "aps-citations:   0%|          | 0/8324632 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# before we can start running our analysis, we have to preprocess the raw data into\n",
    "# DataFrames that are more convinent to work with\n",
    "myaps.preprocess(show_progress=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: APS does not contain disambiguated author or affiliation information by default, although researchers \n",
    "# have produced their own disambiguation to supplement the raw data\n",
    "\n",
    "# Here, we include the author disambiguation used in Sinatra et al. (2016)\n",
    "myaps.download_from_source(files_to_download='paa_supplement')\n",
    "\n",
    "# to use this after downloading you need to set a new path\n",
    "#myaps.set_new_data_path(dataframe_name='paa', new_path='publicationauthoraffiliation2010supplement')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# APS creates three dataframes:\n",
    "# pub  - keeps all of the publication information\n",
    "# columns : ['PublicationId', 'Title', 'Date', 'Year', 'Doi', 'JournalId', 'Volume', 'Issue', 'PageStart', 'PageEnd', 'DocType', 'TeamSize']\n",
    "\n",
    "# journal  - keeps all of the journal information\n",
    "# columns : ['JournalId', 'FullName', 'AbbreviatedName', 'Publisher']\n",
    "\n",
    "# affiliation  - keeps all affiliation information\n",
    "# columns : ['AffiliationId', 'Address']\n",
    "\n",
    "# paa  - links the publications to authors and affiliations\n",
    "# columns : ['PublicationId', 'OrigAuthorName', 'AffiliationId', 'AuthorSequence']\n",
    "\n",
    "# pub2field  - links the publications to fields (aka subjectAreas)\n",
    "# columns : ['PublicationId', 'FieldId']\n",
    "\n",
    "# pub2ref  - keeps the citation information\n",
    "# columns : ['CitingPublicationId', 'CitedPublicationId']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# lets plot the number of publications each year\n",
    "yearly_articles = pyscisci.groupby_count(df=myaps.pub , colgroupby='Year', colcountby='PublicationId', count_unique=True,\n",
    "                               show_progress=True)\n",
    "yearly_articles.sort_values(by='Year', inplace=True)\n",
    "yearly_articles = yearly_articles.loc[yearly_articles['Year'] > 0]\n",
    "\n",
    "fig, ax = plt.subplots(1,1,figsize=(8,5))\n",
    "\n",
    "ax.plot(yearly_articles['Year'],yearly_articles['PublicationIdCount'])\n",
    "\n",
    "ax.set_xlabel('Year')\n",
    "ax.set_ylabel(\"# of publications\")\n",
    "ax.set_yscale('log')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# now we can see the distribution of citation counts \n",
    "citations = pyscisci.groupby_count(df=myaps.pub2ref , colgroupby='CitedPublicationId', colcountby='CitingPublicationId', \n",
    "                          count_unique=True, show_progress=True)\n",
    "\n",
    "citevalues, citecounts = np.unique(citations['CitingPublicationIdCount'].values, return_counts=True)\n",
    "\n",
    "fig, ax = plt.subplots(1,1,figsize=(8,5))\n",
    "\n",
    "ax.scatter(citevalues, citecounts)\n",
    "\n",
    "ax.set_xlabel('# of citations')\n",
    "ax.set_ylabel(\"# of publications\")\n",
    "ax.set_xscale('log')\n",
    "ax.set_yscale('log')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
