Skip to content

API reference

The primary interface to detk is the command line, but the underlying Python modules can be used directly. From 1.0 the command line, with what its --help states (its sections, each argument's metavar, default and choices, and its examples, though not its wording) and its exit codes, is the stable surface that follows semantic versioning; the Python API below is usable but not yet a compatibility promise (see Stability). The core objects:

Common

de_toolkit.common.CountMatrix

A counts matrix (features in rows, samples in columns) and, optionally, its sample information column_data (samples in rows) and a design.

The counts columns and the column data rows must name the same samples (DETK-0600): a sample in only one of them raises :class:SampleMismatchException naming it. The column data is matched to the counts by name, so its rows may come in any order, unless strict, which requires the same order too. subset keeps the samples in both instead, in the counts' order; it is what detk-util tidy does, the explicit way to subset the two.

Source code in de_toolkit/common.py
621
622
623
624
625
626
627
628
629
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
class CountMatrix:
    """
    A counts matrix (features in rows, samples in columns) and, optionally,
    its sample information *column_data* (samples in rows) and a *design*.

    The counts columns and the column data rows must name the same samples
    (DETK-0600): a sample in only one of them raises
    :class:`SampleMismatchException` naming it. The column data is matched
    to the counts by name, so its rows may come in any order, unless
    *strict*, which requires the same order too. *subset* keeps the samples
    in both instead, in the counts' order; it is what ``detk-util tidy``
    does, the explicit way to subset the two.
    """

    def __init__(self, counts, column_data=None, design=None, strict=False, subset=False):

        self.strict = strict

        if column_data is not None:
            in_counts, in_column_data = set(counts.columns), set(column_data.index)
            counts_only = [s for s in counts.columns if s not in in_column_data]
            column_data_only = [s for s in column_data.index if s not in in_counts]
            if (counts_only or column_data_only) and not subset:
                parts = []
                if counts_only:
                    parts.append(f"in the counts only: {_sample_list(counts_only)}")
                if column_data_only:
                    parts.append(
                        f"in the sample information only: {_sample_list(column_data_only)}"
                    )
                raise SampleMismatchException(
                    "the counts columns and the sample information rows must name the "
                    "same samples; " + "; ".join(parts) + " (to subset the two to the "
                    "samples in both, run detk-util tidy first)"
                )
            if strict and list(column_data.index) != list(counts.columns):
                raise SampleMismatchException(
                    "--strict requires the counts columns and the sample information "
                    "rows to name the same samples in the same order"
                )

            common_names = counts.columns.intersection(column_data.index, sort=False)

            logger.debug("common names between counts and column data:\n %s", pformat(common_names))

            # fix to a "no memory available" issue (old Bitbucket tracker) when matrices are
            # empty
            if len(common_names) < 2:
                raise SampleMismatchException(
                    "No sample names were found to be in "
                    "common between the counts and column data or specified sample "
                    "names. Check that the first column of the column_data matrix "
                    "and the first row of the counts matrix contain at least 2 values "
                    "in common"
                )

            counts = counts[common_names]
            column_data = column_data.loc[common_names]

        # if the design is provided, it must have a 'counts' term somewhere
        if design is not None and "counts" not in design:
            raise InvalidDesignException(
                'The term "counts" must exist on at least one side of the CountsMatrix design'
            )

        # set the things
        self.counts = counts
        logger.info("counts matrix has shape: %s", self.counts.shape)

        self.column_data = column_data
        if column_data is not None:
            logger.info("column data matrix has shape: %s", self.column_data.shape)
        else:
            logger.info("column data was not provided")

        # set the design no matta wat
        self._design_matrix = None
        self.design = self._original_design = design
        logger.info("design: %s", design)
        logger.debug("full design:\n %s", pformat(self.design_matrix))

        # TODO this is not yet implemented or thought out
        # members to keep track of count mutations
        self.transformed = {}
        self.normalized = {}

    @property
    def column_data(self):
        return self._column_data

    @column_data.setter
    def column_data(self, column_data):
        # if column_data does not have a counts column, add one with trivial values
        # so things work
        if column_data is not None and "counts" not in column_data:
            column_data["counts"] = 0

        self._column_data = column_data

        # update the design matrix by setting the design to itself
        self.design = self.design

    @property
    def design(self):
        if hasattr(self, "design_matrix") and self.design_matrix is not None:
            return self.design_matrix.design
        if hasattr(self, "_design"):
            return self._design
        return None

    @design.setter
    def design(self, design):
        self._design = design
        if design is not None and self.column_data is not None:
            try:
                self.design_matrix = DesignMatrix(design, self.column_data)
            except FormulaParseError as e:
                # each FormulaParseError names its cause: a term that is not
                # a column, a level the data lacks, a number-like term
                # (DETK-0190), or formula syntax detk could not read
                raise InvalidDesignException(
                    "Invalid design: " + "; ".join(str(a) for a in e.args)
                ) from e

            # check if the full design matrix has lost any rows due to
            # missing data
            if self.design_matrix.full_matrix.index.size != self.column_data.index.size:
                msg = (
                    "The full design matrix rows do not match the input column "
                    "data matrix, likely due to some missing fields. "
                    f"# design matrix rows: {self.design_matrix.full_matrix.index.size}, # column data rows: {self.column_data.shape[0]}. "
                )

                if self.strict:
                    raise SampleMismatchException(msg + "Aborting.")
                else:
                    warnings.warn(
                        msg + "Adjusting the counts matrix and column data to fit.", stacklevel=2
                    )
                    logger.warning(msg + "Adjusting the counts matrix and column data to fit.")
                    logger.warning("counts shape prior to fit: %s", self.counts.shape)
                    logger.warning("column data prior to fit: %s", self.column_data.shape)
                    self.counts = self.counts[self.design_matrix.full_matrix.index]
                    self._column_data = self.column_data.loc[self.design_matrix.full_matrix.index]

                    logger.warning("counts shape after fit: %s", self.counts.shape)
                    logger.warning("column data after fit: %s", self._column_data.shape)

        elif design is not None and self.column_data is None:
            raise InvalidDesignException(
                "There must be column data associated with a "
                "CountMatrix object before specifying a design"
            )

    @property
    def design_matrix(self):
        return self._design_matrix

    @design_matrix.setter
    def design_matrix(self, design_matrix):
        self._design_matrix = design_matrix

    @property
    def sample_names(self):
        return self.counts.columns

    @sample_names.setter
    def sample_names(self, value):
        try:
            self.counts = self.counts[value]
        except Exception as e:
            raise Exception(
                "Sample names provided that are not contained in the counts matrix"
            ) from e

    @property
    def feature_names(self):
        return self.counts.index

    @feature_names.setter
    def feature_names(self, value):
        try:
            self.counts = self.counts.loc[value]
        except Exception as e:
            raise Exception(
                "Feature names provided that are not contained in the counts matrix"
            ) from e

    def copy(self):
        return deepcopy(self)

    def transform(self, transf):
        self.transformed[transf.__name__] = transf(self)

    def add_normalized(self, method="deseq2"):
        pass

de_toolkit.common.CountMatrixFile

Bases: CountMatrix

A :class:CountMatrix read from the counts file count_f (and the column data file column_data_f). With check "ids" or "raw", the counts are run through :func:check_counts as read, before the column data selects or reorders any sample: "ids" for the repeated sample header and feature ID checks only, "raw" for all of them. The default, None, checks nothing, as in 1.0.0.

Source code in de_toolkit/common.py
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
class CountMatrixFile(CountMatrix):
    """
    A :class:`CountMatrix` read from the counts file *count_f* (and the column
    data file *column_data_f*). With *check* ``"ids"`` or ``"raw"``, the
    counts are run through :func:`check_counts` as read, before the column
    data selects or reorders any sample: ``"ids"`` for the repeated sample
    header and feature ID checks only, ``"raw"`` for all of them. The
    default, ``None``, checks nothing, as in 1.0.0.
    """

    def __init__(self, count_f, column_data_f=None, design=None, check=None, **kwargs):

        counts = read_id_table(count_f)
        if check is not None:
            if check not in ("ids", "raw"):
                raise ValueError(f"check must be None, 'ids' or 'raw', not {check!r}")
            check_counts(counts, _source_name(count_f), values=check == "raw")

        column_data = None
        if column_data_f is not None:
            column_data = read_id_table(column_data_f)

        CountMatrix.__init__(self, counts, column_data=column_data, design=design, **kwargs)

de_toolkit.common.DetkModule

Bases: OrderedDict

Base class for all detk methods.

Each function in detk is a subclass of this class. A module has the following properties: - name: name of the module - params: the module-dependent params passed to the module - output: the output of the module in tabular form - properties: properties and statistics about the module, used for formatting the results into a report

All of these properties are JSON serializable, i.e. basic python types (int, float, str, bool, array, dict).

Source code in de_toolkit/common.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
class DetkModule(OrderedDict):
    """
    Base class for all detk methods.

    Each function in detk is a subclass of this class.
    A module has the following properties:
    - ``name``: name of the module
    - ``params``: the module-dependent params passed to the module
    - ``output``: the output of the module in tabular form
    - ``properties``: properties and statistics about the module, used for
        formatting the results into a report

    All of these properties are JSON serializable, i.e. basic python
    types (int, float, str, bool, array, dict).
    """

    @property
    def json(self):
        """
        Format the module object into a form amenable to serializing with JSON
        for report creation. By default this returns all of the module-level
        fields except output. Override if additional serialization is needed.
        """
        return {"name": self.name, "params": self.params, "properties": self.properties}

    @property
    def params(self):
        """
        Override this method to return a dictionary with relevant parameters
        for the method.
        """
        return self.get("params", {})

    @property
    def output(self):
        """
        Override this method to return a tabular form of the output. Can be
        any rectangular-shaped object (i.e. list of lists, pandas.DataFrame,
        numpy array, etc)
        """
        return []

    @property
    def properties(self):
        """
        Override this method to return a dictionary with relevant properties
        for the method. These might include metadata or summary statistics of
        the output that would not otherwise be included. Primarily used in the
        construction of report sections.
        """
        return self.get("properties", {})

    @property
    def name(self):
        "Name of this stats object, by default the class name in all lower case"
        return self.__class__.__name__.lower()

json property

Format the module object into a form amenable to serializing with JSON for report creation. By default this returns all of the module-level fields except output. Override if additional serialization is needed.

name property

Name of this stats object, by default the class name in all lower case

output property

Override this method to return a tabular form of the output. Can be any rectangular-shaped object (i.e. list of lists, pandas.DataFrame, numpy array, etc)

params property

Override this method to return a dictionary with relevant parameters for the method.

properties property

Override this method to return a dictionary with relevant properties for the method. These might include metadata or summary statistics of the output that would not otherwise be included. Primarily used in the construction of report sections.

Reporting

de_toolkit.report.DetkReport

Collects detk module JSON and renders a single self-contained, offline HTML report. Each module run serializes its JSON into <report_dir>/json/ (the machine-readable layer); write assembles every JSON found there into one detk_report.html whose charts are rendered client-side by a vendored, no-build Vega-Lite bundle, with the raw JSON embedded for provenance.

Source code in de_toolkit/report.py
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
class DetkReport:
    """
    Collects detk module JSON and renders a single self-contained, offline HTML
    report. Each module run serializes its JSON into ``<report_dir>/json/`` (the
    machine-readable layer); ``write`` assembles every JSON found there into one
    ``detk_report.html`` whose charts are rendered client-side by a vendored,
    no-build Vega-Lite bundle, with the raw JSON embedded for provenance.
    """

    template_name = "report.html"
    vega_assets = ("vega.min.js", "vega-lite.min.js", "vega-embed.min.js")

    def __init__(self, report_dir="./detk_report", crate_dir=None):
        self.report_dir = os.path.realpath(report_dir)
        logger.debug("creating DetkReport at report dir: %s", self.report_dir)

        # the Process Run Crate goes with the report and is rooted in the
        # report directory (DETK-0280), so each report has its own and its
        # file references resolve from where it sits; pass crate_dir to
        # root it elsewhere
        self.crate_dir = os.path.realpath(crate_dir) if crate_dir is not None else self.report_dir

        self.json_dir = os.path.join(self.report_dir, "json")
        logger.debug("json dir: %s", self.json_dir)

        pathlib.Path(self.json_dir).mkdir(parents=True, exist_ok=True)
        self.report_path = os.path.join(self.report_dir, "detk_report.html")
        logger.debug("report path: %s", self.report_path)

        self.modules = []

    def add_module(
        self,
        module,
        in_file_path=None,
        out_file_path=None,
        column_data_path=None,
        workdir=None,
        in_file_paths=None,
        out_file_paths=None,
    ):
        """Add and serialize the given module to the report directory;
        *in_file_paths* and *out_file_paths* list every input and output
        file of a step with several (detk-util record)"""
        module_json = DetkModuleJSON(
            module,
            in_file_path=in_file_path,
            out_file_path=out_file_path,
            column_data_path=column_data_path,
            workdir=workdir,
            json_dir=self.json_dir,
            in_file_paths=in_file_paths,
            out_file_paths=out_file_paths,
            report_dir=self.report_dir,
        )
        logger.debug("adding detk module json for module %s", module.name)
        self.modules.append(module_json)

    @property
    def json(self):
        "Serialize pending modules, then load every module JSON in the report dir."
        for module in self.modules:
            logger.debug("writing module JSON: %s", module.out_d.get("name"))
            module.write()

        json_str = []
        for fn in sorted(glob(os.path.join(self.json_dir, "*.json"))):
            logger.debug("found module json: %s", fn)
            with open(fn) as f:
                json_str.append(json.loads(f.read().strip()))

        return json_str

    def build_modules(self):
        "Turn each collected module JSON into a render descriptor for the SPA."
        modules, raw, seen = [], {}, {}
        for mj in self.json:
            family, title, desc, view = view_for(mj)
            base = mj.get("name", "unknown")
            n = seen.get(base, 0)
            seen[base] = n + 1
            dom_id = base if n == 0 else f"{base}-{n}"
            modules.append(
                {
                    "id": dom_id,
                    "module": base,
                    "family": family,
                    "title": title,
                    "desc": desc,
                    "view": view,
                }
            )
            raw[dom_id] = mj

        fam_rank = {f: i for i, f in enumerate(FAMILY_ORDER)}
        modules.sort(key=lambda m: (fam_rank.get(m["family"], len(FAMILY_ORDER)), m["title"]))
        return modules, raw

    def write(self, dev=False):
        logger.debug("writing out report to %s", self.report_path)

        modules, raw = self.build_modules()
        indent = 2 if dev else None

        vega = {
            name.split(".")[0].replace("-", ""): _asset("templates", "vega", name)
            for name in self.vega_assets
        }

        template = jinja2.Template(_asset("templates", self.template_name))
        html = template.render(
            # the payload goes inside <script> elements: escape it so no
            # user string (feature ID, sample name, annotation) can end them
            modules_json=script_json(clean(modules), indent=indent),
            raw_json=script_json(clean(raw), indent=indent),
            vega_js=vega["vega"],
            vegalite_js=vega["vegalite"],
            vegaembed_js=vega["vegaembed"],
        )
        with open(self.report_path, "w", encoding="utf-8") as f:
            f.write(html)
        logger.info("wrote report (%d modules) to %s", len(modules), self.report_path)

        # standards-facing provenance: a Process Run Crate describing every
        # recorded invocation, rooted in the report directory
        crate_path = write_crate(list(raw.values()), self.crate_dir, report_dir=self.report_dir)
        if crate_path:
            logger.info("wrote provenance crate to %s", crate_path)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.write()

json property

Serialize pending modules, then load every module JSON in the report dir.

add_module(module, in_file_path=None, out_file_path=None, column_data_path=None, workdir=None, in_file_paths=None, out_file_paths=None)

Add and serialize the given module to the report directory; in_file_paths and out_file_paths list every input and output file of a step with several (detk-util record)

Source code in de_toolkit/report.py
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
def add_module(
    self,
    module,
    in_file_path=None,
    out_file_path=None,
    column_data_path=None,
    workdir=None,
    in_file_paths=None,
    out_file_paths=None,
):
    """Add and serialize the given module to the report directory;
    *in_file_paths* and *out_file_paths* list every input and output
    file of a step with several (detk-util record)"""
    module_json = DetkModuleJSON(
        module,
        in_file_path=in_file_path,
        out_file_path=out_file_path,
        column_data_path=column_data_path,
        workdir=workdir,
        json_dir=self.json_dir,
        in_file_paths=in_file_paths,
        out_file_paths=out_file_paths,
        report_dir=self.report_dir,
    )
    logger.debug("adding detk module json for module %s", module.name)
    self.modules.append(module_json)

build_modules()

Turn each collected module JSON into a render descriptor for the SPA.

Source code in de_toolkit/report.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def build_modules(self):
    "Turn each collected module JSON into a render descriptor for the SPA."
    modules, raw, seen = [], {}, {}
    for mj in self.json:
        family, title, desc, view = view_for(mj)
        base = mj.get("name", "unknown")
        n = seen.get(base, 0)
        seen[base] = n + 1
        dom_id = base if n == 0 else f"{base}-{n}"
        modules.append(
            {
                "id": dom_id,
                "module": base,
                "family": family,
                "title": title,
                "desc": desc,
                "view": view,
            }
        )
        raw[dom_id] = mj

    fam_rank = {f: i for i, f in enumerate(FAMILY_ORDER)}
    modules.sort(key=lambda m: (fam_rank.get(m["family"], len(FAMILY_ORDER)), m["title"]))
    return modules, raw

de_toolkit.report.DetkModuleJSON

Source code in de_toolkit/report.py
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
class DetkModuleJSON:
    def __init__(
        self,
        module,
        in_file_path=None,
        out_file_path=None,
        column_data_path=None,
        workdir=None,
        json_dir=".",
        json_path=None,
        in_file_paths=None,
        out_file_paths=None,
        report_dir=None,
    ):

        # recorded paths name no directory of this machine (DETK-0280):
        # workdir relative to the report directory, the file paths relative
        # to workdir
        if report_dir is None:
            report_dir = os.path.dirname(os.path.realpath(json_dir))
        report_dir = os.path.realpath(report_dir)
        workdir = os.path.realpath(os.getcwd() if workdir is None else workdir)

        def rel(path):
            return _file_relpath(path, workdir)

        paths = OrderedDict(
            [
                ("in_file_path", rel(in_file_path)),
                ("out_file_path", rel(out_file_path)),
                ("column_data_path", rel(column_data_path)),
            ]
        )
        if in_file_paths is not None:
            paths["in_file_paths"] = [rel(p) for p in in_file_paths]
        if out_file_paths is not None:
            paths["out_file_paths"] = [rel(p) for p in out_file_paths]
        argv = _argv(workdir, getattr(module, "command_argv", None))

        module_id = record_id(module.name, module.params, paths, argv)
        logger.debug("writing module for module_id: %s", module_id)

        filename = f"{module_id}.json"

        if json_path is not None:
            self.filepath = json_path
        else:
            self.filepath = os.path.realpath(os.path.join(json_dir, filename))
        logger.debug("writing module JSON to: %s", self.filepath)

        module_json = module.json
        self.out_d = OrderedDict(
            [
                ("name", module.name),
                ("id", module_id),
                ("schema_version", MODULE_SCHEMA_VERSION),
                ("detk_version", __version__),
                ("last_modified", int(1000 * time.time())),
                # start_time approximates process start (module import time);
                # end_time is when the module was recorded
                ("start_time", _PROCESS_START.isoformat()),
                ("end_time", datetime.now(UTC).isoformat()),
                ("argv", argv),
                ("in_file_path", paths["in_file_path"]),
                ("out_file_path", paths["out_file_path"]),
                ("column_data_path", paths["column_data_path"]),
                ("workdir", _relpath(workdir, report_dir)),
                ("params", module_json["params"]),
                ("properties", module_json["properties"]),
            ]
        )
        # every input and output file of a step with several (schema 1.1);
        # left out otherwise, so other modules' documents are as before
        for key in ("in_file_paths", "out_file_paths"):
            if key in paths:
                self.out_d[key] = paths[key]

    def write(self, indent=None):
        """
        Write out the module JSON to file.

        Each JSON file has one top level object with the following properties:
        - ``name``: name of the module
        - ``id``: machine readable ID
        - ``detk_version``: version of detk that generated this file
        - ``last_modified``: local system timestamp in milliseconds when this
          file was created/modified
        - ``argv``: the command line, ``argv[0]`` the command's name only and
          an absolute path among the arguments relative to ``workdir``
        - ``workdir``: the directory where detk was run, relative to the
          report directory (``..`` for the default ``./detk_report``)
        - ``in_file_path``: path to the file that was processed
        - ``out_file_path``: path to the file that was output, if available
        - ``column_data_path``: path to the column data file used, if available
        - ``in_file_paths``, ``out_file_paths``: every input and output file,
          for a step with several (optional, schema 1.1)

        Every file path is relative to ``workdir`` (schema 1.2, DETK-0280).
        """

        logger.debug(
            "writing out module JSON for module %s (id: %s)", self.out_d["name"], self.out_d["id"]
        )

        with open(self.filepath, "w") as f:
            json.dump(self.out_d, f, indent=indent, cls=NumpyEncoder)

write(indent=None)

Write out the module JSON to file.

Each JSON file has one top level object with the following properties: - name: name of the module - id: machine readable ID - detk_version: version of detk that generated this file - last_modified: local system timestamp in milliseconds when this file was created/modified - argv: the command line, argv[0] the command's name only and an absolute path among the arguments relative to workdir - workdir: the directory where detk was run, relative to the report directory (.. for the default ./detk_report) - in_file_path: path to the file that was processed - out_file_path: path to the file that was output, if available - column_data_path: path to the column data file used, if available - in_file_paths, out_file_paths: every input and output file, for a step with several (optional, schema 1.1)

Every file path is relative to workdir (schema 1.2, DETK-0280).

Source code in de_toolkit/report.py
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
def write(self, indent=None):
    """
    Write out the module JSON to file.

    Each JSON file has one top level object with the following properties:
    - ``name``: name of the module
    - ``id``: machine readable ID
    - ``detk_version``: version of detk that generated this file
    - ``last_modified``: local system timestamp in milliseconds when this
      file was created/modified
    - ``argv``: the command line, ``argv[0]`` the command's name only and
      an absolute path among the arguments relative to ``workdir``
    - ``workdir``: the directory where detk was run, relative to the
      report directory (``..`` for the default ``./detk_report``)
    - ``in_file_path``: path to the file that was processed
    - ``out_file_path``: path to the file that was output, if available
    - ``column_data_path``: path to the column data file used, if available
    - ``in_file_paths``, ``out_file_paths``: every input and output file,
      for a step with several (optional, schema 1.1)

    Every file path is relative to ``workdir`` (schema 1.2, DETK-0280).
    """

    logger.debug(
        "writing out module JSON for module %s (id: %s)", self.out_d["name"], self.out_d["id"]
    )

    with open(self.filepath, "w") as f:
        json.dump(self.out_d, f, indent=indent, cls=NumpyEncoder)

R bridge

de_toolkit.wrapr.WrapR

Wrapper object for calling R code with Rscript.

.. note:: The attributes are only populated after the execute() method has been run

Parameters

rscript_path : str path to the R script to run

counts : pandas.DataFrame, optional dataframe containing counts to be passed to R

metadata : pandas.DataFrame, optional dataframe containing metadata to be passed to R

params : dict, optional dict of parameters to be passed to R

output_fn : str, optional path to file where R should write output, if not provided the output is written to a temporary file and deleted upon WrapR object deletion

metadata_out_fn : str, optional path to file where R should write metadata output

rpath : str path to the Rscript executable, taken from the PATH environment variable if None

raise_on_error : bool raise an exception if R encounters an error, other wise fail silently and deadly

Attributes

output : pandas.DataFrame dataframe of the tabular output created by R script, indexed by its first column read as text (see :func:de_toolkit.common.read_id_table), so an ID such as 007 is kept as written

metadata_out : pandas.DataFrame dataframe of the tabular metadata output created by R script, indexed by its first column read as text

params_out : dict dict of the output parameters list created by R script

stdout : str string capturing the standard output of the R script

stderr : str string capturing the standard error of the R script

retcode : int return code of the R process

success : bool True if retcode == 0

Raises

de_toolkit.wrapr.RExecutionError when raise_on_error is True, raise whenever R encounters an error

Examples

Basic usage accepts a path to an R script and loads the content of the file pointed to by out.fn in the R script into the output attribute:

with open('script.R','wt') as f : # note reference to implicitly defined out.fn # R variable f.write('write.csv(c(1,2,3,4),out.fn)') r = WrapR('script.R',output_fn='test.csv') r.execute() r.output x 1 1 2 2 3 3 4 4 pandas.read_csv('test.csv',index_col=0) x 1 1 2 2 3 3 4 4

Can also use a context manager when the output doesn't need to be written to a named file:

with WrapR('script.R') as r : r.execute() print(r.output) x 1 1 2 2 3 3 4 4

The standard output of the R script can be accessed with the stdout attribute:

with open('euler.R','wt') as f : f.write('exp(complex(real=0,imag=pi))+1') with WrapR('euler.R','wt') as r : r.execute() print(r.stdout) [1] 0+1.224647e-16i

Source code in de_toolkit/wrapr.py
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
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
604
605
606
607
608
609
610
611
612
613
614
615
class WrapR:
    """
    Wrapper object for calling R code with Rscript.

    .. note::
        The attributes are only populated after the execute() method has
        been run

    Parameters
    ----------

    rscript_path : str
        path to the R script to run

    counts : pandas.DataFrame, optional
        dataframe containing counts to be passed to R

    metadata : pandas.DataFrame, optional
        dataframe containing metadata to be passed to R

    params : dict, optional
        dict of parameters to be passed to R

    output_fn : str, optional
        path to file where R should write output, if not provided the output
        is written to a temporary file and deleted upon WrapR object deletion

    metadata_out_fn : str, optional
        path to file where R should write metadata output

    rpath : str
        path to the Rscript executable, taken from the PATH environment
        variable if None

    raise_on_error : bool
        raise an exception if R encounters an error, other wise fail silently
        and deadly

    Attributes
    ----------

    output : pandas.DataFrame
        dataframe of the tabular output created by R script, indexed by its
        first column read as text (see :func:`de_toolkit.common.read_id_table`),
        so an ID such as ``007`` is kept as written

    metadata_out : pandas.DataFrame
        dataframe of the tabular metadata output created by R script, indexed
        by its first column read as text

    params_out : dict
        dict of the output parameters list created by R script

    stdout : str
        string capturing the standard output of the R script

    stderr : str
        string capturing the standard error of the R script

    retcode : int
        return code of the R process

    success : bool
        True if retcode == 0

    Raises
    ------

    de_toolkit.wrapr.RExecutionError
        when *raise_on_error* is True, raise whenever R encounters an error

    Examples
    --------

    Basic usage accepts a path to an R script and loads the content of
    the file pointed to by *out.fn* in the R script into the *output*
    attribute:

    >>> with open('script.R','wt') as f :
            # note reference to implicitly defined *out.fn*
            # R variable
            f.write('write.csv(c(1,2,3,4),out.fn)')
    >>> r = WrapR('script.R',output_fn='test.csv')
    >>> r.execute()
    >>> r.output
       x
    1  1
    2  2
    3  3
    4  4
    >>> pandas.read_csv('test.csv',index_col=0)
       x
    1  1
    2  2
    3  3
    4  4

    Can also use a context manager when the output doesn't need to be
    written to a named file:

    >>> with WrapR('script.R') as r :
            r.execute()
            print(r.output)
       x
    1  1
    2  2
    3  3
    4  4

    The standard output of the R script can be accessed with the *stdout*
    attribute:

    >>> with open('euler.R','wt') as f :
            f.write('exp(complex(real=0,imag=pi))+1')
    >>> with WrapR('euler.R','wt') as r :
            r.execute()
            print(r.stdout)
    [1] 0+1.224647e-16i


    """

    def __init__(
        self,
        rscript_path,
        counts=None,
        metadata=None,
        params=None,
        output_fn=None,
        metadata_out_fn=None,
        params_out_fn=None,
        rpath=None,
        raise_on_error=True,
        routput_dir=None,
    ):

        self._files = {}
        self._paths = defaultdict(str)

        # custom rpath
        self._paths["rpath"] = rpath or get_r_path()

        logger.debug("rpath: %s", self._paths["rpath"])

        # if routput_dir is specified, create the directory if necessary and
        # write all of the temporary files to it
        self.routput_dir = routput_dir
        self._tempdir = None
        if routput_dir is not None:
            pathlib.Path(routput_dir).mkdir(parents=True, exist_ok=True)
        else:
            self._tempdir = TemporaryDirectory()
            self.routput_dir = self._tempdir.name
        logger.debug("R output dir: %s", self.routput_dir)

        # load script code and put into the template that defines convenience
        # in/out filename variables
        with open(os.path.join(self.routput_dir, "script.R"), "w") as f:
            self._files["rscript"] = f
            self._paths["rscript"] = f.name
            with open(os.path.realpath(rscript_path)) as f_in:
                f.write(_script_tmpl.format(script=f_in.read()))
            f.flush()

        # write counts to tempfile
        with open(os.path.join(self.routput_dir, "counts.csv"), "w") as f:
            self._files["counts_in"] = f
            self._paths["counts_in"] = f.name
            if counts is not None:
                counts.to_csv(self._files["counts_in"])
                f.flush()

        # set counts output file if provided, otherwise create temp file
        self._paths["output"] = output_fn
        if output_fn is None:
            self._files["output"] = open(os.path.join(self.routput_dir, "counts_out.csv"), "w")
            self._paths["output"] = self._files["output"].name

        # write metadata to tempfile if provided
        with open(os.path.join(self.routput_dir, "meta_in.csv"), "w") as f:
            self._files["meta_in"] = f
            self._paths["meta_in"] = f.name
            if metadata is not None:
                metadata.to_csv(self._files["meta_in"])
                f.flush()

        # set metadata output file if provided, otherwise create temp file
        self._paths["meta_out"] = metadata_out_fn
        if metadata_out_fn is None:
            self._files["meta_out"] = open(os.path.join(self.routput_dir, "meta_out.csv"), "w")
            self._paths["meta_out"] = self._files["meta_out"].name

        # write out params json if provided
        with open(os.path.join(self.routput_dir, "params_in.json"), "w") as f:
            self._files["params_in"] = f
            self._paths["params_in"] = f.name
            if params is not None:
                json.dump(params, f)
                f.flush()

        self._paths["params_out"] = params_out_fn
        if params_out_fn is None:
            self._files["params_out"] = open(os.path.join(self.routput_dir, "params_out.json"), "w")
            self._paths["params_out"] = self._files["params_out"].name

        logger.debug("wrapr paths:\n %s", pformat(self._paths))

        # initialize output members
        self.output = None
        self.metadata_out = None
        self.params_out = None

        self.raise_on_error = raise_on_error

    @require_r
    def execute(self):
        """
        Execute the R script and load in the resulting output files, if any.
        """

        # construct Rscript command
        cmd = (
            (
                "{rpath} --vanilla {rscript} {counts_in} {meta_in} {params_in} "
                "{output} {meta_out} {params_out}"
            )
            .format(**self._paths)
            .split(" ")
        )
        logger.info("executing Rscript: %s", self._paths["rscript"])
        logger.debug(cmd)

        # run the R script
        p = subprocess.run(cmd, capture_output=True)

        self.process = p
        self.stdout = p.stdout.decode()
        logger.debug("R script stdout:\n %s", pformat(self.stdout))

        # write stdout to file in the r output directory
        with open(os.path.join(self.routput_dir, "stdout"), "w") as f:
            f.write(self.stdout)

        self.stderr = p.stderr.decode()
        logger.debug("R script stderr:\n %s", pformat(self.stderr))

        # write stderr to file in the r output directory
        with open(os.path.join(self.routput_dir, "stderr"), "w") as f:
            f.write(self.stderr)

        self.returncode = p.returncode
        logger.debug("R script return code: %d", self.returncode)
        self.success = p.returncode == 0

        if self.raise_on_error and not self.success:
            # the first line is the cause a command prints (common.cli_main):
            # R's own error line, and where R's full output was written
            if self._tempdir is not None:
                # the temporary directory goes when the command exits
                where = "rerun with --routput-dir DIR to keep R's output"
            else:
                where = f"R's output is in {self.routput_dir}"
            raise RExecutionError(
                f"R encountered an error (exit {self.returncode}): "
                f"{r_error_cause(self.stderr)} [{where}]\n\n"
                + f"stdout:\n{self.stdout}\n\n"
                + f"stderr:\n{self.stderr}\n"
            )

        # read in the outputs
        if os.path.exists(self._paths["output"]):
            try:
                self.output = read_id_table(self._paths["output"])
            except pd.errors.EmptyDataError:
                logger.debug("No output was found, continuing")
                pass

        if os.path.exists(self._paths["meta_out"]):
            try:
                self.metadata_out = read_id_table(self._paths["meta_out"])
            except pd.errors.EmptyDataError:
                logger.debug("No metadata output was found, continuing")
                pass

        if os.path.exists(self._paths["params_out"]):
            logger.info("writing out R script params json to %s", self._paths["params_out"])
            with open(self._paths["params_out"]) as f:
                json_str = f.read()
                if len(json_str) > 0:
                    self.params_out = json.loads(json_str)

                    # jsonlite puts all elements of lists into arrays,
                    # recurse through params and replace length 1 lists
                    # with the value
                    def flat(e):
                        if isinstance(e, dict):
                            return {k: flat(v) for k, v in e.items()}
                        elif isinstance(e, list):
                            if len(e) == 1:
                                return flat(e[0])
                            else:
                                return [flat(_) for _ in e]
                        else:
                            return e

                    self.params_out = flat(self.params_out)

        logger.info("R script done executing")

    def __enter__(self):
        logger.debug("entered WrapR context manager")
        return self

    def __exit__(self, *args):
        logger.debug("exitred WrapR context manager")
        # clean up the temp files if no r output directory was supplied
        if self._tempdir is not None:
            self._tempdir.cleanup()

execute()

Execute the R script and load in the resulting output files, if any.

Source code in de_toolkit/wrapr.py
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
604
605
@require_r
def execute(self):
    """
    Execute the R script and load in the resulting output files, if any.
    """

    # construct Rscript command
    cmd = (
        (
            "{rpath} --vanilla {rscript} {counts_in} {meta_in} {params_in} "
            "{output} {meta_out} {params_out}"
        )
        .format(**self._paths)
        .split(" ")
    )
    logger.info("executing Rscript: %s", self._paths["rscript"])
    logger.debug(cmd)

    # run the R script
    p = subprocess.run(cmd, capture_output=True)

    self.process = p
    self.stdout = p.stdout.decode()
    logger.debug("R script stdout:\n %s", pformat(self.stdout))

    # write stdout to file in the r output directory
    with open(os.path.join(self.routput_dir, "stdout"), "w") as f:
        f.write(self.stdout)

    self.stderr = p.stderr.decode()
    logger.debug("R script stderr:\n %s", pformat(self.stderr))

    # write stderr to file in the r output directory
    with open(os.path.join(self.routput_dir, "stderr"), "w") as f:
        f.write(self.stderr)

    self.returncode = p.returncode
    logger.debug("R script return code: %d", self.returncode)
    self.success = p.returncode == 0

    if self.raise_on_error and not self.success:
        # the first line is the cause a command prints (common.cli_main):
        # R's own error line, and where R's full output was written
        if self._tempdir is not None:
            # the temporary directory goes when the command exits
            where = "rerun with --routput-dir DIR to keep R's output"
        else:
            where = f"R's output is in {self.routput_dir}"
        raise RExecutionError(
            f"R encountered an error (exit {self.returncode}): "
            f"{r_error_cause(self.stderr)} [{where}]\n\n"
            + f"stdout:\n{self.stdout}\n\n"
            + f"stderr:\n{self.stderr}\n"
        )

    # read in the outputs
    if os.path.exists(self._paths["output"]):
        try:
            self.output = read_id_table(self._paths["output"])
        except pd.errors.EmptyDataError:
            logger.debug("No output was found, continuing")
            pass

    if os.path.exists(self._paths["meta_out"]):
        try:
            self.metadata_out = read_id_table(self._paths["meta_out"])
        except pd.errors.EmptyDataError:
            logger.debug("No metadata output was found, continuing")
            pass

    if os.path.exists(self._paths["params_out"]):
        logger.info("writing out R script params json to %s", self._paths["params_out"])
        with open(self._paths["params_out"]) as f:
            json_str = f.read()
            if len(json_str) > 0:
                self.params_out = json.loads(json_str)

                # jsonlite puts all elements of lists into arrays,
                # recurse through params and replace length 1 lists
                # with the value
                def flat(e):
                    if isinstance(e, dict):
                        return {k: flat(v) for k, v in e.items()}
                    elif isinstance(e, list):
                        if len(e) == 1:
                            return flat(e[0])
                        else:
                            return [flat(_) for _ in e]
                    else:
                        return e

                self.params_out = flat(self.params_out)

    logger.info("R script done executing")

de_toolkit.wrapr.wrapr(Rcode, **kwargs)

Convenience wrapper for WrapR object. Writes Rcode to a temporary file and executes it as it would if it were provided.

Parameters

Rcode : str string containing valid R code to be executed

Returns

obj A WrapR object executed with the code in input string

Examples

with wrapr('write.csv(c(1,2,3,4),out.fn)') as r : print(r.output) x 1 1 2 2 3 3 4 4

Source code in de_toolkit/wrapr.py
618
619
620
621
622
623
624
625
626
627
628
629
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
def wrapr(Rcode, **kwargs):
    """Convenience wrapper for WrapR object. Writes *Rcode* to a temporary file
    and executes it as it would if it were provided.

    Parameters
    ----------

    Rcode : str
        string containing valid R code to be executed

    Returns
    -------

    obj
        A WrapR object executed with the code in input string

    Examples
    --------

    >>> with wrapr('write.csv(c(1,2,3,4),out.fn)') as r :
            print(r.output)
       x
    1  1
    2  2
    3  3
    4  4

    """

    logger.info("wrapr() executing")
    with NamedTemporaryFile("wt") as f:
        logger.debug("writing R code to %s", f.name)
        logger.debug("R code:\n%s", pformat(Rcode))
        f.write(Rcode)
        f.flush()
        wr = WrapR(f.name, **kwargs)
        wr.execute()
        return wr

de_toolkit.wrapr.check_r()

Tests whether the Rscript executable can be found.

Source code in de_toolkit/wrapr.py
162
163
164
def check_r():
    "Tests whether the Rscript executable can be found."
    return get_r_path() is not None

de_toolkit.wrapr.check_r_package(pkg)

Tests whether the R package pkg is installed.

Source code in de_toolkit/wrapr.py
167
168
169
170
171
172
173
174
175
176
177
178
179
def check_r_package(pkg):
    "Tests whether the R package *pkg* is installed."
    r_path = get_r_path()
    if r_path is None:
        # Rscript is not installed, so no R package can be available
        return False
    cmd = [r_path, "-e", f"library({pkg})"]
    logger.debug("check_r_package cmd: %s", cmd)
    p = subprocess.run(cmd, shell=False, capture_output=True)
    logger.debug("check_r_package stdout:\n%s", pformat(p.stdout.decode("utf-8")))
    logger.debug("check_r_package stderr:\n%s", pformat(p.stderr.decode("utf-8")))

    return p.returncode == 0