|
| 1 | +"""Example nqdc plugin: plots the number of articles per publication year.""" |
| 2 | +import argparse |
| 3 | +import logging |
| 4 | +from pathlib import Path |
| 5 | +from typing import Tuple, Mapping, Optional, Union, Dict, List |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | + |
| 9 | +ArgparseActions = Union[argparse.ArgumentParser, argparse._ArgumentGroup] |
| 10 | + |
| 11 | +_LOG = logging.getLogger(__name__) |
| 12 | +_STEP_NAME = "plot_pub_dates" |
| 13 | +_STEP_DESCRIPTION = "Example plugin: plot histogram of publication years." |
| 14 | + |
| 15 | + |
| 16 | +def plot_publication_dates(extracted_data_dir: Path) -> Tuple[Path, int]: |
| 17 | + """Make a bar plot of the number of articles per year. |
| 18 | +
|
| 19 | + Parameters |
| 20 | + ---------- |
| 21 | + extracted_data_dir |
| 22 | + The directory containing the articles' metadata. It is a directory |
| 23 | + created by `nqdc.extract_data_to_csv`: it contains a file named |
| 24 | + `metadata.csv`. |
| 25 | +
|
| 26 | + Returns |
| 27 | + ------- |
| 28 | + output_dir |
| 29 | + The directory where the plot is stored. |
| 30 | + exit_code |
| 31 | + Always 0, used by nqdc command-line interface. |
| 32 | +
|
| 33 | + """ |
| 34 | + output_dir = extracted_data_dir.with_name( |
| 35 | + extracted_data_dir.name.replace( |
| 36 | + "_extractedData", "_examplePluginPubDatesPlot" |
| 37 | + ) |
| 38 | + ) |
| 39 | + output_dir.mkdir(exist_ok=True) |
| 40 | + meta_data = pd.read_csv(str(extracted_data_dir.joinpath("metadata.csv"))) |
| 41 | + min_year, max_year = ( |
| 42 | + meta_data["publication_year"].min(), |
| 43 | + meta_data["publication_year"].max(), |
| 44 | + ) |
| 45 | + years = list(range(min_year, max_year + 2)) |
| 46 | + ax = meta_data["publication_year"].hist( |
| 47 | + bins=years, grid=False, rwidth=0.5, align="left" |
| 48 | + ) |
| 49 | + ax.set_xticks(years[:-1]) |
| 50 | + ax.set_xlabel("Publication year") |
| 51 | + ax.set_ylabel("Number of articles") |
| 52 | + output_file = output_dir.joinpath("plot.png") |
| 53 | + ax.figure.savefig(str(output_file)) |
| 54 | + _LOG.info(f"Publication dates histogram saved in {output_file}.") |
| 55 | + return output_dir, 0 |
| 56 | + |
| 57 | + |
| 58 | +class PlotPubDatesStep: |
| 59 | + """Plot publication dates as part of a pipeline (`nqdc run`).""" |
| 60 | + |
| 61 | + # Used for the command-line help |
| 62 | + name = _STEP_NAME |
| 63 | + short_description = _STEP_DESCRIPTION |
| 64 | + |
| 65 | + def edit_argument_parser(self, argument_parser: ArgparseActions) -> None: |
| 66 | + """Add an argument to indicate if the plugin should run. |
| 67 | +
|
| 68 | + When `nqdc run` is invoked, this optional step is executed only if the |
| 69 | + `--plot_pub_dates` flag is passed on the command line. |
| 70 | +
|
| 71 | + """ |
| 72 | + argument_parser.add_argument( |
| 73 | + "--plot_pub_dates", |
| 74 | + action="store_true", |
| 75 | + help="Save a histogram plot of publication years of " |
| 76 | + "downloaded articles.", |
| 77 | + ) |
| 78 | + |
| 79 | + def run( |
| 80 | + self, |
| 81 | + args: argparse.Namespace, |
| 82 | + previous_steps_output: Mapping[str, Path], |
| 83 | + ) -> Tuple[Optional[Path], int]: |
| 84 | + """Execute this step: plot the publication dates.""" |
| 85 | + # `args` are the command-line arguments, we check if running this |
| 86 | + # plugin was required with the `--plot_pub_dates` argument. |
| 87 | + if not args.plot_pub_dates: |
| 88 | + return None, 0 |
| 89 | + # `previous_steps_output` maps step names to the directories where they |
| 90 | + # stored their output; we need the metadata generated by the |
| 91 | + # `extract_data` step. |
| 92 | + return plot_publication_dates(previous_steps_output["extract_data"]) |
| 93 | + |
| 94 | + |
| 95 | +class StandalonePlotPubDatesStep: |
| 96 | + """Plot publication dates as a standalone step (`nqdc plot_pub_dates`).""" |
| 97 | + |
| 98 | + name = _STEP_NAME |
| 99 | + short_description = _STEP_DESCRIPTION |
| 100 | + |
| 101 | + def edit_argument_parser(self, argument_parser: ArgparseActions) -> None: |
| 102 | + """Add an argument to specify the extracted data dir. |
| 103 | +
|
| 104 | + This directory contains the metadata file that provides the publication |
| 105 | + dates. |
| 106 | +
|
| 107 | + """ |
| 108 | + argument_parser.add_argument( |
| 109 | + "extracted_data_dir", |
| 110 | + help="Directory containing extracted data CSV files." |
| 111 | + "It is a directory created by nqdc whose name ends " |
| 112 | + "with 'extractedData'.", |
| 113 | + ) |
| 114 | + |
| 115 | + def run( |
| 116 | + self, |
| 117 | + args: argparse.Namespace, |
| 118 | + previous_steps_output: Mapping[str, Path], |
| 119 | + ) -> Tuple[Path, int]: |
| 120 | + """Execute the `nqdc plot_pub_dates` command.""" |
| 121 | + # In this case the plugin is run on its own rather than as a step in |
| 122 | + # the full pipeline, so the `extracted_data_dir` is not produced by a |
| 123 | + # previous step but it is passed as a command-line argument. |
| 124 | + return plot_publication_dates(args.extracted_data_dir) |
| 125 | + |
| 126 | + |
| 127 | +def get_nqdc_processing_steps() -> Dict[str, List]: |
| 128 | + """Entry point used by nqdc. |
| 129 | +
|
| 130 | + Needed to discover the plugin steps and add them to the command-line |
| 131 | + interface. It returns a mapping with 2 (optional) keys: "pipeline_steps" |
| 132 | + for steps that must be added to the full pipeline (executed when `nqdc run` |
| 133 | + is invoked), and "standalone_steps" for steps that run on their own (are |
| 134 | + added as separate subcommands, in this case `nqdc plot_pub_dates`). |
| 135 | +
|
| 136 | + The values are lists of objects that provide the same interface as |
| 137 | + `nqdc.BaseProcessingStep`: they have `name` and `short_description` |
| 138 | + attributes, and `edit_argument_parser` and `run` methods. |
| 139 | +
|
| 140 | + This entry point must be referenced in the `[options.entry_points]` section |
| 141 | + in `setup.cfg`. |
| 142 | +
|
| 143 | + """ |
| 144 | + return { |
| 145 | + "pipeline_steps": [PlotPubDatesStep()], |
| 146 | + "standalone_steps": [StandalonePlotPubDatesStep()], |
| 147 | + } |
0 commit comments