# katmap **Repository Path**: arhelion/katmap ## Basic Information - **Project Name**: katmap - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-23 - **Last Updated**: 2026-11-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # katmap > A library for interpreting splicing changes in terms of RBP binding. KATMAP is a python library designed to learn interpretable models of splicing regulation from splicing factor (SF) perturbation RNA-seq experiments. Using the results of differential splicing analysis and information about SF's binding motif, KATMAP learns the perturbed SF's position-specific regulatory activity and predicts which exons are direct targets of the SF: ![activity](docs/images/LearningModels.png) Once learned, these models can be applied to other datasets to * Predict regulation and cis-elements at exons of interest * Infer which SFs might be responsible for splicing changes observed in an RNA-seq dataset of interest Pretrained models are provided in the `/models` directory and the documentation below describes how to use the KATMAP python library to perform these analyses. ![activity](docs/images/ApplyingModelsExample.png) ## Installation (Note: We highly recommend using [mamba](https://mamba.readthedocs.io/en/latest/installation/mamba-installation.html) rather than conda to install KATMAP. Mamba is a drop-in replacement for conda, but will solve the KATMAP environment more quickly) Rather than manually install all of the dependencies, the simplest way to install `katmap` is to first install the enviroment that meets the package requirements, and then install `katmap` in that environment using pip. First, download the repository with git clone and enter the directory ```sh $ git clone https://gitlab.com/LaptopBiologist/katmap.git $ cd katmap ``` Note, there is a subdirectory ```./katmap/katmap``` which contains the actual python scripts; do not cd into this. If your computer does not have an Nvidia GPU (or you want to keep things simple), use the `katmap.yaml` file provided in the repository to create a new conda environment. If you have an Nvidia GPU and want to enable GPU acceleration, see the GPU instructions at the end of this section. ```sh $ mamba env create -f katmap.yaml -n {env_name} ``` If instead you wish to install the dependencies in an existing environment (named, for example, `my_env`), instead run ```sh $ mamba env update -n my_env -f katmap.yaml ``` Once the environment is installed/updated, activate the environment (replace `env_name` with the enviroment's name) and install `katmap`. To do this, while in the `katmap` directory (not `katmap/katmap`) run: ```sh $ mamba activate env_name $ pip install -e . ``` ### Installing dependencies Because `katmap` is focused on constructing RNA maps, the [spliceformats](https://gitlab.com/LaptopBiologist/spliceformats) is essentially a dependency, but one which currently cannot be installed through `conda`. The `katmap.yaml`, however, includes all of the dependencies needed by `spliceformats`. So, once `katmap` is installed return to the parent directory, download the `spliceformats` repository, move to that directory, and install with pip ```sh $ cd .. $ git clone https://gitlab.com/LaptopBiologist/spliceformats.git $ cd spliceformats $ pip install -e . ``` to install `spliceformats` in the conda environment. Second, KATMAP's statistical model requires an custom statistical library [amppl](https://gitlab.com/LaptopBiologist/amppl). This is a lightweight probabilistic programming language built on Jax. So again, download the `amppl` repository, move to that directory and run ```sh $ cd .. $ git clone https://gitlab.com/LaptopBiologist/amppl.git $ cd amppl $ pip install -e . ``` ### Recap ```sh $ cd {parent_directory_for_repositories} $ git clone https://gitlab.com/LaptopBiologist/katmap.git $ git clone https://gitlab.com/LaptopBiologist/spliceformats.git $ git clone https://gitlab.com/LaptopBiologist/amppl.git $ cd katmap $ mamba env create -f katmap.yaml -n {env_name} $ mamba activate env_name $ pip install -e . $ cd .. $ cd spliceformats $ pip install -e . $ cd .. $ cd amppl $ pip install -e . ``` The provided environment includes jupyter and jupyter lab, so jupyter notebooks that can access the library can be opened ```sh $ jupyter lab ``` ### GPU installation KATMAP's statistical model is built on JAX and can take advantage of (Nvidia) GPU acceleration. To take advantage of this, first modify the katmap_cuda.yaml to match your cuda version (on Linux, you can check this with the `nvidia-smi` command in terminal) ``` channels: - conda-forge - bioconda - nvidia/label/cuda-{your_version_goes_here} ``` then install the environment ```sh $ mamba env create -f katmap_gpu.yaml -n {env_name} ``` and follow all subsequent installation instructions from the previous section. You may need to restart your computer before the JAX installation recognizes the GPU. KATMAP has been tested with CUDA versions `11.4`, `12.2`, and `12.4`. In the absence of a GPU, learning a new model from knockdown data will take longer, but applying learned models to score exons will still be quite fast. ### Testing the installation You can test the installation by running ```bash $ python test_installation.py {path to hg19 reference genome} ``` This will perform an abbreviated sampling run using HNRNPC (HepG2) knockdown data, generating a limited number of posterior samples but confirming that all necessary components of KATMAP function. It will produce an output directory located at `{current_directory}/examples/results/installation_test` ## KATMAP command line utilities KATMAP includes several command line scripts: 1. `makeconfig.py`: Used to specify the file paths, parameters, and options with which a KATMAP analysis will be run. This creates a configuration file which will be passed to `katmap.py` whenever an analysis is run. 1. `precompute_impacts.py`: Scores exons with previously learned KATMAP models and adds these to an analysis 1. `katmap.py`: Runs the inference algorithm to either learn a KATMAP model from perturbation data or infer perturbations with previously learned models. Running `katmap.py` requires a configuration file created with `makeconfig.py`. In the instructions below, we assume that these scripts are being called from within the KATMAP directory. For example: ```sh $ python katmap.py {path_to_config} ``` If the current working directory is elsewhere, the full path to the script needs to be written: ```sh $ python {PATH_TO_KATMAP}/katmap.py {path_to_config} ``` ## Running KATMAP from command line to learn models The command line interface for model inference is ```sh $ python katmap.py {path_to_config} ``` KATMAP's model can be specified with a variety of arguments that determine the model inputs, structure, and control statistical inference. These choices are organized in a configuration files, rather than specified in command line. A separate script is provided to construct the configuration file. For example, to run an analysis using an rmats output table where the second condition is the control condition, the corresponding reference genome, and a motif: ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_KATMAP_output_directory} --ctrl-index 1 $ python katmap.py {path_to_config} ``` The first script creates the configuration file at the specified path. The second uses the configuration file to set up the model and run the inference algorithm, and saving the results in the specified output directory. **When using rMATS results as inputs it is critically important that the control condition be correctly specified when setting up the configuration file.** If the index is incorrect, direction of the observed splicing changes will be flipped and so will the inferred regulatory activities (enhancing activity will be incorrectly inferred as repressing activity). If the control sample in the rMATS analysis was the first rather than second condition, then `--ctrl-index` should be set to `0` (we use Python's base-0 indexing): ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_output_directory} --ctrl-index 0 ``` If the control sample in the rMATS analysis is the second condition, then `--ctrl-index` should be set to `1`: ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_output_directory} --ctrl-index 1 ``` In place of rMATS results, KATMAP can also be run using a properly formatted table describing the splicing changes at exons. We call this a `FeatureTable` and instructions for setting up such a table are provided later in the documentation. The `--features` argument can be used set up an analysis using a `FeatureTable` ```sh $ python makeconfig.py {path_to_config} --features {path_to_feature_table} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_output_directory} ``` In this case, the `--ctrl-index` option is not needed because KATMAP uses the splicing changes defined in the FeatureTable. If makeconfig.py is run without any optional arguments ```sh $ python makeconfig.py {path_to_config} ``` it will create a file with default arguments and no paths specified. This can be edited manually. The full set of options that can be specified from commandline are ```python MakeConfigCommandParser().parser.print_help() ``` usage: make_config filepath [-OPTIONS] Builds the configuration file used to run an analysis with KATMAP. If no options are provided, writes a default analysis specification. positional arguments: filepath Path to the configuration file optional arguments: -h, --help show this help message and exit File paths: Paths to files used as inputs to the analysis --ref REF Path to reference genome (default: None) --rmats RMATS Path to rmats results to use as input. If used, automatically generates "phi_ctrl" and "logreads" as linear features (default: None) --motif MOTIF Path to the motif file used to score binding sites (default: None) --features FEATURES Path to precomputed data (used instead of "rmats") (default: None) --out OUT Path for the output directory (default: None) Inference settings: Arguments controlling Monte Carlo sampling from the posterior --target-size TARGET_SIZE Minimum number of posterior samples per chain (default: 400) --proposal-size PROPOSAL_SIZE Number of hyperparameters to evaluate at each round of importance sampling (default: 400) --nchains NCHAINS Number of replicates of importance sampling to perform. Convergence can only be evaluated if nchains>=2 (default: 2) --maxiter MAXITER Maximum number of iterations to run the importance sampling algorithm before quitting (default: 20) Model specification: Parameters that influence how the model is constructed and fit --omit-activity OMIT_ACTIVITY Whether the model should be fit without splicing activity (default: False) --ctrl-index CTRL_INDEX When using rMATS results, the index of the control condition (index starts at 0) (default: 1) --event-struc EVENT_STRUC [EVENT_STRUC ...] A list of the splice junction identifiers to use in the model. A: Acceptor (3ss); D: Donor (5ss). (default: ['A1', 'D2']) --binding_func {deltaocc,sigmoid} The binding function used by the model. "deltaocc" specifies the relative change in binding described in the manuscript. "sigmoid" specifies the Hill equation with free protein equal to F=exp(-m). (default: deltaocc) --formula FORMULA A formula describing how splice sites are combined to compute the splicing impacts. (Experimental feature) (default: ) --exonic EXONIC The size of the window on the exonic side of splice sites to score (default: 60) --intronic INTRONIC The size of the window on the intronic side of splice sites to score (default: 200) --binsize BINSIZE The size of bins in which binding sites will be aggregated (default: 10) --largest-binding-change LARGEST_BINDING_CHANGE The change in binding (d) assumed to occur at the most relevant motif, -1 < d < 1. Choose a negative value (-0.50) for knockdown and a positive value (0.50) for overexpression experiments. Values of |d|<0.9 yield the same relative binding function and equivalent inference results. (default: -0.5) --ci-level CI_LEVEL The ci-level used to call significance if using an rmats table as input (default: 0.94) --training-frac-sig TRAINING_FRAC_SIG The fraction of significant events to train on (default: 1.0) --training-num-nonsig TRAINING_NUM_NONSIG The number of nonsignificant events to include in the training set (default: 2000) --pred-biol PRED_BIOL Comma separated list of linear features to apply to the upreg and downreg predictions. (default: phi_ctrl) --pred-tech PRED_TECH Comma separated list of linear features to apply to the unchanged predictions. (default: logreads) --pred-opposing PRED_OPPOSING Comma separated list of linear features to have opposite effects on the upreg and downreg predictions. (default: ) --pred-quad PRED_QUAD Comma separated list of linear features to generate quadratic terms from. '*': do so for all linear features; 'none': Do not include any quadratic terms. (default: *) --pred-center PRED_CENTER List of linear features to mean center. '*': do so for all linear features; 'none': do not mean center any. (default: *) --pred-std PRED_STD Comma separated list of linear features to standardize. '*': do so for all linear features; 'none': do not standardize any. (default: *) Adaptive proposal settings: Arguments controlling the adaptive proposal used in importance sampling --num-components NUM_COMPONENTS Controls how the size of mixture model grows during importance sampling. Adds this many components at each iteration. (default: 10) --init-df INIT_DF The degrees-of-freedom the Student t mixture (TMM) is initialized at. Controls how non-normal the TMM is; This is optimized unless the degrees of freedom are held constant. (default: 35) --fix-df FIX_DF Should the degrees-of-freedom of the Student t mixture (TMM) be held at the initial value? Not recommended (but freedom, I guess?) (default: False) For example, the splice sites of the flanking exons could be included in the analysis by specifying ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_output_directory} --event-struc D1 A1 D2 A2 ``` To model overexpression data, we can specify that occupancy at motifs should increase following the perturbation by setting the `--largest-binding-change` argument to a positive value: ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_output_directory} --largest-binding-change 0.5 ``` Larger or smaller posterior sample sizes can be specified with the `--target-size` argument ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --motif {path_to_motif} --out {name_for_output_directory} --target-size 600 ``` There are other arguments which can be specified in the configuration file, including the parameters of the model's priors, but we do not anticipate most users will need to do so. ### Example As an example, we'll walk through how to use KATMAP to infer the splicing regulatory activity of HNRNPC. The skipped exon table from the ENCODE HNRNPC (HepG2) knockdown [rMATS results](https://www.encodeproject.org/files/ENCFF244XJW/) is located at `examples/data/HNRNPC_HepG2_SE.tsv.gz`. If you don't already have the hg19 reference genome downloaded, go to [UCSC's ftp server](https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/) and download [hg19.fa.gz](https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.fa.gz). Motif files can be found in [./examples/motifs](https://gitlab.com/LaptopBiologist/katmap/-/tree/master/examples/motifs). You can use either the RNAcompete motif ([HNRNPC.pwm](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/motifs/HNRNPC.pwm)) or RBPamp affinity model ([HNRNPC.psam](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/motifs/HNRNPC.psam)). If using a GPU, the default model specification should be fine: ```sh $ python makeconfig.py {path_to_config} --rmats examples/data/HNRNPC_HepG2_SE.tsv.gz --ref {path_to_hg19.fa.gz} --motif examples/motifs/HNRNPC.psam --out {name_for_KATMAP_output_directory} --ctrl-index 1 ``` If working on a CPU, we recommend decreasing the size of the training set. While by default 2,000 nonsignificant exons are included, we have found that activity can be successfully inferred with as few 400. ```sh $ python makeconfig.py {path_to_config} --rmats examples/data/HNRNPC_HepG2_SE.tsv.gz --ref {path_to_hg19.fa.gz} --motif examples/motifs/HNRNPC.psam --out {name_for_KATMAP_output_directory} --ctrl-index 1 --training-num-nonsig 400 ``` This will create a specification file at the indicated path, which can be examined or edited in a text editor. To run the inference algorithm using this configuration file ```sh $ python katmap.py {path_to_config} ``` Which will generate a directory populated with KATMAP's outputs in the specified location ## Details on inputs To set up an analysis we need to provide input data using either the `--rmats` or `--features` argument, the reference genome to which the data were aligned with the `--ref` argument, and the motif model we'll use to score the sequences to the `--motif` argument. ### Data to be modelled The splicing changes to be modelled can be provided as either rMATS outputs or a properly formatted tab-delimited table, which we term a `FeatureTable`. If rMATS results are used, KATMAP will automatically extract the information it needs to build the required FeatureTable. rMATS results can be provided as a tarball storing the full rMATS outputs: ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats.tar.gz} --ref {path_to_hg19.fa.gz} --motif {path_to_HNRNPC.txt} --out {name_for_KATMAP_output_directory} --ctrl-index 1 ``` or the table describing the specific class of events (e.g. SE, A3SS, etc) you wish to model. For an example, see [./examples/data/HNRNPC_HepG2_SE.tsv.gz](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/data/HNRNPC_HepG2_SE.tsv.gz) Alternatively, you may use a FeatureTable you have constructed yourself as inputs ```sh $ python makeconfig.py {path_to_config} --features examples/data/HNRNPC_hepg2_majiq_features.tsv --ref {path_to_ref} --motif {path_to_motif} --out {name_for_KATMAP_output_directory} ``` A more complete description of the format and instructions for organizing data in the required manner can be found in the **Advanced Usage** section at the end of the documentation. Example feature tables build from [rMATS results](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/data/HNRNPC_HepG2_FeatureTable.tsv.gz) and [MAJIQ results](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/data/HNRNPC_hepg2_majiq_features.tsv) can be found in [examples/data](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/data) ### Reference genome The reference genome passed to `--ref` should match the reference genome to which the data were aligned. ### Motif models For KATMAP to learn a regulatory model, a motif model must be provided in the `--motif` argument. The only exception is when `--omit-activity` is set to True (for example when inferring SF perturbations, as described later). KATMAP can accept several formats describing the SF's binding motif. The simplest option to provide a position-weight matrix (PWM) as a tab-delimited table, where the rows represent positions and the columns represent nucleotides (A,C,G,T/U). For an example, see [./examples/motifs/hnrnpc.pwm] ```python import pandas as pd pd.read_csv('examples/motifs/HNRNPC.pwm', sep='\t') ```
Position A C G T
0 1 1.178391 -0.437680 -1.637667 -0.562642
1 2 -5.344465 -5.344465 -5.344465 1.973120
2 3 -5.344465 -5.344465 -5.344465 1.973120
3 4 -5.344465 -5.344465 -5.344465 1.973120
4 5 -5.344465 -5.344465 -5.344465 1.973120
5 6 -5.344465 -5.344465 -5.344465 1.973120
6 7 -2.195799 -0.760979 0.122831 1.072286
Note that this should be an information-based PWM, not a frequency or count matrix. In addition to position weight matrices, KATMAP can use the outputs of [RBPamp](https://bitbucket.org/marjens/rbpamp/src/master/) (see [examples/motifs/HNRNPC.psam](https://gitlab.com/LaptopBiologist/katmap/-/blob/master/examples/motifs/HNRNPC.psam) for an example HNRNPC affinity model) and [ProBound](http://probound.bussemakerlab.org/) (see [here](http://probound.bussemakerlab.org/files/example_output/RBP/fit.final.json) for an [example RBFOX2](http://probound.bussemakerlab.org/files/example_output/RBP/index.html) model). Users can also provide a collections of weighted PWMs organized in a \*.json file. Details on how to construct this are described in the **Advanced Usage** section at the end of the documentation. ## Description of outputs Upon completion, KATMAP generates multiple files summarizing the results. The learned model is saved as a `*.katmap` file with the same name as the output directory. This can be opened with the `KatmapModel` and `GroupedKatmapModels` classes and used to interpret new sequences (see **"Inferring SF perturbations with learned models"** and **"Applying KATMAP models"**). * `00_did_it_work.txt`: Reports diagnostics regarding inference and provides any warnings about convergence or reliability. * `01_analysis_specification.json`: The set of parameters used for the analysis * `01b_model_data.tsv`: The FeatureTable used as inputs for the analysis * `02_results_summary.json`: Summary statistics and diagnostics regarding the analysis. * `03_activity_plot.png`: A visualization of the posterior sample of the activity maps * `04_binding_plot.png`: The posterior sample of binding functions * `05b_changes_per_exon_plot.png`: The posterior distribution over the average number of knockdown-affected binding motifs per exons. This provides a visual diagnostic of whether the binding motif provides a good description of the sequence composition of knockdown-affected exons. * `06_model_fit.tsv`: Summarizes model fit, comparing the full model to a reduced model. * `07_posterior_summary.tsv`: A table summarizing the posterior samples over each parameter. Reports the posterion mean, median, 94\%-CI, and the r-hat convergence statistic. * `08_posterior_sample.tsv`: A table storing the full posterior sample over all model parameters * `09_target_prediction_summary.tsv`: A table describing the numbers of predicted targets of the SF's enhancing and repression activity * `10_target_predictions.tsv`: Exon-level target predictions, including the splicing impacts, predicted target labels, and the model predictions under the full and reduced models * `*.katmap`: A gzipped dill pickle file storing the learned model. Intended to be opened with `KatmapModel` and `GroupedKatmapModels` You should check the `00_did_it_work.txt` file upon completion. This will provide high-level summaries of inference and provide information and guidance regarding any problems that occurred. There are two main classes of warnings to be aware of: 1. Monte Carlo Sampling and/or Convergence warnings: These indicate either that fewer samples from the posterior were obtained than desired or that the posterior sampling procedure itself failed. Severe sampling and convergence warnings should be taken seriously, and the associated model should not be trusted. 2. Motif model warnings: These indicate that the learned model predicts an unrealistically high number of binding sites per exon, suggesting that the motif model used may be suboptimal. Depending on the severity the model may still be useful, but if other PWMs or motif models are available for the factor of interest, it may be worth using those instead. Examining the `04_binding_plot.png` and `05b_changes_per_exon_plot.png` plots may also be informative. In both cases, the `00_did_it_work.txt` file will include recommendations that may help resolve the problem. ## Inferring SF perturbations with learned models As with learning a KATMAP model, we need to begin by making a config file that tells KATMAP how to perform the analysis. Unlike the standard analysis, we'll use the `--omit-activity` parameter to tell KATMAP that we do not want to learn an activity map. ```sh $ python makeconfig.py {path_to_config} --rmats {path_to_rmats} --ref {path_to_ref} --out {name_for_KATMAP_output_directory} --omit-activity True ``` To set this up using the HNRNPC rMATS results ```sh $ python makeconfig.py {path_to_directory}/{config_name}.json --rmats examples/data/HNRNPC_HepG2_SE.tsv.gz --ref {path_to_ref} --out {name_for_KATMAP_output_directory} --ctrl-index 1 --omit-activity True ``` This creates a configuration file that has most of the information we need to run the analysis. The only thing we are missing is the impact scores from the learned KATMAP models. We can add these to the data and update the configuration file to tell KATMAP how to use the impacts using ```sh $ python precompute_impacts.py {path_to_config} {path_model_directory} [-OPTIONS] ``` Learned models are provided with KATMAP in `models/best_model_per_SF`. To use these: ```sh $ python precompute_impacts.py {path_to_config} {path_to_katmap}/models/best_model_per_SF [-OPTIONS] ``` The full usage of the command is as follows: ```python UpdateConfigCommandParser().parser.print_help() ``` usage: python precompute_impacts.py {filepath} [-OPTIONS] Takes a prespecified configuration file, scores the exons with prelearned KATMAP models, and adds the computed splicing impacts to the model as opposing linear predictors. positional arguments: config Path to the configuration file models Path to a directory containing the *.katmap files that will be used to compute the impacts or a tab-delimited file containing the paths. If a table is provided, it should not have column names. The table may have one or two columns. If it has only one column, that column should store one path to a *.katmap file per row. If two columns are provided, the first column should store labels used to name the models (e.g. "RBFOX2", "HNRNPC") and the second column should store the corresponding file path. optional arguments: -h, --help show this help message and exit --include INCLUDE [INCLUDE ...] If provided, only the specified models will be used (do not include the ".katmap" extension). (default: []) --exclude EXCLUDE [EXCLUDE ...] If provided, the specified models will not be used (do not include the ".katmap" extension). (default: []) --only-score-training-set ONLY_SCORE_TRAINING_SET Whether to only score the exons in the training set. (default: True) --normalize NORMALIZE Whether to normalize the impacts. (default: False) --mean-center MEAN_CENTER Whether to mean-center the impacts (not recommended). (default: False) --standardize STANDARDIZE Whether to divide the impacts by their standard deviation. (default: False) --quad-terms QUAD_TERMS Whether to add quadratic terms for the impacts. (default: False) --verbose VERBOSE Whether to show a progress bar. (default: True) Running `precompute_impacts.py` will save a FeatureTable with the precomputed splicing impacts in the output directory specified in the configuration file and update the configuration file to include these splicing impacts as opposing predictors (each impact contributes positively to the prediction that an exon is upregulated and negatively to the downregulation prediction). As with learning models, we use `katmap.py` to call the inference algorithm ```sh $ python katmap.py {path_to_config} ``` As an example, if we want infer SF perturbations from the rMATS output `examples/data/HNRNPC_HepG2_SE.tsv.gz`, we would use the following commands: ```sh $ python makeconfig.py {path_to_config} --rmats examples/data/HNRNPC_HepG2_SE.tsv.gz --ref {path_to_ref} --out {name_for_KATMAP_output_directory} --ctrl-index 1 --omit-activity True $ python precompute_impacts.py {path_to_config} models/best_model_per_SF $ python katmap.py {path_to_config} ``` If instead we want to infer SF perturbations from a previously constructed FeatureTable, `examples/data/HNRNPC_HepG2_SE.tsv.gz`, we would use the following commands: ```sh $ python makeconfig.py examples/configs/HNRNPC_HepG2_Perturbation.json --features examples/data/HNRNPC_HepG2_FeatureTable.tsv.gz --ref {path_to_ref} --out examples/results/HNRNPC_HepG2_Perturbation --omit-activity True $ python precompute_impacts.py examples/configs/HNRNPC_HepG2_Perturbation.json models/best_model_per_SF $ python katmap.py examples/configs/HNRNPC_HepG2_Perturbation.json ``` with the configuration file and outputs found in the `examples` directory. ### Outputs of the perturbation analysis Running KATMAP with `--omit-activity True` generates a smaller set of output files, because we are fitting a simpler generalized linear model (GLM) rather than the full generalized additive model. * `01_analysis_specification.json`: The set of parameters used for the analysis * `02_model_data.tsv`: The FeatureTable used as inputs for the analysis. This includes the splicing impacts computed for each exon using the models provided to `precompute_impacts.py` * `03_coefficient_plot.png`: A plot of the regression coefficients for the SF perturbations and the respective Z-scores * `04_posterior_summary.tsv`: A table summarizing the posterior samples over each coefficient. Reports the posterion mean, standard deviation, Z-score, and 94\%-CI. * `05_posterior_sample.tsv`: A table storing the full posterior sample over all coefficients. Of these `02_coefficient_plot.png` and `04_posterior_sample.tsv` provide direct summaries of the results. ```python pd.read_csv('examples/results/HNRNPC_HepG2_Perturbation/04_posterior_summary.tsv', sep='\t', index_col=0) ```
Parameter PosteriorMean PosteriorStd Z 3%-ile 97%-ile
0 coef_downreg_phi_ctrl -0.993 0.092 -10.838 -1.183 -0.828
1 coef_downreg_phi_ctrl^2 -2.239 0.121 -18.530 -2.453 -2.019
2 coef_upreg_phi_ctrl -3.552 0.201 -17.689 -3.904 -3.195
3 coef_upreg_phi_ctrl^2 -2.343 0.128 -18.369 -2.592 -2.114
4 coef_logreads -2.167 0.085 -25.568 -2.317 -1.996
5 coef_logreads^2 0.305 0.055 5.533 0.199 0.409
6 coef_DAZAP1_HepG2_RBPamp -0.208 0.055 -3.755 -0.310 -0.108
7 coef_HNRNPC_K562_RBPamp -1.210 0.092 -13.114 -1.386 -1.041
8 coef_HNRNPF_K562_RBPamp -0.143 0.115 -1.245 -0.358 0.070
9 coef_HNRNPH1_K562_RBPamp 0.159 0.100 1.587 -0.028 0.347
10 coef_HNRNPK_HepG2_PWM 0.279 0.105 2.663 0.091 0.480
11 coef_HNRNPL_K562_RBPamp -0.039 0.083 -0.467 -0.198 0.103
12 coef_MATR3_HepG2_PWM 0.033 0.175 0.187 -0.293 0.358
13 coef_PCBP1_HepG2_PWM -0.011 0.068 -0.159 -0.142 0.113
14 coef_PTBP1_K562_RBPamp 0.299 0.113 2.637 0.089 0.522
15 coef_PUF60_HepG2_RBPamp -0.052 0.075 -0.683 -0.193 0.087
16 coef_QKI_HepG2_PWM 0.109 0.136 0.798 -0.163 0.358
17 coef_RBFOX2_HepG2_RBPamp 0.117 0.113 1.034 -0.102 0.330
18 coef_SRSF1_K562_PWM -0.541 0.139 -3.886 -0.808 -0.287
19 coef_SRSF7_HepG2_PWM 0.013 0.134 0.098 -0.243 0.263
20 coef_TRA2AB_Hs_RBPamp 0.016 0.048 0.337 -0.072 0.105
21 coef_U2AF2_HepG2_PWM 0.498 0.202 2.460 0.079 0.870
22 intercept_downreg -0.508 0.451 -1.125 -1.379 0.322
23 intercept_upreg -0.043 0.449 -0.095 -0.880 0.800
We can use three functions found in `katmap.plotting` to visualize this table. ```python from matplotlib import pyplot import seaborn from katmap.plotting import plot_perturbations, plot_perturbation_zscores, plot_perturbations_fdr ``` If we want to plot the estimated coefficients and associated 94\%-credible intervals, we can pass the output directory to `plot_perturbations`: ```python pyplot.figure(figsize=(5,2)) plot_perturbations('examples/results/HNRNPC_HepG2_Perturbation', ci=.94) xt=pyplot.xticks(size=8) ``` ![png](docs/images/output_29_0.png) Positive values suggest gains in regulation by a factor, negative values suggest loss in regulation. If we want to plot the z-scores associated with each coefficient we can use `plot_perturbation_zscores`: ```python pyplot.figure(figsize=(5,2)) plot_perturbation_zscores('examples/results/HNRNPC_HepG2_Perturbation', min_sig_zscore=3) xt=pyplot.xticks(size=8) ``` ![png](docs/images/output_32_0.png) Finally, if we want to be stringent about how we define potential perturbations, we can apply a form of multiple test corrections to these estimates using [`ashr`](https://cran.r-project.org/web/packages/ashr/index.html) ([Stephens 2017](https://academic.oup.com/biostatistics/article/18/2/275/2557030)) with `plot_perturbations_fdr`. This considers all estimated parameters and the associated uncertainties to obtain more robust estimates of the true values ```python pyplot.figure(figsize=(5,2)) ash_res=plot_perturbations_fdr('examples/results/HNRNPC_HepG2_Perturbation', n_stdev=2, #Number of standard deviations for error bars fdr_cutoff=0.1,) #Color estimates that satisfy this FDR cutoff xt=pyplot.xticks(size=8) ``` ![png](docs/images/output_34_0.png) This function also returns a summary of the `ashr` results, including estimated false discovery rates (FDR) and false sign rates (the probability the inferred direction of perturbation is wrong, FSR): ```python ash_res.sort_values('FDR').round(3) ```
Parameter shrunk_mean shrunk_std FDR FSR raw_mean raw_std
1 HNRNPC_K562_RBPamp -1.196 0.092 0.000 0.000 -1.210 0.092
12 SRSF1_K562_PWM -0.508 0.149 0.012 0.012 -0.541 0.139
0 DAZAP1_HepG2_RBPamp -0.198 0.065 0.032 0.032 -0.208 0.055
4 HNRNPK_HepG2_PWM 0.165 0.121 0.339 0.342 0.279 0.105
8 PTBP1_K562_RBPamp 0.171 0.129 0.350 0.353 0.299 0.114
15 U2AF2_HepG2_PWM 0.183 0.211 0.472 0.479 0.498 0.202
3 HNRNPH1_K562_RBPamp 0.029 0.071 0.806 0.814 0.159 0.100
11 RBFOX2_HepG2_RBPamp 0.013 0.050 0.883 0.896 0.117 0.113
2 HNRNPF_K562_RBPamp -0.014 0.057 0.885 0.904 -0.143 0.115
10 QKI_HepG2_PWM 0.011 0.047 0.890 0.908 0.109 0.136
6 MATR3_HepG2_PWM 0.004 0.049 0.901 0.935 0.033 0.175
13 SRSF7_HepG2_PWM 0.002 0.035 0.920 0.949 0.013 0.134
5 HNRNPL_K562_RBPamp -0.001 0.021 0.947 0.969 -0.039 0.083
9 PUF60_HepG2_RBPamp -0.002 0.021 0.947 0.965 -0.052 0.075
7 PCBP1_HepG2_PWM 0.000 0.014 0.957 0.977 -0.011 0.068
14 TRA2AB_Hs_RBPamp 0.001 0.009 0.965 0.974 0.016 0.048
Correlations in the uncertainty coefficient estimates can be explored in the full posterior sample stored in `05_posterior_sample.tsv`. ## Applying KATMAP models The KATMAP python library can be used to apply learned models to analyze other data. ```python import numpy, scipy import numpy as np import scipy.stats as st import pandas as pd ``` To load a learned model, we can use the `KatmapModel` class found in the `katmap.mikesmaps` submodule. ```python from katmap.mikesmaps import KatmapModel model=KatmapModel.load('models/models_for_both_cells/HNRNPC_HepG2_RBPamp.katmap') ``` This contains all of the information we need to score new sequences, including the activity map: ```python from katmap.plotting import plot_rna_map plot_rna_map(model) ``` ![png](docs/images/output_44_0.png) And the motif model ```python model.motif_model ``` ### Building an RNAmap object for scoring exons We consider an RNAmap to be, in its most general form, a means of organizing information around reference points that can be meaningfully compared across exons or transcripts. We use the `RNAmap` class to accomplish this. To score exons with the `KatmapModel`, we need to organize the splice sites of our exons of interest in an RNAmap object. This is straightforward with rMATS output tables: we just need to open the table with `spliceformats` ```python from spliceformats.readMATS import read_rmats from spliceformats.rmats.utilities import remove_redundant_splicing_events rmats_data=read_rmats('examples/data/HNRNPC_HepG2_SE.tsv.gz', filter_func= remove_redundant_splicing_events) #rMATS often reports overlapping events ``` For more details on how this organizes the rMATS result, see the `spliceformats` library. We're going to focus on skipped exons, which are found in the `.SE` attribute. ```python rmats_data.SE.df ```
ID GeneID geneSymbol chr strand exonStart_0base exonEnd upstreamES upstreamEE downstreamES ... IncLevelDifference Total_reads PSI1 PSI2 dPSI_corr FDR_corr dPSI dPSI_3% dPSI_97% Direction
0 10993 ENSG00000117139.12 KDM5B chr1 - 202735524 202735632 202733176 202733273 202736053 ... 0.572 44.50 0.511291 0.030576 4.807149e-01 2.197414e-13 4.807149e-01 0.272185 0.685387 1.0
1 12410 ENSG00000197912.9 SPG7 chr16 + 89612279 89612438 89611055 89611180 89613065 ... 0.327 70.25 0.303556 0.025021 2.785345e-01 7.884081e-14 2.785345e-01 0.154327 0.440017 1.0
2 13276 ENSG00000092841.14 MYL6 chr12 + 56553378 56553406 56552467 56552495 56553758 ... -0.426 135.50 0.079970 0.493450 -4.134793e-01 6.880408e-14 -4.134793e-01 -0.447999 -0.356502 -1.0
3 13279 ENSG00000092841.14 MYL6 chr12 + 56554409 56554454 56554026 56554104 56555170 ... -0.136 578.25 0.039468 0.171645 -1.321772e-01 1.595857e-14 -1.321772e-01 -0.144430 -0.114730 -1.0
4 14249 ENSG00000072210.14 ALDH3A2 chr17 + 19576463 19576588 19575033 19575269 19578870 ... 0.436 135.75 0.469563 0.071449 3.981143e-01 4.805712e-14 3.981143e-01 0.258594 0.542560 1.0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
20296 9958 ENSG00000073792.11 IGF2BP2 chr3 - 185404844 185404979 185393578 185393701 185407142 ... -0.002 380.25 0.999558 0.999558 -2.954490e-09 3.673856e-01 -2.954490e-09 -0.999558 0.000442 -0.0
20297 9967 ENSG00000189306.6 RRP7A chr22 - 42914010 42914153 42912016 42912142 42915719 ... 0.030 83.25 0.971201 0.963039 8.161983e-03 5.592170e-01 8.161983e-03 -0.679363 0.036613 -0.0
20298 9974 ENSG00000137207.7 YIPF3 chr6 - 43483343 43483439 43481325 43481371 43483626 ... 0.001 241.25 0.987334 0.987465 -1.317768e-04 4.237455e-01 -1.317768e-04 -0.096367 0.011190 -0.0
20299 9990 ENSG00000157224.11 CLDN12 chr7 + 90034832 90034922 90032703 90032863 90041957 ... -0.028 74.50 0.997910 0.998211 -3.007326e-04 3.692203e-01 -3.007326e-04 -0.390561 0.001782 -0.0
20300 9991 ENSG00000080822.12 CLDND1 chr3 - 98235643 98235723 98234327 98234676 98235895 ... -0.016 58.00 0.997524 0.997533 -9.219580e-06 3.677278e-01 -9.219580e-06 -0.997533 0.002467 -0.0

20301 rows × 32 columns

Here we can find the `.splicesite_info` attribute, which stores the genomic coordinates of the splicesites associated with each exon. The `ID` column indicates which splicing event in the rMATS table the splice site belongs to and the `feature` column describes the type of splice site (A: acceptor/3ss, D: donor/5ss; D1: upstream flanking exon's 5ss, A1: cassette exon's 3ss, D2: cassette exon's 5ss, A2: downstream flanking exon's 3ss). The other columns describe the genomic coordinates of the splice sites, with `start` indicating the exonic side of the splice site. ```python rmats_data.SE.splicesite_info ```
ID Feature Chromosome Strand Start End
0 10993 D1 chr1 - 202736053 202736054
1 10993 A1 chr1 - 202735632 202735633
2 10993 D2 chr1 - 202735524 202735525
3 10993 A2 chr1 - 202733273 202733274
4 12410 D1 chr16 + 89611180 89611181
... ... ... ... ... ... ...
81199 9990 A2 chr7 + 90041957 90041958
81200 9991 D1 chr3 - 98235895 98235896
81201 9991 A1 chr3 - 98235723 98235724
81202 9991 D2 chr3 - 98235643 98235644
81203 9991 A2 chr3 - 98234676 98234677

81204 rows × 6 columns

This is the information around which we'll build our RNAmap containing the splicing events we wish to score. If instead you have a BED format table that stores exons and their splice sites, you use `bed2splicesiteinfo` to construct this table: ```python from katmap.rnamap import bed2splicesiteinfo ``` ```python import pandas as pd bed_table=pd.read_csv('examples/data/hg19GencodeV46_first50000.bed.gz', sep='\t', header=None) ss_info_from_bed=bed2splicesiteinfo(bed_table) ``` ```python bed_table ```
0 1 2 3 4 5
0 chr1 66999043 66999090 NM_001376549.1_exon_0_0_chr1_66999044_f 0 +
1 chr1 66999928 67000051 NM_001376549.1_exon_1_0_chr1_66999929_f 0 +
2 chr1 67091529 67091593 NM_001376549.1_exon_2_0_chr1_67091530_f 0 +
3 chr1 67098752 67098777 NM_001376549.1_exon_3_0_chr1_67098753_f 0 +
4 chr1 67101626 67101698 NM_001376549.1_exon_4_0_chr1_67101627_f 0 +
... ... ... ... ... ... ...
49995 chr1 24996610 24996806 NM_001366582.1_exon_14_0_chr1_24996611_f 0 +
49996 chr1 24997876 24998086 NM_001366582.1_exon_15_0_chr1_24997877_f 0 +
49997 chr1 24998672 24999772 NM_001366582.1_exon_16_0_chr1_24998673_f 0 +
49998 chr1 24969792 24969838 NM_001366569.1_exon_0_0_chr1_24969793_f 0 +
49999 chr1 24972474 24972564 NM_001366569.1_exon_1_0_chr1_24972475_f 0 +

50000 rows × 6 columns

Or load directly from the file: ```python ss_info_from_bed=bed2splicesiteinfo(path='examples/data/hg19GencodeV46_first50000.bed.gz') ``` If the columns indicating the chromosome, strand, start, or end are in different locations compared to the standard bed format, the locations can be specified using the `chrom_col`, `strand_col`, `start_col`, and `end_col` arguments. ```python ss_info_from_bed=bed2splicesiteinfo(path='examples/data/hg19GencodeV46_first50000.bed.gz', chrom_col=0, start_col=1, end_col=2, strand_col=5) ``` Once the splice site information is in hand, an `RNAmap` object can be built around it. ```python from katmap.rnamap import RNAmap ``` ```python rnamap=RNAmap(rmats_data.SE.splicesite_info) ``` We also need to load the appropriate reference genome for reading. The `FastaReader` class calls the `Fasta` class from the `pyfastx`, but includes some additional functionality (batching and caching queries) to make loading sequences more efficient. ```python from katmap.parsers import FastaReader ref_parser=FastaReader('00_data/hg19.fa.gz') ``` ```python model.compute_positional_impact ``` > Now we have everything we need to make predictions about exons. The `KatmapModel` class has several methods for scoring exons: 1. `KatmapModel.compute_affinity`: Computes the calibrated affinities of binding sites around the exons 1. `KatmapModel.compute_change_in_binding`: Computes the relative changes in occupancy around the exons. 1. `KatmapModel.compute_positional_impact`: Computes the change in regulation due to altered binding at sites around the exons. 1. `KatmapModel.compute_impact`: Computes the total change in regulation at the exon due to altered binding. 1. `KatmapModel.compute_occupancy`: Computes the occupancy at binding sites around the exon, assuming a given free protein concentration. 1. `KatmapModel.compute_positional_regulation`: Computes the regulation at binding sites around the exon, assuming a given free protein concentration. 1. `KatmapModel.compute_regulation`: Computes the total regulation at exons, assuming a given free protein concentration. The first four functions can be computed using parameters learned from the knockdown, though alternative values can be passed as arguments. The last three require making some assumption about the SF's free protein concentration (relative to the optimal motif's affinity). ### Computing the splicing impact at individual exons The **splicing impact** is the portion of KATMAP's model that predicts the splicing regulation an SF exerts on an exon. When modelling perturbation data, the purpose of these splicing impacts is to predict changes in splicing in terms of SF binding and activity. This is accomplished by predicting changes in binding around an exon's splice sites and then multiplying these by the activity map: ![Activity](docs/images/SplicingImpactExample.png) The total splicing impact at the exon is computed by summing across all positions. In this example, loss of binding in a region with suppressing activity is predicted to result in upregulation of the exon. This can be computed manually: ```python change_in_binding=model.compute_change_in_binding(rnamap, ref_parser, ) activity=model.activity position_wise_splicing_impacts=change_in_binding*activity splicing_impact=position_wise_splicing_impacts.sum(-1) ``` WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.) However, the KatmapModel class has a `compute_impact` method to compute this for you: ```python pyplot.figure(figsize=(4,3)) impacts_knockdown_model=model.compute_impact(rnamap, ref_parser, report_direction_of_regulation=False, normalize_activities=False) seaborn.histplot(impacts_knockdown_model, element='step', color='dodgerblue',alpha=.7) pyplot.xlabel('HNRNPC impact in knockdown experiment') pyplot.show() ``` ![png](docs/images/output_74_0.png) In the context of a knockdown experiment, the HNRNPC model predicts the inclusion at HNRNPC targets should increase, reflecting the loss of HNRNPC's repressing activity. However, most users are likely interested in *whether a factor enhances or represses inclusion, not how that regulation changes after knockdown.* For models learned from knockdown experiments **the default behavior of** `.compute_impact` **is to report how much higher regulation was prior to knockdown by flipping the sign of the raw splicing impacts.** So when scoring exons, HNRNPC's splicing impacts will be negative to indicate that HNRNPC represses exon inclusion: ```python impacts=model.compute_impact(rnamap, ref_parser, ) ``` ```python pyplot.figure(figsize=(4,3)) seaborn.histplot(impacts, element='step', color='dodgerblue',alpha=.7) pyplot.xlabel('HNRNPC impact') pyplot.show() ``` ![png](docs/images/output_77_0.png) In addition to flipping the signs of the impacts learned from knockdown data, `compute_impact` also normalizes impacts to the activity coefficient with greatest magnitude, which represents the largest effect a single binding site could contribute to the prediction. This simplifies comparisons across different factors. This can be disabled by setting `normalize_activities` to False. Finally, the default behavior is to compute impacts based on relative changes in binding, as is done during model inference. This is because the exact change in free protein due to knockdown is not identifiable during inference (changing the value of this parameter simply changes the scale of the splicing impacts). However, if you are willing to assume a specific value for the change in free protein (for example based on some direct measurement), these can be converted to absolute impacts by setting `change_in_free_protein` to the value you wish to assume. ```python impacts_relative=model.compute_impact(rnamap, ref_parser, normalize_binding=False) impacts_absolute=model.compute_impact(rnamap, ref_parser, change_in_free_protein=2**-2.55, normalize_binding=False) ``` Unless the factor is assumed to be completely lost, this simply rescales the impacts without change the ordering of predictions. We therefore recommend using the default approach in most circumstances. ```python pyplot.figure(figsize=(4,4)) pyplot.scatter(impacts_relative, impacts_absolute) pyplot.plot([-2.5,0],[-2.5,0], c='k', ls='--', label='one-to-one') pyplot.ylabel('Impacts assuming 80% decrease in [F]',size=12) pyplot.xlabel('Default splicing impacts',size=12) pyplot.legend() seaborn.despine() pyplot.gca().set_aspect('equal') ``` ![png](docs/images/output_82_0.png) To compare these predictions to those learned from an HNRNPC knockdown in a different cell type, all we have to do is load that model in and use it to score the exons: ```python model_k562=KatmapModel.load('models/models_for_both_cells/HNRNPC_K562_RBPamp.katmap') ``` ```python impacts_hepg2=model.compute_impact(rnamap, ref_parser) impacts_k562=model_k562.compute_impact(rnamap, ref_parser) ``` KATMAP has learned essentially the same picture of HNRNPC's regulation from the two different knockdown experiments: ```python pyplot.figure(figsize=(4,4)) pyplot.hexbin(impacts_hepg2, impacts_k562, bins='log', mincnt=1) pyplot.gca().set_aspect('equal') pyplot.ylabel('K562 model impact', size=12) xlabel=pyplot.xlabel('HepG2 model impact', size=12) ``` ![png](docs/images/output_87_0.png) Because KATMAP's model of regulation is additive, the total splicing impact for an exon can be thought of as the sum of the regulation at its 3SS and the regulation at its 5SS. To compute impacts for only the 3SS or 5SS, this can be specified using the `event_structure` argument ```python impact_3ss=model.compute_impact(rnamap, ref_parser, event_structure=['A1']) impact_5ss=model.compute_impact(rnamap, ref_parser, event_structure=['D2']) ``` ```python pyplot.figure(figsize=(4,4)) pyplot.scatter(impact_3ss+impact_5ss, impacts) pyplot.xlabel( '3SS impact + 5SS impact') pyplot.ylabel('Impact') pyplot.gca().set_aspect('equal') ``` ![png](docs/images/output_90_0.png) ### Computing the impact at different positions around individual exons KATMAP's predictions are rooted in predicted changes in occupancy at binding sites around an exon. Often we'll want to take advantage of this interpretability to see how different binding sites around the exons contribute to the splicing impact. We can do this with `.compute_positional_impact` ```python pos_impacts=model.compute_positional_impact(rnamap, ref_parser) # pos_binding=model.compute_change_in_binding(rnamap, ref_parser, max_occ_change=-.5) ``` Let's take a look at 100 upregulated and 100 unchanged exons: ```python # idx=numpy.hstack([numpy.where(direction==1)[0][:100],numpy.where(direction==0)[0][:100],numpy.where(direction==-1)[0][:100]]) direction=numpy.sign(rmats_data.SE.dpsi)*(rmats_data.SE.fdr<.05) fig,axes=pyplot.subplots(1,3, figsize=(9,5), gridspec_kw={'width_ratios':[1,1,.1]}) ax=seaborn.heatmap(pos_impacts[numpy.where(direction==1)[0][:100]], cmap='bwr',yticklabels=[], vmin=-1, vmax=1, ax=axes[0], cbar_ax=axes[-1]) ax=seaborn.heatmap(pos_impacts[numpy.where(direction==0)[0][:100]], cmap='bwr',yticklabels=[], vmin=-1, vmax=1, ax=axes[1], cbar=False) titles=['100 upreg exons', '100 NS exons'] for i in range(2): #Add some annotations and labels to make it interpretable pyplot.sca(axes[i]) # pyplot.ylabel([],[]) pyplot.title(titles[i], size=16) pyplot.axvline(20, zorder=100, c='k', lw=1, ls='--') pyplot.axvline(20+12, zorder=100, c='k', lw=1, ls='--') pyplot.xlabel('Dist. from 3 and 5ss') frames=[pyplot.axvline(pos, zorder=100, c='k', lw=3, ls='-') for pos in [0.5,26,51.5]] xt=pyplot.xticks(list(numpy.arange(0,26,4))+list(numpy.arange(2,26+4,4)+26), list(numpy.arange(0,26,4)*10-200)+list(numpy.arange(2,26+4,4)*10-60), rotation=45 ) ``` ![png](docs/images/output_94_0.png) ## Computing target predictions Intuitively, exons with larger absolute splicing impacts are more likely to be targets, but the cutoff that separates plausible targets from nontargets is not obvious *a priori*. When modelling knockdown data, KATMAP uses model comparison against a simplified model to identify predicted targets as exons where including splice regulatory in the model improves the predictions. It further constructs predictions that integrate whether the exon was affected by knockdown. These target predictions leveraging both the learned splicing impacts and whether the exon was affected by knockdown are available in the [KATMAP Zenodo archive](https://zenodo.org/records/15298342). However, this approach cannot be directly applied when scoring new exons not included in the original perturbation experiment. In these cases, the KatmapModel class can still generate target predictions by asking **what fraction of exons with a given splicing impact were predicted to be targets in the original knockdown experiment**. This is somewhat more conservative, but can still be useful when prioritizing which exons to focus on. To compute this, we can use the `compute_target_confidence` method. ```python target_probs=model.compute_target_confidence(rnamap, ref_parser) ``` This assigns each splicing event three predictions: the confidence that the event is a suppression target, not a target, or an enhancing target. By default, this is structured as an xarray.DataArray, where the first dimension represents splicing events and the second to the three predictions. This can be converted to a numpy array with the `.to_numpy` method ```python target_probs_array=target_probs.to_numpy() ``` or by setting `return_xarray` to False when calling `.compute_target_confidence`. ```python pyplot.figure(figsize=(4,3)) seaborn.ecdfplot(target_probs[:,0]) pyplot.xlabel('Confidence suppression target') ``` Text(0.5, 0, 'Confidence suppression target') ![png](docs/images/output_101_1.png) If we plot the splicing impacts against the target predictions, we can see the threshold ```python pyplot.figure(figsize=(4,3)) pyplot.scatter (impacts,target_probs[:,0], c='b') pyplot.ylabel('Confidence repression target') pyplot.xlabel('HNRNPC impact') seaborn.despine() ``` ![png](docs/images/output_103_0.png) We can also ask how particular regions around an exon contribute to this target probability with `.compute_positional_target_confidence`. This asks how much the target predictions would change if a given region were left out: ```python sre_probs=model.compute_positional_target_confidence(rnamap, ref_parser, report_difference=False) ``` This returns a three-dimensional `xarray.DataArray`, describing how much higher the suppression, nontarget, and enhancing target predictions are with all regions around the exon included (e.g. $\text{PrEnh}_{full}$) versus the prediction with region $j$ left out ($\text{PrEnh}_{\neg j}$): ![Activity](docs/images/target_probability_formulas.png) The first dimension corresponds to events, the second to the different regions around the exon, and the third to the three categories of predictions. A simplified version of this can obtained by setting `report_difference` to `True`. This will return the difference between the position-wise enhancing and suppression target predictions, such that positive values suggest enhancing cis-elements and negative values suggest repressing cis-elements: ![Activity](docs/images/target_probability_formulas_simplified.png) The scale of this quantity ranges from -1 (high confidence silencing element) to +1 (high confidence enhancing element). ```python sre_probs=model.compute_positional_target_confidence(rnamap, ref_parser, report_difference=True) ``` ```python # idx=numpy.hstack([numpy.where(direction==1)[0][:100],numpy.where(direction==0)[0][:100],numpy.where(direction==-1)[0][:100]]) direction=numpy.sign(rmats_data.SE.dpsi)*(rmats_data.SE.fdr<.05) fig,axes=pyplot.subplots(1,3, figsize=(7,4), gridspec_kw={'width_ratios':[1,1,.1]}) ax=seaborn.heatmap(sre_probs[numpy.where(target_probs[:,0]>=0.5)[0][:100]], cmap='bwr',yticklabels=[], vmin=-1, vmax=1, ax=axes[0], cbar_ax=axes[-1]) ax=seaborn.heatmap(sre_probs[numpy.where(target_probs[:,0]<0.5)[0][:100]] ,cmap='bwr',yticklabels=[], vmin=-1, vmax=1, ax=axes[1], cbar=False) titles=['Target confidence ≥ 50%', 'Target confidence < 50%'] for i in range(2): #Add some annotations and labels to make it interpretable pyplot.sca(axes[i]) # pyplot.ylabel([],[]) pyplot.title(titles[i], size=14) pyplot.axvline(20, zorder=100, c='k', lw=1, ls='--') pyplot.axvline(20+12, zorder=100, c='k', lw=1, ls='--') pyplot.xlabel('Dist. from 3 and 5ss') frames=[pyplot.axvline(pos, zorder=100, c='k', lw=2, ls='-') for pos in [0.5,26,51.5]] xt=pyplot.xticks(list(numpy.arange(0,26,4))+list(numpy.arange(2,26+4,4)+26), list(numpy.arange(0,26,4)*10-200)+list(numpy.arange(2,26+4,4)*10-60), rotation=45 ) ``` ![png](docs/images/output_108_0.png) ## Scoring an exon of interest with multiple models We might be interested in the regulation of a particular exon. For example exon, let's consider exon 16 of NF2: We first need a table describing the splice sites of the exon we're interested in: ```python exon_table=pd.DataFrame.from_dict({'event_id':[1], 'Chromosome':['chr22'],'Strand':['+'], 'A1':[30079008], 'D2':[30079053]}) exon_table ```
event_id Chromosome Strand A1 D2
0 1 chr22 + 30079008 30079053
We can reorganize this into the format that KatmapModel expects by first extracting the splice site info ```python from spliceformats.parsers import extract_splicesites_from_dataframe ss_info=extract_splicesites_from_dataframe(exon_table) ss_info ```
ID Feature Chromosome Strand Start End
0 1 A1 chr22 + 30079008 30079009
1 1 D2 chr22 + 30079053 30079054
And using this to build an RNAmap ```python from katmap.rnamap import RNAmap ``` ```python NF2_ex16_map=RNAmap(ss_info) ``` We can use the `GroupedKatmapModels` class to score the sequence with multiple models at once. First we'll load the models in the `models/best_model_per_SF` directory ```python from katmap.mikesmaps import GroupedKatmapModels katmap_models=GroupedKatmapModels(directory='models/best_model_per_SF') ``` Again, we need to have the reference genome loaded with a FastaReader instance to score sequences: ```python from katmap.parsers import FastaReader ref_parser=FastaReader('00_data/hg19.fa.gz') ``` And then we just use the `.compute_positional_impact` method to compute position-wise impacts with each model ```python SF_impacts=katmap_models.compute_positional_impact(NF2_ex16_map, ref_parser, bin_positions=True) ``` This returns a dictionary, keyed by the model names and storing the position-wise scores. Because only scored a single sequence, we can convert this to a dataframe with pandas: ```python NF2_impacts=pd.DataFrame.from_dict(SF_impacts).T ``` And then visualize the results as a heatmap ```python import pandas as pd NF2_impacts=pd.DataFrame.from_dict(SF_impacts).T pyplot.figure(figsize=(6,4)) seaborn.heatmap(NF2_impacts,cmap='RdBu_r', vmin=-1, vmax=1, yticklabels= [val.split('_')[0] for val in NF2_impacts.index] ) for i in range(len(NF2_impacts.columns)): pyplot.axhline(i, c='grey', lw=1) pyplot.axvline(20, c='k', ls='--', lw=1) pyplot.axvline(20+12, c='k', ls='--',lw=1) ``` ![png](docs/images/output_127_1.png) These splicing impacts suggests that several SFs have binding sites in regions where they could exert splicing regulatory activity. In the downstream intron, QKI, RBFOX2 and HNRNPs F and H are predicted to have enhancing activity. The predicted activity in the upstream intron is primarily from PUF60 and U2AF2 at the polyY tract. We can also compute the impacts at nucleotide resolution by setting `bin_positions` to False. ```python SF_impacts_nt=katmap_models.compute_positional_impact(NF2_ex16_map, ref_parser, bin_positions=False) ``` ```python import pandas as pd ``` ```python NF2_impacts_nt=pd.DataFrame.from_dict(SF_impacts_nt).T ``` This can also be visualized as a heatmap: ```python pyplot.figure(figsize=(12,5)) seaborn.heatmap(NF2_impacts_nt,cmap='RdBu_r', vmin=-1, vmax=1, yticklabels= [val.split('_')[0] for val in NF2_impacts.index]) for i in range(len(NF2_impacts_nt.columns)): pyplot.axhline(i, c='grey', lw=1) pyplot.axvline(200, c='k', ls='--', lw=1) pyplot.axvline(200+120, c='k', ls='--',lw=1) ``` ![png](docs/images/output_134_1.png) Or we might focus on a few factors and visualize the predicted SREs in the downstream intron. ```python positions=numpy.arange(-60, 200)+30079053 pyplot.figure(figsize=(6,3)) pyplot.axvline(30079053, c='k') pyplot.plot(positions,SF_impacts_nt['HNRNPF_K562_RBPamp'][260:], c='orange', label='HNRNPF', lw=2) pyplot.plot(positions,SF_impacts_nt['RBFOX2_HepG2_RBPamp'][260:], c='r', label='RBFOX2', lw=2) pyplot.plot(positions,SF_impacts_nt['QKI_HepG2_PWM'][260:], c='b', label='QKI', lw=2) pyplot.gca().ticklabel_format(useOffset=False,style='plain') pyplot.ylabel('Impact') pyplot.legend() seaborn.despine() xt=pyplot.xticks(rotation=45) xl=pyplot.xlabel('Chr22, + strand') ``` ![png](docs/images/output_136_0.png) While splicing impacts indicate whether there are binding sites in regions where an SF is expected to have activity, it may not be obvious how high a splicing impact must be before we should be interested in it. Further, this threshold may vary among factors. If we want to be more conservative, we can use `compute_target_confidence` to ask which factors have high enough splicing impacts for a confident target prediction: ```python nf2_target_probs=katmap_models.compute_target_confidence(NF2_ex16_map, ref_parser) ``` ```python target_df=pd.DataFrame.from_dict(nf2_target_probs, orient='index', columns=['PrSuppTarget', 'PrNontarget', 'PrEnhTarget']) pyplot.figure(figsize=(3,5)) ax=seaborn.heatmap(target_df.round(2), cmap='Reds', annot=True,linewidths=1, linecolor='white') ax.xaxis.tick_top() xt=pyplot.xticks(rotation=45) ``` ![png](docs/images/output_139_0.png) As a reminder, the target confidence predictions indicate what fraction of exons with a given splicing impact were predicted to be repression targets, nontargets, and enhancing targets in the original analysis of the knockdown data. These target confidence predictions are relatively conservative for two reasons: 1) they cannot incorporate information about whether the exon was affected by knockdown and 2) they reflect the power the KATMAP model had in the original knockdown experiment to distinguish targets from nontargets. While a high target confidence suggests the exon is regulated by the factor, a low target confidence does not necessarily mean the exon is not regulated by the factor. The target model simply isn't confident regarding regulation. To illustrate the first point, we can dig into the underlying target model and see how the predictions change if the effect of knockdown on inclusion is known. In the original knockdown experiment, this exon's inclusion ***was*** downregulated upon QKI knockdown. If we dig into the underlying target model and provide it this information, the enhancing target confidence increases from $34\%$ to $90\%$: ```python raw_impacts=katmap_models.compute_positional_impact(NF2_ex16_map, ref_parser, bin_positions=True, #report the splicing impacts as they are used in the knockdown model report_direction_of_regulation=False, normalize_activities=False) np.round(katmap_models.models['QKI_HepG2_PWM'].target_prediction_model.compute_predictions(impacts=raw_impacts['QKI_HepG2_PWM'].sum(), directions=-1),2) ``` array([0. , 0.1, 0.9]) This example, however, is provided for illustration purposes only and would not represent good practice in general. If you want target predictions that incorporate the direction of splicing changes due to knockdown, you should use the target predictions directly obtained from analyzing knockdown data (see the Zenodo repository), not provide arbitrary directions to the target prediction model when scoring exons. As with as single KATMAP model, we can do this in a position-wise manner to ask which regions around the exon contribute substantially to the target predictions: ```python nf2_sre_probs=katmap_models.compute_positional_target_confidence(NF2_ex16_map, ref_parser,) ``` And visualize this as a heatmap: ```python NF2_probs=pd.DataFrame.from_dict(nf2_sre_probs).T pyplot.figure(figsize=(6,4)) seaborn.heatmap(NF2_probs,cmap='RdBu_r', vmin=-1, vmax=1, yticklabels= [val.split('_')[0] for val in NF2_impacts.index] ) for i in range(len(NF2_probs.columns)): pyplot.axhline(i, c='grey', lw=1) pyplot.axvline(20, c='k', ls='--', lw=1) pyplot.axvline(20+12, c='k', ls='--',lw=1) ``` ![png](docs/images/output_146_1.png) ## Which to use: Splicing impacts or target confidence? Depending on the goals of the analysis, the splicing impacts or target confidence predictions may be more appropriate. For example, in situations where you wish to assess whether some class of exons is enriched for targets, target confidence may be easier to interpret than the splicing impacts. They can also be useful for analyses where you wish to prioritize on a few high-confidence predictions. In the NF2 example, the target confidence predictions would favor focusing on the predicted RBFOX2 or QKI motifs in the downstream intron rather than the HNRNPF motifs. The splicing impacts, on the other hand, may be a more useful guide in exploratory analysis where you have the resources to investigate multiple cis-elements. In contrast to the target confidence predictions, splicing impacts would suggest considering the RBFOX2, QKI, and HNRNPF motifs because they all reflect SF motifs in regions where SF binding is expected to influence splicing. ```python import pandas as pd SF_impacts=katmap_models.compute_positional_impact(NF2_ex16_map, ref_parser, bin_positions=True, report_direction_of_regulation=True, ) NF2_impacts=pd.DataFrame.from_dict(SF_impacts).T fig,axes=pyplot.subplots(1,3, figsize=(10,4), gridspec_kw={'width_ratios':[.5,.5,.02]}) seaborn.heatmap(NF2_impacts,cmap='RdBu_r', vmin=-1, vmax=1, yticklabels= [val.split('_')[0] for val in NF2_impacts.index], ax=axes[0],cbar_ax=axes[2] ) seaborn.heatmap(NF2_probs,cmap='RdBu_r', vmin=-1, vmax=1, yticklabels= [val.split('_')[0] for val in NF2_impacts.index], ax=axes[1],cbar_ax=axes[2] ) pyplot.sca(axes[0]) pyplot.title('Splicing impacts') pyplot.sca(axes[1]) pyplot.title('Target confidence') pyplot.yticks([],[]) for j in [0,1]: pyplot.sca(axes[j]) for i in range(len(NF2_impacts.columns)): pyplot.axhline(i, c='grey', lw=1) pyplot.axvline(20, c='k', ls='--', lw=1) pyplot.axvline(20+12, c='k', ls='--',lw=1) ``` ![png](docs/images/output_148_0.png) An additional situation where the position-wise target confidence may be too conservative is when regulation arises from multiple strong cis-elements. Target confidence asks what fraction of exons with a given splicing impact were predicted to be targets in the original knockdown experiment. This roughly defines a threshold on the splicing impacts. The position-wise target confidence essentially asks how much removing a particular 10 nucleotide region affects this target prediction. If an exon is regulated by multiple cis-elements, its splicing impact will typically be sufficiently high enough that removing any one cis-element will not decrease the splicing impact below the threshold defining high-confidence targets. As an example, let's return to the HNRNPC model and compute the target confidence for each exon, and then score the exons with position-wise target predictions and position-wise splicing impacts: ```python model=KatmapModel.load('models/models_for_both_cells/HNRNPC_HepG2_RBPamp.katmap') impacts=model.compute_impact(rnamap, ref_parser) target_probs=model.compute_target_confidence(rnamap, ref_parser) pos_impacts=model.compute_positional_impact(rnamap, ref_parser) sre_probs=model.compute_positional_target_confidence(rnamap, ref_parser, report_difference=True) ``` If we divide exons into low confidence targets (target confidence <50\%), moderate confidence targets, (50-90\%), and high confidence (>90\%) targets, we can see that the moderate-confidence targets have stronger position-wise target predictions than the high- and low-confidence targets. ```python pyplot.figure(figsize=(4,4)) seaborn.ecdfplot(sre_probs.min(1)[(target_probs[:,0]<.5)],label='Low target confidence', c='k', ls='--') seaborn.ecdfplot(sre_probs.min(1)[(target_probs[:,0]>=.5)&(target_probs[:,0]<.9)],label='Moderate target confidence', c='b') seaborn.ecdfplot(sre_probs.min(1)[target_probs[:,0]>=.9],label='High target confidence', c='r' ) pyplot.legend(bbox_to_anchor=(1,0.2,.1,.1), frameon=False) pyplot.xlabel('Strongest position-wise target prediction at exon') seaborn.despine() ``` ![png](docs/images/output_152_0.png) This may feel counterintuitive, but to understand why this is the case we can refer back to the relationship between splicing impact and target confidence: ```python pyplot.figure(figsize=(4,3)) pyplot.scatter (impacts,target_probs[:,0], c='b') pyplot.ylabel('Confidence repression target') pyplot.xlabel('HNRNPC impact') seaborn.despine() ``` ![png](docs/images/output_154_0.png) If an exon's full splicing impact is $-4$, removing a single region can at most reduce the impact to $-3$. But splicing impacts of $-4$ and $-3$ both correspond to high target confidence and so the position-wise target predictions will be very small: multiple binding sites contribute to the exon's target prediction, removing a single binding site has little effect. On the other hand, if the exon's splicing impact were $-3$, removing a single region could reduce the impact to $-2$, which would correspond to a more appreciable position-wise target prediction of $-0.36$. In these cases, selecting exons predicted to be targets, and then examining the **position-wise splicing impacts** may generate more useful hypotheses about cis-elements. If we instead compare the position-specific splicing impacts between moderate and high confidence targets, we can see that the moderate-confidence targets and high-confidence have comparable position-wise splicing impacts. ```python pyplot.figure(figsize=(4,4)) seaborn.ecdfplot(pos_impacts.min(1)[(target_probs[:,0]<.5)],label='Low target confidence', c='k', ls='--') seaborn.ecdfplot(pos_impacts.min(1)[(target_probs[:,0]>=.5)&(target_probs[:,0]<.9)],label='Moderate target-confidence', c='b') seaborn.ecdfplot(pos_impacts.min(1)[target_probs[:,0]>=.9],label='High-probability targets', c='r' ) pyplot.legend(bbox_to_anchor=(1,0.2,.1,.1), frameon=False) pyplot.xlabel('Strongest position-wise splicing impact at exon') seaborn.despine() ``` ![png](docs/images/output_157_0.png) To recap: * **Splicing impacts** indicate whether there are potential binding sites near an exon in locations where they would be expected to affect splicing * **Target confidence** asks what fraction of exons with a given splicing impact were predicted to be targets in original knockdown experiment * **Position-wise splicing impacts** indicate which regions around an exon have binding sites expected to affect splicing * **Position-wise target confidence** indicates whether a particular region around the exon strongly contributes to the predicted target confidence. These provide related, but sometimes distinct, predictions of regulation at exons. Which is most useful will depend on the questions and goals. ## Advanced usage: Setting up a weighted collection of PWMs for scoring Some tools may provide multiple PWMs representing the same factor. In the event that you wish to combine these into a single scoring system, you can use the `MultiPWM` class to do so. The results can be saved as a \*.json file and used as the motif model when running KATMAP. Creating a `MultiPWM` object requires passing a list of PWMs and an optional set of weights As example of how to construct a MultiPWM file from a list of PWMs and weights, we'll first load the example RBPamp output: ```python from katmap.seq.summaries import MultiPWM, RBPampAffinityModel psams=RBPampAffinityModel('examples/motifs/HNRNPC.psam') ``` And then pass the stored PWMs to the `pwms` argument and use the associated affinities as weights ```python weights=psams.A0s pwms=psams.PSAMs multipwm=MultiPWM(pwms=pwms, weights=weights) ``` 100%|█████████████████████████████████████████████| 2/2 [00:00<00:00, 14.08it/s] We can now save this as a JSON file. ```python multipwm.to_json('examples/motifs/hnrnpc_multipwm.json') ``` If we use this to score a bit of random sequence, we can see that the MultiPWM we've created assigns the same scores as the original RBPamp model: ```python print (psams.score_sequence('ATCTTTGCGTCTTTTTTGCTTC')) ``` [-24.69196428 -25.77122322 -12.76251952 -19.58498608 -12.56923464 -10.16387869 -5.31042067 -7.03924544 -5.41626584 -17.84586095 -24.6593254 -10.86600743] ```python print(multipwm.score_sequence('ATCTTTGCGTCTTTTTTGCTTC')) ``` [-24.69196428 -25.77122322 -12.76251952 -19.58498608 -12.56923464 -10.16387869 -5.31042067 -7.03924544 -5.41626584 -17.84586095 -24.6593254 -10.86600743] ## Advanced usage: Manually organizing inputs for KATMAP models > An overview of how to use the `FeatureTable` class to organize differential splicing data for use in a KATMAP model To learn a factor's regulatory activity from perturbation data with KATMAP we need several pieces of information about each exon. In particular, we need to know 1. The way in which the exon's inclusion changed after knockdown 1. The coordinates of the splice sites associated with the exon 1. Any additional information associated with the exon we wished to include in the model To organize this information, KATMAP uses a table where each row represents a splicing event and stores all of the necessary information associated with it. All columns of this table can be divided into five categories: 1. `EventInfo`: Stores the coordinates of the splice sites involved in the splicing event 1. `AnalysisInfo`: Information about which exons are part of the training set 1. `Observations`: The direction 1. `LinearPredictors`: Any columns included here can be added to the model as linear features 1. `OtherInfo`: Any additional information you want to keep associated with the exons in the output tables goes here. It will not be used by the model in anyway, but will be included in the output. Because this table needs to be organized properly, KATMAP includes the`FeatureTable` class to facilitate building and working with the table. This can be imported from the `katmap.mikesmaps` submodule: ```python from katmap.mikesmaps import FeatureTable ``` To build a FeatureTable from scratch we need to define the splicing events we intend to model. Under the surface `FeatureTable` is built around a `pandas.DataFrame` with `MultiIndex` columns. This is fundamentally a tab-delimited table where the first two rows are headers. The first row represents `column labels` describing the kind of information stored in each column. KATMAP uses this information when deciding what to do with each column. The second row represents `column names`. ```python df=pd.read_csv('examples/data/HNRNPC_HepG2_FeatureTable.tsv.gz', header=[0,1], #Treat the first and second rows as column names sep='\t') df ```
EventInfo AnalysisInfo Observations LinearPredictors OtherInfo
event_id Chromosome Strand A1 D2 training downreg unchanged upreg phi_ctrl logreads ID GeneID geneSymbol PSI_ctrl PSI_exp dpsi dpsi_lo dpsi_hi dpsi_logodds
0 10993 chr1 - 202735632 202735524 True 0 0 1 -3.460544 1.648360 10993 ENSG00000117139.12 KDM5B 0.030456 0.516833 4.863772e-01 0.276831 0.690166 3.527902
1 12410 chr16 + 89612279 89612438 True 0 0 1 -3.665472 1.846646 12410 ENSG00000197912.9 SPG7 0.024953 0.307901 2.829480e-01 0.157340 0.445328 2.855524
2 13276 chr12 + 56553378 56553406 True 1 0 0 -0.026581 2.131939 13276 ENSG00000092841.14 MYL6 0.493355 0.076416 -4.169391e-01 -0.449995 -0.362138 -2.465487
3 13279 chr12 + 56554409 56554454 True 1 0 0 -1.574076 2.762116 13279 ENSG00000092841.14 MYL6 0.171636 0.038772 -1.328640e-01 -0.144907 -0.115706 -1.636436
4 14249 chr17 + 19576463 19576588 True 0 0 1 -2.565218 2.132740 14249 ENSG00000072210.14 ALDH3A2 0.071411 0.473491 4.020805e-01 0.262103 0.546353 2.459083
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
20296 9958 chr3 - 185404979 185404844 False 0 1 0 7.732123 2.580069 9958 ENSG00000073792.11 IGF2BP2 0.999562 0.999562 -5.663684e-09 -0.999562 0.000438 -0.000013
20297 9967 chr22 - 42914153 42914010 False 0 1 0 3.260544 1.920384 9967 ENSG00000189306.6 RRP7A 0.963050 0.975978 1.292798e-02 -0.628054 0.036645 0.443932
20298 9974 chr6 - 43483439 43483343 False 0 1 0 4.367036 2.382467 9974 ENSG00000137207.7 YIPF3 0.987470 0.987268 -2.020285e-04 -0.109316 0.011333 -0.016200
20299 9990 chr7 + 90034832 90034922 False 0 1 0 6.333145 1.872156 9990 ENSG00000157224.11 CLDN12 0.998227 0.997714 -5.129629e-04 -0.418242 0.001766 -0.254592
20300 9991 chr3 - 98235723 98235643 False 0 1 0 6.011175 1.763428 9991 ENSG00000080822.12 CLDND1 0.997555 0.997539 -1.533581e-05 -0.997555 0.002445 -0.006268

20301 rows × 20 columns

If we already have an appropriately formatted table as a `DataFrame`, we can create a `FeatureTable` directly from it: ```python ft=FeatureTable(df) ``` ### Saving and loading `FeatureTable`s We can save a Feature to a delimited table using the `.to_csv` method: ```python ft.to_csv('00_data/SavedFeatureTable.tsv.gz') ``` We can load a feature table previously saved as a tab-delimited tab with the `.from_cvs` method: ```python ft=FeatureTable.from_csv('examples/data/HNRNPC_HepG2_FeatureTable.tsv.gz') ``` ### Building a `FeatureTable` from rMATS outputs. The simplest way to build a FeatureTable from rMATS outputs is with the `.build_from_rMATS` method, which automatically extracts the coordinates of the splice sites, labels which events are up- or downregulated, constructs the linear predictors from the control PSI values and the total read counts supporting each event, and adds training labels. ```python ft=FeatureTable.build_from_rMATS('examples/data/HNRNPC_HepG2_SE.tsv.gz') ``` Shrinking dpsi estimates... ```python ft.df ```
EventInfo AnalysisInfo Observations ... OtherInfo
event_id Chromosome Strand D1 A1 D2 A2 training downreg unchanged ... PSI_ctrl PSI_exp FDR dpsi dpsi_lo dpsi_hi dpsi_logodds ID GeneID geneSymbol
0 10993 chr1 - 202736053 202735632 202735524 202733273 True 0 0 ... 0.030576 0.511291 0.0 0.480715 0.272186 0.685388 3.501661 10993 ENSG00000117139.12 KDM5B
1 12410 chr16 + 89611180 89612279 89612438 89613065 True 0 0 ... 0.025021 0.303556 0.0 0.278535 0.154327 0.440017 2.832274 12410 ENSG00000197912.9 SPG7
2 13276 chr12 + 56552495 56553378 56553406 56553758 True 1 0 ... 0.49345 0.07997 0.0 -0.413479 -0.447999 -0.356502 -2.416548 13276 ENSG00000092841.14 MYL6
3 13277 chr12 + 56552495 56553370 56553514 56553758 True 1 0 ... 0.992712 0.936208 0.0 -0.056503 -0.098207 -0.030588 -2.227988 13277 ENSG00000092841.14 MYL6
4 13279 chr12 + 56554104 56554409 56554454 56555170 True 1 0 ... 0.171645 0.039468 0.0 -0.132177 -0.14443 -0.11473 -1.617982 13279 ENSG00000092841.14 MYL6
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286 False 0 1 ... 0.761614 0.760274 0.578934 -0.00134 -0.175273 0.114866 -0.007366 9994 ENSG00000080822.12 CLDND1
42912 9995 chr3 - 98241692 98240547 98240496 98240281 False 0 1 ... 0.147391 0.151532 0.574792 0.004141 -0.14727 0.848829 0.032575 9995 ENSG00000080822.12 CLDND1
42913 9996 chr3 - 98241692 98240540 98240496 98240286 False 0 1 ... 0.044401 0.045584 0.774637 0.001183 -0.025133 0.05963 0.027537 9996 ENSG00000080822.12 CLDND1
42914 9997 chr3 - 98241385 98240540 98240496 98240286 False 0 1 ... 0.786168 0.780075 0.406653 -0.006094 -0.605129 0.196564 -0.03588 9997 ENSG00000080822.12 CLDND1
42915 9998 chr3 - 98241692 98240540 98240496 98240281 False 0 1 ... 0.311353 0.30385 0.629284 -0.007502 -0.117159 0.130148 -0.035226 9998 ENSG00000080822.12 CLDND1

42916 rows × 23 columns

The API of this function is as follows:

FeatureTable.build_from_rMATS[source]

> FeatureTable.build_from_rMATS(**`rmats_path`**, **`control_index`**=*`1`*, **`structure`**=*`None`*, **`shrink`**=*`True`*, **`event_class`**=*`'SE'`*, **`sig_method`**=*`'ci'`*, **`alpha`**=*`0.1`*, **`ci_level`**=*`0.94`*, **`training_frac_true`**=*`1`*, **`training_num_false`**=*`5000`*, **`other_columns`**=*`['ID', 'GeneID', 'geneSymbol']`*, **`remove_redundant`**=*`False`*) Construct a FeatureTable from an rMATs table or archive. **** **Arguments:** `rmats_path` (str): The path to the rmats data. `control_index` (0 or 1): Whether the control sample is the first (0) or second (1) condition. `structure` (list or None): Which splice sites to include in the FeatureTable. If `None`, includes all splice sites in the rmats table, `shrink` (bool, default True): Whether to shrink the rMATS effect size estimates with ashr `event_class` (str, one of 'SE', 'A3SS', 'A5SS', 'MXE', 'RI': The class of rMATS events to build the FeatureTable for. `sig_method` (str): The method used to define significant events. If 'ci', the events are called significant if a credibility interval defined based on the ashr shrunk effect size and standard error does not overlap zero. If 'fdr', the FDR-corrected p-values from the rMATS table are used to define significant events. `alpha` (0 < float < 1): The FDR cutoff used to define significance when `sig_method='fdr'`. `ci_level` (0 < float < 1): The credibility level used to define significance when `sig_method='ci'`. `training_frac_true` (0 < float < 1): The fraction of significant events to include in the training set. `training_num_true` (int): The maximum number of nonsignificant events to include in the training set. `other_columns` (list of strings): The names of columns in the rMATS table to include as additional info. `filter_redundant` (bool): Whether to filter out overlapping splicing events. **** **Returns:** A FeatureTable **** ### Building a `FeatureTable` manually In many cases, we'll need to create the table manually. Because KATMAP has requirements for how this table is structured, the `FeatureTable` class has a number of utility functions for simplifying this process. The most important category of columns are under the `EventInfo` label, which describes the coordinates of the splice sites associated with each splicing event. This must contain the following columns 1. `event_id`: A unique identifier for each row (for example, arbitrary numbers such as 1,2,3... or in the case of rMATS or MAJIQ output, the ID assigned to the splicing event) 1. `Chromosome`: The reference chromosome on which the exons are located (matching the reference to which the data was aligned) 1. `Strand`: The strand of the chromosome on which the exons are located 1. `{A/D}{1/2/3..}`: Additional columns indicating the coordinates of each splice site associated with the splicing events. The columns should be named in the following format `D1`, `A1`, `D2`, `A2`, etc. where "D" denotes donor/5SS and "A" denotes acceptor/3SS. The numbers indicate the order of the donor and acceptors sites, beginning with the most promoter proximal. That is, D1 denotes the first donor in the splicing event (from 5' (TSS) -> 3' (TES)), D2 denotes the second, and so forth. The coordinates stored in the columns are assumed to be base 0 and to represent the exonic nucleotide adjacent to the splice site. If this information is already available, a FeatureTable storing only the `EventInfo` can be constructed as before. Add schematic ```python eventinfo=ft.event_info eventinfo ```
event_id Chromosome Strand D1 A1 D2 A2
0 10993 chr1 - 202736053 202735632 202735524 202733273
1 12410 chr16 + 89611180 89612279 89612438 89613065
2 13276 chr12 + 56552495 56553378 56553406 56553758
3 13277 chr12 + 56552495 56553370 56553514 56553758
4 13279 chr12 + 56554104 56554409 56554454 56555170
... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286
42912 9995 chr3 - 98241692 98240547 98240496 98240281
42913 9996 chr3 - 98241692 98240540 98240496 98240286
42914 9997 chr3 - 98241385 98240540 98240496 98240286
42915 9998 chr3 - 98241692 98240540 98240496 98240281

42916 rows × 7 columns

We need to tell the `FeatureTable` that these columns represent `EventInfo`, so we need to update the columns to a `pandas.MultiIndex` with `EventInfo` as the top level: ```python eventinfo.columns=pd.MultiIndex.from_tuples([('EventInfo', colname) for colname in eventinfo.columns]) eventinfo ```
EventInfo
event_id Chromosome Strand D1 A1 D2 A2
0 10993 chr1 - 202736053 202735632 202735524 202733273
1 12410 chr16 + 89611180 89612279 89612438 89613065
2 13276 chr12 + 56552495 56553378 56553406 56553758
3 13277 chr12 + 56552495 56553370 56553514 56553758
4 13279 chr12 + 56554104 56554409 56554454 56555170
... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286
42912 9995 chr3 - 98241692 98240547 98240496 98240281
42913 9996 chr3 - 98241692 98240540 98240496 98240286
42914 9997 chr3 - 98241385 98240540 98240496 98240286
42915 9998 chr3 - 98241692 98240540 98240496 98240281

42916 rows × 7 columns

Now we can build a (mostly empty) `FeatureTable` from this dataframe: ```python ft=FeatureTable(eventinfo) ft.df ```
EventInfo
event_id Chromosome Strand D1 A1 D2 A2
0 10993 chr1 - 202736053 202735632 202735524 202733273
1 12410 chr16 + 89611180 89612279 89612438 89613065
2 13276 chr12 + 56552495 56553378 56553406 56553758
3 13277 chr12 + 56552495 56553370 56553514 56553758
4 13279 chr12 + 56554104 56554409 56554454 56555170
... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286
42912 9995 chr3 - 98241692 98240547 98240496 98240281
42913 9996 chr3 - 98241692 98240540 98240496 98240286
42914 9997 chr3 - 98241385 98240540 98240496 98240286
42915 9998 chr3 - 98241692 98240540 98240496 98240281

42916 rows × 7 columns

```python eventinfo=ft.df['EventInfo'] ft=FeatureTable(eventinfo) ``` ### Building from splice site coordinates Alternatively, we can build a new FeatureTable from a set of splice site coordinates. Here we need a table where each row represents a splice site's coordinate and indicates which splicing event it belongs to. The dataframe of splice site coordinates should have the following columns: 1. `ID`: Stores a numerical ID indicating which splicing event a given splice site is associated with. 1. `Feature`: Indicates which kind of splice site the row represents. The format is `{D/A}{#}` where `A` denotes an acceptor/3ss (e.g. `A1`, `A2`, ...) and `D` denotes a donor/5ss (e.g. `D1`, `D2`, ...). The numbers indicate the order of splice sites in the event, starting with the most promoter proximal splice sites (i.e `D1` and `A1`) 1. `Chromosome`: The chromosome where the splice site is located. 1. `Strand`: The strand of the splice site. 1. `Start`: The coordinate of the first exonic position adjacent to the splice site (base 0) If we use `spliceformats` to load rMATS results, the required table of splice sites can be found in each of the `rmatsEvents` attributes (`SE`, `A3SS`, etc.) ```python from spliceformats.readMATS import read_rmats rmats_data=read_rmats('examples/data/HNRNPC_HepG2_SE.tsv.gz') rmats_data.SE.splicesite_info ```
ID Feature Chromosome Strand Start End
0 10993 D1 chr1 - 202736053 202736054
1 10993 A1 chr1 - 202735632 202735633
2 10993 D2 chr1 - 202735524 202735525
3 10993 A2 chr1 - 202733273 202733274
4 12410 D1 chr16 + 89611180 89611181
... ... ... ... ... ... ...
171659 9997 A2 chr3 - 98240286 98240287
171660 9998 D1 chr3 - 98241692 98241693
171661 9998 A1 chr3 - 98240540 98240541
171662 9998 D2 chr3 - 98240496 98240497
171663 9998 A2 chr3 - 98240281 98240282

171664 rows × 6 columns

There are four main points to note. First, each row represents a splice site and describes its genomic coordinates. Second, the `Feature` column indicates the kind of splice site. Third, the `ID` column indicates which splicing event the splice site belongs to. For example, the first four rows all belong to the same splicing event. Finally, this data structure is the same format used by the `RNAmap` class to build an RNAmap for organizing information around splice sites and splicing events. If we want to build a `FeatureTable` around these splicing events, we can use the `FeatureTable.from_coordinates` method: ```python ft=FeatureTable.from_coordinates(rmats_data.SE.splicesite_info) ft.df ```
EventInfo
event_id Chromosome Strand D1 A1 D2 A2
0 10993 chr1 - 202736053 202735632 202735524 202733273
1 12410 chr16 + 89611180 89612279 89612438 89613065
2 13276 chr12 + 56552495 56553378 56553406 56553758
3 13277 chr12 + 56552495 56553370 56553514 56553758
4 13279 chr12 + 56554104 56554409 56554454 56555170
... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286
42912 9995 chr3 - 98241692 98240547 98240496 98240281
42913 9996 chr3 - 98241692 98240540 98240496 98240286
42914 9997 chr3 - 98241385 98240540 98240496 98240286
42915 9998 chr3 - 98241692 98240540 98240496 98240281

42916 rows × 7 columns

#### Building from a *.bed file We can also build a table of splicesites from a bed file storing exons coordinates. For example, if we load in a bed file storing the first 50,000 exons in the human genome: ```python bed_table=pd.read_csv('examples/data/hg19GencodeV46_first50000.bed.gz', sep='\t', header=None) bed_table ```
0 1 2 3 4 5
0 chr1 66999043 66999090 NM_001376549.1_exon_0_0_chr1_66999044_f 0 +
1 chr1 66999928 67000051 NM_001376549.1_exon_1_0_chr1_66999929_f 0 +
2 chr1 67091529 67091593 NM_001376549.1_exon_2_0_chr1_67091530_f 0 +
3 chr1 67098752 67098777 NM_001376549.1_exon_3_0_chr1_67098753_f 0 +
4 chr1 67101626 67101698 NM_001376549.1_exon_4_0_chr1_67101627_f 0 +
... ... ... ... ... ... ...
49995 chr1 24996610 24996806 NM_001366582.1_exon_14_0_chr1_24996611_f 0 +
49996 chr1 24997876 24998086 NM_001366582.1_exon_15_0_chr1_24997877_f 0 +
49997 chr1 24998672 24999772 NM_001366582.1_exon_16_0_chr1_24998673_f 0 +
49998 chr1 24969792 24969838 NM_001366569.1_exon_0_0_chr1_24969793_f 0 +
49999 chr1 24972474 24972564 NM_001366569.1_exon_1_0_chr1_24972475_f 0 +

50000 rows × 6 columns

We can use `bed2splicesiteinfo` to generate the required table of splice site coordinates: ```python from katmap.rnamap import bed2splicesiteinfo bed_table=pd.read_csv('examples/data/hg19GencodeV46_first50000.bed.gz', sep='\t', header=None) ss_info_from_bed=bed2splicesiteinfo(bed_table) ss_info_from_bed ```
ID Feature Chromosome Strand Start End
0 0 A1 chr1 + 66999043 66999044
1 0 D2 chr1 + 66999090 66999091
2 1 A1 chr1 + 66999928 66999929
3 1 D2 chr1 + 67000051 67000052
4 2 A1 chr1 + 67091529 67091530
... ... ... ... ... ... ...
99995 49997 D2 chr1 + 24999772 24999773
99996 49998 A1 chr1 + 24969792 24969793
99997 49998 D2 chr1 + 24969838 24969839
99998 49999 A1 chr1 + 24972474 24972475
99999 49999 D2 chr1 + 24972564 24972565

100000 rows × 6 columns

which we could pass to `FeatureTable.from_coordinates`. ## Adding to the `FeatureTable` The `FeatureTable` class has a utility method for adding columns to the underlying dataframe. These both update the dataframe (`FeatureTable.df`) and all internal attributes that depend on the dataframe. ****

FeatureTable.add_column[source]

> FeatureTable.add_column(**`label`**=*`''`*, **`colname`**=*`''`*, **`values`**=*`[]`*, **`replace`**=*`False`*) Utility function for adding a single column to a particular category. **** **Arguments:** `label` (str): The category of information to which the columns will be added. Should be one of `EventInfo`, `AnalysisInfo`, `Observations`,`LinearPredictors`, `OtherInfo`. `values` (list or array): The values to be added to the FeatureTable. `colname` (str): The name of the column to be added. **** ### Adding `Observations` Columns labelled`Observations` describe the splicing changes to be modelled. KATMAP models the direction of splicing changes, so `Observations` should contain three columns: `downreg`, `unchanged`, and `upreg`. However, `FeatureTable` has a method `add_observations` which simplifies this

FeatureTable.add_observations[source]

> FeatureTable.add_observations(**`values`**=*`[]`*, **`colnames`**=*`[]`*, **`kind`**=*`'direction'`*, **`replace`**=*`False`*) Utility function for adding columns under Observations. **** **Arguments:** `values` (list, array, or pandas.DataFrame): The values to be added to the FeatureTable. `colnames` (list): The names of the columns to be added. Must be provided if `values` is not a DataFrame. If `values` is a DataFrame and `colnames` is not provided, the column names from `values` will be used; if `colnames` is provided it will be used instead of `values.columns`. `kind` (str): If `values` is an array of {-1, 0, 1}, setting `kind='direction'` will automatically convert the observations to the required table of one-hot encoded categories. **** For example, we might define exons as significantly differentially spliced base on whether the rMATS FDR-corrected p-value is less than $0.1$, and construct an array denoting significantly downregulated exons with `-1`, unchanged exons with `0`, and upregulated exons with `1`. ```python is_sig=rmats_data.SE.fdr<0.1 sign_of_dpsi=np.sign(rmats_data.SE.dpsi) direction=is_sig*sign_of_dpsi direction ``` array([ 1., 1., -1., ..., 0., -0., -0.]) We can add these observations to the model by passing the array of directions to `FeatureTable.add_observations` ```python ft.add_observations(direction) ``` This automatically converts the directions to a table of one-hot encoded categories ```python ft.df ```
EventInfo Observations
event_id Chromosome Strand D1 A1 D2 A2 downreg unchanged upreg
0 10993 chr1 - 202736053 202735632 202735524 202733273 0 0 1
1 12410 chr16 + 89611180 89612279 89612438 89613065 0 0 1
2 13276 chr12 + 56552495 56553378 56553406 56553758 1 0 0
3 13277 chr12 + 56552495 56553370 56553514 56553758 1 0 0
4 13279 chr12 + 56554104 56554409 56554454 56555170 1 0 0
... ... ... ... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286 0 1 0
42912 9995 chr3 - 98241692 98240547 98240496 98240281 0 1 0
42913 9996 chr3 - 98241692 98240540 98240496 98240286 0 1 0
42914 9997 chr3 - 98241385 98240540 98240496 98240286 0 1 0
42915 9998 chr3 - 98241692 98240540 98240496 98240281 0 1 0

42916 rows × 10 columns

If we wanted to change how we define splicing changes--for example calling an event significant if the 94\% credibility interval over dPSI is entirely less than or greater than zero--we can overwrite the values in the table by setting the `replace` argument to `True`. ```python ci_lo=rmats_data.SE.dpsi_lo ci_hi=rmats_data.SE.dpsi_hi direction=np.sign(ci_hi)*(np.sign(ci_hi)==np.sign(ci_lo)) ft.add_observations(direction, replace=True) ``` ### Adding training labels The `AnalysisInfo` label is used to indicate which events should be used in training. Only one column under the label `AnalysisInfo` will be used by the model: 1. `training`: Should contain `True`/`False` values indicate which events will be used in training. When a `FeatureTable` is first created, all observations are treated as part of the training set. Inference, however, may be substantially slower when all data points are included. We can use the `FeatureTable.add_training_labels` method to reduce the size of the training set. ****

FeatureTable.add_training_labels[source]

> FeatureTable.add_training_labels(**`true_frac`**=*`1.0`*, **`num_false`**=*`5000`*, **`nonsig_ind`**=*`1`*, **`filter_label`**=*`None`*, **`filter_column`**=*`None`*, **`replace`**=*`True`*, **\*`args`**, **\*\*`kwargs`**) Add labels defining which observations belong to the training set. **** **Arguments:** `observations` (N-length array): The observations for which the training labels will be defined. The second column is assumed to represent. `true_frac`: The fraction of differentially spliced events to include in the training set. If `true_frac=1.0` all significant events will receive a training label of `True`. If `true_frac=0.5` half of the significant events (rounded down to the nearest integer) will receive a training label of `True`. `num_false`: The maximum number of nonsignificant events to include in the training set. `filter_label`, `filter_column (str; Default: None): Optionally, label and column pair pointing to a set of True/False values used to apply an additional filter to the splicing events before constructing the training set. If provided, only splicing events labelled True will be included in the training set. **** The default behavior of `FeatureTable.add_training_labels` is to include all significant events, but downsample the number of nonsignificant events to a maximum of 5000 events: ```python ft.add_training_labels() print(ft.df['Observations'][ft.training_labels].sum(0)) ``` downreg 2266 unchanged 5000 upreg 1702 dtype: int64 However, we can adjust the fraction of significant events included using the `true_frac` argument (for example, to hold exons to check for overfitting) or the maximum number of significant events with the `num_false` argument (to speed up model inference): ```python ft.add_training_labels(true_frac=.5, num_false=2000) print(ft.df['Observations'][ft.training_labels].sum(0)) ``` downreg 1118 unchanged 2000 upreg 866 dtype: int64 ### Adding `LinearPredictors` The columns stored under `LinearPredictors` can be used as linear features by the KATMAP model. There are no required columns, but any columns included under this label can be referenced in the model configuration file to be included in the model as linear features. When working with rMATS outputs, KATMAP includes the control inclusion level (in log-odds scale) and the log10 read counts of each event as predictors by default. If we wished to do this manually, we would first construct a dictionary (or `pandas.DataFrame`) storing this information: ```python lin_predictors={'phi_ctrl':rmats_data.SE.phi[rmats_data.SE.ctrl_idx], 'logreads':np.log10(rmats_data.SE.totalreads)} lin_predictors # ``` {'phi_ctrl': array([-3.45648839, -3.66269545, -0.0262033 , ..., -3.06908021, 1.30198174, -0.79380255]), 'logreads': array([1.64836001, 1.84664633, 2.1319393 , ..., 1.87069646, 0.77815125, 0.54406804])} And then add it to the `FeatureTable` using `FeatureTable.add_linear_predictors`: ```python ft.add_linear_predictors(lin_predictors, replace=True) ``` ```python ft.df ```
EventInfo AnalysisInfo Observations LinearPredictors
event_id Chromosome Strand D1 A1 D2 A2 training downreg unchanged upreg phi_ctrl logreads
0 10993 chr1 - 202736053 202735632 202735524 202733273 False 0 0 1 -3.456488 1.648360
1 12410 chr16 + 89611180 89612279 89612438 89613065 False 0 0 1 -3.662695 1.846646
2 13276 chr12 + 56552495 56553378 56553406 56553758 False 1 0 0 -0.026203 2.131939
3 13277 chr12 + 56552495 56553370 56553514 56553758 True 1 0 0 4.914206 3.700617
4 13279 chr12 + 56554104 56554409 56554454 56555170 True 1 0 0 -1.574010 2.762116
... ... ... ... ... ... ... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286 False 0 1 0 1.161546 0.778151
42912 9995 chr3 - 98241692 98240547 98240496 98240281 False 0 1 0 -1.755214 0.477121
42913 9996 chr3 - 98241692 98240540 98240496 98240286 False 0 1 0 -3.069080 1.870696
42914 9997 chr3 - 98241385 98240540 98240496 98240286 False 0 1 0 1.301982 0.778151
42915 9998 chr3 - 98241692 98240540 98240496 98240281 False 0 1 0 -0.793803 0.544068

42916 rows × 13 columns

If we wanted to add the lengths of the introns and exons as potential linear predictors, we could do so by first computing these lengths and storing them as a dataframe: ```python log_lengths=np.log2(pd.DataFrame.from_dict({'us_intron_log2length':(np.abs(ft.event_info['D1'].values-ft.event_info['A1'].values)), 'exon_log2length':(np.abs(ft.event_info['D2'].values-ft.event_info['A1'].values)), 'ds_intron_log2length':(np.abs(ft.event_info['D2'].values-ft.event_info['A2'].values))}, dtype=float)) ``` And then adding these as linear predictors ```python ft.add_linear_predictors(log_lengths, replace=True) ``` ```python ft.linear_predictors ```
phi_ctrl logreads us_intron_log2length exon_log2length ds_intron_log2length
0 -3.456488 1.648360 8.717676 6.754888 11.136350
1 -3.662695 1.846646 10.101976 7.312883 9.292322
2 -0.026203 2.131939 9.786270 4.807355 8.459432
3 4.914206 3.700617 9.773139 7.169925 7.930737
4 -1.574010 2.762116 8.252665 5.491853 9.483816
... ... ... ... ... ...
42911 1.161546 0.778151 9.710806 5.672425 7.714246
42912 -1.755214 0.477121 10.161132 5.672425 7.748193
42913 -3.069080 1.870696 10.169925 5.459432 7.714246
42914 1.301982 0.778151 9.722808 5.459432 7.714246
42915 -0.793803 0.544068 10.169925 5.459432 7.748193

42916 rows × 5 columns

### Adding `OtherInfo` Finally, we can use the `OtherInfo` label to add information that will not be used by the KATMAP model during inference, but will be carried forward in its output tables. ```python other_info={'fdr':rmats_data.SE.fdr, 'pval':rmats_data.SE.fdr, 'dpsi':rmats_data.SE.dpsi, 'psi1':rmats_data.SE.psi1, 'psi2':rmats_data.SE.psi2,} ``` ```python ft.add_other_info(other_info) ``` ```python ft.df ```
EventInfo AnalysisInfo Observations ... LinearPredictors OtherInfo
event_id Chromosome Strand D1 A1 D2 A2 training downreg unchanged ... phi_ctrl logreads us_intron_log2length exon_log2length ds_intron_log2length fdr pval dpsi psi1 psi2
0 10993 chr1 - 202736053 202735632 202735524 202733273 False 0 0 ... -3.456488 1.648360 8.717676 6.754888 11.136350 0.0 0.0 0.573041 0.603617 0.030576
1 12410 chr16 + 89611180 89612279 89612438 89613065 False 0 0 ... -3.662695 1.846646 10.101976 7.312883 9.292322 0.0 0.0 0.324991 0.350012 0.025021
2 13276 chr12 + 56552495 56553378 56553406 56553758 False 1 0 ... -0.026203 2.131939 9.786270 4.807355 8.459432 0.0 0.0 -0.429276 0.064174 0.493450
3 13277 chr12 + 56552495 56553370 56553514 56553758 True 1 0 ... 4.914206 3.700617 9.773139 7.169925 7.930737 0.0 0.0 -0.068893 0.923819 0.992712
4 13279 chr12 + 56554104 56554409 56554454 56555170 True 1 0 ... -1.574010 2.762116 8.252665 5.491853 9.483816 0.0 0.0 -0.134989 0.036657 0.171645
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
42911 9994 chr3 - 98241385 98240547 98240496 98240286 False 0 1 ... 1.161546 0.778151 9.710806 5.672425 7.714246 1.0 1.0 -0.003913 0.757700 0.761614
42912 9995 chr3 - 98241692 98240547 98240496 98240281 False 0 1 ... -1.755214 0.477121 10.161132 5.672425 7.748193 1.0 1.0 0.131768 0.279158 0.147391
42913 9996 chr3 - 98241692 98240540 98240496 98240286 False 0 1 ... -3.069080 1.870696 10.169925 5.459432 7.714246 1.0 1.0 0.006410 0.050811 0.044401
42914 9997 chr3 - 98241385 98240540 98240496 98240286 False 0 1 ... 1.301982 0.778151 9.722808 5.459432 7.714246 1.0 1.0 -0.038209 0.747959 0.786168
42915 9998 chr3 - 98241692 98240540 98240496 98240281 False 0 1 ... -0.793803 0.544068 10.169925 5.459432 7.748193 1.0 1.0 -0.022409 0.288943 0.311353

42916 rows × 21 columns

### Flagging overlapping splicing events Some differentially splicing frameworks will report overlapping exons as distinct splicing events. Including these overlapping exons in the training data might allow some exon sequences too much influence on the conclusions of inference. `FeatureTable.select_overlapping_events` can used to identify groups of overlapping events and select one event from each cluster based on the value of a specified column in the `FeatureTable`.

FeatureTable.select_overlapping_events[source]

> FeatureTable.select_overlapping_events(**`boundaries`**=*`None`*, **`selection_label`**=*`None`*, **`selection_column`**=*`None`*, **`method`**=*`'min'`*, **`replace`**=*`True`*) Identify groups of events that overlap and select one splicing event from each cluster. Adds two columns to `OtherInfo`: 1. `SelectedFromCluster` (bool): True/False labels indicating whether the splicing event was selected from among the overlapping events in its cluster 1. `ClusterID`: An ID indicating which cluster a splicing event overlaps with. **** **Arguments:** `boundaries` (list of two ): Which two columns in `EventInfo` will be used to define the boundaries of events when checking for overlaps. For cassette exons, choosing `['A1', 'D2']` will groups events where the cassette exons overlap. Choosing `['D1', 'A2']` is a more stringent filter, grouping together splicing events where the exons or flanking introns overlap. `selection_label`, `selection_column` (str): The label and name of the column that will be used to select among overlapping events. `method` (str): The method by which events will be selected from overlapping clusters. If not specified, events will be selected randomly. Options are: 1. `min`: Choose the event in the cluster with the smallest value in `df[(selection_label,selection_column)] 1. `max`: Choose the event in the cluster with the largest value in `df[(selection_label,selection_column)] 1. `absmin`: Choose the event in the cluster with the smallest absolute value in `df[(selection_label,selection_column)] 1. `absmax`: Choose the event in the cluster with the largest absolute value in `df[(selection_label,selection_column)] **** This adds tow additional columns to `OtherInfo`: `SelectedFromCluster ```python ft.select_overlapping_events(boundaries=['D1','A2']) ft.other_info ```
fdr pval dpsi psi1 psi2 SelectedFromCluster ClusterID
0 0.0 0.0 0.573041 0.603617 0.030576 False 1816
1 0.0 0.0 0.324991 0.350012 0.025021 False 15175
2 0.0 0.0 -0.429276 0.064174 0.493450 False 11977
3 0.0 0.0 -0.068893 0.923819 0.992712 False 11977
4 0.0 0.0 -0.134989 0.036657 0.171645 True 11978
... ... ... ... ... ... ... ...
42911 1.0 1.0 -0.003913 0.757700 0.761614 False 4551
42912 1.0 1.0 0.131768 0.279158 0.147391 False 4551
42913 1.0 1.0 0.006410 0.050811 0.044401 False 4551
42914 1.0 1.0 -0.038209 0.747959 0.786168 False 4551
42915 1.0 1.0 -0.022409 0.288943 0.311353 False 4551

42916 rows × 7 columns

If we don't specify a selection column, one row will be selected randomly from among each group of overlapping events. We might instead want to select the exon with lowest FDR adjusted p-value from each cluster ```python ft.select_overlapping_events(boundaries=['D1','A2'], selection_label='OtherInfo', selection_column='fdr', ) ft.other_info ```
fdr pval dpsi psi1 psi2 SelectedFromCluster ClusterID
0 0.0 0.0 0.573041 0.603617 0.030576 True 1816
1 0.0 0.0 0.324991 0.350012 0.025021 True 15175
2 0.0 0.0 -0.429276 0.064174 0.493450 True 11977
3 0.0 0.0 -0.068893 0.923819 0.992712 False 11977
4 0.0 0.0 -0.134989 0.036657 0.171645 True 11978
... ... ... ... ... ... ... ...
42911 1.0 1.0 -0.003913 0.757700 0.761614 False 4551
42912 1.0 1.0 0.131768 0.279158 0.147391 False 4551
42913 1.0 1.0 0.006410 0.050811 0.044401 False 4551
42914 1.0 1.0 -0.038209 0.747959 0.786168 False 4551
42915 1.0 1.0 -0.022409 0.288943 0.311353 False 4551

42916 rows × 7 columns

We can pass this column to `FeatureTable.add_training_labels` to ensure that the training set is only built from these exons: ```python ft.add_training_labels(true_frac=1, num_false=2000, ) print(ft.df['Observations'][ft.training_labels].sum(0)) ``` downreg 2266 unchanged 2000 upreg 1702 dtype: int64 ```python ft.add_training_labels(true_frac=1, num_false=2000, filter_label='OtherInfo', filter_column='SelectedFromCluster') print(ft.df['Observations'][ft.training_labels].sum(0)) ``` downreg 1519 unchanged 2000 upreg 1247 dtype: int64 ## Building a FeatureTable from MAJIQ modularize outputs MAJIQ models inclusion differently than rMATS. While rMATS aims to directly estimate the inclusion of an exon segment (assumed to fall into one of five predefined event structures), MAJIQ estimates the usage of splice sites conditioned on some fixed splice sites. So for a cassette exon, MAJIQ reports two separate inclusion estimates: one for the junction with the upstream flanking exon and one for the downstream flanking exon. To prepare MAJIQ outputs for analysis with KATMAP, we'll begin with the results of the MAJIQ's (v2.6) modularize function, which groups together splice sites representing the same event (e.g. cassette exon). ```python majiq_df=pd.read_csv('examples/data/HNRNPC_HepG2_hg38_MAJIQ_Cassette_modularize.tsv', sep='\t', comment='#') #Ignore lines beginning with "#" ``` ```python majiq_df.columns ``` Index(['module_id', 'gene_id', 'gene_name', 'seqid', 'strand', 'lsv_id', 'event_id', 'complex', 'denovo', 'reference_exon_coord', 'spliced_with', 'spliced_with_coord', 'junction_name', 'junction_coord', 'event_size', 'event_non_changing', 'event_changing', 'junction_changing', 'Control_median_reads', 'Experimental_median_reads', 'Control_median_psi', 'Experimental_median_psi', 'Experimental-Control_median_dpsi', 'Experimental-Control_probability_changing', 'Experimental-Control_probability_non_changing'], dtype='object') Each splice junction will be assigned an inclusion estimate. For cassette exons, MAJIQ labels the two flanking exons as C1 and C2, and the alternative exon A. We'll pull out the rows corresponding to the two junctions with alternative exon "C1_A" and "C2_A" ```python sel_df=majiq_df[np.isin(majiq_df['junction_name'].values,['C1_A','C2_A'])] ``` The coordinates of the cassette exon are in the `spliced_with_coord` column, and formatted as `{left}-{right}`. We'll first create a small table describing the coordinates of every cassette exon in the table ```python coord_dict={'Chromosome':sel_df['seqid'], 'Strand':sel_df['strand'], 'Start':[int(val.split('-')[0]) for val in sel_df['spliced_with_coord'].values], 'End':[int(val.split('-')[1]) for val in sel_df['spliced_with_coord'].values], } coord_df=pd.DataFrame.from_dict(coord_dict) coord_df ```
Chromosome Strand Start End
1 chr21 - 29008240 29008307
3 chr21 - 29008240 29008307
5 chr3 + 40529319 40529445
7 chr3 + 40529319 40529445
9 chr10 + 63150134 63150356
... ... ... ... ...
20587 chr4 - 151165589 151165696
20589 chr4 - 151144220 151144288
20591 chr4 - 151144220 151144288
20593 chr4 - 151672762 151672896
20595 chr4 - 151672762 151672896

10298 rows × 4 columns

Then we'll convert this table to a set of splice site coordinates that labels each splice sites as either A1 or D2 and indicates which splicing event they represent with an `event_id`. We can then build a FeatureTable around them: ```python ss_info=bed2splicesiteinfo(coord_df, chrom_col=0, strand_col=1, start_col=2, end_col=3) ft=FeatureTable.from_coordinates(ss_info) ft.df ```
EventInfo
event_id Chromosome Strand A1 D2
0 0 chr21 - 29008307 29008240
1 1 chr21 - 29008307 29008240
2 2 chr3 + 40529319 40529445
3 3 chr3 + 40529319 40529445
4 4 chr10 + 63150134 63150356
... ... ... ... ... ...
10293 10293 chr4 - 151165696 151165589
10294 10294 chr4 - 151144288 151144220
10295 10295 chr4 - 151144288 151144220
10296 10296 chr4 - 151672896 151672762
10297 10297 chr4 - 151672896 151672762

10298 rows × 5 columns

Note that the feature table has the same shape as `sel_df`. Next, we'll add the observations for each event. We'll consider events significant if there is $>0.95$ posterior probability that $|\psi|>0.05$. (users should choose the degree of confidence they desire) . This is stored in the column `Experimental-Control_probability_changing`, and we can get the direction of the splicing from the column `Experimental-Control_median_dpsi` ```python dpsi=sel_df['Experimental-Control_median_dpsi'].values prob_changing=sel_df['Experimental-Control_probability_changing'].values direction=np.sign(dpsi)*(prob_changing>.95) ft.add_observations(direction) ft.df ```
EventInfo Observations
event_id Chromosome Strand A1 D2 downreg unchanged upreg
0 0 chr21 - 29008307 29008240 0 1 0
1 1 chr21 - 29008307 29008240 0 1 0
2 2 chr3 + 40529319 40529445 0 1 0
3 3 chr3 + 40529319 40529445 0 1 0
4 4 chr10 + 63150134 63150356 0 0 1
... ... ... ... ... ... ... ... ...
10293 10293 chr4 - 151165696 151165589 0 1 0
10294 10294 chr4 - 151144288 151144220 0 1 0
10295 10295 chr4 - 151144288 151144220 0 1 0
10296 10296 chr4 - 151672896 151672762 0 1 0
10297 10297 chr4 - 151672896 151672762 0 1 0

10298 rows × 8 columns

Note that each exon is assigned two observations: this is because MAJIQ computes the inclusion change for the junctions with up- and downstream flanking exons separately, rather than the single dPSI estimated by rMATS. Now we need to add any linear features we wish to include in the model. As with the rMATS model, the control inclusion level (in log-odds scale) and the number of reads supported the splice junctions (in log-scale) will likely be predictive of whether a significant change was detected. So we'll grab that information and add it as `LinearPredictors` ```python import scipy.special as sp import numpy as np lin_pred={'phi_ctrl':sp.logit(sel_df['Control_median_psi'] .values), 'logreads': np.log10(sel_df['Control_median_reads'].fillna(0).values+ #Note, junctions absent from one condition are assigned nan sel_df['Experimental_median_reads'].fillna(0).values)} ft.add_linear_predictors(lin_pred) ft.df ```
EventInfo Observations LinearPredictors
event_id Chromosome Strand A1 D2 downreg unchanged upreg phi_ctrl logreads
0 0 chr21 - 29008307 29008240 0 1 0 1.376324 1.643453
1 1 chr21 - 29008307 29008240 0 1 0 1.503527 1.819544
2 2 chr3 + 40529319 40529445 0 1 0 0.272473 1.255273
3 3 chr3 + 40529319 40529445 0 1 0 0.462470 1.414973
4 4 chr10 + 63150134 63150356 0 0 1 -4.105784 1.041393
... ... ... ... ... ... ... ... ... ... ...
10293 10293 chr4 - 151165696 151165589 0 1 0 2.613101 2.264818
10294 10294 chr4 - 151144288 151144220 0 1 0 -0.777773 1.770852
10295 10295 chr4 - 151144288 151144220 0 1 0 -1.465681 1.579784
10296 10296 chr4 - 151672896 151672762 0 1 0 3.038880 2.127105
10297 10297 chr4 - 151672896 151672762 0 1 0 2.250574 1.977724

10298 rows × 10 columns

For the sake of completeness, we'll add most of the other columns present in the MAJIQ output as `OtherInfo` ```python other_cols=['Control_median_psi','Experimental_median_psi','Experimental-Control_median_dpsi', 'Experimental-Control_probability_changing','Experimental-Control_probability_non_changing', 'lsv_id', 'event_id', 'complex', 'denovo', 'reference_exon_coord', 'spliced_with', 'spliced_with_coord', 'junction_name', 'junction_coord', 'event_size', 'event_non_changing', 'event_changing', 'junction_changing'] ft.add_other_info(sel_df[other_cols]) ``` ```python ft.df[:10] ```
EventInfo Observations LinearPredictors ... OtherInfo
event_id Chromosome Strand A1 D2 downreg unchanged upreg phi_ctrl logreads ... denovo reference_exon_coord spliced_with spliced_with_coord junction_name junction_coord event_size event_non_changing event_changing junction_changing
0 0 chr21 - 29008307 29008240 0 1 0 1.376324 1.643453 ... False 29008395-29008621 A 29008240-29008307 C1_A 29008307-29008395 68 False False False
1 1 chr21 - 29008307 29008240 0 1 0 1.503527 1.819544 ... False 29007761-29008123 A 29008240-29008307 C2_A 29008123-29008240 68 False False False
2 2 chr3 + 40529319 40529445 0 1 0 0.272473 1.255273 ... False 40525779-40525864 A 40529319-40529445 C1_A 40525864-40529319 127 False False False
3 3 chr3 + 40529319 40529445 0 1 0 0.462470 1.414973 ... False 40530209-40530316 A 40529319-40529445 C2_A 40529445-40530209 127 False False False
4 4 chr10 + 63150134 63150356 0 0 1 -4.105784 1.041393 ... True 63146209-63146293 A 63150134-63150356 C1_A 63146293-63150134 223 False False True
5 5 chr10 + 63150134 63150356 0 0 1 -3.256613 1.041393 ... True 63152150-63152190 A 63150134-63150356 C2_A 63150356-63152150 223 False False True
6 6 chr10 - 63219983 63219878 0 1 0 0.536509 1.591065 ... False 63264651-63264764 A 63219878-63219983 C1_A 63219983-63264651 106 False False False
7 7 chr10 - 63219983 63219878 0 1 0 0.087656 1.491362 ... False 63217207-63217331 A 63219878-63219983 C2_A 63217331-63219878 106 False False False
8 8 chr10 + 67906163 67906287 0 1 0 -2.302453 0.903090 ... False 67891402-67891554 A 67906163-67906287 C1_A 67891554-67906163 125 False False False
9 9 chr10 + 67906163 67906287 0 1 0 -1.923246 1.000000 ... False 67906790-67906937 A 67906163-67906287 C2_A 67906287-67906790 125 False False False

10 rows × 28 columns

Finally, for a handful of splice junctions, no inclusion change was measured. We need to filter those out: ```python print (f'{np.isnan(dpsi).sum()} nans') print (f'{np.isinf(dpsi).sum()} infs') ft=ft[(~np.isnan(dpsi))&(~np.isinf(dpsi))] ``` 69 nans 0 infs Now, we can add training labels and save the table as a tab-delimited file ```python ft.add_training_labels() ft.df.to_csv('examples/data/HNRNPC_hepg2_majiq_features.tsv', sep='\t', index=None) ``` This is ready to be used as input features for a KATMAP model. For example, to build a configuration file using this table to learn a model: ``` $ python makeconfig.py {path_to_config} --features examples/data/HNRNPC_hepg2_majiq_features.tsv --ref {path_to_ref} --motif {path_to_motif} --out {name_for_KATMAP_output_directory} ```