code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def forward(self, x: Tensor, include_embeddings: bool = False): """ x : torch.Tensor, shape = (batch_size, n_mels, n_ctx) the mel spectrogram of the audio include_embeddings: bool whether to include intermediate steps in the output """ x = F.gelu(self.conv1(x)) x = F.gelu(self.conv2(x)) x = x.permute(0, 2, 1) assert x.shape[1:] == self.positional_embedding.shape, "incorrect audio shape" x = (x + self.positional_embedding).to(x.dtype) if include_embeddings: embeddings = [x.cpu().detach().numpy()] for block in self.blocks: x = block(x) if include_embeddings: embeddings.append(x.cpu().detach().numpy()) x = self.ln_post(x) if include_embeddings: embeddings = np.stack(embeddings, axis=1) return x, embeddings else: return x
x : torch.Tensor, shape = (batch_size, n_mels, n_ctx) the mel spectrogram of the audio include_embeddings: bool whether to include intermediate steps in the output
forward
python
bytedance/LatentSync
latentsync/whisper/whisper/model.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/model.py
Apache-2.0
def forward(self, x: Tensor, xa: Tensor, kv_cache: Optional[dict] = None, include_embeddings: bool = False): """ x : torch.LongTensor, shape = (batch_size, <= n_ctx) the text tokens xa : torch.Tensor, shape = (batch_size, n_mels, n_audio_ctx) the encoded audio features to be attended on include_embeddings : bool Whether to include intermediate values in the output to this function """ offset = next(iter(kv_cache.values())).shape[1] if kv_cache else 0 x = self.token_embedding(x) + self.positional_embedding[offset : offset + x.shape[-1]] x = x.to(xa.dtype) if include_embeddings: embeddings = [x.cpu().detach().numpy()] for block in self.blocks: x = block(x, xa, mask=self.mask, kv_cache=kv_cache) if include_embeddings: embeddings.append(x.cpu().detach().numpy()) x = self.ln(x) logits = (x @ torch.transpose(self.token_embedding.weight.to(x.dtype), 0, 1)).float() if include_embeddings: embeddings = np.stack(embeddings, axis=1) return logits, embeddings else: return logits
x : torch.LongTensor, shape = (batch_size, <= n_ctx) the text tokens xa : torch.Tensor, shape = (batch_size, n_mels, n_audio_ctx) the encoded audio features to be attended on include_embeddings : bool Whether to include intermediate values in the output to this function
forward
python
bytedance/LatentSync
latentsync/whisper/whisper/model.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/model.py
Apache-2.0
def install_kv_cache_hooks(self, cache: Optional[dict] = None): """ The `MultiHeadAttention` module optionally accepts `kv_cache` which stores the key and value tensors calculated for the previous positions. This method returns a dictionary that stores all caches, and the necessary hooks for the key and value projection modules that save the intermediate tensors to be reused during later calculations. Returns ------- cache : Dict[nn.Module, torch.Tensor] A dictionary object mapping the key/value projection modules to its cache hooks : List[RemovableHandle] List of PyTorch RemovableHandle objects to stop the hooks to be called """ cache = {**cache} if cache is not None else {} hooks = [] def save_to_cache(module, _, output): if module not in cache or output.shape[1] > self.decoder.positional_embedding.shape[0]: cache[module] = output # save as-is, for the first token or cross attention else: cache[module] = torch.cat([cache[module], output], dim=1).detach() return cache[module] def install_hooks(layer: nn.Module): if isinstance(layer, MultiHeadAttention): hooks.append(layer.key.register_forward_hook(save_to_cache)) hooks.append(layer.value.register_forward_hook(save_to_cache)) self.decoder.apply(install_hooks) return cache, hooks
The `MultiHeadAttention` module optionally accepts `kv_cache` which stores the key and value tensors calculated for the previous positions. This method returns a dictionary that stores all caches, and the necessary hooks for the key and value projection modules that save the intermediate tensors to be reused during later calculations. Returns ------- cache : Dict[nn.Module, torch.Tensor] A dictionary object mapping the key/value projection modules to its cache hooks : List[RemovableHandle] List of PyTorch RemovableHandle objects to stop the hooks to be called
install_kv_cache_hooks
python
bytedance/LatentSync
latentsync/whisper/whisper/model.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/model.py
Apache-2.0
def decode_with_timestamps(self, tokens) -> str: """ Timestamp tokens are above the special tokens' id range and are ignored by `decode()`. This method decodes given tokens with timestamps tokens annotated, e.g. "<|1.08|>". """ outputs = [[]] for token in tokens: if token >= self.timestamp_begin: timestamp = f"<|{(token - self.timestamp_begin) * 0.02:.2f}|>" outputs.append(timestamp) outputs.append([]) else: outputs[-1].append(token) outputs = [s if isinstance(s, str) else self.tokenizer.decode(s) for s in outputs] return "".join(outputs)
Timestamp tokens are above the special tokens' id range and are ignored by `decode()`. This method decodes given tokens with timestamps tokens annotated, e.g. "<|1.08|>".
decode_with_timestamps
python
bytedance/LatentSync
latentsync/whisper/whisper/tokenizer.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/tokenizer.py
Apache-2.0
def language_token(self) -> int: """Returns the token id corresponding to the value of the `language` field""" if self.language is None: raise ValueError(f"This tokenizer does not have language token configured") additional_tokens = dict( zip( self.tokenizer.additional_special_tokens, self.tokenizer.additional_special_tokens_ids, ) ) candidate = f"<|{self.language}|>" if candidate in additional_tokens: return additional_tokens[candidate] raise KeyError(f"Language {self.language} not found in tokenizer.")
Returns the token id corresponding to the value of the `language` field
language_token
python
bytedance/LatentSync
latentsync/whisper/whisper/tokenizer.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/tokenizer.py
Apache-2.0
def write_srt(transcript: Iterator[dict], file: TextIO): """ Write a transcript to a file in SRT format. Example usage: from pathlib import Path from whisper.utils import write_srt result = transcribe(model, audio_path, temperature=temperature, **args) # save SRT audio_basename = Path(audio_path).stem with open(Path(output_dir) / (audio_basename + ".srt"), "w", encoding="utf-8") as srt: write_srt(result["segments"], file=srt) """ for i, segment in enumerate(transcript, start=1): # write srt lines print( f"{i}\n" f"{format_timestamp(segment['start'], always_include_hours=True, decimal_marker=',')} --> " f"{format_timestamp(segment['end'], always_include_hours=True, decimal_marker=',')}\n" f"{segment['text'].strip().replace('-->', '->')}\n", file=file, flush=True, )
Write a transcript to a file in SRT format. Example usage: from pathlib import Path from whisper.utils import write_srt result = transcribe(model, audio_path, temperature=temperature, **args) # save SRT audio_basename = Path(audio_path).stem with open(Path(output_dir) / (audio_basename + ".srt"), "w", encoding="utf-8") as srt: write_srt(result["segments"], file=srt)
write_srt
python
bytedance/LatentSync
latentsync/whisper/whisper/utils.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/utils.py
Apache-2.0
def load_model( name: str, device: Optional[Union[str, torch.device]] = None, download_root: str = None, in_memory: bool = False ) -> Whisper: """ Load a Whisper ASR model Parameters ---------- name : str one of the official model names listed by `whisper.available_models()`, or path to a model checkpoint containing the model dimensions and the model state_dict. device : Union[str, torch.device] the PyTorch device to put the model into download_root: str path to download the model files; by default, it uses "~/.cache/whisper" in_memory: bool whether to preload the model weights into host memory Returns ------- model : Whisper The Whisper ASR model instance """ if device is None: device = "cuda" if torch.cuda.is_available() else "cpu" if download_root is None: download_root = os.getenv("XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache", "whisper")) if name in _MODELS: checkpoint_file = _download(_MODELS[name], download_root, in_memory) elif os.path.isfile(name): checkpoint_file = open(name, "rb").read() if in_memory else name else: raise RuntimeError(f"Model {name} not found; available models = {available_models()}") with io.BytesIO(checkpoint_file) if in_memory else open(checkpoint_file, "rb") as fp: checkpoint = torch.load(fp, map_location=device, weights_only=True) del checkpoint_file dims = ModelDimensions(**checkpoint["dims"]) model = Whisper(dims) model.load_state_dict(checkpoint["model_state_dict"]) del checkpoint torch.cuda.empty_cache() return model.to(device)
Load a Whisper ASR model Parameters ---------- name : str one of the official model names listed by `whisper.available_models()`, or path to a model checkpoint containing the model dimensions and the model state_dict. device : Union[str, torch.device] the PyTorch device to put the model into download_root: str path to download the model files; by default, it uses "~/.cache/whisper" in_memory: bool whether to preload the model weights into host memory Returns ------- model : Whisper The Whisper ASR model instance
load_model
python
bytedance/LatentSync
latentsync/whisper/whisper/__init__.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/__init__.py
Apache-2.0
def remove_symbols_and_diacritics(s: str, keep=""): """ Replace any other markers, symbols, and punctuations with a space, and drop any diacritics (category 'Mn' and some manual mappings) """ return "".join( c if c in keep else ADDITIONAL_DIACRITICS[c] if c in ADDITIONAL_DIACRITICS else "" if unicodedata.category(c) == "Mn" else " " if unicodedata.category(c)[0] in "MSP" else c for c in unicodedata.normalize("NFKD", s) )
Replace any other markers, symbols, and punctuations with a space, and drop any diacritics (category 'Mn' and some manual mappings)
remove_symbols_and_diacritics
python
bytedance/LatentSync
latentsync/whisper/whisper/normalizers/basic.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/normalizers/basic.py
Apache-2.0
def remove_symbols(s: str): """ Replace any other markers, symbols, punctuations with a space, keeping diacritics """ return "".join( " " if unicodedata.category(c)[0] in "MSP" else c for c in unicodedata.normalize("NFKC", s) )
Replace any other markers, symbols, punctuations with a space, keeping diacritics
remove_symbols
python
bytedance/LatentSync
latentsync/whisper/whisper/normalizers/basic.py
https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/whisper/normalizers/basic.py
Apache-2.0
def cpg(): """ >>> # +--------------+-----------+-----------+-----------+ >>> # | Chromosome | Start | End | CpG | >>> # | (category) | (int64) | (int64) | (int64) | >>> # |--------------+-----------+-----------+-----------| >>> # | chrX | 64181 | 64793 | 62 | >>> # | chrX | 69133 | 70029 | 100 | >>> # | chrX | 148685 | 149461 | 85 | >>> # | chrX | 166504 | 167721 | 96 | >>> # | ... | ... | ... | ... | >>> # | chrY | 28555535 | 28555932 | 32 | >>> # | chrY | 28773315 | 28773544 | 25 | >>> # | chrY | 59213794 | 59214183 | 36 | >>> # | chrY | 59349266 | 59349574 | 29 | >>> # +--------------+-----------+-----------+-----------+ >>> # Unstranded PyRanges object has 1,077 rows and 4 columns from 2 chromosomes. >>> # For printing, the PyRanges was sorted on Chromosome. """ full_path = get_example_path("cpg.bed") df = pd.read_csv(full_path, sep="\t", header=None, names="Chromosome Start End CpG".split()) return pr.PyRanges(df)
>>> # +--------------+-----------+-----------+-----------+ >>> # | Chromosome | Start | End | CpG | >>> # | (category) | (int64) | (int64) | (int64) | >>> # |--------------+-----------+-----------+-----------| >>> # | chrX | 64181 | 64793 | 62 | >>> # | chrX | 69133 | 70029 | 100 | >>> # | chrX | 148685 | 149461 | 85 | >>> # | chrX | 166504 | 167721 | 96 | >>> # | ... | ... | ... | ... | >>> # | chrY | 28555535 | 28555932 | 32 | >>> # | chrY | 28773315 | 28773544 | 25 | >>> # | chrY | 59213794 | 59214183 | 36 | >>> # | chrY | 59349266 | 59349574 | 29 | >>> # +--------------+-----------+-----------+-----------+ >>> # Unstranded PyRanges object has 1,077 rows and 4 columns from 2 chromosomes. >>> # For printing, the PyRanges was sorted on Chromosome.
cpg
python
pyranges/pyranges
pyranges/data.py
https://github.com/pyranges/pyranges/blob/master/pyranges/data.py
MIT
def ucsc_bed(): """ >>> # +--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------+ >>> # | Chromosome | Start | End | Feature | gene_id | transcript_id | Strand | exon_number | transcript_name | >>> # | (category) | (int64) | (int64) | (object) | (object) | (float64) | (category) | (float64) | (object) | >>> # |--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------| >>> # | chr1 | 12776117 | 12788726 | gene | AADACL3 | nan | + | nan | nan | >>> # | chr1 | 169075927 | 169101957 | gene | ATP1B1 | nan | + | nan | nan | >>> # | chr1 | 6845383 | 7829766 | gene | CAMTA1 | nan | + | nan | nan | >>> # | chr1 | 20915589 | 20945396 | gene | CDA | nan | + | nan | nan | >>> # | ... | ... | ... | ... | ... | ... | ... | ... | ... | >>> # | chrX | 152661096 | 152663330 | exon | PNMA6E | 260.0 | - | 0.0 | NM_001351293 | >>> # | chrX | 152661096 | 152666808 | transcript | PNMA6E | 260.0 | - | nan | NM_001351293 | >>> # | chrX | 152664164 | 152664378 | exon | PNMA6E | 260.0 | - | 1.0 | NM_001351293 | >>> # | chrX | 152666701 | 152666808 | exon | PNMA6E | 260.0 | - | 2.0 | NM_001351293 | >>> # +--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------+ >>> # Stranded PyRanges object has 5,519 rows and 9 columns from 30 chromosomes. >>> # For printing, the PyRanges was sorted on Chromosome and Strand. """ full_path = get_example_path("ucsc_human.bed.gz") names = "Chromosome Start End Feature gene_id transcript_id Strand exon_number transcript_name".split() df = pd.read_csv(full_path, sep="\t", names=names) return pr.PyRanges(df)
>>> # +--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------+ >>> # | Chromosome | Start | End | Feature | gene_id | transcript_id | Strand | exon_number | transcript_name | >>> # | (category) | (int64) | (int64) | (object) | (object) | (float64) | (category) | (float64) | (object) | >>> # |--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------| >>> # | chr1 | 12776117 | 12788726 | gene | AADACL3 | nan | + | nan | nan | >>> # | chr1 | 169075927 | 169101957 | gene | ATP1B1 | nan | + | nan | nan | >>> # | chr1 | 6845383 | 7829766 | gene | CAMTA1 | nan | + | nan | nan | >>> # | chr1 | 20915589 | 20945396 | gene | CDA | nan | + | nan | nan | >>> # | ... | ... | ... | ... | ... | ... | ... | ... | ... | >>> # | chrX | 152661096 | 152663330 | exon | PNMA6E | 260.0 | - | 0.0 | NM_001351293 | >>> # | chrX | 152661096 | 152666808 | transcript | PNMA6E | 260.0 | - | nan | NM_001351293 | >>> # | chrX | 152664164 | 152664378 | exon | PNMA6E | 260.0 | - | 1.0 | NM_001351293 | >>> # | chrX | 152666701 | 152666808 | exon | PNMA6E | 260.0 | - | 2.0 | NM_001351293 | >>> # +--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------+ >>> # Stranded PyRanges object has 5,519 rows and 9 columns from 30 chromosomes. >>> # For printing, the PyRanges was sorted on Chromosome and Strand.
ucsc_bed
python
pyranges/pyranges
pyranges/data.py
https://github.com/pyranges/pyranges/blob/master/pyranges/data.py
MIT
def tss(self): """Return the transcription start sites. Returns the 5' for every interval with feature "transcript". See Also -------- pyranges.genomicfeatures.GenomicFeaturesMethods.tes : return the transcription end sites Examples -------- >>> gr = pr.data.ensembl_gtf()[["Source", "Feature"]] >>> gr +--------------+------------+--------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (category) | (int64) | (int64) | (category) | |--------------+------------+--------------+-----------+-----------+--------------| | 1 | havana | gene | 11868 | 14409 | + | | 1 | havana | transcript | 11868 | 14409 | + | | 1 | havana | exon | 11868 | 12227 | + | | 1 | havana | exon | 12612 | 12721 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1173055 | 1179555 | - | | 1 | havana | transcript | 1173055 | 1179555 | - | | 1 | havana | exon | 1179364 | 1179555 | - | | 1 | havana | exon | 1173055 | 1176396 | - | +--------------+------------+--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.tss() +--------------+------------+------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (object) | (int64) | (int64) | (category) | |--------------+------------+------------+-----------+-----------+--------------| | 1 | havana | tss | 11868 | 11869 | + | | 1 | havana | tss | 12009 | 12010 | + | | 1 | havana | tss | 29553 | 29554 | + | | 1 | havana | tss | 30266 | 30267 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | tss | 1092812 | 1092813 | - | | 1 | havana | tss | 1116086 | 1116087 | - | | 1 | havana | tss | 1116088 | 1116089 | - | | 1 | havana | tss | 1179554 | 1179555 | - | +--------------+------------+------------+-----------+-----------+--------------+ Stranded PyRanges object has 280 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ pr = self.pr if not pr.stranded: raise Exception( "Cannot compute TSSes or TESes without strand info. Perhaps use extend() or subsequence() or spliced_subsequence() instead?" ) pr = pr[pr.Feature == "transcript"] pr = pr.apply(lambda df: _tss(df)) pr.Feature = "tss" return pr
Return the transcription start sites. Returns the 5' for every interval with feature "transcript". See Also -------- pyranges.genomicfeatures.GenomicFeaturesMethods.tes : return the transcription end sites Examples -------- >>> gr = pr.data.ensembl_gtf()[["Source", "Feature"]] >>> gr +--------------+------------+--------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (category) | (int64) | (int64) | (category) | |--------------+------------+--------------+-----------+-----------+--------------| | 1 | havana | gene | 11868 | 14409 | + | | 1 | havana | transcript | 11868 | 14409 | + | | 1 | havana | exon | 11868 | 12227 | + | | 1 | havana | exon | 12612 | 12721 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1173055 | 1179555 | - | | 1 | havana | transcript | 1173055 | 1179555 | - | | 1 | havana | exon | 1179364 | 1179555 | - | | 1 | havana | exon | 1173055 | 1176396 | - | +--------------+------------+--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.tss() +--------------+------------+------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (object) | (int64) | (int64) | (category) | |--------------+------------+------------+-----------+-----------+--------------| | 1 | havana | tss | 11868 | 11869 | + | | 1 | havana | tss | 12009 | 12010 | + | | 1 | havana | tss | 29553 | 29554 | + | | 1 | havana | tss | 30266 | 30267 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | tss | 1092812 | 1092813 | - | | 1 | havana | tss | 1116086 | 1116087 | - | | 1 | havana | tss | 1116088 | 1116089 | - | | 1 | havana | tss | 1179554 | 1179555 | - | +--------------+------------+------------+-----------+-----------+--------------+ Stranded PyRanges object has 280 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
tss
python
pyranges/pyranges
pyranges/genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/pyranges/genomicfeatures.py
MIT
def tes(self, slack=0): """Return the transcription end sites. Returns the 3' for every interval with feature "transcript". See Also -------- pyranges.genomicfeatures.GenomicFeaturesMethods.tss : return the transcription start sites Examples -------- >>> gr = pr.data.ensembl_gtf()[["Source", "Feature"]] >>> gr +--------------+------------+--------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (category) | (int64) | (int64) | (category) | |--------------+------------+--------------+-----------+-----------+--------------| | 1 | havana | gene | 11868 | 14409 | + | | 1 | havana | transcript | 11868 | 14409 | + | | 1 | havana | exon | 11868 | 12227 | + | | 1 | havana | exon | 12612 | 12721 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1173055 | 1179555 | - | | 1 | havana | transcript | 1173055 | 1179555 | - | | 1 | havana | exon | 1179364 | 1179555 | - | | 1 | havana | exon | 1173055 | 1176396 | - | +--------------+------------+--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.tes() +--------------+------------+------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (object) | (int64) | (int64) | (category) | |--------------+------------+------------+-----------+-----------+--------------| | 1 | havana | tes | 14408 | 14409 | + | | 1 | havana | tes | 13669 | 13670 | + | | 1 | havana | tes | 31096 | 31097 | + | | 1 | havana | tes | 31108 | 31109 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | tes | 1090405 | 1090406 | - | | 1 | havana | tes | 1091045 | 1091046 | - | | 1 | havana | tes | 1091499 | 1091500 | - | | 1 | havana | tes | 1173055 | 1173056 | - | +--------------+------------+------------+-----------+-----------+--------------+ Stranded PyRanges object has 280 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ pr = self.pr if not pr.stranded: raise Exception( "Cannot compute TSSes or TESes without strand info. Perhaps use extend() or subsequence() or spliced_subsequence() instead?" ) pr = pr[pr.Feature == "transcript"] pr = pr.apply(lambda df: _tes(df)) pr.Feature = "tes" return pr
Return the transcription end sites. Returns the 3' for every interval with feature "transcript". See Also -------- pyranges.genomicfeatures.GenomicFeaturesMethods.tss : return the transcription start sites Examples -------- >>> gr = pr.data.ensembl_gtf()[["Source", "Feature"]] >>> gr +--------------+------------+--------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (category) | (int64) | (int64) | (category) | |--------------+------------+--------------+-----------+-----------+--------------| | 1 | havana | gene | 11868 | 14409 | + | | 1 | havana | transcript | 11868 | 14409 | + | | 1 | havana | exon | 11868 | 12227 | + | | 1 | havana | exon | 12612 | 12721 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1173055 | 1179555 | - | | 1 | havana | transcript | 1173055 | 1179555 | - | | 1 | havana | exon | 1179364 | 1179555 | - | | 1 | havana | exon | 1173055 | 1176396 | - | +--------------+------------+--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.tes() +--------------+------------+------------+-----------+-----------+--------------+ | Chromosome | Source | Feature | Start | End | Strand | | (category) | (object) | (object) | (int64) | (int64) | (category) | |--------------+------------+------------+-----------+-----------+--------------| | 1 | havana | tes | 14408 | 14409 | + | | 1 | havana | tes | 13669 | 13670 | + | | 1 | havana | tes | 31096 | 31097 | + | | 1 | havana | tes | 31108 | 31109 | + | | ... | ... | ... | ... | ... | ... | | 1 | havana | tes | 1090405 | 1090406 | - | | 1 | havana | tes | 1091045 | 1091046 | - | | 1 | havana | tes | 1091499 | 1091500 | - | | 1 | havana | tes | 1173055 | 1173056 | - | +--------------+------------+------------+-----------+-----------+--------------+ Stranded PyRanges object has 280 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
tes
python
pyranges/pyranges
pyranges/genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/pyranges/genomicfeatures.py
MIT
def introns(self, by="gene", nb_cpu=1): """Return the introns. Parameters ---------- by : str, {"gene", "transcript"}, default "gene" Whether to find introns per gene or transcript. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. See Also -------- pyranges.genomicfeatures.GenomicFeaturesMethods.tss : return the transcription start sites Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_id", "transcript_id"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-----------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | transcript_id | | (category) | (category) | (int64) | (int64) | (category) | (object) | (object) | |--------------+--------------+-----------+-----------+--------------+-----------------+-----------------| | 1 | gene | 11868 | 14409 | + | ENSG00000223972 | nan | | 1 | transcript | 11868 | 14409 | + | ENSG00000223972 | ENST00000456328 | | 1 | exon | 11868 | 12227 | + | ENSG00000223972 | ENST00000456328 | | 1 | exon | 12612 | 12721 | + | ENSG00000223972 | ENST00000456328 | | ... | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | ENSG00000205231 | nan | | 1 | transcript | 1173055 | 1179555 | - | ENSG00000205231 | ENST00000379317 | | 1 | exon | 1179364 | 1179555 | - | ENSG00000205231 | ENST00000379317 | | 1 | exon | 1173055 | 1176396 | - | ENSG00000205231 | ENST00000379317 | +--------------+--------------+-----------+-----------+--------------+-----------------+-----------------+ Stranded PyRanges object has 2,446 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.introns(by="gene") +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | transcript_id | | (object) | (object) | (int64) | (int64) | (category) | (object) | (object) | |--------------+------------+-----------+-----------+--------------+-----------------+-----------------| | 1 | intron | 1173926 | 1174265 | + | ENSG00000162571 | nan | | 1 | intron | 1174321 | 1174423 | + | ENSG00000162571 | nan | | 1 | intron | 1174489 | 1174520 | + | ENSG00000162571 | nan | | 1 | intron | 1175034 | 1179188 | + | ENSG00000162571 | nan | | ... | ... | ... | ... | ... | ... | ... | | 1 | intron | 874591 | 875046 | - | ENSG00000283040 | nan | | 1 | intron | 875155 | 875525 | - | ENSG00000283040 | nan | | 1 | intron | 875625 | 876526 | - | ENSG00000283040 | nan | | 1 | intron | 876611 | 876754 | - | ENSG00000283040 | nan | +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ Stranded PyRanges object has 311 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.introns(by="transcript") +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | transcript_id | | (object) | (object) | (int64) | (int64) | (category) | (object) | (object) | |--------------+------------+-----------+-----------+--------------+-----------------+-----------------| | 1 | intron | 818202 | 818722 | + | ENSG00000177757 | ENST00000326734 | | 1 | intron | 960800 | 961292 | + | ENSG00000187961 | ENST00000338591 | | 1 | intron | 961552 | 961628 | + | ENSG00000187961 | ENST00000338591 | | 1 | intron | 961750 | 961825 | + | ENSG00000187961 | ENST00000338591 | | ... | ... | ... | ... | ... | ... | ... | | 1 | intron | 732207 | 732980 | - | ENSG00000230021 | ENST00000648019 | | 1 | intron | 168165 | 169048 | - | ENSG00000241860 | ENST00000655252 | | 1 | intron | 165942 | 167958 | - | ENSG00000241860 | ENST00000662089 | | 1 | intron | 168165 | 169048 | - | ENSG00000241860 | ENST00000662089 | +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ Stranded PyRanges object has 1,043 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ kwargs = {"by": by, "nb_cpu": nb_cpu} kwargs = pr.pyranges_main.fill_kwargs(kwargs) assert by in ["gene", "transcript"] id_column = by_to_id[by] gr = self.pr.sort(id_column) if not len(gr): return pr.PyRanges() exons = gr.subset(lambda df: df.Feature == "exon") exons = exons.merge(by=id_column) by_gr = gr.subset(lambda df: df.Feature == by) result = pyrange_apply(_introns2, by_gr, exons, **kwargs) return pr.PyRanges(result)
Return the introns. Parameters ---------- by : str, {"gene", "transcript"}, default "gene" Whether to find introns per gene or transcript. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. See Also -------- pyranges.genomicfeatures.GenomicFeaturesMethods.tss : return the transcription start sites Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_id", "transcript_id"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-----------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | transcript_id | | (category) | (category) | (int64) | (int64) | (category) | (object) | (object) | |--------------+--------------+-----------+-----------+--------------+-----------------+-----------------| | 1 | gene | 11868 | 14409 | + | ENSG00000223972 | nan | | 1 | transcript | 11868 | 14409 | + | ENSG00000223972 | ENST00000456328 | | 1 | exon | 11868 | 12227 | + | ENSG00000223972 | ENST00000456328 | | 1 | exon | 12612 | 12721 | + | ENSG00000223972 | ENST00000456328 | | ... | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | ENSG00000205231 | nan | | 1 | transcript | 1173055 | 1179555 | - | ENSG00000205231 | ENST00000379317 | | 1 | exon | 1179364 | 1179555 | - | ENSG00000205231 | ENST00000379317 | | 1 | exon | 1173055 | 1176396 | - | ENSG00000205231 | ENST00000379317 | +--------------+--------------+-----------+-----------+--------------+-----------------+-----------------+ Stranded PyRanges object has 2,446 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.introns(by="gene") +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | transcript_id | | (object) | (object) | (int64) | (int64) | (category) | (object) | (object) | |--------------+------------+-----------+-----------+--------------+-----------------+-----------------| | 1 | intron | 1173926 | 1174265 | + | ENSG00000162571 | nan | | 1 | intron | 1174321 | 1174423 | + | ENSG00000162571 | nan | | 1 | intron | 1174489 | 1174520 | + | ENSG00000162571 | nan | | 1 | intron | 1175034 | 1179188 | + | ENSG00000162571 | nan | | ... | ... | ... | ... | ... | ... | ... | | 1 | intron | 874591 | 875046 | - | ENSG00000283040 | nan | | 1 | intron | 875155 | 875525 | - | ENSG00000283040 | nan | | 1 | intron | 875625 | 876526 | - | ENSG00000283040 | nan | | 1 | intron | 876611 | 876754 | - | ENSG00000283040 | nan | +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ Stranded PyRanges object has 311 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.features.introns(by="transcript") +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | transcript_id | | (object) | (object) | (int64) | (int64) | (category) | (object) | (object) | |--------------+------------+-----------+-----------+--------------+-----------------+-----------------| | 1 | intron | 818202 | 818722 | + | ENSG00000177757 | ENST00000326734 | | 1 | intron | 960800 | 961292 | + | ENSG00000187961 | ENST00000338591 | | 1 | intron | 961552 | 961628 | + | ENSG00000187961 | ENST00000338591 | | 1 | intron | 961750 | 961825 | + | ENSG00000187961 | ENST00000338591 | | ... | ... | ... | ... | ... | ... | ... | | 1 | intron | 732207 | 732980 | - | ENSG00000230021 | ENST00000648019 | | 1 | intron | 168165 | 169048 | - | ENSG00000241860 | ENST00000655252 | | 1 | intron | 165942 | 167958 | - | ENSG00000241860 | ENST00000662089 | | 1 | intron | 168165 | 169048 | - | ENSG00000241860 | ENST00000662089 | +--------------+------------+-----------+-----------+--------------+-----------------+-----------------+ Stranded PyRanges object has 1,043 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
introns
python
pyranges/pyranges
pyranges/genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/pyranges/genomicfeatures.py
MIT
def genome_bounds(gr, chromsizes, clip=False, only_right=False): """Remove or clip intervals outside of genome bounds. Parameters ---------- gr : PyRanges Input intervals chromsizes : dict or PyRanges or pyfaidx.Fasta Dict or PyRanges describing the lengths of the chromosomes. pyfaidx.Fasta object is also accepted since it conveniently loads chromosome length clip : bool, default False Returns the portions of intervals within bounds, instead of dropping intervals entirely if they are even partially out of bounds only_right : bool, default False If True, remove or clip only intervals that are out-of-bounds on the right, and do not alter those out-of-bounds on the left (whose Start is < 0) Examples -------- >>> d = {"Chromosome": [1, 1, 3], "Start": [1, 249250600, 5], "End": [2, 249250640, 7]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 1 | 249250600 | 249250640 | | 3 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> chromsizes = {"1": 249250621, "3": 500} >>> chromsizes {'1': 249250621, '3': 500} >>> pr.gf.genome_bounds(gr, chromsizes) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 3 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.gf.genome_bounds(gr, chromsizes, clip=True) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 1 | 249250600 | 249250621 | | 3 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> del chromsizes['3'] >>> chromsizes {'1': 249250621} >>> pr.gf.genome_bounds(gr, chromsizes) Traceback (most recent call last): ... KeyError: '3' """ if isinstance(chromsizes, pr.PyRanges): chromsizes = {k: v for k, v in zip(chromsizes.Chromosome, chromsizes.End)} elif isinstance(chromsizes, dict): pass else: try: import pyfaidx # type: ignore if isinstance(chromsizes, pyfaidx.Fasta): chromsizes = {k: len(chromsizes[k]) for k in chromsizes.keys()} except ImportError: pass assert isinstance( chromsizes, dict ), "ERROR chromsizes must be a dictionary, or a PyRanges, or a pyfaidx.Fasta object" return gr.apply(_outside_bounds, chromsizes=chromsizes, clip=clip, only_right=only_right)
Remove or clip intervals outside of genome bounds. Parameters ---------- gr : PyRanges Input intervals chromsizes : dict or PyRanges or pyfaidx.Fasta Dict or PyRanges describing the lengths of the chromosomes. pyfaidx.Fasta object is also accepted since it conveniently loads chromosome length clip : bool, default False Returns the portions of intervals within bounds, instead of dropping intervals entirely if they are even partially out of bounds only_right : bool, default False If True, remove or clip only intervals that are out-of-bounds on the right, and do not alter those out-of-bounds on the left (whose Start is < 0) Examples -------- >>> d = {"Chromosome": [1, 1, 3], "Start": [1, 249250600, 5], "End": [2, 249250640, 7]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 1 | 249250600 | 249250640 | | 3 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> chromsizes = {"1": 249250621, "3": 500} >>> chromsizes {'1': 249250621, '3': 500} >>> pr.gf.genome_bounds(gr, chromsizes) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 3 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.gf.genome_bounds(gr, chromsizes, clip=True) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 1 | 249250600 | 249250621 | | 3 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> del chromsizes['3'] >>> chromsizes {'1': 249250621} >>> pr.gf.genome_bounds(gr, chromsizes) Traceback (most recent call last): ... KeyError: '3'
genome_bounds
python
pyranges/pyranges
pyranges/genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/pyranges/genomicfeatures.py
MIT
def tile_genome(genome, tile_size, tile_last=False): """Create a tiled genome. Parameters ---------- chromsizes : dict or PyRanges Dict or PyRanges describing the lengths of the chromosomes. tile_size : int Length of the tiles. tile_last : bool, default False Use genome length as end of last tile. See Also -------- pyranges.PyRanges.tile : split intervals into adjacent non-overlapping tiles. Examples -------- >>> chromsizes = pr.data.chromsizes() >>> chromsizes +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.gf.tile_genome(chromsizes, int(1e6)) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 1000000 | | chr1 | 1000000 | 2000000 | | chr1 | 2000000 | 3000000 | | chr1 | 3000000 | 4000000 | | ... | ... | ... | | chrY | 56000000 | 57000000 | | chrY | 57000000 | 58000000 | | chrY | 58000000 | 59000000 | | chrY | 59000000 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3,114 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ if isinstance(genome, dict): chromosomes, ends = list(genome.keys()), list(genome.values()) df = pd.DataFrame({"Chromosome": chromosomes, "Start": 0, "End": ends}) genome = pr.PyRanges(df) gr = genome.tile(tile_size) if not tile_last: gr = gr.apply(_last_tile, sizes=genome) return gr
Create a tiled genome. Parameters ---------- chromsizes : dict or PyRanges Dict or PyRanges describing the lengths of the chromosomes. tile_size : int Length of the tiles. tile_last : bool, default False Use genome length as end of last tile. See Also -------- pyranges.PyRanges.tile : split intervals into adjacent non-overlapping tiles. Examples -------- >>> chromsizes = pr.data.chromsizes() >>> chromsizes +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.gf.tile_genome(chromsizes, int(1e6)) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 1000000 | | chr1 | 1000000 | 2000000 | | chr1 | 2000000 | 3000000 | | chr1 | 3000000 | 4000000 | | ... | ... | ... | | chrY | 56000000 | 57000000 | | chrY | 57000000 | 58000000 | | chrY | 58000000 | 59000000 | | chrY | 59000000 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3,114 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome.
tile_genome
python
pyranges/pyranges
pyranges/genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/pyranges/genomicfeatures.py
MIT
def get_sequence(gr, path=None, pyfaidx_fasta=None): """Get the sequence of the intervals from a fasta file Parameters ---------- gr : PyRanges Coordinates. path : str Path to fasta file. It will be indexed using pyfaidx if an index is not found pyfaidx_fasta : pyfaidx.Fasta Alternative method to provide fasta target, as a pyfaidx.Fasta object Returns ------- Series Sequences, one per interval. Note ---- This function requires the library pyfaidx, it can be installed with ``conda install -c bioconda pyfaidx`` or ``pip install pyfaidx``. Sorting the PyRanges is likely to improve the speed. Intervals on the negative strand will be reverse complemented. Warning ------- Note that the names in the fasta header and gr must be the same. See also -------- get_transcript_sequence : obtain mRNA sequences, by joining exons belonging to the same transcript Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1", "chr1"], ... "Start": [5, 0], "End": [8, 5]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 5 | 8 | | chr1 | 0 | 5 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> tmp_handle = open("temp.fasta", "w+") >>> _ = tmp_handle.write(">chr1\\n") >>> _ = tmp_handle.write("ATTACCAT\\n") >>> tmp_handle.close() >>> seq = pr.get_sequence(gr, "temp.fasta") >>> seq 0 CAT 1 ATTAC dtype: object >>> gr.seq = seq >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | seq | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 5 | 8 | CAT | | chr1 | 0 | 5 | ATTAC | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ try: import pyfaidx # type: ignore except ImportError: print( "pyfaidx must be installed to get fasta sequences. Use `conda install -c bioconda pyfaidx` or `pip install pyfaidx` to install it." ) sys.exit(1) if pyfaidx_fasta is None: if path is None: raise Exception("ERROR get_sequence : you must provide a fasta path or pyfaidx_fasta object") pyfaidx_fasta = pyfaidx.Fasta(path, read_ahead=int(1e5)) seqs = [] for k, df in gr: if type(k) is tuple: # input is Stranded _fasta = pyfaidx_fasta[k[0]] if k[1] == "-": for start, end in zip(df.Start, df.End): seqs.append((-_fasta[start:end]).seq) # reverse complement else: for start, end in zip(df.Start, df.End): seqs.append(_fasta[start:end].seq) else: _fasta = pyfaidx_fasta[k] for start, end in zip(df.Start, df.End): seqs.append(_fasta[start:end].seq) return pd.concat([pd.Series(s) for s in seqs]).reset_index(drop=True)
Get the sequence of the intervals from a fasta file Parameters ---------- gr : PyRanges Coordinates. path : str Path to fasta file. It will be indexed using pyfaidx if an index is not found pyfaidx_fasta : pyfaidx.Fasta Alternative method to provide fasta target, as a pyfaidx.Fasta object Returns ------- Series Sequences, one per interval. Note ---- This function requires the library pyfaidx, it can be installed with ``conda install -c bioconda pyfaidx`` or ``pip install pyfaidx``. Sorting the PyRanges is likely to improve the speed. Intervals on the negative strand will be reverse complemented. Warning ------- Note that the names in the fasta header and gr must be the same. See also -------- get_transcript_sequence : obtain mRNA sequences, by joining exons belonging to the same transcript Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1", "chr1"], ... "Start": [5, 0], "End": [8, 5]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 5 | 8 | | chr1 | 0 | 5 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> tmp_handle = open("temp.fasta", "w+") >>> _ = tmp_handle.write(">chr1\n") >>> _ = tmp_handle.write("ATTACCAT\n") >>> tmp_handle.close() >>> seq = pr.get_sequence(gr, "temp.fasta") >>> seq 0 CAT 1 ATTAC dtype: object >>> gr.seq = seq >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | seq | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 5 | 8 | CAT | | chr1 | 0 | 5 | ATTAC | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
get_sequence
python
pyranges/pyranges
pyranges/get_fasta.py
https://github.com/pyranges/pyranges/blob/master/pyranges/get_fasta.py
MIT
def get_transcript_sequence(gr, group_by, path=None, pyfaidx_fasta=None): """Get the sequence of mRNAs, e.g. joining intervals corresponding to exons of the same transcript Parameters ---------- gr : PyRanges Coordinates. group_by : str or list of str intervals are grouped by this/these ID column(s): these are exons belonging to same transcript path : str Path to fasta file. It will be indexed using pyfaidx if an index is not found pyfaidx_fasta : pyfaidx.Fasta Alternative method to provide fasta target, as a pyfaidx.Fasta object Returns ------- DataFrame Pandas DataFrame with a column for Sequence, plus ID column(s) provided with "group_by" Note ---- This function requires the library pyfaidx, it can be installed with ``conda install -c bioconda pyfaidx`` or ``pip install pyfaidx``. Sorting the PyRanges is likely to improve the speed. Intervals on the negative strand will be reverse complemented. Warning ------- Note that the names in the fasta header and gr must be the same. See also -------- get_sequence : obtain sequence of single intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ['chr1', 'chr1', 'chr1'], ... "Start": [0, 9, 18], "End": [4, 13, 21], ... "Strand":['+', '-', '-'], ... "transcript": ['t1', 't2', 't2']}) >>> gr +--------------+-----------+-----------+--------------+--------------+ | Chromosome | Start | End | Strand | transcript | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+--------------| | chr1 | 0 | 4 | + | t1 | | chr1 | 9 | 13 | - | t2 | | chr1 | 18 | 21 | - | t2 | +--------------+-----------+-----------+--------------+--------------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> tmp_handle = open("temp.fasta", "w+") >>> _ = tmp_handle.write(">chr1\\n") >>> _ = tmp_handle.write("AAACCCTTTGGGAAACCCTTTGGG\\n") >>> tmp_handle.close() >>> seq = pr.get_transcript_sequence(gr, path="temp.fasta", group_by='transcript') >>> seq transcript Sequence 0 t1 AAAC 1 t2 AAATCCC To write to a file in fasta format: # with open('outfile.fasta', 'w') as fw: # nchars=60 # for row in seq.itertuples(): # s = '\\n'.join([ row.Sequence[i:i+nchars] for i in range(0, len(row.Sequence), nchars)]) # fw.write(f'>{row.transcript}\\n{s}\\n') """ if gr.stranded: gr = gr.sort("5") else: gr = gr.sort() z = gr.df z["Sequence"] = get_sequence(gr, path=path, pyfaidx_fasta=pyfaidx_fasta) return z.groupby(group_by, as_index=False, observed=False).agg({"Sequence": "".join})
Get the sequence of mRNAs, e.g. joining intervals corresponding to exons of the same transcript Parameters ---------- gr : PyRanges Coordinates. group_by : str or list of str intervals are grouped by this/these ID column(s): these are exons belonging to same transcript path : str Path to fasta file. It will be indexed using pyfaidx if an index is not found pyfaidx_fasta : pyfaidx.Fasta Alternative method to provide fasta target, as a pyfaidx.Fasta object Returns ------- DataFrame Pandas DataFrame with a column for Sequence, plus ID column(s) provided with "group_by" Note ---- This function requires the library pyfaidx, it can be installed with ``conda install -c bioconda pyfaidx`` or ``pip install pyfaidx``. Sorting the PyRanges is likely to improve the speed. Intervals on the negative strand will be reverse complemented. Warning ------- Note that the names in the fasta header and gr must be the same. See also -------- get_sequence : obtain sequence of single intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ['chr1', 'chr1', 'chr1'], ... "Start": [0, 9, 18], "End": [4, 13, 21], ... "Strand":['+', '-', '-'], ... "transcript": ['t1', 't2', 't2']}) >>> gr +--------------+-----------+-----------+--------------+--------------+ | Chromosome | Start | End | Strand | transcript | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+--------------| | chr1 | 0 | 4 | + | t1 | | chr1 | 9 | 13 | - | t2 | | chr1 | 18 | 21 | - | t2 | +--------------+-----------+-----------+--------------+--------------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> tmp_handle = open("temp.fasta", "w+") >>> _ = tmp_handle.write(">chr1\n") >>> _ = tmp_handle.write("AAACCCTTTGGGAAACCCTTTGGG\n") >>> tmp_handle.close() >>> seq = pr.get_transcript_sequence(gr, path="temp.fasta", group_by='transcript') >>> seq transcript Sequence 0 t1 AAAC 1 t2 AAATCCC To write to a file in fasta format: # with open('outfile.fasta', 'w') as fw: # nchars=60 # for row in seq.itertuples(): # s = '\n'.join([ row.Sequence[i:i+nchars] for i in range(0, len(row.Sequence), nchars)]) # fw.write(f'>{row.transcript}\n{s}\n')
get_transcript_sequence
python
pyranges/pyranges
pyranges/get_fasta.py
https://github.com/pyranges/pyranges/blob/master/pyranges/get_fasta.py
MIT
def count_overlaps(grs, features=None, strandedness=None, how=None, nb_cpu=1): """Count overlaps in multiple pyranges. Parameters ---------- grs : dict of PyRanges The PyRanges to use as queries. features : PyRanges, default None The PyRanges to use as subject in the query. If None, the PyRanges themselves are used as a query. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are stranded, otherwise ignore the strand information. how : {None, "all", "containment"}, default None, i.e. all What intervals to report. By default reports all overlapping intervals. "containment" reports intervals where the overlapping is contained within it. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Examples -------- >>> a = '''Chromosome Start End ... chr1 6 12 ... chr1 10 20 ... chr1 22 27 ... chr1 24 30''' >>> b = '''Chromosome Start End ... chr1 12 32 ... chr1 14 30''' >>> c = '''Chromosome Start End ... chr1 8 15 ... chr1 10 14 ... chr1 32 34''' >>> grs = {n: pr.from_string(s) for n, s in zip(["a", "b", "c"], [a, b, c])} >>> for k, v in grs.items(): ... print("Name: " + k) ... print(v) Name: a +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 6 | 12 | | chr1 | 10 | 20 | | chr1 | 22 | 27 | | chr1 | 24 | 30 | +--------------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Name: b +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 12 | 32 | | chr1 | 14 | 30 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Name: c +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 8 | 15 | | chr1 | 10 | 14 | | chr1 | 32 | 34 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.count_overlaps(grs) +--------------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | a | b | c | | (object) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------| | chr1 | 6 | 8 | 1 | 0 | 0 | | chr1 | 8 | 10 | 1 | 0 | 1 | | chr1 | 10 | 12 | 2 | 0 | 2 | | chr1 | 12 | 14 | 1 | 1 | 2 | | ... | ... | ... | ... | ... | ... | | chr1 | 24 | 27 | 2 | 2 | 0 | | chr1 | 27 | 30 | 1 | 2 | 0 | | chr1 | 30 | 32 | 0 | 1 | 0 | | chr1 | 32 | 34 | 0 | 0 | 1 | +--------------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 12 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr = pr.PyRanges(chromosomes=["chr1"] * 4, starts=[0, 10, 20, 30], ends=[10, 20, 30, 40]) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 10 | | chr1 | 10 | 20 | | chr1 | 20 | 30 | | chr1 | 30 | 40 | +--------------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.count_overlaps(grs, gr) +--------------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | a | b | c | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------| | chr1 | 0 | 10 | 1 | 0 | 1 | | chr1 | 10 | 20 | 2 | 2 | 2 | | chr1 | 20 | 30 | 2 | 2 | 0 | | chr1 | 30 | 40 | 0 | 1 | 1 | +--------------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ kwargs = { "as_pyranges": False, "nb_cpu": nb_cpu, "strandedness": strandedness, "how": how, "nb_cpu": nb_cpu, } names = list(grs.keys()) if features is None: features = pr.concat(grs.values()).split(between=True) else: features = features.copy() from pyranges.methods.intersection import _count_overlaps for name, gr in grs.items(): gr = gr.drop() kwargs["name"] = name features.apply_pair(gr, _count_overlaps, **kwargs) # count overlaps modifies the ranges in-place def to_int(df): df[names] = df[names].astype(np.int64) return df features = features.apply(to_int) return features
Count overlaps in multiple pyranges. Parameters ---------- grs : dict of PyRanges The PyRanges to use as queries. features : PyRanges, default None The PyRanges to use as subject in the query. If None, the PyRanges themselves are used as a query. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are stranded, otherwise ignore the strand information. how : {None, "all", "containment"}, default None, i.e. all What intervals to report. By default reports all overlapping intervals. "containment" reports intervals where the overlapping is contained within it. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Examples -------- >>> a = '''Chromosome Start End ... chr1 6 12 ... chr1 10 20 ... chr1 22 27 ... chr1 24 30''' >>> b = '''Chromosome Start End ... chr1 12 32 ... chr1 14 30''' >>> c = '''Chromosome Start End ... chr1 8 15 ... chr1 10 14 ... chr1 32 34''' >>> grs = {n: pr.from_string(s) for n, s in zip(["a", "b", "c"], [a, b, c])} >>> for k, v in grs.items(): ... print("Name: " + k) ... print(v) Name: a +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 6 | 12 | | chr1 | 10 | 20 | | chr1 | 22 | 27 | | chr1 | 24 | 30 | +--------------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Name: b +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 12 | 32 | | chr1 | 14 | 30 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Name: c +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 8 | 15 | | chr1 | 10 | 14 | | chr1 | 32 | 34 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.count_overlaps(grs) +--------------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | a | b | c | | (object) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------| | chr1 | 6 | 8 | 1 | 0 | 0 | | chr1 | 8 | 10 | 1 | 0 | 1 | | chr1 | 10 | 12 | 2 | 0 | 2 | | chr1 | 12 | 14 | 1 | 1 | 2 | | ... | ... | ... | ... | ... | ... | | chr1 | 24 | 27 | 2 | 2 | 0 | | chr1 | 27 | 30 | 1 | 2 | 0 | | chr1 | 30 | 32 | 0 | 1 | 0 | | chr1 | 32 | 34 | 0 | 0 | 1 | +--------------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 12 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr = pr.PyRanges(chromosomes=["chr1"] * 4, starts=[0, 10, 20, 30], ends=[10, 20, 30, 40]) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 10 | | chr1 | 10 | 20 | | chr1 | 20 | 30 | | chr1 | 30 | 40 | +--------------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> pr.count_overlaps(grs, gr) +--------------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | a | b | c | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------| | chr1 | 0 | 10 | 1 | 0 | 1 | | chr1 | 10 | 20 | 2 | 2 | 2 | | chr1 | 20 | 30 | 2 | 2 | 0 | | chr1 | 30 | 40 | 0 | 1 | 1 | +--------------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
count_overlaps
python
pyranges/pyranges
pyranges/multioverlap.py
https://github.com/pyranges/pyranges/blob/master/pyranges/multioverlap.py
MIT
def fill_kwargs(kwargs): """Give the kwargs dict default options.""" defaults = { "strandedness": None, "overlap": True, "how": None, "invert": None, "new_pos": None, "suffixes": ["_a", "_b"], "suffix": "_b", "sparse": {"self": False, "other": False}, } defaults.update(kwargs) return defaults
Give the kwargs dict default options.
fill_kwargs
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def __array_ufunc__(self, *args, **kwargs): """Apply unary numpy-function. Apply function to all columns which are not index, i.e. Chromosome, Start, End nor Strand. Notes ----- Function must produce a vector of equal length. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 2, 3], "Start": [1, 2, 3], ... "End": [2, 3, 4], "Score": [9, 16, 25], "Score2": [121, 144, 169], ... "Name": ["n1", "n2", "n3"]}) >>> gr +--------------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Score | Score2 | Name | | (category) | (int64) | (int64) | (int64) | (int64) | (object) | |--------------+-----------+-----------+-----------+-----------+------------| | 1 | 1 | 2 | 9 | 121 | n1 | | 2 | 2 | 3 | 16 | 144 | n2 | | 3 | 3 | 4 | 25 | 169 | n3 | +--------------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> np.sqrt(gr) +--------------+-----------+-----------+-------------+-------------+------------+ | Chromosome | Start | End | Score | Score2 | Name | | (category) | (int64) | (int64) | (float64) | (float64) | (object) | |--------------+-----------+-----------+-------------+-------------+------------| | 1 | 1 | 2 | 3 | 11 | n1 | | 2 | 2 | 3 | 4 | 12 | n2 | | 3 | 3 | 4 | 5 | 13 | n3 | +--------------+-----------+-----------+-------------+-------------+------------+ Unstranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ func, call, gr = args columns = list(gr.columns) non_index = [c for c in columns if c not in ["Chromosome", "Start", "End", "Strand"]] for chromosome, df in gr: subset = df.head(1)[non_index].select_dtypes(include=np.number).columns _v = getattr(func, call)(df[subset], **kwargs) # print(_v) # print(df[_c]) df[subset] = _v return gr # self.apply()
Apply unary numpy-function. Apply function to all columns which are not index, i.e. Chromosome, Start, End nor Strand. Notes ----- Function must produce a vector of equal length. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 2, 3], "Start": [1, 2, 3], ... "End": [2, 3, 4], "Score": [9, 16, 25], "Score2": [121, 144, 169], ... "Name": ["n1", "n2", "n3"]}) >>> gr +--------------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Score | Score2 | Name | | (category) | (int64) | (int64) | (int64) | (int64) | (object) | |--------------+-----------+-----------+-----------+-----------+------------| | 1 | 1 | 2 | 9 | 121 | n1 | | 2 | 2 | 3 | 16 | 144 | n2 | | 3 | 3 | 4 | 25 | 169 | n3 | +--------------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> np.sqrt(gr) +--------------+-----------+-----------+-------------+-------------+------------+ | Chromosome | Start | End | Score | Score2 | Name | | (category) | (int64) | (int64) | (float64) | (float64) | (object) | |--------------+-----------+-----------+-------------+-------------+------------| | 1 | 1 | 2 | 3 | 11 | n1 | | 2 | 2 | 3 | 4 | 12 | n2 | | 3 | 3 | 4 | 5 | 13 | n3 | +--------------+-----------+-----------+-------------+-------------+------------+ Unstranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome.
__array_ufunc__
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def __getattr__(self, name): """Return column. Parameters ---------- name : str Column to return Returns ------- pandas.Series Example ------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [0, 100, 250], "End": [10, 125, 251]}) >>> gr.Start 0 0 1 100 2 250 Name: Start, dtype: int64 """ from pyranges.methods.attr import _getattr return _getattr(self, name)
Return column. Parameters ---------- name : str Column to return Returns ------- pandas.Series Example ------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [0, 100, 250], "End": [10, 125, 251]}) >>> gr.Start 0 0 1 100 2 250 Name: Start, dtype: int64
__getattr__
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def __setattr__(self, column_name, column): """Insert or update column. Parameters ---------- column_name : str Name of column to update or insert. column : list, np.array or pd.Series Data to insert. Example ------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [0, 100, 250], "End": [10, 125, 251]}) >>> gr.Start = np.array([1, 1, 2], dtype=np.int64) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 10 | | 1 | 1 | 125 | | 1 | 2 | 251 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from pyranges.methods.attr import _setattr if column_name == "columns": dfs = {} for k, df in self: df.columns = column dfs[k] = df self.__dict__["dfs"] = dfs else: _setattr(self, column_name, column) if column_name in ["Start", "End"]: if self.dtypes["Start"] != self.dtypes["End"]: print( "Warning! Start and End columns now have different dtypes: {} and {}".format( self.dtypes["Start"], self.dtypes["End"] ) )
Insert or update column. Parameters ---------- column_name : str Name of column to update or insert. column : list, np.array or pd.Series Data to insert. Example ------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [0, 100, 250], "End": [10, 125, 251]}) >>> gr.Start = np.array([1, 1, 2], dtype=np.int64) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 10 | | 1 | 1 | 125 | | 1 | 2 | 251 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
__setattr__
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def __getitem__(self, val): """Fetch columns or subset on position. If a list is provided, the column(s) in the list is returned. This subsets on columns. If a numpy array is provided, it must be of type bool and the same length as the PyRanges. Otherwise, a subset of the rows is returned with the location info provided. Parameters ---------- val : bool array/Series, tuple, list, str or slice Data to fetch. Examples -------- >>> gr = pr.data.ensembl_gtf() >>> list(gr.columns) ['Chromosome', 'Source', 'Feature', 'Start', 'End', 'Score', 'Strand', 'Frame', 'gene_biotype', 'gene_id', 'gene_name', 'gene_source', 'gene_version', 'tag', 'transcript_biotype', 'transcript_id', 'transcript_name', 'transcript_source', 'transcript_support_level', 'transcript_version', 'exon_id', 'exon_number', 'exon_version', '(assigned', 'previous', 'protein_id', 'protein_version', 'ccds_id'] >>> gr = gr[["Source", "Feature", "gene_id"]] >>> gr +--------------+------------+--------------+-----------+-----------+--------------+-----------------+ | Chromosome | Source | Feature | Start | End | Strand | gene_id | | (category) | (object) | (category) | (int64) | (int64) | (category) | (object) | |--------------+------------+--------------+-----------+-----------+--------------+-----------------| | 1 | havana | gene | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | transcript | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | exon | 11868 | 12227 | + | ENSG00000223972 | | 1 | havana | exon | 12612 | 12721 | + | ENSG00000223972 | | ... | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | havana | transcript | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | havana | exon | 1179364 | 1179555 | - | ENSG00000205231 | | 1 | havana | exon | 1173055 | 1176396 | - | ENSG00000205231 | +--------------+------------+--------------+-----------+-----------+--------------+-----------------+ Stranded PyRanges object has 2,446 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Create boolean Series and use it to subset: >>> s = (gr.Feature == "gene") | (gr.gene_id == "ENSG00000223972") >>> gr[s] +--------------+----------------+--------------+-----------+-----------+--------------+-----------------+ | Chromosome | Source | Feature | Start | End | Strand | gene_id | | (category) | (object) | (category) | (int64) | (int64) | (category) | (object) | |--------------+----------------+--------------+-----------+-----------+--------------+-----------------| | 1 | havana | gene | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | transcript | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | exon | 11868 | 12227 | + | ENSG00000223972 | | 1 | havana | exon | 12612 | 12721 | + | ENSG00000223972 | | ... | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1062207 | 1063288 | - | ENSG00000273443 | | 1 | ensembl_havana | gene | 1070966 | 1074306 | - | ENSG00000237330 | | 1 | ensembl_havana | gene | 1081817 | 1116361 | - | ENSG00000131591 | | 1 | havana | gene | 1173055 | 1179555 | - | ENSG00000205231 | +--------------+----------------+--------------+-----------+-----------+--------------+-----------------+ Stranded PyRanges object has 95 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs = pr.data.chipseq() >>> cs[10000:100000] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr2 | 33241 | 33266 | U0 | 0 | + | | chr2 | 13611 | 13636 | U0 | 0 | - | | chr2 | 32620 | 32645 | U0 | 0 | - | | chr3 | 87179 | 87204 | U0 | 0 | + | | chr4 | 45413 | 45438 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 5 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs["chr1", "-"] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 100079649 | 100079674 | U0 | 0 | - | | chr1 | 223587418 | 223587443 | U0 | 0 | - | | chr1 | 202450161 | 202450186 | U0 | 0 | - | | chr1 | 156338310 | 156338335 | U0 | 0 | - | | ... | ... | ... | ... | ... | ... | | chr1 | 203557775 | 203557800 | U0 | 0 | - | | chr1 | 28114107 | 28114132 | U0 | 0 | - | | chr1 | 21622765 | 21622790 | U0 | 0 | - | | chr1 | 80668132 | 80668157 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 437 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs["chr5", "-", 90000:] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr5 | 399682 | 399707 | U0 | 0 | - | | chr5 | 1847502 | 1847527 | U0 | 0 | - | | chr5 | 5247533 | 5247558 | U0 | 0 | - | | chr5 | 5300394 | 5300419 | U0 | 0 | - | | ... | ... | ... | ... | ... | ... | | chr5 | 178786234 | 178786259 | U0 | 0 | - | | chr5 | 179268931 | 179268956 | U0 | 0 | - | | chr5 | 179289594 | 179289619 | U0 | 0 | - | | chr5 | 180513795 | 180513820 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 285 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs["chrM"] Empty PyRanges """ from pyranges.methods.getitem import _getitem return _getitem(self, val)
Fetch columns or subset on position. If a list is provided, the column(s) in the list is returned. This subsets on columns. If a numpy array is provided, it must be of type bool and the same length as the PyRanges. Otherwise, a subset of the rows is returned with the location info provided. Parameters ---------- val : bool array/Series, tuple, list, str or slice Data to fetch. Examples -------- >>> gr = pr.data.ensembl_gtf() >>> list(gr.columns) ['Chromosome', 'Source', 'Feature', 'Start', 'End', 'Score', 'Strand', 'Frame', 'gene_biotype', 'gene_id', 'gene_name', 'gene_source', 'gene_version', 'tag', 'transcript_biotype', 'transcript_id', 'transcript_name', 'transcript_source', 'transcript_support_level', 'transcript_version', 'exon_id', 'exon_number', 'exon_version', '(assigned', 'previous', 'protein_id', 'protein_version', 'ccds_id'] >>> gr = gr[["Source", "Feature", "gene_id"]] >>> gr +--------------+------------+--------------+-----------+-----------+--------------+-----------------+ | Chromosome | Source | Feature | Start | End | Strand | gene_id | | (category) | (object) | (category) | (int64) | (int64) | (category) | (object) | |--------------+------------+--------------+-----------+-----------+--------------+-----------------| | 1 | havana | gene | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | transcript | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | exon | 11868 | 12227 | + | ENSG00000223972 | | 1 | havana | exon | 12612 | 12721 | + | ENSG00000223972 | | ... | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | havana | transcript | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | havana | exon | 1179364 | 1179555 | - | ENSG00000205231 | | 1 | havana | exon | 1173055 | 1176396 | - | ENSG00000205231 | +--------------+------------+--------------+-----------+-----------+--------------+-----------------+ Stranded PyRanges object has 2,446 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Create boolean Series and use it to subset: >>> s = (gr.Feature == "gene") | (gr.gene_id == "ENSG00000223972") >>> gr[s] +--------------+----------------+--------------+-----------+-----------+--------------+-----------------+ | Chromosome | Source | Feature | Start | End | Strand | gene_id | | (category) | (object) | (category) | (int64) | (int64) | (category) | (object) | |--------------+----------------+--------------+-----------+-----------+--------------+-----------------| | 1 | havana | gene | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | transcript | 11868 | 14409 | + | ENSG00000223972 | | 1 | havana | exon | 11868 | 12227 | + | ENSG00000223972 | | 1 | havana | exon | 12612 | 12721 | + | ENSG00000223972 | | ... | ... | ... | ... | ... | ... | ... | | 1 | havana | gene | 1062207 | 1063288 | - | ENSG00000273443 | | 1 | ensembl_havana | gene | 1070966 | 1074306 | - | ENSG00000237330 | | 1 | ensembl_havana | gene | 1081817 | 1116361 | - | ENSG00000131591 | | 1 | havana | gene | 1173055 | 1179555 | - | ENSG00000205231 | +--------------+----------------+--------------+-----------+-----------+--------------+-----------------+ Stranded PyRanges object has 95 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs = pr.data.chipseq() >>> cs[10000:100000] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr2 | 33241 | 33266 | U0 | 0 | + | | chr2 | 13611 | 13636 | U0 | 0 | - | | chr2 | 32620 | 32645 | U0 | 0 | - | | chr3 | 87179 | 87204 | U0 | 0 | + | | chr4 | 45413 | 45438 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 5 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs["chr1", "-"] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 100079649 | 100079674 | U0 | 0 | - | | chr1 | 223587418 | 223587443 | U0 | 0 | - | | chr1 | 202450161 | 202450186 | U0 | 0 | - | | chr1 | 156338310 | 156338335 | U0 | 0 | - | | ... | ... | ... | ... | ... | ... | | chr1 | 203557775 | 203557800 | U0 | 0 | - | | chr1 | 28114107 | 28114132 | U0 | 0 | - | | chr1 | 21622765 | 21622790 | U0 | 0 | - | | chr1 | 80668132 | 80668157 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 437 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs["chr5", "-", 90000:] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr5 | 399682 | 399707 | U0 | 0 | - | | chr5 | 1847502 | 1847527 | U0 | 0 | - | | chr5 | 5247533 | 5247558 | U0 | 0 | - | | chr5 | 5300394 | 5300419 | U0 | 0 | - | | ... | ... | ... | ... | ... | ... | | chr5 | 178786234 | 178786259 | U0 | 0 | - | | chr5 | 179268931 | 179268956 | U0 | 0 | - | | chr5 | 179289594 | 179289619 | U0 | 0 | - | | chr5 | 180513795 | 180513820 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 285 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> cs["chrM"] Empty PyRanges
__getitem__
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def apply(self, f, strand=None, as_pyranges=True, nb_cpu=1, **kwargs): """Apply a function to the PyRanges. Parameters ---------- f : function Function to apply on each DataFrame in a PyRanges strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. as_pyranges : bool, default True Whether to return as a PyRanges or dict. If `f` does not return a DataFrame valid for PyRanges, `as_pyranges` must be False. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges or dict Result of applying f to each DataFrame in the PyRanges See also -------- pyranges.PyRanges.apply_pair: apply a function to a pair of PyRanges pyranges.PyRanges.apply_chunks: apply a row-based function to a PyRanges in parallel Note ---- This is the function used internally to carry out almost all unary PyRanges methods. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 2, 2], "Strand": ["+", "+", "-", "+"], ... "Start": [1, 4, 2, 9], "End": [2, 27, 13, 10]}) >>> gr +--------------+--------------+-----------+-----------+ | Chromosome | Strand | Start | End | | (category) | (category) | (int64) | (int64) | |--------------+--------------+-----------+-----------| | 1 | + | 1 | 2 | | 1 | + | 4 | 27 | | 2 | + | 9 | 10 | | 2 | - | 2 | 13 | +--------------+--------------+-----------+-----------+ Stranded PyRanges object has 4 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.apply(lambda df: len(df), as_pyranges=False) {('1', '+'): 2, ('2', '+'): 1, ('2', '-'): 1} >>> gr.apply(lambda df: len(df), as_pyranges=False, strand=False) {'1': 2, '2': 2} >>> def add_to_ends(df, **kwargs): ... df.loc[:, "End"] = kwargs["slack"] + df.End ... return df >>> gr.apply(add_to_ends, slack=500) +--------------+--------------+-----------+-----------+ | Chromosome | Strand | Start | End | | (category) | (category) | (int64) | (int64) | |--------------+--------------+-----------+-----------| | 1 | + | 1 | 502 | | 1 | + | 4 | 527 | | 2 | + | 9 | 510 | | 2 | - | 2 | 513 | +--------------+--------------+-----------+-----------+ Stranded PyRanges object has 4 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if strand is None: strand = self.stranded kwargs.update({"strand": strand}) kwargs.update(kwargs.get("kwargs", {})) kwargs = fill_kwargs(kwargs) result = pyrange_apply_single(f, self, **kwargs) if not as_pyranges: return result else: return PyRanges(result)
Apply a function to the PyRanges. Parameters ---------- f : function Function to apply on each DataFrame in a PyRanges strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. as_pyranges : bool, default True Whether to return as a PyRanges or dict. If `f` does not return a DataFrame valid for PyRanges, `as_pyranges` must be False. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges or dict Result of applying f to each DataFrame in the PyRanges See also -------- pyranges.PyRanges.apply_pair: apply a function to a pair of PyRanges pyranges.PyRanges.apply_chunks: apply a row-based function to a PyRanges in parallel Note ---- This is the function used internally to carry out almost all unary PyRanges methods. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 2, 2], "Strand": ["+", "+", "-", "+"], ... "Start": [1, 4, 2, 9], "End": [2, 27, 13, 10]}) >>> gr +--------------+--------------+-----------+-----------+ | Chromosome | Strand | Start | End | | (category) | (category) | (int64) | (int64) | |--------------+--------------+-----------+-----------| | 1 | + | 1 | 2 | | 1 | + | 4 | 27 | | 2 | + | 9 | 10 | | 2 | - | 2 | 13 | +--------------+--------------+-----------+-----------+ Stranded PyRanges object has 4 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.apply(lambda df: len(df), as_pyranges=False) {('1', '+'): 2, ('2', '+'): 1, ('2', '-'): 1} >>> gr.apply(lambda df: len(df), as_pyranges=False, strand=False) {'1': 2, '2': 2} >>> def add_to_ends(df, **kwargs): ... df.loc[:, "End"] = kwargs["slack"] + df.End ... return df >>> gr.apply(add_to_ends, slack=500) +--------------+--------------+-----------+-----------+ | Chromosome | Strand | Start | End | | (category) | (category) | (int64) | (int64) | |--------------+--------------+-----------+-----------| | 1 | + | 1 | 502 | | 1 | + | 4 | 527 | | 2 | + | 9 | 510 | | 2 | - | 2 | 513 | +--------------+--------------+-----------+-----------+ Stranded PyRanges object has 4 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
apply
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def apply_chunks(self, f, as_pyranges=False, nb_cpu=1, **kwargs): """Apply a row-based function to arbitrary partitions of the PyRanges. apply_chunks speeds up the application of functions where the result is not affected by applying the function to ordered, non-overlapping splits of the data. Parameters ---------- f : function Row-based or associative function to apply on the partitions. as_pyranges : bool, default False Whether to return as a PyRanges or dict. nb_cpu: int, default 1 How many cpus to use. The data is split into nb_cpu partitions. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- dict of lists Result of applying f to each partition of the DataFrames in the PyRanges. See also -------- pyranges.PyRanges.apply_pair: apply a function to a pair of PyRanges pyranges.PyRanges.apply_chunks: apply a row-based function to a PyRanges in parallel Note ---- apply_chunks will only lead to speedups on large datasets or slow-running functions. Using it with nb_cpu=1 is pointless; use apply instead. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [2, 3, 5], "End": [9, 4, 6]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 2 | 9 | | 1 | 3 | 4 | | 1 | 5 | 6 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.apply_chunks( ... lambda df, **kwargs: list(df.End + kwargs["add"]), nb_cpu=1, add=1000) {'1': [[1009, 1004, 1006]]} """ kwargs.update(kwargs.get("kwargs", {})) kwargs = fill_kwargs(kwargs) result = pyrange_apply_chunks(f, self, as_pyranges, **kwargs) return result
Apply a row-based function to arbitrary partitions of the PyRanges. apply_chunks speeds up the application of functions where the result is not affected by applying the function to ordered, non-overlapping splits of the data. Parameters ---------- f : function Row-based or associative function to apply on the partitions. as_pyranges : bool, default False Whether to return as a PyRanges or dict. nb_cpu: int, default 1 How many cpus to use. The data is split into nb_cpu partitions. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- dict of lists Result of applying f to each partition of the DataFrames in the PyRanges. See also -------- pyranges.PyRanges.apply_pair: apply a function to a pair of PyRanges pyranges.PyRanges.apply_chunks: apply a row-based function to a PyRanges in parallel Note ---- apply_chunks will only lead to speedups on large datasets or slow-running functions. Using it with nb_cpu=1 is pointless; use apply instead. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [2, 3, 5], "End": [9, 4, 6]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 2 | 9 | | 1 | 3 | 4 | | 1 | 5 | 6 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.apply_chunks( ... lambda df, **kwargs: list(df.End + kwargs["add"]), nb_cpu=1, add=1000) {'1': [[1009, 1004, 1006]]}
apply_chunks
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def apply_pair(self, other, f, strandedness=None, as_pyranges=True, **kwargs): """Apply a function to a pair of PyRanges. The function is applied to each chromosome or chromosome/strand pair found in at least one of the PyRanges. Parameters ---------- f : function Row-based or associative function to apply on the DataFrames. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. as_pyranges : bool, default False Whether to return as a PyRanges or dict. If `f` does not return a DataFrame valid for PyRanges, `as_pyranges` must be False. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- dict of lists Result of applying f to each partition of the DataFrames in the PyRanges. See also -------- pyranges.PyRanges.apply_pair: apply a function to a pair of PyRanges pyranges.PyRanges.apply_chunks: apply a row-based function to a PyRanges in parallel pyranges.iter: iterate over two or more PyRanges Note ---- This is the function used internally to carry out almost all comparison functions in PyRanges. Examples -------- >>> gr = pr.data.chipseq() >>> gr2 = pr.data.chipseq_background() >>> gr.apply_pair(gr2, pr.methods.intersection._intersection) # same as gr.intersect(gr2) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 226987603 | 226987617 | U0 | 0 | + | | chr8 | 38747236 | 38747251 | U0 | 0 | - | | chr15 | 26105515 | 26105518 | U0 | 0 | + | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1 = pr.data.f1() >>> f1 +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.data.f2() >>> f2 +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 1 | 2 | a | 0 | + | | chr1 | 6 | 7 | b | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.apply_pair(f2, lambda df, df2: (len(df), len(df2)), as_pyranges=False) {('chr1', '+'): (2, 2), ('chr1', '-'): (1, 2)} """ kwargs.update({"strandedness": strandedness}) kwargs.update(kwargs.get("kwargs", {})) kwargs = fill_kwargs(kwargs) result = pyrange_apply(f, self, other, **kwargs) if not as_pyranges: return result else: return PyRanges(result)
Apply a function to a pair of PyRanges. The function is applied to each chromosome or chromosome/strand pair found in at least one of the PyRanges. Parameters ---------- f : function Row-based or associative function to apply on the DataFrames. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. as_pyranges : bool, default False Whether to return as a PyRanges or dict. If `f` does not return a DataFrame valid for PyRanges, `as_pyranges` must be False. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- dict of lists Result of applying f to each partition of the DataFrames in the PyRanges. See also -------- pyranges.PyRanges.apply_pair: apply a function to a pair of PyRanges pyranges.PyRanges.apply_chunks: apply a row-based function to a PyRanges in parallel pyranges.iter: iterate over two or more PyRanges Note ---- This is the function used internally to carry out almost all comparison functions in PyRanges. Examples -------- >>> gr = pr.data.chipseq() >>> gr2 = pr.data.chipseq_background() >>> gr.apply_pair(gr2, pr.methods.intersection._intersection) # same as gr.intersect(gr2) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 226987603 | 226987617 | U0 | 0 | + | | chr8 | 38747236 | 38747251 | U0 | 0 | - | | chr15 | 26105515 | 26105518 | U0 | 0 | + | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1 = pr.data.f1() >>> f1 +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.data.f2() >>> f2 +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 1 | 2 | a | 0 | + | | chr1 | 6 | 7 | b | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.apply_pair(f2, lambda df, df2: (len(df), len(df2)), as_pyranges=False) {('chr1', '+'): (2, 2), ('chr1', '-'): (1, 2)}
apply_pair
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def as_df(self): """Return PyRanges as DataFrame. Returns ------- DataFrame A DataFrame natural sorted on Chromosome and Strand. The ordering of rows within chromosomes and strands is preserved. See also -------- PyRanges.df : Return PyRanges as DataFrame. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 2, 2], "Start": [1, 2, 3, 9], ... "End": [3, 3, 10, 12], "Gene": ["A", "B", "C", "D"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Gene | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | 1 | 1 | 3 | A | | 1 | 2 | 3 | B | | 2 | 3 | 10 | C | | 2 | 9 | 12 | D | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 4 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.as_df() Chromosome Start End Gene 0 1 1 3 A 1 1 2 3 B 2 2 3 10 C 3 2 9 12 D """ if len(self) == 0: return pd.DataFrame() elif len(self) == 1: return self.values()[0] else: return pd.concat(self.values()).reset_index(drop=True)
Return PyRanges as DataFrame. Returns ------- DataFrame A DataFrame natural sorted on Chromosome and Strand. The ordering of rows within chromosomes and strands is preserved. See also -------- PyRanges.df : Return PyRanges as DataFrame. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 2, 2], "Start": [1, 2, 3, 9], ... "End": [3, 3, 10, 12], "Gene": ["A", "B", "C", "D"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Gene | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | 1 | 1 | 3 | A | | 1 | 2 | 3 | B | | 2 | 3 | 10 | C | | 2 | 9 | 12 | D | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 4 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.as_df() Chromosome Start End Gene 0 1 1 3 A 1 1 2 3 B 2 2 3 10 C 3 2 9 12 D
as_df
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def assign(self, col, f, strand=None, nb_cpu=1, **kwargs): """Add or replace a column. Does not change the original PyRanges. Parameters ---------- col : str Name of column. f : function Function to create new column. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges A copy of the PyRanges with the column inserted. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1], "Start": [1, 2], "End": [3, 5], ... "Name": ["a", "b"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | 1 | 1 | 3 | a | | 1 | 2 | 5 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.assign("Blabla", lambda df: df.Chromosome.astype(str) + "_yadayada") +--------------+-----------+-----------+------------+------------+ | Chromosome | Start | End | Name | Blabla | | (category) | (int64) | (int64) | (object) | (object) | |--------------+-----------+-----------+------------+------------| | 1 | 1 | 3 | a | 1_yadayada | | 1 | 2 | 5 | b | 1_yadayada | +--------------+-----------+-----------+------------+------------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Note that assigning to an existing name replaces the column: >>> gr.assign("Name", ... lambda df, **kwargs: df.Start.astype(str) + kwargs["sep"] + ... df.Name.str.capitalize(), sep="_") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | 1 | 1 | 3 | 1_A | | 1 | 2 | 5 | 2_B | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ self = self.copy() if strand is None: strand = self.stranded kwargs["strand"] = strand kwargs = fill_kwargs(kwargs) result = pyrange_apply_single(f, self, **kwargs) first_result = next(iter(result.values())) assert isinstance(first_result, pd.Series), "result of assign function must be Series, but is {}".format( type(first_result) ) # do a deepcopy of object new_self = self.copy() new_self.__setattr__(col, result) return new_self
Add or replace a column. Does not change the original PyRanges. Parameters ---------- col : str Name of column. f : function Function to create new column. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges A copy of the PyRanges with the column inserted. Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1], "Start": [1, 2], "End": [3, 5], ... "Name": ["a", "b"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | 1 | 1 | 3 | a | | 1 | 2 | 5 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.assign("Blabla", lambda df: df.Chromosome.astype(str) + "_yadayada") +--------------+-----------+-----------+------------+------------+ | Chromosome | Start | End | Name | Blabla | | (category) | (int64) | (int64) | (object) | (object) | |--------------+-----------+-----------+------------+------------| | 1 | 1 | 3 | a | 1_yadayada | | 1 | 2 | 5 | b | 1_yadayada | +--------------+-----------+-----------+------------+------------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Note that assigning to an existing name replaces the column: >>> gr.assign("Name", ... lambda df, **kwargs: df.Start.astype(str) + kwargs["sep"] + ... df.Name.str.capitalize(), sep="_") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | 1 | 1 | 3 | 1_A | | 1 | 2 | 5 | 2_B | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
assign
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def boundaries(self, group_by, agg=None): """Return the boundaries of groups of intervals (e.g. transcripts) Parameters ---------- group_by : str or list of str Name(s) of column(s) to group intervals agg : dict or None Defines how to aggregate metadata columns. Provided as dictionary of column names -> functions, function names or list of such, as accepted by the Pandas.DataFrame.agg method. Returns ------- PyRanges One interval per group, with the min(Start) and max(End) of the group Examples -------- >>> d = {"Chromosome": [1, 1, 1], "Start": [1, 60, 110], "End": [40, 68, 130], "transcript_id": ["tr1", "tr1", "tr2"], "meta": ["a", "b", "c"]} >>> gr = pr.from_dict(d) >>> gr.length=gr.lengths() >>> gr +--------------+-----------+-----------+-----------------+------------+-----------+ | Chromosome | Start | End | transcript_id | meta | length | | (category) | (int64) | (int64) | (object) | (object) | (int64) | |--------------+-----------+-----------+-----------------+------------+-----------| | 1 | 1 | 40 | tr1 | a | 39 | | 1 | 60 | 68 | tr1 | b | 8 | | 1 | 110 | 130 | tr2 | c | 20 | +--------------+-----------+-----------+-----------------+------------+-----------+ Unstranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.boundaries("transcript_id") +--------------+-----------+-----------+-----------------+ | Chromosome | Start | End | transcript_id | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+-----------------| | 1 | 1 | 68 | tr1 | | 1 | 110 | 130 | tr2 | +--------------+-----------+-----------+-----------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.boundaries("transcript_id", agg={"length":"sum", "meta": ",".join}) +--------------+-----------+-----------+-----------------+------------+-----------+ | Chromosome | Start | End | transcript_id | meta | length | | (category) | (int64) | (int64) | (object) | (object) | (int64) | |--------------+-----------+-----------+-----------------+------------+-----------| | 1 | 1 | 68 | tr1 | a,b | 47 | | 1 | 110 | 130 | tr2 | c | 20 | +--------------+-----------+-----------+-----------------+------------+-----------+ Unstranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from pyranges.methods.boundaries import _bounds kwargs = {"group_by": group_by, "agg": agg, "strand": self.stranded} kwargs = fill_kwargs(kwargs) result = pyrange_apply_single(_bounds, self, **kwargs) return pr.PyRanges(result)
Return the boundaries of groups of intervals (e.g. transcripts) Parameters ---------- group_by : str or list of str Name(s) of column(s) to group intervals agg : dict or None Defines how to aggregate metadata columns. Provided as dictionary of column names -> functions, function names or list of such, as accepted by the Pandas.DataFrame.agg method. Returns ------- PyRanges One interval per group, with the min(Start) and max(End) of the group Examples -------- >>> d = {"Chromosome": [1, 1, 1], "Start": [1, 60, 110], "End": [40, 68, 130], "transcript_id": ["tr1", "tr1", "tr2"], "meta": ["a", "b", "c"]} >>> gr = pr.from_dict(d) >>> gr.length=gr.lengths() >>> gr +--------------+-----------+-----------+-----------------+------------+-----------+ | Chromosome | Start | End | transcript_id | meta | length | | (category) | (int64) | (int64) | (object) | (object) | (int64) | |--------------+-----------+-----------+-----------------+------------+-----------| | 1 | 1 | 40 | tr1 | a | 39 | | 1 | 60 | 68 | tr1 | b | 8 | | 1 | 110 | 130 | tr2 | c | 20 | +--------------+-----------+-----------+-----------------+------------+-----------+ Unstranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.boundaries("transcript_id") +--------------+-----------+-----------+-----------------+ | Chromosome | Start | End | transcript_id | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+-----------------| | 1 | 1 | 68 | tr1 | | 1 | 110 | 130 | tr2 | +--------------+-----------+-----------+-----------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.boundaries("transcript_id", agg={"length":"sum", "meta": ",".join}) +--------------+-----------+-----------+-----------------+------------+-----------+ | Chromosome | Start | End | transcript_id | meta | length | | (category) | (int64) | (int64) | (object) | (object) | (int64) | |--------------+-----------+-----------+-----------------+------------+-----------| | 1 | 1 | 68 | tr1 | a,b | 47 | | 1 | 110 | 130 | tr2 | c | 20 | +--------------+-----------+-----------+-----------------+------------+-----------+ Unstranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
boundaries
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def calculate_frame(self, by): """Calculate the frame of each genomic interval, assuming all are coding sequences (CDS), and add it as column inplace. After this, the input Pyranges will contain an added "Frame" column, which determines the base of the CDS that is the first base of a codon. Resulting values are in range between 0 and 2 included. 0 indicates that the first base of the CDS is the first base of a codon, 1 indicates the second base and 2 indicates the third base of the CDS. While the 5'-most interval of each transcript has always 0 frame, the following ones may have any of these values. Parameters ---------- by : str or list of str Column(s) to group by the intervals: coding exons belonging to the same transcript have the same values in this/these column(s). Returns ------- None The "Frame" column is added inplace. Examples -------- >>> p= pr.from_dict({"Chromosome": [1,1,1,2,2], ... "Strand": ["+","+","+","-","-"], ... "Start": [1,31,52,101,201], ... "End": [10,45,90,130,218], ... "transcript_id": ["t1","t1","t1","t2","t2"] }) >>> p +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 10 | t1 | | 1 | + | 31 | 45 | t1 | | 1 | + | 52 | 90 | t1 | | 2 | - | 101 | 130 | t2 | | 2 | - | 201 | 218 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> p.calculate_frame(by=['transcript_id']) >>> p +--------------+--------------+-----------+-----------+-----------------+-----------+ | Chromosome | Strand | Start | End | transcript_id | Frame | | (category) | (category) | (int64) | (int64) | (object) | (int64) | |--------------+--------------+-----------+-----------+-----------------+-----------| | 1 | + | 1 | 10 | t1 | 0 | | 1 | + | 31 | 45 | t1 | 9 | | 1 | + | 52 | 90 | t1 | 23 | | 2 | - | 101 | 130 | t2 | 17 | | 2 | - | 201 | 218 | t2 | 0 | +--------------+--------------+-----------+-----------+-----------------+-----------+ Stranded PyRanges object has 5 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ # Column to save the initial index self.__index__ = np.arange(len(self)) # Filtering for desired columns lst = by if type(by) is list else [by] sorted_p = self[["Strand", "__index__"] + lst] # Sorting by 5' (Intervals on + are sorted by ascending order and - are sorted by descending order) sorted_p = sorted_p.sort(by="5") # Creating a column saving the length for the intervals (for selenoprofiles and ensembl) sorted_p.__length__ = sorted_p.End - sorted_p.Start # Creating a column saving the cummulative length for the intervals for k, df in sorted_p: sorted_p.dfs[k]["__cumsum__"] = df.groupby(by=by, observed=False).__length__.cumsum() # Creating a frame column sorted_p.Frame = sorted_p.__cumsum__ - sorted_p.__length__ # Appending the Frame of sorted_p by the index of p sorted_p = sorted_p.apply(lambda df: df.sort_values(by="__index__")) self.Frame = sorted_p.Frame # Drop __index__ column self.apply(lambda df: df.drop("__index__", axis=1, inplace=True))
Calculate the frame of each genomic interval, assuming all are coding sequences (CDS), and add it as column inplace. After this, the input Pyranges will contain an added "Frame" column, which determines the base of the CDS that is the first base of a codon. Resulting values are in range between 0 and 2 included. 0 indicates that the first base of the CDS is the first base of a codon, 1 indicates the second base and 2 indicates the third base of the CDS. While the 5'-most interval of each transcript has always 0 frame, the following ones may have any of these values. Parameters ---------- by : str or list of str Column(s) to group by the intervals: coding exons belonging to the same transcript have the same values in this/these column(s). Returns ------- None The "Frame" column is added inplace. Examples -------- >>> p= pr.from_dict({"Chromosome": [1,1,1,2,2], ... "Strand": ["+","+","+","-","-"], ... "Start": [1,31,52,101,201], ... "End": [10,45,90,130,218], ... "transcript_id": ["t1","t1","t1","t2","t2"] }) >>> p +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 10 | t1 | | 1 | + | 31 | 45 | t1 | | 1 | + | 52 | 90 | t1 | | 2 | - | 101 | 130 | t2 | | 2 | - | 201 | 218 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> p.calculate_frame(by=['transcript_id']) >>> p +--------------+--------------+-----------+-----------+-----------------+-----------+ | Chromosome | Strand | Start | End | transcript_id | Frame | | (category) | (category) | (int64) | (int64) | (object) | (int64) | |--------------+--------------+-----------+-----------+-----------------+-----------| | 1 | + | 1 | 10 | t1 | 0 | | 1 | + | 31 | 45 | t1 | 9 | | 1 | + | 52 | 90 | t1 | 23 | | 2 | - | 101 | 130 | t2 | 17 | | 2 | - | 201 | 218 | t2 | 0 | +--------------+--------------+-----------+-----------+-----------------+-----------+ Stranded PyRanges object has 5 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
calculate_frame
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def cluster(self, strand=None, by=None, slack=0, count=False, nb_cpu=1): """Give overlapping intervals a common id. Parameters ---------- strand : bool, default None, i.e. auto Whether to ignore strand information if PyRanges is stranded. by : str or list, default None Only intervals with an equal value in column(s) `by` are clustered. slack : int, default 0 Consider intervals separated by less than `slack` to be in the same cluster. If `slack` is negative, intervals overlapping less than `slack` are not considered to be in the same cluster. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with an ID-column "Cluster" added. Warning ------- Bookended intervals (i.e. the End of a PyRanges interval is the Start of another one) are by default considered to overlap. Avoid this with slack=-1. See also -------- PyRanges.merge: combine overlapping intervals into one Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1, 1], "Start": [1, 2, 3, 9], ... "End": [3, 3, 10, 12], "Gene": [1, 2, 3, 3]}) >>> gr +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | | 1 | 2 | 3 | 2 | | 1 | 3 | 10 | 3 | | 1 | 9 | 12 | 3 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.cluster() +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | Cluster | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | 1 | | 1 | 2 | 3 | 2 | 1 | | 1 | 3 | 10 | 3 | 1 | | 1 | 9 | 12 | 3 | 1 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.cluster(by="Gene", count=True) +--------------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | Cluster | Count | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | 1 | 1 | | 1 | 2 | 3 | 2 | 2 | 1 | | 1 | 3 | 10 | 3 | 3 | 2 | | 1 | 9 | 12 | 3 | 3 | 2 | +--------------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Avoid clustering bookended intervals with slack=-1: >>> gr.cluster(slack=-1) +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | Cluster | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | 1 | | 1 | 2 | 3 | 2 | 1 | | 1 | 3 | 10 | 3 | 2 | | 1 | 9 | 12 | 3 | 2 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.data.ensembl_gtf()[["Feature", "Source"]] >>> gr2.cluster(by=["Feature", "Source"]) +--------------+--------------+---------------+-----------+-----------+--------------+-----------+ | Chromosome | Feature | Source | Start | End | Strand | Cluster | | (category) | (category) | (object) | (int64) | (int64) | (category) | (int64) | |--------------+--------------+---------------+-----------+-----------+--------------+-----------| | 1 | CDS | ensembl | 69090 | 70005 | + | 1 | | 1 | CDS | ensembl | 925941 | 926013 | + | 2 | | 1 | CDS | ensembl | 925941 | 926013 | + | 2 | | 1 | CDS | ensembl | 925941 | 926013 | + | 2 | | ... | ... | ... | ... | ... | ... | ... | | 1 | transcript | havana_tagene | 167128 | 169240 | - | 1142 | | 1 | transcript | mirbase | 17368 | 17436 | - | 1143 | | 1 | transcript | mirbase | 187890 | 187958 | - | 1144 | | 1 | transcript | mirbase | 632324 | 632413 | - | 1145 | +--------------+--------------+---------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2,446 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if strand is None: strand = self.stranded kwargs = {"strand": strand, "slack": slack, "count": count, "by": by} kwargs = fill_kwargs(kwargs) _stranded = self.stranded if not strand and _stranded: self.Strand2 = self.Strand self = self.unstrand() if not by: from pyranges.methods.cluster import _cluster df = pyrange_apply_single(_cluster, self, **kwargs) else: from pyranges.methods.cluster import _cluster_by kwargs["by"] = by df = pyrange_apply_single(_cluster_by, self, **kwargs) gr = PyRanges(df) # each chromosome got overlapping ids (0 to len). Need to make unique! new_dfs = {} first = True max_id = 0 for k, v in gr.items(): if first: max_id = v.Cluster.max() new_dfs[k] = v first = False continue v.loc[:, "Cluster"] += max_id max_id = v.Cluster.max() new_dfs[k] = v if not strand and _stranded: new_dfs = {k: d.rename(columns={"Strand2": "Strand"}) for k, d in new_dfs.items()} self = PyRanges(new_dfs) return self
Give overlapping intervals a common id. Parameters ---------- strand : bool, default None, i.e. auto Whether to ignore strand information if PyRanges is stranded. by : str or list, default None Only intervals with an equal value in column(s) `by` are clustered. slack : int, default 0 Consider intervals separated by less than `slack` to be in the same cluster. If `slack` is negative, intervals overlapping less than `slack` are not considered to be in the same cluster. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with an ID-column "Cluster" added. Warning ------- Bookended intervals (i.e. the End of a PyRanges interval is the Start of another one) are by default considered to overlap. Avoid this with slack=-1. See also -------- PyRanges.merge: combine overlapping intervals into one Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1, 1, 1], "Start": [1, 2, 3, 9], ... "End": [3, 3, 10, 12], "Gene": [1, 2, 3, 3]}) >>> gr +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | | 1 | 2 | 3 | 2 | | 1 | 3 | 10 | 3 | | 1 | 9 | 12 | 3 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.cluster() +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | Cluster | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | 1 | | 1 | 2 | 3 | 2 | 1 | | 1 | 3 | 10 | 3 | 1 | | 1 | 9 | 12 | 3 | 1 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.cluster(by="Gene", count=True) +--------------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | Cluster | Count | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | 1 | 1 | | 1 | 2 | 3 | 2 | 2 | 1 | | 1 | 3 | 10 | 3 | 3 | 2 | | 1 | 9 | 12 | 3 | 3 | 2 | +--------------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Avoid clustering bookended intervals with slack=-1: >>> gr.cluster(slack=-1) +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Gene | Cluster | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | 1 | 1 | 3 | 1 | 1 | | 1 | 2 | 3 | 2 | 1 | | 1 | 3 | 10 | 3 | 2 | | 1 | 9 | 12 | 3 | 2 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.data.ensembl_gtf()[["Feature", "Source"]] >>> gr2.cluster(by=["Feature", "Source"]) +--------------+--------------+---------------+-----------+-----------+--------------+-----------+ | Chromosome | Feature | Source | Start | End | Strand | Cluster | | (category) | (category) | (object) | (int64) | (int64) | (category) | (int64) | |--------------+--------------+---------------+-----------+-----------+--------------+-----------| | 1 | CDS | ensembl | 69090 | 70005 | + | 1 | | 1 | CDS | ensembl | 925941 | 926013 | + | 2 | | 1 | CDS | ensembl | 925941 | 926013 | + | 2 | | 1 | CDS | ensembl | 925941 | 926013 | + | 2 | | ... | ... | ... | ... | ... | ... | ... | | 1 | transcript | havana_tagene | 167128 | 169240 | - | 1142 | | 1 | transcript | mirbase | 17368 | 17436 | - | 1143 | | 1 | transcript | mirbase | 187890 | 187958 | - | 1144 | | 1 | transcript | mirbase | 632324 | 632413 | - | 1145 | +--------------+--------------+---------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2,446 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
cluster
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def columns(self): """Return the column labels of the PyRanges. Returns ------- pandas.Index See also -------- PyRanges.chromosomes : return the chromosomes in the PyRanges Examples -------- >>> f2 = pr.data.f2() >>> f2 +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 1 | 2 | a | 0 | + | | chr1 | 6 | 7 | b | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2.columns Index(['Chromosome', 'Start', 'End', 'Name', 'Score', 'Strand'], dtype='object') >>> f2.columns = f2.columns.str.replace("Sco|re", "NYAN", regex=True) >>> f2 +--------------+-----------+-----------+------------+------------+--------------+ | Chromosome | Start | End | Name | NYANNYAN | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+------------+--------------| | chr1 | 1 | 2 | a | 0 | + | | chr1 | 6 | 7 | b | 0 | - | +--------------+-----------+-----------+------------+------------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if not len(self.values()): return [] first = next(iter(self.values())) columns = first.columns return columns
Return the column labels of the PyRanges. Returns ------- pandas.Index See also -------- PyRanges.chromosomes : return the chromosomes in the PyRanges Examples -------- >>> f2 = pr.data.f2() >>> f2 +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 1 | 2 | a | 0 | + | | chr1 | 6 | 7 | b | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2.columns Index(['Chromosome', 'Start', 'End', 'Name', 'Score', 'Strand'], dtype='object') >>> f2.columns = f2.columns.str.replace("Sco|re", "NYAN", regex=True) >>> f2 +--------------+-----------+-----------+------------+------------+--------------+ | Chromosome | Start | End | Name | NYANNYAN | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+------------+--------------| | chr1 | 1 | 2 | a | 0 | + | | chr1 | 6 | 7 | b | 0 | - | +--------------+-----------+-----------+------------+------------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
columns
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def count_overlaps( self, other, strandedness=None, keep_nonoverlapping=True, overlap_col="NumberOverlaps", ): """Count number of overlaps per interval. Count how many intervals in self overlap with those in other. Parameters ---------- strandedness : {"same", "opposite", None, False}, default None, i.e. auto Whether to perform the operation on the same, opposite or no strand. Use False to ignore the strand. None means use "same" if both PyRanges are stranded, otherwise ignore. keep_nonoverlapping : bool, default True Keep intervals without overlaps. overlap_col : str, default "NumberOverlaps" Name of column with overlap counts. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with a column of overlaps added. See also -------- PyRanges.coverage: find coverage of PyRanges pyranges.count_overlaps: count overlaps from multiple PyRanges Examples -------- >>> f1 = pr.data.f1().drop() >>> f1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.data.f2().drop() >>> f2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 2 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.count_overlaps(f2, overlap_col="Count") +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Count | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 3 | 6 | + | 0 | | chr1 | 8 | 9 | + | 0 | | chr1 | 5 | 7 | - | 1 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ kwargs = { "strandedness": strandedness, "keep_nonoverlapping": keep_nonoverlapping, "overlap_col": overlap_col, } kwargs = fill_kwargs(kwargs) from pyranges.methods.coverage import _number_overlapping counts = pyrange_apply(_number_overlapping, self, other, **kwargs) return pr.PyRanges(counts)
Count number of overlaps per interval. Count how many intervals in self overlap with those in other. Parameters ---------- strandedness : {"same", "opposite", None, False}, default None, i.e. auto Whether to perform the operation on the same, opposite or no strand. Use False to ignore the strand. None means use "same" if both PyRanges are stranded, otherwise ignore. keep_nonoverlapping : bool, default True Keep intervals without overlaps. overlap_col : str, default "NumberOverlaps" Name of column with overlap counts. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with a column of overlaps added. See also -------- PyRanges.coverage: find coverage of PyRanges pyranges.count_overlaps: count overlaps from multiple PyRanges Examples -------- >>> f1 = pr.data.f1().drop() >>> f1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.data.f2().drop() >>> f2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 2 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.count_overlaps(f2, overlap_col="Count") +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Count | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 3 | 6 | + | 0 | | chr1 | 8 | 9 | + | 0 | | chr1 | 5 | 7 | - | 1 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
count_overlaps
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def coverage( self, other, strandedness=None, keep_nonoverlapping=True, overlap_col="NumberOverlaps", fraction_col="FractionOverlaps", nb_cpu=1, ): """Count number of overlaps and their fraction per interval. Count how many intervals in self overlap with those in other. Parameters ---------- strandedness : {"same", "opposite", None, False}, default None, i.e. auto Whether to perform the operation on the same, opposite or no strand. Use False to ignore the strand. None means use "same" if both PyRanges are stranded, otherwise ignore. keep_nonoverlapping : bool, default True Keep intervals without overlaps. overlap_col : str, default "NumberOverlaps" Name of column with overlap counts. fraction_col : str, default "FractionOverlaps" Name of column with fraction of counts. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with a column of overlaps added. See also -------- pyranges.count_overlaps: count overlaps from multiple PyRanges Examples -------- >>> f1 = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [3, 8, 5], ... "End": [6, 9, 7]}) >>> f1 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 3 | 6 | | 1 | 8 | 9 | | 1 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f2 = pr.from_dict({"Chromosome": [1, 1], "Start": [1, 6], ... "End": [2, 7]}) >>> f2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 1 | 6 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.coverage(f2, overlap_col="C", fraction_col="F") +--------------+-----------+-----------+-----------+-------------+ | Chromosome | Start | End | C | F | | (category) | (int64) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-----------+-------------| | 1 | 3 | 6 | 0 | 0 | | 1 | 8 | 9 | 0 | 0 | | 1 | 5 | 7 | 1 | 0.5 | +--------------+-----------+-----------+-----------+-------------+ Unstranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ kwargs = { "strandedness": strandedness, "keep_nonoverlapping": keep_nonoverlapping, "overlap_col": overlap_col, "fraction_col": fraction_col, "nb_cpu": nb_cpu, } kwargs = fill_kwargs(kwargs) counts = self.count_overlaps( other, keep_nonoverlapping=True, overlap_col=overlap_col, strandedness=strandedness, ) strand = True if kwargs["strandedness"] else False other = other.merge(count=True, strand=strand) from pyranges.methods.coverage import _coverage counts = pr.PyRanges(pyrange_apply(_coverage, counts, other, **kwargs)) return counts
Count number of overlaps and their fraction per interval. Count how many intervals in self overlap with those in other. Parameters ---------- strandedness : {"same", "opposite", None, False}, default None, i.e. auto Whether to perform the operation on the same, opposite or no strand. Use False to ignore the strand. None means use "same" if both PyRanges are stranded, otherwise ignore. keep_nonoverlapping : bool, default True Keep intervals without overlaps. overlap_col : str, default "NumberOverlaps" Name of column with overlap counts. fraction_col : str, default "FractionOverlaps" Name of column with fraction of counts. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with a column of overlaps added. See also -------- pyranges.count_overlaps: count overlaps from multiple PyRanges Examples -------- >>> f1 = pr.from_dict({"Chromosome": [1, 1, 1], "Start": [3, 8, 5], ... "End": [6, 9, 7]}) >>> f1 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 3 | 6 | | 1 | 8 | 9 | | 1 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f2 = pr.from_dict({"Chromosome": [1, 1], "Start": [1, 6], ... "End": [2, 7]}) >>> f2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 1 | 2 | | 1 | 6 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.coverage(f2, overlap_col="C", fraction_col="F") +--------------+-----------+-----------+-----------+-------------+ | Chromosome | Start | End | C | F | | (category) | (int64) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-----------+-------------| | 1 | 3 | 6 | 0 | 0 | | 1 | 8 | 9 | 0 | 0 | | 1 | 5 | 7 | 1 | 0.5 | +--------------+-----------+-----------+-----------+-------------+ Unstranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
coverage
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def drop(self, drop=None, like=None): """Drop column(s). If no arguments are given, all the columns except Chromosome, Start, End and Strand are dropped. Parameters ---------- drop : str or list, default None Columns to drop. like : str, default None Regex-string matching columns to drop. Matches with Chromosome, Start, End or Strand are ignored. See also -------- PyRanges.unstrand : drop strand information Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1], "Start": [1, 4], "End": [5, 6], ... "Strand": ["+", "-"], "Count": [1, 2], ... "Type": ["exon", "exon"]}) >>> gr +--------------+-----------+-----------+--------------+-----------+------------+ | Chromosome | Start | End | Strand | Count | Type | | (category) | (int64) | (int64) | (category) | (int64) | (object) | |--------------+-----------+-----------+--------------+-----------+------------| | 1 | 1 | 5 | + | 1 | exon | | 1 | 4 | 6 | - | 2 | exon | +--------------+-----------+-----------+--------------+-----------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop() +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 1 | 1 | 5 | + | | 1 | 4 | 6 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Matches with position-columns are ignored: >>> gr.drop(like="Chromosome|Strand") +--------------+-----------+-----------+--------------+-----------+------------+ | Chromosome | Start | End | Strand | Count | Type | | (category) | (int64) | (int64) | (category) | (int64) | (object) | |--------------+-----------+-----------+--------------+-----------+------------| | 1 | 1 | 5 | + | 1 | exon | | 1 | 4 | 6 | - | 2 | exon | +--------------+-----------+-----------+--------------+-----------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop(like="e$") +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Count | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | 1 | 1 | 5 | + | 1 | | 1 | 4 | 6 | - | 2 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.drop import _drop return _drop(self, drop, like)
Drop column(s). If no arguments are given, all the columns except Chromosome, Start, End and Strand are dropped. Parameters ---------- drop : str or list, default None Columns to drop. like : str, default None Regex-string matching columns to drop. Matches with Chromosome, Start, End or Strand are ignored. See also -------- PyRanges.unstrand : drop strand information Examples -------- >>> gr = pr.from_dict({"Chromosome": [1, 1], "Start": [1, 4], "End": [5, 6], ... "Strand": ["+", "-"], "Count": [1, 2], ... "Type": ["exon", "exon"]}) >>> gr +--------------+-----------+-----------+--------------+-----------+------------+ | Chromosome | Start | End | Strand | Count | Type | | (category) | (int64) | (int64) | (category) | (int64) | (object) | |--------------+-----------+-----------+--------------+-----------+------------| | 1 | 1 | 5 | + | 1 | exon | | 1 | 4 | 6 | - | 2 | exon | +--------------+-----------+-----------+--------------+-----------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop() +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 1 | 1 | 5 | + | | 1 | 4 | 6 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Matches with position-columns are ignored: >>> gr.drop(like="Chromosome|Strand") +--------------+-----------+-----------+--------------+-----------+------------+ | Chromosome | Start | End | Strand | Count | Type | | (category) | (int64) | (int64) | (category) | (int64) | (object) | |--------------+-----------+-----------+--------------+-----------+------------| | 1 | 1 | 5 | + | 1 | exon | | 1 | 4 | 6 | - | 2 | exon | +--------------+-----------+-----------+--------------+-----------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop(like="e$") +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Count | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | 1 | 1 | 5 | + | 1 | | 1 | 4 | 6 | - | 2 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
drop
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def drop_duplicate_positions(self, strand=None, keep="first"): """Return PyRanges with duplicate postion rows removed. Parameters ---------- strand : bool, default None, i.e. auto Whether to take strand-information into account when considering duplicates. keep : {"first", "last", False} Whether to keep first, last or drop all duplicates. Examples -------- >>> gr = pr.from_string('''Chromosome Start End Strand Name ... 1 1 2 + A ... 1 1 2 - B ... 1 1 2 + Z''') >>> gr +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | + | A | | 1 | 1 | 2 | + | Z | | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop_duplicate_positions() +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | + | A | | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop_duplicate_positions(keep="last") +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | + | Z | | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Note that the reverse strand is considered to be behind the forward strand: >>> gr.drop_duplicate_positions(keep="last", strand=False) +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 1 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop_duplicate_positions(keep=False, strand=False) Empty PyRanges """ from pyranges.methods.drop_duplicates import _drop_duplicate_positions if strand is None: strand = self.stranded kwargs = {} kwargs["sparse"] = {"self": False} kwargs["keep"] = keep kwargs = fill_kwargs(kwargs) kwargs["strand"] = strand and self.stranded return PyRanges(pyrange_apply_single(_drop_duplicate_positions, self, **kwargs))
Return PyRanges with duplicate postion rows removed. Parameters ---------- strand : bool, default None, i.e. auto Whether to take strand-information into account when considering duplicates. keep : {"first", "last", False} Whether to keep first, last or drop all duplicates. Examples -------- >>> gr = pr.from_string('''Chromosome Start End Strand Name ... 1 1 2 + A ... 1 1 2 - B ... 1 1 2 + Z''') >>> gr +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | + | A | | 1 | 1 | 2 | + | Z | | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop_duplicate_positions() +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | + | A | | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop_duplicate_positions(keep="last") +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | + | Z | | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Note that the reverse strand is considered to be behind the forward strand: >>> gr.drop_duplicate_positions(keep="last", strand=False) +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Name | | (category) | (int64) | (int64) | (category) | (object) | |--------------+-----------+-----------+--------------+------------| | 1 | 1 | 2 | - | B | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 1 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.drop_duplicate_positions(keep=False, strand=False) Empty PyRanges
drop_duplicate_positions
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def extend(self, ext, group_by=None): """Extend the intervals from the ends. Parameters ---------- ext : int or dict of ints with "3" and/or "5" as keys. The number of nucleotides to extend the ends with. If an int is provided, the same extension is applied to both the start and end of intervals, while a dict input allows to control differently the two ends. Note also that 5' and 3' extensions take the strand into account, if the intervals are stranded. group_by : str or list of str, default: None group intervals by these column name(s), so that the extension is applied only to the left-most and/or right-most interval. See Also -------- PyRanges.subsequence : obtain subsequences of intervals PyRanges.spliced_subsequence : obtain subsequences of intervals, providing transcript-level coordinates Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], 'End': [6, 9, 7], ... 'Strand': ['+', '+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend(4) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 0 | 10 | + | | chr1 | 4 | 13 | + | | chr1 | 1 | 11 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend({"3": 1}) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 7 | + | | chr1 | 8 | 10 | + | | chr1 | 4 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend({"3": 1, "5": 2}) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 7 | + | | chr1 | 6 | 10 | + | | chr1 | 4 | 9 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend(-1) Traceback (most recent call last): ... AssertionError: Some intervals are negative or zero length after applying extend! """ if isinstance(ext, dict): assert self.stranded, "PyRanges must be stranded to add 5/3-end specific extend." kwargs = fill_kwargs({"ext": ext, "strand": self.stranded}) if group_by is None: prg = PyRanges(pyrange_apply_single(_extend, self, **kwargs)) else: kwargs["group_by"] = group_by prg = PyRanges(pyrange_apply_single(_extend_grp, self, **kwargs)) return prg
Extend the intervals from the ends. Parameters ---------- ext : int or dict of ints with "3" and/or "5" as keys. The number of nucleotides to extend the ends with. If an int is provided, the same extension is applied to both the start and end of intervals, while a dict input allows to control differently the two ends. Note also that 5' and 3' extensions take the strand into account, if the intervals are stranded. group_by : str or list of str, default: None group intervals by these column name(s), so that the extension is applied only to the left-most and/or right-most interval. See Also -------- PyRanges.subsequence : obtain subsequences of intervals PyRanges.spliced_subsequence : obtain subsequences of intervals, providing transcript-level coordinates Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], 'End': [6, 9, 7], ... 'Strand': ['+', '+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend(4) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 0 | 10 | + | | chr1 | 4 | 13 | + | | chr1 | 1 | 11 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend({"3": 1}) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 7 | + | | chr1 | 8 | 10 | + | | chr1 | 4 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend({"3": 1, "5": 2}) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 7 | + | | chr1 | 6 | 10 | + | | chr1 | 4 | 9 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.extend(-1) Traceback (most recent call last): ... AssertionError: Some intervals are negative or zero length after applying extend!
extend
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def five_end(self): """Return the five prime end of intervals. The five prime end is the start of a forward strand or the end of a reverse strand. Returns ------- PyRanges PyRanges with the five prime ends Notes ----- Requires the PyRanges to be stranded. See Also -------- PyRanges.three_end : return the 3' end Examples -------- >>> gr = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [3, 5], 'End': [9, 7], ... 'Strand': ["+", "-"]}) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.five_end() +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 4 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ assert self.stranded, "Need stranded pyrange to find 5'." kwargs = fill_kwargs({"strand": self.stranded}) return PyRanges(pyrange_apply_single(_tss, self, **kwargs))
Return the five prime end of intervals. The five prime end is the start of a forward strand or the end of a reverse strand. Returns ------- PyRanges PyRanges with the five prime ends Notes ----- Requires the PyRanges to be stranded. See Also -------- PyRanges.three_end : return the 3' end Examples -------- >>> gr = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [3, 5], 'End': [9, 7], ... 'Strand': ["+", "-"]}) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.five_end() +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 4 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
five_end
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def head(self, n=8): """Return the n first rows. Parameters ---------- n : int, default 8 Return n rows. Returns ------- PyRanges PyRanges with the n first rows. See Also -------- PyRanges.tail : return the last rows PyRanges.sample : return random rows Examples -------- >>> gr = pr.data.chipseq() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.head(3) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ subsetter = np.zeros(len(self), dtype=np.bool_) subsetter[:n] = True return self[subsetter]
Return the n first rows. Parameters ---------- n : int, default 8 Return n rows. Returns ------- PyRanges PyRanges with the n first rows. See Also -------- PyRanges.tail : return the last rows PyRanges.sample : return random rows Examples -------- >>> gr = pr.data.chipseq() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.head(3) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
head
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def insert(self, other, loc=None): """Add one or more columns to the PyRanges. Parameters ---------- other : Series, DataFrame or dict Data to insert into the PyRanges. `other` must have the same number of rows as the PyRanges. loc : int, default None, i.e. after last column of PyRanges. Insertion index. Returns ------- PyRanges A copy of the PyRanges with the column(s) inserted starting at `loc`. Note ---- If a Series, or a dict of Series is used, the Series must have a name. Examples -------- >>> gr = pr.from_dict({"Chromosome": ["L", "E", "E", "T"], "Start": [1, 1, 2, 3], "End": [5, 8, 13, 21]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | E | 1 | 8 | | E | 2 | 13 | | L | 1 | 5 | | T | 3 | 21 | +--------------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 3 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> s = pd.Series(data = [1, 3, 3, 7], name="Column") >>> gr.insert(s) +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | Column | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | E | 1 | 8 | 1 | | E | 2 | 13 | 3 | | L | 1 | 5 | 3 | | T | 3 | 21 | 7 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 4 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> df = pd.DataFrame({"NY": s, "AN": s}) >>> df NY AN 0 1 1 1 3 3 2 3 3 3 7 7 Note that the original PyRanges was not affected by previously inserting Column: >>> gr.insert(df, 1) +--------------+-----------+-----------+-----------+-----------+ | Chromosome | NY | AN | Start | End | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | E | 1 | 1 | 1 | 8 | | E | 3 | 3 | 2 | 13 | | L | 3 | 3 | 1 | 5 | | T | 7 | 7 | 3 | 21 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> arbitrary_result = gr.apply( ... lambda df: pd.Series(df.Start + df.End, name="Hi!"), as_pyranges=False) >>> arbitrary_result {'E': 1 9 2 15 Name: Hi!, dtype: int64, 'L': 0 6 Name: Hi!, dtype: int64, 'T': 3 24 Name: Hi!, dtype: int64} >>> gr.insert(arbitrary_result) +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | Hi! | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | E | 1 | 8 | 9 | | E | 2 | 13 | 15 | | L | 1 | 5 | 6 | | T | 3 | 21 | 24 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 4 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ if loc is None: loc = len(self.columns) self = self.copy() from pyranges.methods.attr import _setattr if isinstance(other, (pd.Series, pd.DataFrame)): assert len(other) == len(self), "Pandas Series or DataFrame must be same length as PyRanges!" if isinstance(other, pd.Series): if not other.name: raise Exception("Series must have a name!") _setattr(self, other.name, other, loc) if isinstance(other, pd.DataFrame): for c in other: _setattr(self, c, other[c], loc) loc += 1 elif isinstance(other, dict) and other: first = next(iter(other.values())) is_dataframe = isinstance(first, pd.DataFrame) if is_dataframe: columns = first.columns ds = [] for c in columns: ds.append({k: v[c] for k, v in other.items()}) for c, d in zip(columns, ds): _setattr(self, str(c), d, loc) loc += 1 else: if not first.name: raise Exception("Series must have a name!") d = {k: v for k, v in other.items()} _setattr(self, first.name, d, loc) return self
Add one or more columns to the PyRanges. Parameters ---------- other : Series, DataFrame or dict Data to insert into the PyRanges. `other` must have the same number of rows as the PyRanges. loc : int, default None, i.e. after last column of PyRanges. Insertion index. Returns ------- PyRanges A copy of the PyRanges with the column(s) inserted starting at `loc`. Note ---- If a Series, or a dict of Series is used, the Series must have a name. Examples -------- >>> gr = pr.from_dict({"Chromosome": ["L", "E", "E", "T"], "Start": [1, 1, 2, 3], "End": [5, 8, 13, 21]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | E | 1 | 8 | | E | 2 | 13 | | L | 1 | 5 | | T | 3 | 21 | +--------------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 3 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> s = pd.Series(data = [1, 3, 3, 7], name="Column") >>> gr.insert(s) +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | Column | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | E | 1 | 8 | 1 | | E | 2 | 13 | 3 | | L | 1 | 5 | 3 | | T | 3 | 21 | 7 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 4 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> df = pd.DataFrame({"NY": s, "AN": s}) >>> df NY AN 0 1 1 1 3 3 2 3 3 3 7 7 Note that the original PyRanges was not affected by previously inserting Column: >>> gr.insert(df, 1) +--------------+-----------+-----------+-----------+-----------+ | Chromosome | NY | AN | Start | End | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | E | 1 | 1 | 1 | 8 | | E | 3 | 3 | 2 | 13 | | L | 3 | 3 | 1 | 5 | | T | 7 | 7 | 3 | 21 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> arbitrary_result = gr.apply( ... lambda df: pd.Series(df.Start + df.End, name="Hi!"), as_pyranges=False) >>> arbitrary_result {'E': 1 9 2 15 Name: Hi!, dtype: int64, 'L': 0 6 Name: Hi!, dtype: int64, 'T': 3 24 Name: Hi!, dtype: int64} >>> gr.insert(arbitrary_result) +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | Hi! | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | E | 1 | 8 | 9 | | E | 2 | 13 | 15 | | L | 1 | 5 | 6 | | T | 3 | 21 | 24 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 4 rows and 4 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome.
insert
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def intersect(self, other, strandedness=None, how=None, invert=False, nb_cpu=1): """Return overlapping subintervals. Returns the segments of the intervals in self which overlap with those in other. Parameters ---------- other : PyRanges PyRanges to intersect. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {None, "first", "last", "containment"}, default None, i.e. all What intervals to report. By default reports all overlapping intervals. "containment" reports intervals where the overlapping is contained within it. invert : bool, default False Whether to return the intervals without overlaps. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with overlapping subintervals. See also -------- PyRanges.set_intersect : set-intersect PyRanges PyRanges.overlap : report overlapping intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.intersect(gr2) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 2 | 3 | a | | chr1 | 2 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.intersect(gr2, how="first") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 2 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.intersect(gr2, how="containment") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ kwargs = {"how": how, "strandedness": strandedness, "nb_cpu": nb_cpu} kwargs = fill_kwargs(kwargs) kwargs["sparse"] = {"self": False, "other": True} if len(self) == 0: return self if invert: self.__ix__ = np.arange(len(self)) dfs = pyrange_apply(_intersection, self, other, **kwargs) result = pr.PyRanges(dfs) if invert: found_idxs = getattr(result, "__ix__", []) result = self[~self.__ix__.isin(found_idxs)] result = result.drop("__ix__") return result
Return overlapping subintervals. Returns the segments of the intervals in self which overlap with those in other. Parameters ---------- other : PyRanges PyRanges to intersect. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {None, "first", "last", "containment"}, default None, i.e. all What intervals to report. By default reports all overlapping intervals. "containment" reports intervals where the overlapping is contained within it. invert : bool, default False Whether to return the intervals without overlaps. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with overlapping subintervals. See also -------- PyRanges.set_intersect : set-intersect PyRanges PyRanges.overlap : report overlapping intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.intersect(gr2) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 2 | 3 | a | | chr1 | 2 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.intersect(gr2, how="first") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 2 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.intersect(gr2, how="containment") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
intersect
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def join( self, other, strandedness=None, how=None, report_overlap=False, slack=0, suffix="_b", nb_cpu=1, apply_strand_suffix=None, preserve_order=False, ): """Join PyRanges on genomic location. Parameters ---------- other : PyRanges PyRanges to join. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {None, "left", "right"}, default None, i.e. "inner" How to handle intervals without overlap. None means only keep overlapping intervals. "left" keeps all intervals in self, "right" keeps all intervals in other. report_overlap : bool, default False Report amount of overlap in base pairs. slack : int, default 0 Lengthen intervals in self before joining. suffix : str or tuple, default "_b" Suffix to give overlapping columns in other. apply_strand_suffix : bool, default None If first pyranges is unstranded, but the second is not, the first will be given a strand column. apply_strand_suffix makes the added strand column a regular data column instead by adding a suffix. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. preserve_order : bool, default False If True, preserves the order after performing the join (only relevant in "outer", "left" and "right" joins). Returns ------- PyRanges A PyRanges appended with columns of another. Notes ----- The chromosome from other will never be reported as it is always the same as in self. As pandas did not have NaN for non-float datatypes until recently, "left" and "right" join give non-overlapping rows the value -1 to avoid promoting columns to object. This will change to NaN in a future version as general NaN becomes stable in pandas. See also -------- PyRanges.new_position : give joined PyRanges new coordinates Examples -------- >>> f1 = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Name': ['interval1', 'interval3', 'interval2']}) >>> f1 +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 3 | 6 | interval1 | | chr1 | 8 | 9 | interval3 | | chr1 | 5 | 7 | interval2 | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [2, 7], 'Name': ['a', 'b']}) >>> f2 +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 2 | a | | chr1 | 6 | 7 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.join(f2) +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | 5 | 7 | interval2 | 6 | 7 | b | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.join(f2, how="right") +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | 5 | 7 | interval2 | 6 | 7 | b | | chr1 | -1 | -1 | -1 | 1 | 2 | a | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. With slack 1, bookended features are joined (see row 1): >>> f1.join(f2, slack=1) +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | 3 | 6 | interval1 | 6 | 7 | b | | chr1 | 5 | 7 | interval2 | 6 | 7 | b | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.join(f2, how="right", preserve_order=True) +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | -1 | -1 | -1 | 1 | 2 | a | | chr1 | 5 | 7 | interval2 | 6 | 7 | b | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from pyranges.methods.join import _write_both kwargs = { "strandedness": strandedness, "how": how, "report_overlap": report_overlap, "suffix": suffix, "nb_cpu": nb_cpu, "apply_strand_suffix": apply_strand_suffix, "preserve_order": preserve_order, } if slack: self = self.copy() self.Start__slack = self.Start self.End__slack = self.End self = self.extend(slack) if "suffix" in kwargs and isinstance(kwargs["suffix"], str): suffixes = "", kwargs["suffix"] kwargs["suffixes"] = suffixes kwargs = fill_kwargs(kwargs) how = kwargs.get("how") if how in ["left", "outer"]: kwargs["example_header_other"] = other.head(1).df if how in ["right", "outer"]: kwargs["example_header_self"] = self.head(1).df dfs = pyrange_apply(_write_both, self, other, **kwargs) gr = PyRanges(dfs) if slack and len(gr) > 0: gr.Start = gr.Start__slack gr.End = gr.End__slack gr = gr.drop(like="(Start|End).*__slack") if not self.stranded and other.stranded: if apply_strand_suffix is None: import sys print( "join: Strand data from other will be added as strand data to self.\nIf this is undesired use the flag apply_strand_suffix=False.\nTo turn off the warning set apply_strand_suffix to True or False.", file=sys.stderr, ) elif apply_strand_suffix: gr.columns = gr.columns.str.replace("Strand", "Strand" + kwargs["suffix"]) return gr
Join PyRanges on genomic location. Parameters ---------- other : PyRanges PyRanges to join. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {None, "left", "right"}, default None, i.e. "inner" How to handle intervals without overlap. None means only keep overlapping intervals. "left" keeps all intervals in self, "right" keeps all intervals in other. report_overlap : bool, default False Report amount of overlap in base pairs. slack : int, default 0 Lengthen intervals in self before joining. suffix : str or tuple, default "_b" Suffix to give overlapping columns in other. apply_strand_suffix : bool, default None If first pyranges is unstranded, but the second is not, the first will be given a strand column. apply_strand_suffix makes the added strand column a regular data column instead by adding a suffix. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. preserve_order : bool, default False If True, preserves the order after performing the join (only relevant in "outer", "left" and "right" joins). Returns ------- PyRanges A PyRanges appended with columns of another. Notes ----- The chromosome from other will never be reported as it is always the same as in self. As pandas did not have NaN for non-float datatypes until recently, "left" and "right" join give non-overlapping rows the value -1 to avoid promoting columns to object. This will change to NaN in a future version as general NaN becomes stable in pandas. See also -------- PyRanges.new_position : give joined PyRanges new coordinates Examples -------- >>> f1 = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Name': ['interval1', 'interval3', 'interval2']}) >>> f1 +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 3 | 6 | interval1 | | chr1 | 8 | 9 | interval3 | | chr1 | 5 | 7 | interval2 | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [2, 7], 'Name': ['a', 'b']}) >>> f2 +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 2 | a | | chr1 | 6 | 7 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.join(f2) +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | 5 | 7 | interval2 | 6 | 7 | b | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.join(f2, how="right") +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | 5 | 7 | interval2 | 6 | 7 | b | | chr1 | -1 | -1 | -1 | 1 | 2 | a | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. With slack 1, bookended features are joined (see row 1): >>> f1.join(f2, slack=1) +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | 3 | 6 | interval1 | 6 | 7 | b | | chr1 | 5 | 7 | interval2 | 6 | 7 | b | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> f1.join(f2, how="right", preserve_order=True) +--------------+-----------+-----------+------------+-----------+-----------+------------+ | Chromosome | Start | End | Name | Start_b | End_b | Name_b | | (category) | (int64) | (int64) | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------+-----------+-----------+------------| | chr1 | -1 | -1 | -1 | 1 | 2 | a | | chr1 | 5 | 7 | interval2 | 6 | 7 | b | +--------------+-----------+-----------+------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
join
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def k_nearest( self, other, k=1, ties=None, strandedness=None, overlap=True, how=None, suffix="_b", nb_cpu=1, apply_strand_suffix=None, ): """Find k nearest intervals. Parameters ---------- other : PyRanges PyRanges to find nearest interval in. k : int or list/array/Series of int Number of closest to return. If iterable, must be same length as PyRanges. ties : {None, "first", "last", "different"}, default None How to resolve ties, i.e. closest intervals with equal distance. None means that the k nearest intervals are kept. "first" means that the first tie is kept, "last" meanst that the last is kept. "different" means that all nearest intervals with the k unique nearest distances are kept. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are stranded, otherwise ignore the strand information. overlap : bool, default True Whether to include overlaps. how : {None, "upstream", "downstream"}, default None, i.e. both directions Whether to only look for nearest in one direction. Always with respect to the PyRanges it is called on. suffix : str, default "_b" Suffix to give columns with shared name in other. apply_strand_suffix : bool, default None If first pyranges is unstranded, but the second is not, the first will be given a strand column. apply_strand_suffix makes the added strand column a regular data column instead by adding a suffix. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with columns of nearest interval horizontally appended. Notes ----- nearest also exists, and is more performant. See also -------- PyRanges.new_position : give joined PyRanges new coordinates PyRanges.nearest : find nearest intervals Examples -------- >>> f1 = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Strand': ['+', '+', '-']}) >>> f1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [2, 7], 'Strand': ['+', '-']}) >>> f2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 2 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.k_nearest(f2, k=2) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 6 | 7 | - | 1 | | chr1 | 3 | 6 | + | 1 | 2 | + | -2 | | chr1 | 8 | 9 | + | 6 | 7 | - | -2 | | chr1 | 8 | 9 | + | 1 | 2 | + | -7 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | | chr1 | 5 | 7 | - | 1 | 2 | + | 4 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 6 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.k_nearest(f2, how="upstream", k=2) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 1 | 2 | + | -2 | | chr1 | 8 | 9 | + | 6 | 7 | - | -2 | | chr1 | 8 | 9 | + | 1 | 2 | + | -7 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 4 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.k_nearest(f2, k=[1, 2, 1]) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 6 | 7 | - | 1 | | chr1 | 8 | 9 | + | 6 | 7 | - | -2 | | chr1 | 8 | 9 | + | 1 | 2 | + | -7 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 4 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> d1 = {"Chromosome": [1], "Start": [5], "End": [6]} >>> d2 = {"Chromosome": 1, "Start": [1] * 2 + [5] * 2 + [9] * 2, ... "End": [3] * 2 + [7] * 2 + [11] * 2, "ID": range(6)} >>> gr, gr2 = pr.from_dict(d1), pr.from_dict(d2) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 5 | 6 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | 1 | 1 | 3 | 0 | | 1 | 1 | 3 | 1 | | 1 | 5 | 7 | 2 | | 1 | 5 | 7 | 3 | | 1 | 9 | 11 | 4 | | 1 | 9 | 11 | 5 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 6 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=2) +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 5 | 7 | 2 | 0 | | 1 | 5 | 6 | 5 | 7 | 3 | 0 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=2, ties="different") +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 5 | 7 | 2 | 0 | | 1 | 5 | 6 | 5 | 7 | 3 | 0 | | 1 | 5 | 6 | 1 | 3 | 1 | -3 | | 1 | 5 | 6 | 1 | 3 | 0 | -3 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 4 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=3, ties="first") +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 5 | 7 | 2 | 0 | | 1 | 5 | 6 | 1 | 3 | 1 | -3 | | 1 | 5 | 6 | 9 | 11 | 4 | 4 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=1, overlap=False) +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 1 | 3 | 1 | -3 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from sorted_nearest import get_all_ties, get_different_ties # type: ignore from pyranges.methods.k_nearest import _nearest # type: ignore kwargs = { "strandedness": strandedness, "how": how, "overlap": overlap, "nb_cpu": nb_cpu, "k": k, "ties": ties, } kwargs = fill_kwargs(kwargs) kwargs["stranded"] = self.stranded and other.stranded overlap = kwargs.get("overlap", True) ties = kwargs.get("ties", False) self = self.copy() if isinstance(k, pd.Series): k = k.values # how many to nearest to find; might be different for each self.__k__ = k # give each their own unique ID self.__IX__ = np.arange(len(self)) dfs = pyrange_apply(_nearest, self, other, **kwargs) nearest = PyRanges(dfs) if not overlap: result = nearest else: from collections import defaultdict overlap_how = defaultdict(lambda: None, {"first": "first", "last": "last"})[kwargs.get("ties")] overlaps = self.join( other, strandedness=strandedness, how=overlap_how, nb_cpu=nb_cpu, apply_strand_suffix=apply_strand_suffix, ) overlaps.Distance = 0 result = pr.concat([overlaps, nearest]) if not len(result): return pr.PyRanges() new_result = {} if ties in ["first", "last"]: for c, df in result: df = df.sort_values(["__IX__", "Distance"]) grpby = df.groupby("__k__", sort=False, observed=False) dfs = [] for k, kdf in grpby: grpby2 = kdf.groupby("__IX__", sort=False, observed=False) _df = grpby2.head(k) dfs.append(_df) if dfs: new_result[c] = pd.concat(dfs) elif ties == "different" or not ties: for c, df in result: if df.empty: continue dfs = [] df = df.sort_values(["__IX__", "Distance"]) grpby = df.groupby("__k__", sort=False, observed=False) for k, kdf in grpby: if ties: lx = get_different_ties( kdf.index.values, kdf.__IX__.values, kdf.Distance.astype(np.int64).values, k, ) _df = kdf.reindex(lx) else: lx = get_all_ties( kdf.index.values, kdf.__IX__.values, kdf.Distance.astype(np.int64).values, k, ) _df = kdf.reindex(lx) _df = _df.groupby("__IX__", observed=False).head(k) dfs.append(_df) if dfs: new_result[c] = pd.concat(dfs) result = pr.PyRanges(new_result) if not result.__IX__.is_monotonic_increasing: result = result.sort("__IX__") result = result.drop(like="__IX__|__k__") self = self.drop(like="__k__|__IX__") def prev_to_neg(df, **kwargs): strand = df.Strand.iloc[0] if "Strand" in df else "+" suffix = kwargs["suffix"] bools = df["End" + suffix] < df.Start if not strand == "+": bools = ~bools df.loc[bools, "Distance"] = -df.loc[bools, "Distance"] return df result = result.apply(prev_to_neg, suffix=kwargs["suffix"]) if not self.stranded and other.stranded: if apply_strand_suffix is None: import sys print( "join: Strand data from other will be added as strand data to self.\nIf this is undesired use the flag apply_strand_suffix=False.\nTo turn off the warning set apply_strand_suffix to True or False.", file=sys.stderr, ) elif apply_strand_suffix: result.columns = result.columns.str.replace("Strand", "Strand" + kwargs["suffix"]) return result
Find k nearest intervals. Parameters ---------- other : PyRanges PyRanges to find nearest interval in. k : int or list/array/Series of int Number of closest to return. If iterable, must be same length as PyRanges. ties : {None, "first", "last", "different"}, default None How to resolve ties, i.e. closest intervals with equal distance. None means that the k nearest intervals are kept. "first" means that the first tie is kept, "last" meanst that the last is kept. "different" means that all nearest intervals with the k unique nearest distances are kept. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are stranded, otherwise ignore the strand information. overlap : bool, default True Whether to include overlaps. how : {None, "upstream", "downstream"}, default None, i.e. both directions Whether to only look for nearest in one direction. Always with respect to the PyRanges it is called on. suffix : str, default "_b" Suffix to give columns with shared name in other. apply_strand_suffix : bool, default None If first pyranges is unstranded, but the second is not, the first will be given a strand column. apply_strand_suffix makes the added strand column a regular data column instead by adding a suffix. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with columns of nearest interval horizontally appended. Notes ----- nearest also exists, and is more performant. See also -------- PyRanges.new_position : give joined PyRanges new coordinates PyRanges.nearest : find nearest intervals Examples -------- >>> f1 = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Strand': ['+', '+', '-']}) >>> f1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [2, 7], 'Strand': ['+', '-']}) >>> f2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 2 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.k_nearest(f2, k=2) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 6 | 7 | - | 1 | | chr1 | 3 | 6 | + | 1 | 2 | + | -2 | | chr1 | 8 | 9 | + | 6 | 7 | - | -2 | | chr1 | 8 | 9 | + | 1 | 2 | + | -7 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | | chr1 | 5 | 7 | - | 1 | 2 | + | 4 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 6 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.k_nearest(f2, how="upstream", k=2) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 1 | 2 | + | -2 | | chr1 | 8 | 9 | + | 6 | 7 | - | -2 | | chr1 | 8 | 9 | + | 1 | 2 | + | -7 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 4 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.k_nearest(f2, k=[1, 2, 1]) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 6 | 7 | - | 1 | | chr1 | 8 | 9 | + | 6 | 7 | - | -2 | | chr1 | 8 | 9 | + | 1 | 2 | + | -7 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 4 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> d1 = {"Chromosome": [1], "Start": [5], "End": [6]} >>> d2 = {"Chromosome": 1, "Start": [1] * 2 + [5] * 2 + [9] * 2, ... "End": [3] * 2 + [7] * 2 + [11] * 2, "ID": range(6)} >>> gr, gr2 = pr.from_dict(d1), pr.from_dict(d2) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 5 | 6 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 +--------------+-----------+-----------+-----------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------| | 1 | 1 | 3 | 0 | | 1 | 1 | 3 | 1 | | 1 | 5 | 7 | 2 | | 1 | 5 | 7 | 3 | | 1 | 9 | 11 | 4 | | 1 | 9 | 11 | 5 | +--------------+-----------+-----------+-----------+ Unstranded PyRanges object has 6 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=2) +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 5 | 7 | 2 | 0 | | 1 | 5 | 6 | 5 | 7 | 3 | 0 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=2, ties="different") +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 5 | 7 | 2 | 0 | | 1 | 5 | 6 | 5 | 7 | 3 | 0 | | 1 | 5 | 6 | 1 | 3 | 1 | -3 | | 1 | 5 | 6 | 1 | 3 | 0 | -3 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 4 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=3, ties="first") +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 5 | 7 | 2 | 0 | | 1 | 5 | 6 | 1 | 3 | 1 | -3 | | 1 | 5 | 6 | 9 | 11 | 4 | 4 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.k_nearest(gr2, k=1, overlap=False) +--------------+-----------+-----------+-----------+-----------+-----------+------------+ | Chromosome | Start | End | Start_b | End_b | ID | Distance | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+------------| | 1 | 5 | 6 | 1 | 3 | 1 | -3 | +--------------+-----------+-----------+-----------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
k_nearest
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def lengths(self, as_dict=False): """Return the length of each interval. Parameters ---------- as_dict : bool, default False Whether to return lengths as Series or dict of Series per key. Returns ------- Series or dict of Series with the lengths of each interval. See Also -------- PyRanges.lengths : return the intervals lengths Examples -------- >>> gr = pr.data.f1() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.lengths() 0 3 1 1 2 2 dtype: int64 To find the length of the genome covered by the intervals, use merge first: >>> gr.Length = gr.lengths() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+-----------+ | Chromosome | Start | End | Name | Score | Strand | Length | | (category) | (int64) | (int64) | (object) | (int64) | (category) | (int64) | |--------------+-----------+-----------+------------+-----------+--------------+-----------| | chr1 | 3 | 6 | interval1 | 0 | + | 3 | | chr1 | 8 | 9 | interval3 | 0 | + | 1 | | chr1 | 5 | 7 | interval2 | 0 | - | 2 | +--------------+-----------+-----------+------------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if as_dict: if not len(self): return {} lengths = {} for k, df in self.items(): lengths[k] = df.End - df.Start return lengths else: _lengths = [] if not len(self): return np.array(_lengths, dtype=int) for _, df in self: lengths = df.End - df.Start _lengths.append(lengths) return pd.concat(_lengths).reset_index(drop=True)
Return the length of each interval. Parameters ---------- as_dict : bool, default False Whether to return lengths as Series or dict of Series per key. Returns ------- Series or dict of Series with the lengths of each interval. See Also -------- PyRanges.lengths : return the intervals lengths Examples -------- >>> gr = pr.data.f1() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.lengths() 0 3 1 1 2 2 dtype: int64 To find the length of the genome covered by the intervals, use merge first: >>> gr.Length = gr.lengths() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+-----------+ | Chromosome | Start | End | Name | Score | Strand | Length | | (category) | (int64) | (int64) | (object) | (int64) | (category) | (int64) | |--------------+-----------+-----------+------------+-----------+--------------+-----------| | chr1 | 3 | 6 | interval1 | 0 | + | 3 | | chr1 | 8 | 9 | interval3 | 0 | + | 1 | | chr1 | 5 | 7 | interval2 | 0 | - | 2 | +--------------+-----------+-----------+------------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
lengths
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def max_disjoint(self, strand=None, slack=0, **kwargs): """Find the maximal disjoint set of intervals. Parameters ---------- strand : bool, default None, i.e. auto Find the max disjoint set separately for each strand. slack : int, default 0 Consider intervals within a distance of slack to be overlapping. Returns ------- PyRanges PyRanges with maximal disjoint set of intervals. Examples -------- >>> gr = pr.data.f1() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.max_disjoint(strand=False) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if strand is None: strand = self.stranded kwargs = {"strand": strand, "slack": slack} kwargs = fill_kwargs(kwargs) from pyranges.methods.max_disjoint import _max_disjoint df = pyrange_apply_single(_max_disjoint, self, **kwargs) return pr.PyRanges(df)
Find the maximal disjoint set of intervals. Parameters ---------- strand : bool, default None, i.e. auto Find the max disjoint set separately for each strand. slack : int, default 0 Consider intervals within a distance of slack to be overlapping. Returns ------- PyRanges PyRanges with maximal disjoint set of intervals. Examples -------- >>> gr = pr.data.f1() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.max_disjoint(strand=False) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
max_disjoint
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def merge(self, strand=None, count=False, count_col="Count", by=None, slack=0): """Merge overlapping intervals into one. Parameters ---------- strand : bool, default None, i.e. auto Only merge intervals on same strand. count : bool, default False Count intervals in each superinterval. count_col : str, default "Count" Name of column with counts. by : str or list of str, default None Only merge intervals with equal values in these columns. slack : int, default 0 Allow this many nucleotides between each interval to merge. Returns ------- PyRanges PyRanges with superintervals. Notes ----- To avoid losing metadata, use cluster instead. If you want to perform a reduction function on the metadata, use pandas groupby. See Also -------- PyRanges.cluster : annotate overlapping intervals with common ID Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 14409 | + | DDX11L1 | | 1 | exon | 11868 | 12227 | + | DDX11L1 | | 1 | exon | 12612 | 12721 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | transcript | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1179364 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1173055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.merge(count=True, count_col="Count") +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Count | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | 1 | 11868 | 14409 | + | 12 | | 1 | 29553 | 31109 | + | 11 | | 1 | 52472 | 53312 | + | 3 | | 1 | 57597 | 64116 | + | 7 | | ... | ... | ... | ... | ... | | 1 | 1062207 | 1063288 | - | 4 | | 1 | 1070966 | 1074306 | - | 10 | | 1 | 1081817 | 1116361 | - | 319 | | 1 | 1173055 | 1179555 | - | 4 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 62 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.merge(by="Feature", count=True) +--------------+-----------+-----------+--------------+--------------+-----------+ | Chromosome | Start | End | Strand | Feature | Count | | (category) | (int64) | (int64) | (category) | (category) | (int64) | |--------------+-----------+-----------+--------------+--------------+-----------| | 1 | 65564 | 65573 | + | CDS | 1 | | 1 | 69036 | 70005 | + | CDS | 2 | | 1 | 924431 | 924948 | + | CDS | 1 | | 1 | 925921 | 926013 | + | CDS | 11 | | ... | ... | ... | ... | ... | ... | | 1 | 1062207 | 1063288 | - | transcript | 1 | | 1 | 1070966 | 1074306 | - | transcript | 1 | | 1 | 1081817 | 1116361 | - | transcript | 19 | | 1 | 1173055 | 1179555 | - | transcript | 1 | +--------------+-----------+-----------+--------------+--------------+-----------+ Stranded PyRanges object has 748 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.merge(by=["Feature", "gene_name"], count=True) +--------------+-----------+-----------+--------------+--------------+-------------+-----------+ | Chromosome | Start | End | Strand | Feature | gene_name | Count | | (category) | (int64) | (int64) | (category) | (category) | (object) | (int64) | |--------------+-----------+-----------+--------------+--------------+-------------+-----------| | 1 | 1020172 | 1020373 | + | CDS | AGRN | 1 | | 1 | 1022200 | 1022462 | + | CDS | AGRN | 2 | | 1 | 1034555 | 1034703 | + | CDS | AGRN | 2 | | 1 | 1035276 | 1035324 | + | CDS | AGRN | 4 | | ... | ... | ... | ... | ... | ... | ... | | 1 | 347981 | 348366 | - | transcript | RPL23AP24 | 1 | | 1 | 1173055 | 1179555 | - | transcript | TTLL10-AS1 | 1 | | 1 | 14403 | 29570 | - | transcript | WASH7P | 1 | | 1 | 185216 | 195411 | - | transcript | WASH9P | 1 | +--------------+-----------+-----------+--------------+--------------+-------------+-----------+ Stranded PyRanges object has 807 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if strand is None: strand = self.stranded kwargs = { "strand": strand, "count": count, "by": by, "count_col": count_col, "slack": slack, } if not kwargs["by"]: kwargs["sparse"] = {"self": True} from pyranges.methods.merge import _merge df = pyrange_apply_single(_merge, self, **kwargs) else: kwargs["sparse"] = {"self": False} from pyranges.methods.merge import _merge_by df = pyrange_apply_single(_merge_by, self, **kwargs) return PyRanges(df)
Merge overlapping intervals into one. Parameters ---------- strand : bool, default None, i.e. auto Only merge intervals on same strand. count : bool, default False Count intervals in each superinterval. count_col : str, default "Count" Name of column with counts. by : str or list of str, default None Only merge intervals with equal values in these columns. slack : int, default 0 Allow this many nucleotides between each interval to merge. Returns ------- PyRanges PyRanges with superintervals. Notes ----- To avoid losing metadata, use cluster instead. If you want to perform a reduction function on the metadata, use pandas groupby. See Also -------- PyRanges.cluster : annotate overlapping intervals with common ID Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 14409 | + | DDX11L1 | | 1 | exon | 11868 | 12227 | + | DDX11L1 | | 1 | exon | 12612 | 12721 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | transcript | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1179364 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1173055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.merge(count=True, count_col="Count") +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Count | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | 1 | 11868 | 14409 | + | 12 | | 1 | 29553 | 31109 | + | 11 | | 1 | 52472 | 53312 | + | 3 | | 1 | 57597 | 64116 | + | 7 | | ... | ... | ... | ... | ... | | 1 | 1062207 | 1063288 | - | 4 | | 1 | 1070966 | 1074306 | - | 10 | | 1 | 1081817 | 1116361 | - | 319 | | 1 | 1173055 | 1179555 | - | 4 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 62 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.merge(by="Feature", count=True) +--------------+-----------+-----------+--------------+--------------+-----------+ | Chromosome | Start | End | Strand | Feature | Count | | (category) | (int64) | (int64) | (category) | (category) | (int64) | |--------------+-----------+-----------+--------------+--------------+-----------| | 1 | 65564 | 65573 | + | CDS | 1 | | 1 | 69036 | 70005 | + | CDS | 2 | | 1 | 924431 | 924948 | + | CDS | 1 | | 1 | 925921 | 926013 | + | CDS | 11 | | ... | ... | ... | ... | ... | ... | | 1 | 1062207 | 1063288 | - | transcript | 1 | | 1 | 1070966 | 1074306 | - | transcript | 1 | | 1 | 1081817 | 1116361 | - | transcript | 19 | | 1 | 1173055 | 1179555 | - | transcript | 1 | +--------------+-----------+-----------+--------------+--------------+-----------+ Stranded PyRanges object has 748 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.merge(by=["Feature", "gene_name"], count=True) +--------------+-----------+-----------+--------------+--------------+-------------+-----------+ | Chromosome | Start | End | Strand | Feature | gene_name | Count | | (category) | (int64) | (int64) | (category) | (category) | (object) | (int64) | |--------------+-----------+-----------+--------------+--------------+-------------+-----------| | 1 | 1020172 | 1020373 | + | CDS | AGRN | 1 | | 1 | 1022200 | 1022462 | + | CDS | AGRN | 2 | | 1 | 1034555 | 1034703 | + | CDS | AGRN | 2 | | 1 | 1035276 | 1035324 | + | CDS | AGRN | 4 | | ... | ... | ... | ... | ... | ... | ... | | 1 | 347981 | 348366 | - | transcript | RPL23AP24 | 1 | | 1 | 1173055 | 1179555 | - | transcript | TTLL10-AS1 | 1 | | 1 | 14403 | 29570 | - | transcript | WASH7P | 1 | | 1 | 185216 | 195411 | - | transcript | WASH9P | 1 | +--------------+-----------+-----------+--------------+--------------+-------------+-----------+ Stranded PyRanges object has 807 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
merge
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def nearest( self, other, strandedness=None, overlap=True, how=None, suffix="_b", nb_cpu=1, apply_strand_suffix=None, ): """Find closest interval. Parameters ---------- other : PyRanges PyRanges to find nearest interval in. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. overlap : bool, default True Whether to include overlaps. how : {None, "upstream", "downstream"}, default None, i.e. both directions Whether to only look for nearest in one direction. Always with respect to the PyRanges it is called on. suffix : str, default "_b" Suffix to give columns with shared name in other. apply_strand_suffix : bool, default None If first pyranges is unstranded, but the second is not, the first will be given the strand column of the second. apply_strand_suffix makes the added strand column a regular data column instead by adding a suffix. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with columns representing nearest interval horizontally appended. Notes ----- A k_nearest also exists, but is less performant. See also -------- PyRanges.new_position : give joined PyRanges new coordinates PyRanges.k_nearest : find k nearest intervals Examples -------- >>> f1 = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Strand': ['+', '+', '-']}) >>> f1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [2, 7], 'Strand': ['+', '-']}) >>> f2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 2 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.nearest(f2) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 6 | 7 | - | 1 | | chr1 | 8 | 9 | + | 6 | 7 | - | 2 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 3 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.nearest(f2, how="upstream") +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 1 | 2 | + | 2 | | chr1 | 8 | 9 | + | 6 | 7 | - | 2 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 3 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.nearest import _nearest kwargs = { "strandedness": strandedness, "how": how, "overlap": overlap, "nb_cpu": nb_cpu, "suffix": suffix, "apply_strand_suffix": apply_strand_suffix, } kwargs = fill_kwargs(kwargs) if kwargs.get("how") in "upstream downstream".split(): assert other.stranded, "If doing upstream or downstream nearest, other pyranges must be stranded" dfs = pyrange_apply(_nearest, self, other, **kwargs) gr = PyRanges(dfs) if not self.stranded and other.stranded: if apply_strand_suffix is None: import sys print( "join: Strand data from other will be added as strand data to self.\nIf this is undesired use the flag apply_strand_suffix=False.\nTo turn off the warning set apply_strand_suffix to True or False.", file=sys.stderr, ) elif apply_strand_suffix: gr.columns = gr.columns.str.replace("Strand", "Strand" + kwargs["suffix"]) return gr
Find closest interval. Parameters ---------- other : PyRanges PyRanges to find nearest interval in. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. overlap : bool, default True Whether to include overlaps. how : {None, "upstream", "downstream"}, default None, i.e. both directions Whether to only look for nearest in one direction. Always with respect to the PyRanges it is called on. suffix : str, default "_b" Suffix to give columns with shared name in other. apply_strand_suffix : bool, default None If first pyranges is unstranded, but the second is not, the first will be given the strand column of the second. apply_strand_suffix makes the added strand column a regular data column instead by adding a suffix. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with columns representing nearest interval horizontally appended. Notes ----- A k_nearest also exists, but is less performant. See also -------- PyRanges.new_position : give joined PyRanges new coordinates PyRanges.k_nearest : find k nearest intervals Examples -------- >>> f1 = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Strand': ['+', '+', '-']}) >>> f1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 8 | 9 | + | | chr1 | 5 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [2, 7], 'Strand': ['+', '-']}) >>> f2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 2 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.nearest(f2) +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 6 | 7 | - | 1 | | chr1 | 8 | 9 | + | 6 | 7 | - | 2 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 3 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> f1.nearest(f2, how="upstream") +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Start_b | End_b | Strand_b | Distance | | (category) | (int64) | (int64) | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------| | chr1 | 3 | 6 | + | 1 | 2 | + | 2 | | chr1 | 8 | 9 | + | 6 | 7 | - | 2 | | chr1 | 5 | 7 | - | 6 | 7 | - | 0 | +--------------+-----------+-----------+--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 3 rows and 8 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
nearest
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def new_position(self, new_pos, columns=None): """Give new position. The operation join produces a PyRanges with two pairs of start coordinates and two pairs of end coordinates. This operation uses these to give the PyRanges a new position. Parameters ---------- new_pos : {"union", "intersection", "swap"} Change of coordinates. columns : tuple of str, default None, i.e. auto The name of the coordinate columns. By default uses the two first columns containing "Start" and the two first columns containing "End". See Also -------- PyRanges.join : combine two PyRanges horizontally with SQL-style joins. Returns ------- PyRanges PyRanges with new coordinates. Examples -------- >>> gr = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], ... 'Start': [3, 8, 5], 'End': [6, 9, 7]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 3 | 6 | | chr1 | 8 | 9 | | chr1 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [4, 7]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 1 | 4 | | chr1 | 6 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j = gr.join(gr2) >>> j +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Start_b | End_b | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | chr1 | 3 | 6 | 1 | 4 | | chr1 | 5 | 7 | 6 | 7 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j.new_position("swap") +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Start_b | End_b | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | chr1 | 1 | 4 | 3 | 6 | | chr1 | 6 | 7 | 5 | 7 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j.new_position("union").mp() +--------------------+-----------+-----------+ | - Position - | Start_b | End_b | | (Multiple types) | (int64) | (int64) | |--------------------+-----------+-----------| | chr1 1-6 | 1 | 4 | | chr1 5-7 | 6 | 7 | +--------------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j.new_position("intersection").mp() +--------------------+-----------+-----------+ | - Position - | Start_b | End_b | | (Multiple types) | (int64) | (int64) | |--------------------+-----------+-----------| | chr1 1-4 | 1 | 4 | | chr1 6-7 | 6 | 7 | +--------------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j2 = pr.from_dict({"Chromosome": [1], "Start": [3], ... "End": [4], "A": [1], "B": [3], "C": [2], "D": [5]}) >>> j2 +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | A | B | C | D | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+-----------| | 1 | 3 | 4 | 1 | 3 | 2 | 5 | +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j2.new_position("intersection", ("A", "B", "C", "D")) +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | A | B | C | D | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+-----------| | 1 | 2 | 3 | 1 | 3 | 2 | 5 | +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from pyranges.methods.new_position import _new_position if self.empty: return self kwargs = {"strand": None} kwargs["sparse"] = {"self": False} kwargs["new_pos"] = new_pos if columns is None: start1, start2 = self.columns[self.columns.str.contains("Start")][:2] end1, end2 = self.columns[self.columns.str.contains("End")][:2] columns = (start1, end1, start2, end2) kwargs["columns"] = columns kwargs = fill_kwargs(kwargs) dfs = pyrange_apply_single(_new_position, self, **kwargs) return pr.PyRanges(dfs)
Give new position. The operation join produces a PyRanges with two pairs of start coordinates and two pairs of end coordinates. This operation uses these to give the PyRanges a new position. Parameters ---------- new_pos : {"union", "intersection", "swap"} Change of coordinates. columns : tuple of str, default None, i.e. auto The name of the coordinate columns. By default uses the two first columns containing "Start" and the two first columns containing "End". See Also -------- PyRanges.join : combine two PyRanges horizontally with SQL-style joins. Returns ------- PyRanges PyRanges with new coordinates. Examples -------- >>> gr = pr.from_dict({'Chromosome': ['chr1', 'chr1', 'chr1'], ... 'Start': [3, 8, 5], 'End': [6, 9, 7]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 3 | 6 | | chr1 | 8 | 9 | | chr1 | 5 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [4, 7]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 1 | 4 | | chr1 | 6 | 7 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j = gr.join(gr2) >>> j +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Start_b | End_b | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | chr1 | 3 | 6 | 1 | 4 | | chr1 | 5 | 7 | 6 | 7 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j.new_position("swap") +--------------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | Start_b | End_b | | (category) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------| | chr1 | 1 | 4 | 3 | 6 | | chr1 | 6 | 7 | 5 | 7 | +--------------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j.new_position("union").mp() +--------------------+-----------+-----------+ | - Position - | Start_b | End_b | | (Multiple types) | (int64) | (int64) | |--------------------+-----------+-----------| | chr1 1-6 | 1 | 4 | | chr1 5-7 | 6 | 7 | +--------------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j.new_position("intersection").mp() +--------------------+-----------+-----------+ | - Position - | Start_b | End_b | | (Multiple types) | (int64) | (int64) | |--------------------+-----------+-----------| | chr1 1-4 | 1 | 4 | | chr1 6-7 | 6 | 7 | +--------------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j2 = pr.from_dict({"Chromosome": [1], "Start": [3], ... "End": [4], "A": [1], "B": [3], "C": [2], "D": [5]}) >>> j2 +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | A | B | C | D | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+-----------| | 1 | 3 | 4 | 1 | 3 | 2 | 5 | +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> j2.new_position("intersection", ("A", "B", "C", "D")) +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ | Chromosome | Start | End | A | B | C | D | | (category) | (int64) | (int64) | (int64) | (int64) | (int64) | (int64) | |--------------+-----------+-----------+-----------+-----------+-----------+-----------| | 1 | 2 | 3 | 1 | 3 | 2 | 5 | +--------------+-----------+-----------+-----------+-----------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
new_position
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def overlap(self, other, strandedness=None, how="first", invert=False, nb_cpu=1): """Return overlapping intervals. Returns the intervals in self which overlap with those in other. Parameters ---------- other : PyRanges PyRanges to find overlaps with. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {"first", "containment", False, None}, default "first" What intervals to report. By default, reports every interval in self with overlap once. "containment" reports all intervals where the overlapping is contained within it. invert : bool, default False Whether to return the intervals without overlaps. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with overlapping intervals. See also -------- PyRanges.intersect : report overlapping subintervals PyRanges.set_intersect : set-intersect PyRanges Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2, how=None) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2, how="containment") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2, invert=True) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ kwargs = {"strandedness": strandedness, "nb_cpu": nb_cpu} kwargs["sparse"] = {"self": False, "other": True} kwargs["how"] = how kwargs["invert"] = invert kwargs = fill_kwargs(kwargs) if len(self) == 0: return self if invert: self = self.copy() self.__ix__ = np.arange(len(self)) dfs = pyrange_apply(_overlap, self, other, **kwargs) result = pr.PyRanges(dfs) if invert: found_idxs = getattr(result, "__ix__", []) result = self[~self.__ix__.isin(found_idxs)] result = result.drop("__ix__") return result
Return overlapping intervals. Returns the intervals in self which overlap with those in other. Parameters ---------- other : PyRanges PyRanges to find overlaps with. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {"first", "containment", False, None}, default "first" What intervals to report. By default, reports every interval in self with overlap once. "containment" reports all intervals where the overlapping is contained within it. invert : bool, default False Whether to return the intervals without overlaps. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with overlapping intervals. See also -------- PyRanges.intersect : report overlapping subintervals PyRanges.set_intersect : set-intersect PyRanges Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2, how=None) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2, how="containment") +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 4 | 9 | b | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.overlap(gr2, invert=True) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 1 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
overlap
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def print(self, n=8, merge_position=False, sort=False, formatting=None, chain=False): """Print the PyRanges. Parameters ---------- n : int, default 8 The number of rows to print. merge_postion : bool, default False Print location in same column to save screen space. sort : bool or str, default False Sort the PyRanges before printing. Will print chromosomsomes or strands interleaved on sort columns. formatting : dict, default None Formatting options per column. chain : False Return the PyRanges. Useful to print intermediate results in call chains. See Also -------- PyRanges.pc : print chain PyRanges.sp : sort print PyRanges.mp : merge print PyRanges.spc : sort print chain PyRanges.mpc : merge print chain PyRanges.msp : merge sort print PyRanges.mspc : merge sort print chain PyRanges.rp : raw print dictionary of DataFrames Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5000], ... 'End': [6, 9, 7000], 'Name': ['i1', 'i3', 'i2'], ... 'Score': [1.1, 2.3987, 5.9999995], 'Strand': ['+', '+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+------------+-------------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (float64) | (category) | |--------------+-----------+-----------+------------+-------------+--------------| | chr1 | 3 | 6 | i1 | 1.1 | + | | chr1 | 8 | 9 | i3 | 2.3987 | + | | chr1 | 5000 | 7000 | i2 | 6 | - | +--------------+-----------+-----------+------------+-------------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.print(formatting={"Start": "{:,}", "Score": "{:.2f}"}) +--------------+-----------+-----------+------------+-------------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (float64) | (category) | |--------------+-----------+-----------+------------+-------------+--------------| | chr1 | 3 | 6 | i1 | 1.1 | + | | chr1 | 8 | 9 | i3 | 2.4 | + | | chr1 | 5,000 | 7000 | i2 | 6 | - | +--------------+-----------+-----------+------------+-------------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.print(merge_position=True) # gr.mp() +--------------------+------------+-------------+ | - Position - | Name | Score | | (Multiple types) | (object) | (float64) | |--------------------+------------+-------------| | chr1 3-6 + | i1 | 1.1 | | chr1 8-9 + | i3 | 2.3987 | | chr1 5000-7000 - | i2 | 6 | +--------------------+------------+-------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> chipseq = pr.data.chipseq() >>> chipseq +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. To interleave strands in output, use print with `sort=True`: >>> chipseq.print(sort=True, n=20) # chipseq.sp() +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 1325303 | 1325328 | U0 | 0 | - | | chr1 | 1541598 | 1541623 | U0 | 0 | + | | chr1 | 1599121 | 1599146 | U0 | 0 | + | | chr1 | 1820285 | 1820310 | U0 | 0 | - | | chr1 | 2448322 | 2448347 | U0 | 0 | - | | chr1 | 3046141 | 3046166 | U0 | 0 | - | | chr1 | 3437168 | 3437193 | U0 | 0 | - | | chr1 | 3504032 | 3504057 | U0 | 0 | + | | chr1 | 3637087 | 3637112 | U0 | 0 | - | | chr1 | 3681903 | 3681928 | U0 | 0 | - | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 15548022 | 15548047 | U0 | 0 | + | | chrY | 16045242 | 16045267 | U0 | 0 | - | | chrY | 16495497 | 16495522 | U0 | 0 | - | | chrY | 21559181 | 21559206 | U0 | 0 | + | | chrY | 21707662 | 21707687 | U0 | 0 | - | | chrY | 21751211 | 21751236 | U0 | 0 | - | | chrY | 21910706 | 21910731 | U0 | 0 | - | | chrY | 22054002 | 22054027 | U0 | 0 | - | | chrY | 22210637 | 22210662 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome, Start, End and Strand. >>> pr.data.chromsizes().print() +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ s = tostring(self, n=n, merge_position=merge_position, sort=sort, formatting=formatting) print(s) if chain: return self
Print the PyRanges. Parameters ---------- n : int, default 8 The number of rows to print. merge_postion : bool, default False Print location in same column to save screen space. sort : bool or str, default False Sort the PyRanges before printing. Will print chromosomsomes or strands interleaved on sort columns. formatting : dict, default None Formatting options per column. chain : False Return the PyRanges. Useful to print intermediate results in call chains. See Also -------- PyRanges.pc : print chain PyRanges.sp : sort print PyRanges.mp : merge print PyRanges.spc : sort print chain PyRanges.mpc : merge print chain PyRanges.msp : merge sort print PyRanges.mspc : merge sort print chain PyRanges.rp : raw print dictionary of DataFrames Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5000], ... 'End': [6, 9, 7000], 'Name': ['i1', 'i3', 'i2'], ... 'Score': [1.1, 2.3987, 5.9999995], 'Strand': ['+', '+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+------------+-------------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (float64) | (category) | |--------------+-----------+-----------+------------+-------------+--------------| | chr1 | 3 | 6 | i1 | 1.1 | + | | chr1 | 8 | 9 | i3 | 2.3987 | + | | chr1 | 5000 | 7000 | i2 | 6 | - | +--------------+-----------+-----------+------------+-------------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.print(formatting={"Start": "{:,}", "Score": "{:.2f}"}) +--------------+-----------+-----------+------------+-------------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (float64) | (category) | |--------------+-----------+-----------+------------+-------------+--------------| | chr1 | 3 | 6 | i1 | 1.1 | + | | chr1 | 8 | 9 | i3 | 2.4 | + | | chr1 | 5,000 | 7000 | i2 | 6 | - | +--------------+-----------+-----------+------------+-------------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.print(merge_position=True) # gr.mp() +--------------------+------------+-------------+ | - Position - | Name | Score | | (Multiple types) | (object) | (float64) | |--------------------+------------+-------------| | chr1 3-6 + | i1 | 1.1 | | chr1 8-9 + | i3 | 2.3987 | | chr1 5000-7000 - | i2 | 6 | +--------------------+------------+-------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> chipseq = pr.data.chipseq() >>> chipseq +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. To interleave strands in output, use print with `sort=True`: >>> chipseq.print(sort=True, n=20) # chipseq.sp() +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 1325303 | 1325328 | U0 | 0 | - | | chr1 | 1541598 | 1541623 | U0 | 0 | + | | chr1 | 1599121 | 1599146 | U0 | 0 | + | | chr1 | 1820285 | 1820310 | U0 | 0 | - | | chr1 | 2448322 | 2448347 | U0 | 0 | - | | chr1 | 3046141 | 3046166 | U0 | 0 | - | | chr1 | 3437168 | 3437193 | U0 | 0 | - | | chr1 | 3504032 | 3504057 | U0 | 0 | + | | chr1 | 3637087 | 3637112 | U0 | 0 | - | | chr1 | 3681903 | 3681928 | U0 | 0 | - | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 15548022 | 15548047 | U0 | 0 | + | | chrY | 16045242 | 16045267 | U0 | 0 | - | | chrY | 16495497 | 16495522 | U0 | 0 | - | | chrY | 21559181 | 21559206 | U0 | 0 | + | | chrY | 21707662 | 21707687 | U0 | 0 | - | | chrY | 21751211 | 21751236 | U0 | 0 | - | | chrY | 21910706 | 21910731 | U0 | 0 | - | | chrY | 22054002 | 22054027 | U0 | 0 | - | | chrY | 22210637 | 22210662 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome, Start, End and Strand. >>> pr.data.chromsizes().print() +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome.
print
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def sample(self, n=8, replace=False): """Subsample arbitrary rows of PyRanges. If n is larger than length of PyRanges, replace must be True. Parameters ---------- n : int, default 8 Number of rows to return replace : bool, False Reuse rows. Examples -------- >>> gr = pr.data.chipseq() >>> np.random.seed(0) >>> gr.sample(n=3) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr2 | 76564764 | 76564789 | U0 | 0 | + | | chr3 | 185739979 | 185740004 | U0 | 0 | - | | chr20 | 40373657 | 40373682 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.sample(10001) Traceback (most recent call last): ... ValueError: Cannot take a larger sample than population when 'replace=False' """ sample = np.random.choice(len(self), size=n, replace=replace) subsetter = np.zeros(len(self), dtype=np.bool_) subsetter[sample] = True return self[subsetter]
Subsample arbitrary rows of PyRanges. If n is larger than length of PyRanges, replace must be True. Parameters ---------- n : int, default 8 Number of rows to return replace : bool, False Reuse rows. Examples -------- >>> gr = pr.data.chipseq() >>> np.random.seed(0) >>> gr.sample(n=3) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr2 | 76564764 | 76564789 | U0 | 0 | + | | chr3 | 185739979 | 185740004 | U0 | 0 | - | | chr20 | 40373657 | 40373682 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.sample(10001) Traceback (most recent call last): ... ValueError: Cannot take a larger sample than population when 'replace=False'
sample
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def set_intersect(self, other, strandedness=None, how=None, new_pos=False, nb_cpu=1): """Return set-theoretical intersection. Like intersect, but both PyRanges are merged first. Parameters ---------- other : PyRanges PyRanges to set-intersect. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {None, "first", "last", "containment"}, default None, i.e. all What intervals to report. By default, reports all overlapping intervals. "containment" reports intervals where the overlapping is contained within it. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with overlapping subintervals. See also -------- PyRanges.intersect : find overlapping subintervals PyRanges.overlap : report overlapping intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.set_intersect(gr2) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 4 | 9 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. In this simple unstranded case, this is the same as the below: >>> gr.merge().intersect(gr2.merge()) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 4 | 9 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.set_intersect(gr2, how="containment") +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 4 | 9 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ kwargs = { "strandedness": strandedness, "how": how, "nb_cpu": nb_cpu, "new_pos": new_pos, } kwargs = fill_kwargs(kwargs) strand = True if strandedness else False self_clusters = self.merge(strand=strand) other_clusters = other.merge(strand=strand) dfs = pyrange_apply(_intersection, self_clusters, other_clusters, **kwargs) return PyRanges(dfs)
Return set-theoretical intersection. Like intersect, but both PyRanges are merged first. Parameters ---------- other : PyRanges PyRanges to set-intersect. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. how : {None, "first", "last", "containment"}, default None, i.e. all What intervals to report. By default, reports all overlapping intervals. "containment" reports intervals where the overlapping is contained within it. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with overlapping subintervals. See also -------- PyRanges.intersect : find overlapping subintervals PyRanges.overlap : report overlapping intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.set_intersect(gr2) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 4 | 9 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. In this simple unstranded case, this is the same as the below: >>> gr.merge().intersect(gr2.merge()) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 4 | 9 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.set_intersect(gr2, how="containment") +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 4 | 9 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
set_intersect
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def set_union(self, other, strandedness=None, nb_cpu=1): """Return set-theoretical union. Parameters ---------- other : PyRanges PyRanges to do union with. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with the union of intervals. See also -------- PyRanges.set_intersect : set-theoretical intersection PyRanges.overlap : report overlapping intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.set_union(gr2) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 1 | 11 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ if self.empty and other.empty: return pr.PyRanges() strand = True if strandedness else False if not strand: self = self.unstrand() other = other.unstrand() if strandedness == "opposite" and len(other): other = other.copy() other.Strand = other.Strand.replace({"+": "-", "-": "+"}) gr = pr.concat([self, other], strand) gr = gr.merge(strand=strand) return gr
Return set-theoretical union. Parameters ---------- other : PyRanges PyRanges to do union with. strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges A PyRanges with the union of intervals. See also -------- PyRanges.set_intersect : set-theoretical intersection PyRanges.overlap : report overlapping intervals Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.set_union(gr2) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 1 | 11 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
set_union
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def sort(self, by=None, nb_cpu=1): """Sort by position or columns. Parameters ---------- by : str or list of str, default None Column(s) to sort by. Default is Start and End. Special value "5" can be provided to sort by 5': intervals on + strand are sorted in ascending order, while those on - strand are sorted in descending order. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Note ---- Since a PyRanges contains multiple DataFrames, the sorting only happens within dataframes. Returns ------- PyRanges Sorted PyRanges See Also -------- pyranges.multioverlap : find overlaps with multiple PyRanges Examples -------- >>> p = pr.from_dict({"Chromosome": [1, 1, 1, 1, 1, 1], ... "Strand": ["+", "+", "-", "-", "+", "+"], ... "Start": [40, 1, 10, 70, 140, 160], ... "End": [60, 11, 25, 80, 152, 190], ... "transcript_id":["t3", "t3", "t2", "t2", "t1", "t1"] }) By default, intervals are sorted by position: >>> p.sort() +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t3 | | 1 | + | 40 | 60 | t3 | | 1 | + | 140 | 152 | t1 | | 1 | + | 160 | 190 | t1 | | 1 | - | 10 | 25 | t2 | | 1 | - | 70 | 80 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 6 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. (Note how sorting takes place within Chromosome-Strand pairs.) To sort according to a specified column: >>> p.sort(by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 140 | 152 | t1 | | 1 | + | 160 | 190 | t1 | | 1 | + | 40 | 60 | t3 | | 1 | + | 1 | 11 | t3 | | 1 | - | 10 | 25 | t2 | | 1 | - | 70 | 80 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 6 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. If the special value "5" is provided, intervals are sorted according to their five-prime end: >>> p.sort("5") +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t3 | | 1 | + | 40 | 60 | t3 | | 1 | + | 140 | 152 | t1 | | 1 | + | 160 | 190 | t1 | | 1 | - | 70 | 80 | t2 | | 1 | - | 10 | 25 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 6 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.sort import _sort kwargs = {"strand": self.stranded} kwargs["sparse"] = {"self": False} if by: assert "5" not in by or ( ((type(by) is str and by == "5") or (type(by) is not str and "5" in by)) and self.stranded ), "Only stranded PyRanges can be sorted by 5'! " kwargs["by"] = by kwargs = fill_kwargs(kwargs) return PyRanges(pyrange_apply_single(_sort, self, **kwargs))
Sort by position or columns. Parameters ---------- by : str or list of str, default None Column(s) to sort by. Default is Start and End. Special value "5" can be provided to sort by 5': intervals on + strand are sorted in ascending order, while those on - strand are sorted in descending order. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Note ---- Since a PyRanges contains multiple DataFrames, the sorting only happens within dataframes. Returns ------- PyRanges Sorted PyRanges See Also -------- pyranges.multioverlap : find overlaps with multiple PyRanges Examples -------- >>> p = pr.from_dict({"Chromosome": [1, 1, 1, 1, 1, 1], ... "Strand": ["+", "+", "-", "-", "+", "+"], ... "Start": [40, 1, 10, 70, 140, 160], ... "End": [60, 11, 25, 80, 152, 190], ... "transcript_id":["t3", "t3", "t2", "t2", "t1", "t1"] }) By default, intervals are sorted by position: >>> p.sort() +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t3 | | 1 | + | 40 | 60 | t3 | | 1 | + | 140 | 152 | t1 | | 1 | + | 160 | 190 | t1 | | 1 | - | 10 | 25 | t2 | | 1 | - | 70 | 80 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 6 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. (Note how sorting takes place within Chromosome-Strand pairs.) To sort according to a specified column: >>> p.sort(by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 140 | 152 | t1 | | 1 | + | 160 | 190 | t1 | | 1 | + | 40 | 60 | t3 | | 1 | + | 1 | 11 | t3 | | 1 | - | 10 | 25 | t2 | | 1 | - | 70 | 80 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 6 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. If the special value "5" is provided, intervals are sorted according to their five-prime end: >>> p.sort("5") +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t3 | | 1 | + | 40 | 60 | t3 | | 1 | + | 140 | 152 | t1 | | 1 | + | 160 | 190 | t1 | | 1 | - | 70 | 80 | t2 | | 1 | - | 10 | 25 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 6 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
sort
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def spliced_subsequence(self, start=0, end=None, by=None, strand=None, **kwargs): """Get subsequences of the intervals, using coordinates mapping to spliced transcripts (without introns) The returned intervals are subregions of self, cut according to specifications. Start and end are relative to the 5' end: 0 means the leftmost nucleotide for + strand intervals, while it means the rightmost one for - strand. This method also allows to manipulate groups of intervals (e.g. exons belonging to same transcripts) through the 'by' argument. When using it, start and end refer to the spliced transcript coordinates, meaning that introns are ignored in the count. Parameters ---------- start : int Start of subregion, 0-based and included, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) end : int, default None End of subregion, 0-based and excluded, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) If None, the existing 3' end is returned. by : list of str, default None intervals are grouped by this/these ID column(s) beforehand, e.g. exons belonging to same transcripts strand : bool, default None, i.e. auto Whether strand is considered when interpreting the start and end arguments of this function. If True, counting is from the 5' end, which is the leftmost coordinate for + strand and the rightmost for - strand. If False, all intervals are processed like they reside on the + strand. If None (default), strand is considered if the PyRanges is stranded. Returns ------- PyRanges Subregion of self, subsequenced as specified by arguments Note ---- If the request goes out of bounds (e.g. requesting 100 nts for a 90nt region), only the existing portion is returned See also -------- subsequence : analogous to this method, but input coordinates refer to the unspliced transcript Examples -------- >>> p = pr.from_dict({"Chromosome": [1, 1, 2, 2, 3], ... "Strand": ["+", "+", "-", "-", "+"], ... "Start": [1, 40, 10, 70, 140], ... "End": [11, 60, 25, 80, 152], ... "transcript_id":["t1", "t1", "t2", "t2", "t3"] }) >>> p +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 1 | + | 40 | 60 | t1 | | 2 | - | 10 | 25 | t2 | | 2 | - | 70 | 80 | t2 | | 3 | + | 140 | 152 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the first 15 nucleotides of *each spliced transcript*, grouping exons by transcript_id: >>> p.spliced_subsequence(0, 15, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 1 | + | 40 | 45 | t1 | | 2 | - | 70 | 80 | t2 | | 2 | - | 20 | 25 | t2 | | 3 | + | 140 | 152 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the last 20 nucleotides of each spliced transcript: >>> p.spliced_subsequence(-20, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 40 | 60 | t1 | | 2 | - | 70 | 75 | t2 | | 2 | - | 10 | 25 | t2 | | 3 | + | 140 | 152 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 4 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get region from 25 to 60 of each spliced transcript, or their existing subportion: >>> p.spliced_subsequence(25, 60, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 55 | 60 | t1 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 1 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get region of each spliced transcript which excludes their first and last 3 nucleotides: >>> p.spliced_subsequence(3, -3, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 4 | 11 | t1 | | 1 | + | 40 | 57 | t1 | | 2 | - | 70 | 77 | t2 | | 2 | - | 13 | 25 | t2 | | 3 | + | 143 | 149 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.spliced_subsequence import _spliced_subseq if strand and not self.stranded: raise Exception("spliced_subsequence: you can use strand=True only for stranded PyRanges!") if strand is None: strand = True if self.stranded else False kwargs.update({"strand": strand, "by": by, "start": start, "end": end}) kwargs = fill_kwargs(kwargs) if not strand: sorted_p = self.sort() else: sorted_p = self.sort("5") result = pyrange_apply_single(_spliced_subseq, sorted_p, **kwargs) return pr.PyRanges(result)
Get subsequences of the intervals, using coordinates mapping to spliced transcripts (without introns) The returned intervals are subregions of self, cut according to specifications. Start and end are relative to the 5' end: 0 means the leftmost nucleotide for + strand intervals, while it means the rightmost one for - strand. This method also allows to manipulate groups of intervals (e.g. exons belonging to same transcripts) through the 'by' argument. When using it, start and end refer to the spliced transcript coordinates, meaning that introns are ignored in the count. Parameters ---------- start : int Start of subregion, 0-based and included, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) end : int, default None End of subregion, 0-based and excluded, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) If None, the existing 3' end is returned. by : list of str, default None intervals are grouped by this/these ID column(s) beforehand, e.g. exons belonging to same transcripts strand : bool, default None, i.e. auto Whether strand is considered when interpreting the start and end arguments of this function. If True, counting is from the 5' end, which is the leftmost coordinate for + strand and the rightmost for - strand. If False, all intervals are processed like they reside on the + strand. If None (default), strand is considered if the PyRanges is stranded. Returns ------- PyRanges Subregion of self, subsequenced as specified by arguments Note ---- If the request goes out of bounds (e.g. requesting 100 nts for a 90nt region), only the existing portion is returned See also -------- subsequence : analogous to this method, but input coordinates refer to the unspliced transcript Examples -------- >>> p = pr.from_dict({"Chromosome": [1, 1, 2, 2, 3], ... "Strand": ["+", "+", "-", "-", "+"], ... "Start": [1, 40, 10, 70, 140], ... "End": [11, 60, 25, 80, 152], ... "transcript_id":["t1", "t1", "t2", "t2", "t3"] }) >>> p +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 1 | + | 40 | 60 | t1 | | 2 | - | 10 | 25 | t2 | | 2 | - | 70 | 80 | t2 | | 3 | + | 140 | 152 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the first 15 nucleotides of *each spliced transcript*, grouping exons by transcript_id: >>> p.spliced_subsequence(0, 15, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 1 | + | 40 | 45 | t1 | | 2 | - | 70 | 80 | t2 | | 2 | - | 20 | 25 | t2 | | 3 | + | 140 | 152 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the last 20 nucleotides of each spliced transcript: >>> p.spliced_subsequence(-20, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 40 | 60 | t1 | | 2 | - | 70 | 75 | t2 | | 2 | - | 10 | 25 | t2 | | 3 | + | 140 | 152 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 4 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get region from 25 to 60 of each spliced transcript, or their existing subportion: >>> p.spliced_subsequence(25, 60, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 55 | 60 | t1 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 1 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get region of each spliced transcript which excludes their first and last 3 nucleotides: >>> p.spliced_subsequence(3, -3, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 4 | 11 | t1 | | 1 | + | 40 | 57 | t1 | | 2 | - | 70 | 77 | t2 | | 2 | - | 13 | 25 | t2 | | 3 | + | 143 | 149 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
spliced_subsequence
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def split(self, strand=None, between=False, nb_cpu=1): """Split into non-overlapping intervals. Parameters ---------- strand : bool, default None, i.e. auto Whether to ignore strand information if PyRanges is stranded. between : bool, default False Include lengths between intervals. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with intervals split at overlap points. See Also -------- pyranges.multioverlap : find overlaps with multiple PyRanges Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1', 'chr1'], 'Start': [3, 5, 5, 11], ... 'End': [6, 9, 7, 12], 'Strand': ['+', '+', '-', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 5 | 9 | + | | chr1 | 5 | 7 | - | | chr1 | 11 | 12 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 4 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.split() +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Strand | | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 3 | 5 | + | | chr1 | 5 | 6 | + | | chr1 | 6 | 9 | + | | chr1 | 5 | 7 | - | | chr1 | 11 | 12 | - | +--------------+-----------+-----------+------------+ Stranded PyRanges object has 5 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.split(between=True) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Strand | | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 3 | 5 | + | | chr1 | 5 | 6 | + | | chr1 | 6 | 9 | + | | chr1 | 5 | 7 | - | | chr1 | 7 | 11 | - | | chr1 | 11 | 12 | - | +--------------+-----------+-----------+------------+ Stranded PyRanges object has 6 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.split(strand=False) +--------------+-----------+-----------+ | Chromosome | Start | End | | (object) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 3 | 5 | | chr1 | 5 | 6 | | chr1 | 6 | 7 | | chr1 | 7 | 9 | | chr1 | 11 | 12 | +--------------+-----------+-----------+ Unstranded PyRanges object has 5 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.split(strand=False, between=True) +--------------+-----------+-----------+ | Chromosome | Start | End | | (object) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 3 | 5 | | chr1 | 5 | 6 | | chr1 | 6 | 7 | | chr1 | 7 | 9 | | chr1 | 9 | 11 | | chr1 | 11 | 12 | +--------------+-----------+-----------+ Unstranded PyRanges object has 6 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ if strand is None: strand = self.stranded kwargs = fill_kwargs({"strand": strand}) from pyranges.methods.split import _split df = pyrange_apply_single(_split, self, **kwargs) split = pr.PyRanges(df) if not between: strandedness = "same" if strand else False split = split.overlap(self, strandedness=strandedness) return split
Split into non-overlapping intervals. Parameters ---------- strand : bool, default None, i.e. auto Whether to ignore strand information if PyRanges is stranded. between : bool, default False Include lengths between intervals. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- PyRanges PyRanges with intervals split at overlap points. See Also -------- pyranges.multioverlap : find overlaps with multiple PyRanges Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1', 'chr1'], 'Start': [3, 5, 5, 11], ... 'End': [6, 9, 7, 12], 'Strand': ['+', '+', '-', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 3 | 6 | + | | chr1 | 5 | 9 | + | | chr1 | 5 | 7 | - | | chr1 | 11 | 12 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 4 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.split() +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Strand | | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 3 | 5 | + | | chr1 | 5 | 6 | + | | chr1 | 6 | 9 | + | | chr1 | 5 | 7 | - | | chr1 | 11 | 12 | - | +--------------+-----------+-----------+------------+ Stranded PyRanges object has 5 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.split(between=True) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | Strand | | (object) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 3 | 5 | + | | chr1 | 5 | 6 | + | | chr1 | 6 | 9 | + | | chr1 | 5 | 7 | - | | chr1 | 7 | 11 | - | | chr1 | 11 | 12 | - | +--------------+-----------+-----------+------------+ Stranded PyRanges object has 6 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.split(strand=False) +--------------+-----------+-----------+ | Chromosome | Start | End | | (object) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 3 | 5 | | chr1 | 5 | 6 | | chr1 | 6 | 7 | | chr1 | 7 | 9 | | chr1 | 11 | 12 | +--------------+-----------+-----------+ Unstranded PyRanges object has 5 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.split(strand=False, between=True) +--------------+-----------+-----------+ | Chromosome | Start | End | | (object) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 3 | 5 | | chr1 | 5 | 6 | | chr1 | 6 | 7 | | chr1 | 7 | 9 | | chr1 | 9 | 11 | | chr1 | 11 | 12 | +--------------+-----------+-----------+ Unstranded PyRanges object has 6 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
split
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def stranded(self): """Whether PyRanges has (valid) strand info. Note ---- A PyRanges can have invalid values in the Strand-column. It is not considered stranded. See Also -------- PyRanges.strands : return the strands Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '.']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | . | +--------------+-----------+-----------+--------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Considered unstranded due to these Strand values: '.' >>> gr.stranded False >>> "Strand" in gr.columns True """ keys = self.keys() if not len(keys): # so that stranded ops work with empty dataframes return True key = keys[0] return isinstance(key, tuple)
Whether PyRanges has (valid) strand info. Note ---- A PyRanges can have invalid values in the Strand-column. It is not considered stranded. See Also -------- PyRanges.strands : return the strands Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '.']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | . | +--------------+-----------+-----------+--------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Considered unstranded due to these Strand values: '.' >>> gr.stranded False >>> "Strand" in gr.columns True
stranded
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def strands(self): """Return strands. Notes ----- If the strand-column contains an invalid value, [] is returned. See Also -------- PyRanges.stranded : whether has valid strand info Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '.']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | . | +--------------+-----------+-----------+--------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Considered unstranded due to these Strand values: '.' >>> gr.strands [] >>> gr.Strand.drop_duplicates().to_list() ['+', '.'] >>> gr.Strand = ["+", "-"] >>> gr.strands ['+', '-'] """ if not self.stranded: return [] return natsorted(set([k[1] for k in self.keys()]))
Return strands. Notes ----- If the strand-column contains an invalid value, [] is returned. See Also -------- PyRanges.stranded : whether has valid strand info Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '.']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | . | +--------------+-----------+-----------+--------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. Considered unstranded due to these Strand values: '.' >>> gr.strands [] >>> gr.Strand.drop_duplicates().to_list() ['+', '.'] >>> gr.Strand = ["+", "-"] >>> gr.strands ['+', '-']
strands
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def subset(self, f, strand=None, **kwargs): """Return a subset of the rows. Parameters ---------- f : function Function which returns boolean Series equal to length of df. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Notes ----- PyRanges can also be subsetted directly with a boolean Series. This function is slightly faster, but more cumbersome. Returns ------- PyRanges PyRanges subset on rows. Examples -------- >>> gr = pr.data.f1() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.subset(lambda df: df.Start > 4) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Also possible: >>> gr[gr.Start > 4] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ kwargs = fill_kwargs(kwargs) if strand is None: strand = self.stranded if self.stranded and not strand: self = self.unstrand() kwargs.update({"strand": strand}) result = pyrange_apply_single(f, self, **kwargs) if not result: return pr.PyRanges() first_result = next(iter(result.values())) assert first_result.dtype == bool, "result of subset function must be bool, but is {}".format( first_result.dtype ) return self[result]
Return a subset of the rows. Parameters ---------- f : function Function which returns boolean Series equal to length of df. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Notes ----- PyRanges can also be subsetted directly with a boolean Series. This function is slightly faster, but more cumbersome. Returns ------- PyRanges PyRanges subset on rows. Examples -------- >>> gr = pr.data.f1() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 3 | 6 | interval1 | 0 | + | | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.subset(lambda df: df.Start > 4) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. Also possible: >>> gr[gr.Start > 4] +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 8 | 9 | interval3 | 0 | + | | chr1 | 5 | 7 | interval2 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 2 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
subset
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def subsequence(self, start=0, end=None, by=None, strand=None, **kwargs): """Get subsequences of the intervals. The returned intervals are subregions of self, cut according to specifications. Start and end are relative to the 5' end: 0 means the leftmost nucleotide for + strand intervals, while it means the rightmost one for - strand. This method also allows to manipulate groups of intervals (e.g. exons belonging to same transcripts) through the 'by' argument. When using it, start and end refer to the unspliced transcript coordinates, meaning that introns are included in the count. Parameters ---------- start : int Start of subregion, 0-based and included, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) end : int, default None End of subregion, 0-based and excluded, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) If None, the existing 3' end is returned. by : list of str, default None intervals are grouped by this/these ID column(s) beforehand, e.g. exons belonging to same transcripts strand : bool, default None, i.e. auto Whether strand is considered when interpreting the start and end arguments of this function. If True, counting is from the 5' end, which is the leftmost coordinate for + strand and the rightmost for - strand. If False, all intervals are processed like they reside on the + strand. If None (default), strand is considered if the PyRanges is stranded. Returns ------- PyRanges Subregion of self, subsequenced as specified by arguments Note ---- If the request goes out of bounds (e.g. requesting 100 nts for a 90nt region), only the existing portion is returned See also -------- spliced_subsequence : analogous to this method, but intronic regions are not counted, so that input coordinates refer to the spliced transcript Examples -------- >>> p = pr.from_dict({"Chromosome": [1, 1, 2, 2, 3], ... "Strand": ["+", "+", "-", "-", "+"], ... "Start": [1, 40, 2, 30, 140], ... "End": [20, 60, 13, 45, 155], ... "transcript_id":["t1", "t1", "t2", "t2", "t3"] }) >>> p +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 20 | t1 | | 1 | + | 40 | 60 | t1 | | 2 | - | 2 | 13 | t2 | | 2 | - | 30 | 45 | t2 | | 3 | + | 140 | 155 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the first 10 nucleotides (at the 5') of *each interval* (each line of the dataframe): >>> p.subsequence(0, 10) +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 1 | + | 40 | 50 | t1 | | 2 | - | 3 | 13 | t2 | | 2 | - | 35 | 45 | t2 | | 3 | + | 140 | 150 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the first 10 nucleotides of *each transcript*, grouping exons by transcript_id: >>> p.subsequence(0, 10, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 2 | - | 35 | 45 | t2 | | 3 | + | 140 | 150 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the last 20 nucleotides of each transcript: >>> p.subsequence(-20, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 40 | 60 | t1 | | 2 | - | 2 | 13 | t2 | | 3 | + | 140 | 155 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get region from 30 to 330 of each transcript, or their existing subportion: >>> p.subsequence(30, 300, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 40 | 60 | t1 | | 2 | - | 2 | 13 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 2 rows and 5 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.subsequence import _subseq if strand is None: strand = True if self.stranded else False kwargs.update({"strand": strand, "by": by, "start": start, "end": end}) kwargs = fill_kwargs(kwargs) result = pyrange_apply_single(_subseq, self, **kwargs) return pr.PyRanges(result)
Get subsequences of the intervals. The returned intervals are subregions of self, cut according to specifications. Start and end are relative to the 5' end: 0 means the leftmost nucleotide for + strand intervals, while it means the rightmost one for - strand. This method also allows to manipulate groups of intervals (e.g. exons belonging to same transcripts) through the 'by' argument. When using it, start and end refer to the unspliced transcript coordinates, meaning that introns are included in the count. Parameters ---------- start : int Start of subregion, 0-based and included, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) end : int, default None End of subregion, 0-based and excluded, counting from the 5' end. Use a negative int to count from the 3' (e.g. -1 is the last nucleotide) If None, the existing 3' end is returned. by : list of str, default None intervals are grouped by this/these ID column(s) beforehand, e.g. exons belonging to same transcripts strand : bool, default None, i.e. auto Whether strand is considered when interpreting the start and end arguments of this function. If True, counting is from the 5' end, which is the leftmost coordinate for + strand and the rightmost for - strand. If False, all intervals are processed like they reside on the + strand. If None (default), strand is considered if the PyRanges is stranded. Returns ------- PyRanges Subregion of self, subsequenced as specified by arguments Note ---- If the request goes out of bounds (e.g. requesting 100 nts for a 90nt region), only the existing portion is returned See also -------- spliced_subsequence : analogous to this method, but intronic regions are not counted, so that input coordinates refer to the spliced transcript Examples -------- >>> p = pr.from_dict({"Chromosome": [1, 1, 2, 2, 3], ... "Strand": ["+", "+", "-", "-", "+"], ... "Start": [1, 40, 2, 30, 140], ... "End": [20, 60, 13, 45, 155], ... "transcript_id":["t1", "t1", "t2", "t2", "t3"] }) >>> p +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 20 | t1 | | 1 | + | 40 | 60 | t1 | | 2 | - | 2 | 13 | t2 | | 2 | - | 30 | 45 | t2 | | 3 | + | 140 | 155 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the first 10 nucleotides (at the 5') of *each interval* (each line of the dataframe): >>> p.subsequence(0, 10) +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 1 | + | 40 | 50 | t1 | | 2 | - | 3 | 13 | t2 | | 2 | - | 35 | 45 | t2 | | 3 | + | 140 | 150 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 5 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the first 10 nucleotides of *each transcript*, grouping exons by transcript_id: >>> p.subsequence(0, 10, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 1 | 11 | t1 | | 2 | - | 35 | 45 | t2 | | 3 | + | 140 | 150 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get the last 20 nucleotides of each transcript: >>> p.subsequence(-20, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 40 | 60 | t1 | | 2 | - | 2 | 13 | t2 | | 3 | + | 140 | 155 | t3 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. # Get region from 30 to 330 of each transcript, or their existing subportion: >>> p.subsequence(30, 300, by='transcript_id') +--------------+--------------+-----------+-----------+-----------------+ | Chromosome | Strand | Start | End | transcript_id | | (category) | (category) | (int64) | (int64) | (object) | |--------------+--------------+-----------+-----------+-----------------| | 1 | + | 40 | 60 | t1 | | 2 | - | 2 | 13 | t2 | +--------------+--------------+-----------+-----------+-----------------+ Stranded PyRanges object has 2 rows and 5 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
subsequence
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def subtract(self, other, strandedness=None, nb_cpu=1): """Subtract intervals. Parameters ---------- strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. See Also -------- pyranges.PyRanges.overlap : use with invert=True to return all intervals without overlap Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.subtract(gr2) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 2 | a | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from pyranges.methods.subtraction import _subtraction kwargs = {"strandedness": strandedness} kwargs["sparse"] = {"self": False, "other": True} kwargs = fill_kwargs(kwargs) strand = True if strandedness else False other_clusters = other.merge(strand=strand) self = self.count_overlaps(other_clusters, strandedness=strandedness, overlap_col="__num__") result = pyrange_apply(_subtraction, self, other_clusters, **kwargs) self = self.drop("__num__") return PyRanges(result).drop("__num__")
Subtract intervals. Parameters ---------- strandedness : {None, "same", "opposite", False}, default None, i.e. auto Whether to compare PyRanges on the same strand, the opposite or ignore strand information. The default, None, means use "same" if both PyRanges are strande, otherwise ignore the strand information. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. See Also -------- pyranges.PyRanges.overlap : use with invert=True to return all intervals without overlap Examples -------- >>> gr = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [1, 4, 10], ... "End": [3, 9, 11], "ID": ["a", "b", "c"]}) >>> gr2 = pr.from_dict({"Chromosome": ["chr1"] * 3, "Start": [2, 2, 9], "End": [3, 9, 10]}) >>> gr +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 3 | a | | chr1 | 4 | 9 | b | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 3 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 2 | 3 | | chr1 | 2 | 9 | | chr1 | 9 | 10 | +--------------+-----------+-----------+ Unstranded PyRanges object has 3 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.subtract(gr2) +--------------+-----------+-----------+------------+ | Chromosome | Start | End | ID | | (category) | (int64) | (int64) | (object) | |--------------+-----------+-----------+------------| | chr1 | 1 | 2 | a | | chr1 | 10 | 11 | c | +--------------+-----------+-----------+------------+ Unstranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
subtract
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def summary(self, to_stdout=True, return_df=False): """Return info. Count refers to the number of intervals, the rest to the lengths. The column "pyrange" describes the data as is. "coverage_forward" and "coverage_reverse" describe the data after strand-specific merging of overlapping intervals. "coverage_unstranded" describes the data after merging, without considering the strands. The row "count" is the number of intervals and "sum" is their total length. The rest describe the lengths of the intervals. Parameters ---------- to_stdout : bool, default True Print summary. return_df : bool, default False Return df with summary. Returns ------- None or DataFrame with summary. Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_id"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-----------------| | 1 | gene | 11868 | 14409 | + | ENSG00000223972 | | 1 | transcript | 11868 | 14409 | + | ENSG00000223972 | | 1 | exon | 11868 | 12227 | + | ENSG00000223972 | | 1 | exon | 12612 | 12721 | + | ENSG00000223972 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | transcript | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | exon | 1179364 | 1179555 | - | ENSG00000205231 | | 1 | exon | 1173055 | 1176396 | - | ENSG00000205231 | +--------------+--------------+-----------+-----------+--------------+-----------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.summary() +-------+------------------+--------------------+--------------------+-----------------------+ | | pyrange | coverage_forward | coverage_reverse | coverage_unstranded | |-------+------------------+--------------------+--------------------+-----------------------| | count | 2446 | 39 | 23 | 32 | | mean | 2291.92 | 7058.1 | 30078.6 | 27704.2 | | std | 11906.9 | 10322.3 | 59467.7 | 67026.9 | | min | 1 | 83 | 154 | 83 | | 25% | 90 | 1051 | 1204 | 1155 | | 50% | 138 | 2541 | 6500 | 6343 | | 75% | 382.25 | 7168 | 23778 | 20650.8 | | max | 241726 | 43065 | 241726 | 291164 | | sum | 5.60603e+06 | 275266 | 691807 | 886534 | +-------+------------------+--------------------+--------------------+-----------------------+ >>> gr.summary(return_df=True, to_stdout=False) pyrange coverage_forward coverage_reverse coverage_unstranded count 2.446000e+03 39.000000 23.000000 32.000000 mean 2.291918e+03 7058.102564 30078.565217 27704.187500 std 1.190685e+04 10322.309347 59467.695265 67026.868647 min 1.000000e+00 83.000000 154.000000 83.000000 25% 9.000000e+01 1051.000000 1204.000000 1155.000000 50% 1.380000e+02 2541.000000 6500.000000 6343.000000 75% 3.822500e+02 7168.000000 23778.000000 20650.750000 max 2.417260e+05 43065.000000 241726.000000 291164.000000 sum 5.606031e+06 275266.000000 691807.000000 886534.000000 """ from pyranges.methods.summary import _summary return _summary(self, to_stdout, return_df)
Return info. Count refers to the number of intervals, the rest to the lengths. The column "pyrange" describes the data as is. "coverage_forward" and "coverage_reverse" describe the data after strand-specific merging of overlapping intervals. "coverage_unstranded" describes the data after merging, without considering the strands. The row "count" is the number of intervals and "sum" is their total length. The rest describe the lengths of the intervals. Parameters ---------- to_stdout : bool, default True Print summary. return_df : bool, default False Return df with summary. Returns ------- None or DataFrame with summary. Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_id"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-----------------+ | Chromosome | Feature | Start | End | Strand | gene_id | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-----------------| | 1 | gene | 11868 | 14409 | + | ENSG00000223972 | | 1 | transcript | 11868 | 14409 | + | ENSG00000223972 | | 1 | exon | 11868 | 12227 | + | ENSG00000223972 | | 1 | exon | 12612 | 12721 | + | ENSG00000223972 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | transcript | 1173055 | 1179555 | - | ENSG00000205231 | | 1 | exon | 1179364 | 1179555 | - | ENSG00000205231 | | 1 | exon | 1173055 | 1176396 | - | ENSG00000205231 | +--------------+--------------+-----------+-----------+--------------+-----------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.summary() +-------+------------------+--------------------+--------------------+-----------------------+ | | pyrange | coverage_forward | coverage_reverse | coverage_unstranded | |-------+------------------+--------------------+--------------------+-----------------------| | count | 2446 | 39 | 23 | 32 | | mean | 2291.92 | 7058.1 | 30078.6 | 27704.2 | | std | 11906.9 | 10322.3 | 59467.7 | 67026.9 | | min | 1 | 83 | 154 | 83 | | 25% | 90 | 1051 | 1204 | 1155 | | 50% | 138 | 2541 | 6500 | 6343 | | 75% | 382.25 | 7168 | 23778 | 20650.8 | | max | 241726 | 43065 | 241726 | 291164 | | sum | 5.60603e+06 | 275266 | 691807 | 886534 | +-------+------------------+--------------------+--------------------+-----------------------+ >>> gr.summary(return_df=True, to_stdout=False) pyrange coverage_forward coverage_reverse coverage_unstranded count 2.446000e+03 39.000000 23.000000 32.000000 mean 2.291918e+03 7058.102564 30078.565217 27704.187500 std 1.190685e+04 10322.309347 59467.695265 67026.868647 min 1.000000e+00 83.000000 154.000000 83.000000 25% 9.000000e+01 1051.000000 1204.000000 1155.000000 50% 1.380000e+02 2541.000000 6500.000000 6343.000000 75% 3.822500e+02 7168.000000 23778.000000 20650.750000 max 2.417260e+05 43065.000000 241726.000000 291164.000000 sum 5.606031e+06 275266.000000 691807.000000 886534.000000
summary
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def tail(self, n=8): """Return the n last rows. Parameters ---------- n : int, default 8 Return n rows. Returns ------- PyRanges PyRanges with the n last rows. See Also -------- PyRanges.head : return the first rows PyRanges.sample : return random rows Examples -------- >>> gr = pr.data.chipseq() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.tail(3) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ subsetter = np.zeros(len(self), dtype=np.bool_) subsetter[(len(self) - n) :] = True return self[subsetter]
Return the n last rows. Parameters ---------- n : int, default 8 Return n rows. Returns ------- PyRanges PyRanges with the n last rows. See Also -------- PyRanges.head : return the first rows PyRanges.sample : return random rows Examples -------- >>> gr = pr.data.chipseq() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.tail(3) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 3 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
tail
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def tile(self, tile_size, overlap=False, strand=None, nb_cpu=1): """Return overlapping genomic tiles. The genome is divided into bookended tiles of length `tile_size` and one is returned per overlapping interval. Parameters ---------- tile_size : int Length of the tiles. overlap : bool, default False Add column of nucleotide overlap to each tile. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges Tiled PyRanges. See also -------- pyranges.PyRanges.window : divide intervals into windows Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 14409 | + | DDX11L1 | | 1 | exon | 11868 | 12227 | + | DDX11L1 | | 1 | exon | 12612 | 12721 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | transcript | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1179364 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1173055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.tile(200) +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11800 | 12000 | + | DDX11L1 | | 1 | gene | 12000 | 12200 | + | DDX11L1 | | 1 | gene | 12200 | 12400 | + | DDX11L1 | | 1 | gene | 12400 | 12600 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | exon | 1175600 | 1175800 | - | TTLL10-AS1 | | 1 | exon | 1175800 | 1176000 | - | TTLL10-AS1 | | 1 | exon | 1176000 | 1176200 | - | TTLL10-AS1 | | 1 | exon | 1176200 | 1176400 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 30,538 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.tile(100, overlap=True) +--------------+--------------+-----------+-----------+--------------+-------------+---------------+ | Chromosome | Feature | Start | End | Strand | gene_name | TileOverlap | | (category) | (category) | (int64) | (int64) | (category) | (object) | (int64) | |--------------+--------------+-----------+-----------+--------------+-------------+---------------| | 1 | gene | 11800 | 11900 | + | DDX11L1 | 32 | | 1 | gene | 11900 | 12000 | + | DDX11L1 | 100 | | 1 | gene | 12000 | 12100 | + | DDX11L1 | 100 | | 1 | gene | 12100 | 12200 | + | DDX11L1 | 100 | | ... | ... | ... | ... | ... | ... | ... | | 1 | exon | 1176000 | 1176100 | - | TTLL10-AS1 | 100 | | 1 | exon | 1176100 | 1176200 | - | TTLL10-AS1 | 100 | | 1 | exon | 1176200 | 1176300 | - | TTLL10-AS1 | 100 | | 1 | exon | 1176300 | 1176400 | - | TTLL10-AS1 | 96 | +--------------+--------------+-----------+-----------+--------------+-------------+---------------+ Stranded PyRanges object has 58,516 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.windows import _tiles if strand is None: strand = self.stranded kwargs = {"strand": strand, "overlap": overlap} kwargs["sparse"] = {"self": False} kwargs["tile_size"] = tile_size df = pyrange_apply_single(_tiles, self, **kwargs) return PyRanges(df)
Return overlapping genomic tiles. The genome is divided into bookended tiles of length `tile_size` and one is returned per overlapping interval. Parameters ---------- tile_size : int Length of the tiles. overlap : bool, default False Add column of nucleotide overlap to each tile. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges Tiled PyRanges. See also -------- pyranges.PyRanges.window : divide intervals into windows Examples -------- >>> gr = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 14409 | + | DDX11L1 | | 1 | exon | 11868 | 12227 | + | DDX11L1 | | 1 | exon | 12612 | 12721 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | transcript | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1179364 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1173055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.tile(200) +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11800 | 12000 | + | DDX11L1 | | 1 | gene | 12000 | 12200 | + | DDX11L1 | | 1 | gene | 12200 | 12400 | + | DDX11L1 | | 1 | gene | 12400 | 12600 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | exon | 1175600 | 1175800 | - | TTLL10-AS1 | | 1 | exon | 1175800 | 1176000 | - | TTLL10-AS1 | | 1 | exon | 1176000 | 1176200 | - | TTLL10-AS1 | | 1 | exon | 1176200 | 1176400 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 30,538 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.tile(100, overlap=True) +--------------+--------------+-----------+-----------+--------------+-------------+---------------+ | Chromosome | Feature | Start | End | Strand | gene_name | TileOverlap | | (category) | (category) | (int64) | (int64) | (category) | (object) | (int64) | |--------------+--------------+-----------+-----------+--------------+-------------+---------------| | 1 | gene | 11800 | 11900 | + | DDX11L1 | 32 | | 1 | gene | 11900 | 12000 | + | DDX11L1 | 100 | | 1 | gene | 12000 | 12100 | + | DDX11L1 | 100 | | 1 | gene | 12100 | 12200 | + | DDX11L1 | 100 | | ... | ... | ... | ... | ... | ... | ... | | 1 | exon | 1176000 | 1176100 | - | TTLL10-AS1 | 100 | | 1 | exon | 1176100 | 1176200 | - | TTLL10-AS1 | 100 | | 1 | exon | 1176200 | 1176300 | - | TTLL10-AS1 | 100 | | 1 | exon | 1176300 | 1176400 | - | TTLL10-AS1 | 96 | +--------------+--------------+-----------+-----------+--------------+-------------+---------------+ Stranded PyRanges object has 58,516 rows and 7 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
tile
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def to_example(self, n=10): """Return as dict. Used for easily creating examples for copy and pasting. Parameters ---------- n : int, default 10 Number of rows. Half is taken from the start, the other half from the end. See Also -------- PyRanges.from_dict : create PyRanges from dict Examples -------- >>> gr = pr.data.chipseq() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> d = gr.to_example(n=4) >>> d {'Chromosome': ['chr1', 'chr1', 'chrY', 'chrY'], 'Start': [212609534, 169887529, 8010951, 7405376], 'End': [212609559, 169887554, 8010976, 7405401], 'Name': ['U0', 'U0', 'U0', 'U0'], 'Score': [0, 0, 0, 0], 'Strand': ['+', '+', '-', '-']} >>> pr.from_dict(d) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 4 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ nrows_half = int(min(n, len(self)) / 2) if n < len(self): first = self.head(nrows_half) last = self.tail(nrows_half) example = pr.concat([first, last]) else: example = self d = {c: list(getattr(example, c)) for c in example.columns} return d
Return as dict. Used for easily creating examples for copy and pasting. Parameters ---------- n : int, default 10 Number of rows. Half is taken from the start, the other half from the end. See Also -------- PyRanges.from_dict : create PyRanges from dict Examples -------- >>> gr = pr.data.chipseq() >>> gr +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chr1 | 216711011 | 216711036 | U0 | 0 | + | | chr1 | 144227079 | 144227104 | U0 | 0 | + | | ... | ... | ... | ... | ... | ... | | chrY | 15224235 | 15224260 | U0 | 0 | - | | chrY | 13517892 | 13517917 | U0 | 0 | - | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 10,000 rows and 6 columns from 24 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> d = gr.to_example(n=4) >>> d {'Chromosome': ['chr1', 'chr1', 'chrY', 'chrY'], 'Start': [212609534, 169887529, 8010951, 7405376], 'End': [212609559, 169887554, 8010976, 7405401], 'Name': ['U0', 'U0', 'U0', 'U0'], 'Score': [0, 0, 0, 0], 'Strand': ['+', '+', '-', '-']} >>> pr.from_dict(d) +--------------+-----------+-----------+------------+-----------+--------------+ | Chromosome | Start | End | Name | Score | Strand | | (category) | (int64) | (int64) | (object) | (int64) | (category) | |--------------+-----------+-----------+------------+-----------+--------------| | chr1 | 212609534 | 212609559 | U0 | 0 | + | | chr1 | 169887529 | 169887554 | U0 | 0 | + | | chrY | 8010951 | 8010976 | U0 | 0 | - | | chrY | 7405376 | 7405401 | U0 | 0 | - | +--------------+-----------+-----------+------------+-----------+--------------+ Stranded PyRanges object has 4 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
to_example
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def three_end(self): """Return the 3'-end. The 3'-end is the start of intervals on the reverse strand and the end of intervals on the forward strand. Returns ------- PyRanges PyRanges with the 3'. See Also -------- PyRanges.five_end : return the five prime end Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.three_end() +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 4 | 5 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ assert self.stranded, "Need stranded pyrange to find 3'." kwargs = fill_kwargs({"strand": True}) return PyRanges(pyrange_apply_single(_tes, self, **kwargs))
Return the 3'-end. The 3'-end is the start of intervals on the reverse strand and the end of intervals on the forward strand. Returns ------- PyRanges PyRanges with the 3'. See Also -------- PyRanges.five_end : return the five prime end Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.three_end() +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 4 | 5 | + | | chr1 | 6 | 7 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
three_end
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def to_bed(self, path=None, keep=True, compression="infer", chain=False): r"""Write to bed. Parameters ---------- path : str, default None Where to write. If None, returns string representation. keep : bool, default True Whether to keep all columns, not just Chromosome, Start, End, Name, Score, Strand when writing. compression : str, compression type to use, by default infer based on extension. See pandas.DataFree.to_csv for more info. chain : bool, default False Whether to return the PyRanges after writing. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '-'], "Gene": [1, 2]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Gene | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 5 | + | 1 | | chr1 | 6 | 8 | - | 2 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.to_bed() 'chr1\t1\t5\t.\t.\t+\t1\nchr1\t6\t8\t.\t.\t-\t2\n' # File contents: chr1 1 5 . . + 1 chr1 6 8 . . - 2 Does not include noncanonical bed-column `Gene`: >>> gr.to_bed(keep=False) 'chr1\t1\t5\t.\t.\t+\nchr1\t6\t8\t.\t.\t-\n' # File contents: chr1 1 5 . . + chr1 6 8 . . - >>> gr.to_bed("test.bed", chain=True) +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Gene | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 5 | + | 1 | | chr1 | 6 | 8 | - | 2 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> open("test.bed").readlines() ['chr1\t1\t5\t.\t.\t+\t1\n', 'chr1\t6\t8\t.\t.\t-\t2\n'] """ from pyranges.out import _to_bed result = _to_bed(self, path, keep=keep, compression=compression) if path and chain: return self else: return result
Write to bed. Parameters ---------- path : str, default None Where to write. If None, returns string representation. keep : bool, default True Whether to keep all columns, not just Chromosome, Start, End, Name, Score, Strand when writing. compression : str, compression type to use, by default infer based on extension. See pandas.DataFree.to_csv for more info. chain : bool, default False Whether to return the PyRanges after writing. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '-'], "Gene": [1, 2]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Gene | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 5 | + | 1 | | chr1 | 6 | 8 | - | 2 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.to_bed() 'chr1\t1\t5\t.\t.\t+\t1\nchr1\t6\t8\t.\t.\t-\t2\n' # File contents: chr1 1 5 . . + 1 chr1 6 8 . . - 2 Does not include noncanonical bed-column `Gene`: >>> gr.to_bed(keep=False) 'chr1\t1\t5\t.\t.\t+\nchr1\t6\t8\t.\t.\t-\n' # File contents: chr1 1 5 . . + chr1 6 8 . . - >>> gr.to_bed("test.bed", chain=True) +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Gene | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 5 | + | 1 | | chr1 | 6 | 8 | - | 2 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 2 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> open("test.bed").readlines() ['chr1\t1\t5\t.\t.\t+\t1\n', 'chr1\t6\t8\t.\t.\t-\t2\n']
to_bed
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def to_bigwig( self, path=None, chromosome_sizes=None, rpm=True, divide=None, value_col=None, dryrun=False, chain=False, ): """Write regular or value coverage to bigwig. Note ---- To create one bigwig per strand, subset the PyRanges first. Parameters ---------- path : str Where to write bigwig. chromosome_sizes : PyRanges or dict If dict: map of chromosome names to chromosome length. rpm : True Whether to normalize data by dividing by total number of intervals and multiplying by 1e6. divide : bool, default False (Only useful with value_col) Divide value coverage by regular coverage and take log2. value_col : str, default None Name of column to compute coverage of. dryrun : bool, default False Return data that would be written without writing bigwigs. chain : bool, default False Whether to return the PyRanges after writing. Note ---- Requires pybigwig to be installed. If you require more control over the normalization process, use pyranges.to_bigwig() See Also -------- pyranges.to_bigwig : write pandas DataFrame to bigwig. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [1, 4, 6], ... 'End': [7, 8, 10], 'Strand': ['+', '-', '-'], ... 'Value': [10, 20, 30]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Value | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 7 | + | 10 | | chr1 | 4 | 8 | - | 20 | | chr1 | 6 | 10 | - | 30 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.to_bigwig(dryrun=True, rpm=False) +--------------+-----------+-----------+-------------+ | Chromosome | Start | End | Score | | (category) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-------------| | chr1 | 1 | 4 | 1 | | chr1 | 4 | 6 | 2 | | chr1 | 6 | 7 | 3 | | chr1 | 7 | 8 | 2 | | chr1 | 8 | 10 | 1 | +--------------+-----------+-----------+-------------+ Unstranded PyRanges object has 5 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.to_bigwig(dryrun=True, rpm=False, value_col="Value") +--------------+-----------+-----------+-------------+ | Chromosome | Start | End | Score | | (category) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-------------| | chr1 | 1 | 4 | 10 | | chr1 | 4 | 6 | 30 | | chr1 | 6 | 7 | 60 | | chr1 | 7 | 8 | 50 | | chr1 | 8 | 10 | 30 | +--------------+-----------+-----------+-------------+ Unstranded PyRanges object has 5 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.to_bigwig(dryrun=True, rpm=False, value_col="Value", divide=True) +--------------+-----------+-----------+-------------+ | Chromosome | Start | End | Score | | (category) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-------------| | chr1 | 0 | 1 | nan | | chr1 | 1 | 4 | 3.32193 | | chr1 | 4 | 6 | 3.90689 | | chr1 | 6 | 7 | 4.32193 | | chr1 | 7 | 8 | 4.64386 | | chr1 | 8 | 10 | 4.90689 | +--------------+-----------+-----------+-------------+ Unstranded PyRanges object has 6 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ from pyranges.out import _to_bigwig if chromosome_sizes is None: chromosome_sizes = pr.data.chromsizes() result = _to_bigwig(self, path, chromosome_sizes, rpm, divide, value_col, dryrun) if dryrun: return result if chain: return self else: pass
Write regular or value coverage to bigwig. Note ---- To create one bigwig per strand, subset the PyRanges first. Parameters ---------- path : str Where to write bigwig. chromosome_sizes : PyRanges or dict If dict: map of chromosome names to chromosome length. rpm : True Whether to normalize data by dividing by total number of intervals and multiplying by 1e6. divide : bool, default False (Only useful with value_col) Divide value coverage by regular coverage and take log2. value_col : str, default None Name of column to compute coverage of. dryrun : bool, default False Return data that would be written without writing bigwigs. chain : bool, default False Whether to return the PyRanges after writing. Note ---- Requires pybigwig to be installed. If you require more control over the normalization process, use pyranges.to_bigwig() See Also -------- pyranges.to_bigwig : write pandas DataFrame to bigwig. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [1, 4, 6], ... 'End': [7, 8, 10], 'Strand': ['+', '-', '-'], ... 'Value': [10, 20, 30]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Value | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 7 | + | 10 | | chr1 | 4 | 8 | - | 20 | | chr1 | 6 | 10 | - | 30 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.to_bigwig(dryrun=True, rpm=False) +--------------+-----------+-----------+-------------+ | Chromosome | Start | End | Score | | (category) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-------------| | chr1 | 1 | 4 | 1 | | chr1 | 4 | 6 | 2 | | chr1 | 6 | 7 | 3 | | chr1 | 7 | 8 | 2 | | chr1 | 8 | 10 | 1 | +--------------+-----------+-----------+-------------+ Unstranded PyRanges object has 5 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.to_bigwig(dryrun=True, rpm=False, value_col="Value") +--------------+-----------+-----------+-------------+ | Chromosome | Start | End | Score | | (category) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-------------| | chr1 | 1 | 4 | 10 | | chr1 | 4 | 6 | 30 | | chr1 | 6 | 7 | 60 | | chr1 | 7 | 8 | 50 | | chr1 | 8 | 10 | 30 | +--------------+-----------+-----------+-------------+ Unstranded PyRanges object has 5 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.to_bigwig(dryrun=True, rpm=False, value_col="Value", divide=True) +--------------+-----------+-----------+-------------+ | Chromosome | Start | End | Score | | (category) | (int64) | (int64) | (float64) | |--------------+-----------+-----------+-------------| | chr1 | 0 | 1 | nan | | chr1 | 1 | 4 | 3.32193 | | chr1 | 4 | 6 | 3.90689 | | chr1 | 6 | 7 | 4.32193 | | chr1 | 7 | 8 | 4.64386 | | chr1 | 8 | 10 | 4.90689 | +--------------+-----------+-----------+-------------+ Unstranded PyRanges object has 6 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
to_bigwig
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def to_rle(self, value_col=None, strand=None, rpm=False, nb_cpu=1): """Return as RleDict. Create collection of Rles representing the coverage or other numerical value. Parameters ---------- value_col : str, default None Numerical column to create RleDict from. strand : bool, default None, i.e. auto Whether to treat strands serparately. rpm : bool, default False Normalize by multiplying with `1e6/(number_intervals)`. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- pyrle.RleDict Rle with coverage or other info from the PyRanges. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Score': [0.1, 5, 3.14], 'Strand': ['+', '+', '-']} >>> gr = pr.from_dict(d) >>> gr.to_rle() chr1 + -- +--------+-----+-----+-----+-----+ | Runs | 3 | 3 | 2 | 1 | |--------+-----+-----+-----+-----| | Values | 0.0 | 1.0 | 0.0 | 1.0 | +--------+-----+-----+-----+-----+ Rle of length 9 containing 4 elements (avg. length 2.25) <BLANKLINE> chr1 - -- +--------+-----+-----+ | Runs | 5 | 2 | |--------+-----+-----| | Values | 0.0 | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) RleDict object with 2 chromosomes/strand pairs. >>> gr.to_rle(value_col="Score") chr1 + -- +--------+-----+-----+-----+-----+ | Runs | 3 | 3 | 2 | 1 | |--------+-----+-----+-----+-----| | Values | 0.0 | 0.1 | 0.0 | 5.0 | +--------+-----+-----+-----+-----+ Rle of length 9 containing 4 elements (avg. length 2.25) <BLANKLINE> chr1 - -- +--------+-----+------+ | Runs | 5 | 2 | |--------+-----+------| | Values | 0.0 | 3.14 | +--------+-----+------+ Rle of length 7 containing 2 elements (avg. length 3.5) RleDict object with 2 chromosomes/strand pairs. >>> gr.to_rle(value_col="Score", strand=False) chr1 +--------+-----+-----+------+------+-----+-----+ | Runs | 3 | 2 | 1 | 1 | 1 | 1 | |--------+-----+-----+------+------+-----+-----| | Values | 0.0 | 0.1 | 3.24 | 3.14 | 0.0 | 5.0 | +--------+-----+-----+------+------+-----+-----+ Rle of length 9 containing 6 elements (avg. length 1.5) Unstranded RleDict object with 1 chromosome. >>> gr.to_rle(rpm=True) chr1 + -- +--------+-----+-------------------+-----+-------------------+ | Runs | 3 | 3 | 2 | 1 | |--------+-----+-------------------+-----+-------------------| | Values | 0.0 | 333333.3333333333 | 0.0 | 333333.3333333333 | +--------+-----+-------------------+-----+-------------------+ Rle of length 9 containing 4 elements (avg. length 2.25) <BLANKLINE> chr1 - -- +--------+-----+-------------------+ | Runs | 5 | 2 | |--------+-----+-------------------| | Values | 0.0 | 333333.3333333333 | +--------+-----+-------------------+ Rle of length 7 containing 2 elements (avg. length 3.5) RleDict object with 2 chromosomes/strand pairs. """ if strand is None: strand = self.stranded from pyranges.methods.to_rle import _to_rle return _to_rle(self, value_col, strand=strand, rpm=rpm, nb_cpu=nb_cpu)
Return as RleDict. Create collection of Rles representing the coverage or other numerical value. Parameters ---------- value_col : str, default None Numerical column to create RleDict from. strand : bool, default None, i.e. auto Whether to treat strands serparately. rpm : bool, default False Normalize by multiplying with `1e6/(number_intervals)`. nb_cpu : int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. Returns ------- pyrle.RleDict Rle with coverage or other info from the PyRanges. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [3, 8, 5], ... 'End': [6, 9, 7], 'Score': [0.1, 5, 3.14], 'Strand': ['+', '+', '-']} >>> gr = pr.from_dict(d) >>> gr.to_rle() chr1 + -- +--------+-----+-----+-----+-----+ | Runs | 3 | 3 | 2 | 1 | |--------+-----+-----+-----+-----| | Values | 0.0 | 1.0 | 0.0 | 1.0 | +--------+-----+-----+-----+-----+ Rle of length 9 containing 4 elements (avg. length 2.25) <BLANKLINE> chr1 - -- +--------+-----+-----+ | Runs | 5 | 2 | |--------+-----+-----| | Values | 0.0 | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) RleDict object with 2 chromosomes/strand pairs. >>> gr.to_rle(value_col="Score") chr1 + -- +--------+-----+-----+-----+-----+ | Runs | 3 | 3 | 2 | 1 | |--------+-----+-----+-----+-----| | Values | 0.0 | 0.1 | 0.0 | 5.0 | +--------+-----+-----+-----+-----+ Rle of length 9 containing 4 elements (avg. length 2.25) <BLANKLINE> chr1 - -- +--------+-----+------+ | Runs | 5 | 2 | |--------+-----+------| | Values | 0.0 | 3.14 | +--------+-----+------+ Rle of length 7 containing 2 elements (avg. length 3.5) RleDict object with 2 chromosomes/strand pairs. >>> gr.to_rle(value_col="Score", strand=False) chr1 +--------+-----+-----+------+------+-----+-----+ | Runs | 3 | 2 | 1 | 1 | 1 | 1 | |--------+-----+-----+------+------+-----+-----| | Values | 0.0 | 0.1 | 3.24 | 3.14 | 0.0 | 5.0 | +--------+-----+-----+------+------+-----+-----+ Rle of length 9 containing 6 elements (avg. length 1.5) Unstranded RleDict object with 1 chromosome. >>> gr.to_rle(rpm=True) chr1 + -- +--------+-----+-------------------+-----+-------------------+ | Runs | 3 | 3 | 2 | 1 | |--------+-----+-------------------+-----+-------------------| | Values | 0.0 | 333333.3333333333 | 0.0 | 333333.3333333333 | +--------+-----+-------------------+-----+-------------------+ Rle of length 9 containing 4 elements (avg. length 2.25) <BLANKLINE> chr1 - -- +--------+-----+-------------------+ | Runs | 5 | 2 | |--------+-----+-------------------| | Values | 0.0 | 333333.3333333333 | +--------+-----+-------------------+ Rle of length 7 containing 2 elements (avg. length 3.5) RleDict object with 2 chromosomes/strand pairs.
to_rle
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def unstrand(self): """Remove strand. Note ---- Removes Strand column even if PyRanges is not stranded. See Also -------- PyRanges.stranded : whether PyRanges contains valid strand info. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.unstrand() +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 1 | 5 | | chr1 | 6 | 8 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. """ if not self.stranded and "Strand" in self.columns: return self.drop("Strand") elif not self.stranded: return self gr = pr.concat([self["+"], self["-"]]) gr = gr.apply(lambda df: df.drop("Strand", axis=1).reset_index(drop=True)) return pr.PyRanges(gr.dfs)
Remove strand. Note ---- Removes Strand column even if PyRanges is not stranded. See Also -------- PyRanges.stranded : whether PyRanges contains valid strand info. Examples -------- >>> d = {'Chromosome': ['chr1', 'chr1'], 'Start': [1, 6], ... 'End': [5, 8], 'Strand': ['+', '-']} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 1 | 5 | + | | chr1 | 6 | 8 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 2 rows and 4 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.unstrand() +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 1 | 5 | | chr1 | 6 | 8 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome.
unstrand
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def window(self, window_size, strand=None): """Return overlapping genomic windows. Windows of length `window_size` are returned. Parameters ---------- window_size : int Length of the windows. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges Tiled PyRanges. See also -------- pyranges.PyRanges.tile : divide intervals into adjacent tiles. Examples -------- >>> import pyranges as pr >>> gr = pr.from_dict({"Chromosome": [1], "Start": [895], "End": [1259]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 895 | 1259 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.window(200) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 895 | 1095 | | 1 | 1095 | 1259 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr2 +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 14409 | + | DDX11L1 | | 1 | exon | 11868 | 12227 | + | DDX11L1 | | 1 | exon | 12612 | 12721 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | transcript | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1179364 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1173055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr2 = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr2.window(1000) +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 12868 | + | DDX11L1 | | 1 | gene | 12868 | 13868 | + | DDX11L1 | | 1 | gene | 13868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 12868 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | exon | 1173055 | 1174055 | - | TTLL10-AS1 | | 1 | exon | 1174055 | 1175055 | - | TTLL10-AS1 | | 1 | exon | 1175055 | 1176055 | - | TTLL10-AS1 | | 1 | exon | 1176055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 7,516 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from pyranges.methods.windows import _windows if strand is None: strand = self.stranded kwargs = { "strand": strand, "sparse": {"self": False}, "window_size": window_size, } df = pyrange_apply_single(_windows, self, **kwargs) return PyRanges(df)
Return overlapping genomic windows. Windows of length `window_size` are returned. Parameters ---------- window_size : int Length of the windows. strand : bool, default None, i.e. auto Whether to do operations on chromosome/strand pairs or chromosomes. If None, will use chromosome/strand pairs if the PyRanges is stranded. nb_cpu: int, default 1 How many cpus to use. Can at most use 1 per chromosome or chromosome/strand tuple. Will only lead to speedups on large datasets. **kwargs Additional keyword arguments to pass as keyword arguments to `f` Returns ------- PyRanges Tiled PyRanges. See also -------- pyranges.PyRanges.tile : divide intervals into adjacent tiles. Examples -------- >>> import pyranges as pr >>> gr = pr.from_dict({"Chromosome": [1], "Start": [895], "End": [1259]}) >>> gr +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 895 | 1259 | +--------------+-----------+-----------+ Unstranded PyRanges object has 1 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr.window(200) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | 1 | 895 | 1095 | | 1 | 1095 | 1259 | +--------------+-----------+-----------+ Unstranded PyRanges object has 2 rows and 3 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome. >>> gr2 = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr2 +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 14409 | + | DDX11L1 | | 1 | exon | 11868 | 12227 | + | DDX11L1 | | 1 | exon | 12612 | 12721 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | gene | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | transcript | 1173055 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1179364 | 1179555 | - | TTLL10-AS1 | | 1 | exon | 1173055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 2,446 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr2 = pr.data.ensembl_gtf()[["Feature", "gene_name"]] >>> gr2.window(1000) +--------------+--------------+-----------+-----------+--------------+-------------+ | Chromosome | Feature | Start | End | Strand | gene_name | | (category) | (category) | (int64) | (int64) | (category) | (object) | |--------------+--------------+-----------+-----------+--------------+-------------| | 1 | gene | 11868 | 12868 | + | DDX11L1 | | 1 | gene | 12868 | 13868 | + | DDX11L1 | | 1 | gene | 13868 | 14409 | + | DDX11L1 | | 1 | transcript | 11868 | 12868 | + | DDX11L1 | | ... | ... | ... | ... | ... | ... | | 1 | exon | 1173055 | 1174055 | - | TTLL10-AS1 | | 1 | exon | 1174055 | 1175055 | - | TTLL10-AS1 | | 1 | exon | 1175055 | 1176055 | - | TTLL10-AS1 | | 1 | exon | 1176055 | 1176396 | - | TTLL10-AS1 | +--------------+--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 7,516 rows and 6 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
window
python
pyranges/pyranges
pyranges/pyranges_main.py
https://github.com/pyranges/pyranges/blob/master/pyranges/pyranges_main.py
MIT
def rename_core_attrs(df, ftype, rename_attr=False): """Deduplicate columns from GTF attributes that share names with the default 8 columns by appending "_attr" to each name if rename_attr==True. Otherwise throw an error informing user of formatting issues. Parameters ---------- df : pandas DataFrame DataFrame from read_gtf ftype : str {'gtf' or 'gff3'} rename_attr : bool, default False Whether to rename (potential) attributes with reserved column names with the suffix '_attr' or to just raise an error (default) Returns ------- df : pandas DataFrame DataFrame with deduplicated column names """ if ftype == "gtf": core_cols = _ordered_gtf_columns elif ftype == "gff3": core_cols = _ordered_gff3_columns dupe_core_cols = list(set(df.columns) & set(core_cols)) # if duplicate columns were found if len(dupe_core_cols) > 0: print(f"Found attributes with reserved names: {dupe_core_cols}.") if not rename_attr: raise ValueError else: print("Renaming attributes with suffix '_attr'") dupe_core_dict = dict() for c in dupe_core_cols: dupe_core_dict[c] = f"{c}_attr" df.rename(dupe_core_dict, axis=1, inplace=True) return df
Deduplicate columns from GTF attributes that share names with the default 8 columns by appending "_attr" to each name if rename_attr==True. Otherwise throw an error informing user of formatting issues. Parameters ---------- df : pandas DataFrame DataFrame from read_gtf ftype : str {'gtf' or 'gff3'} rename_attr : bool, default False Whether to rename (potential) attributes with reserved column names with the suffix '_attr' or to just raise an error (default) Returns ------- df : pandas DataFrame DataFrame with deduplicated column names
rename_core_attrs
python
pyranges/pyranges
pyranges/readers.py
https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py
MIT
def read_bam(f, sparse=True, as_df=False, mapq=0, required_flag=0, filter_flag=1540): """Return bam file as PyRanges. Parameters ---------- f : str Path to bam file sparse : bool, default True Whether to return only. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. mapq : int, default 0 Minimum mapping quality score. required_flag : int, default 0 Flags which must be present for the interval to be read. filter_flag : int, default 1540 Ignore reads with these flags. Default 1540, which means that either the read is unmapped, the read failed vendor or platfrom quality checks, or the read is a PCR or optical duplicate. Notes ----- This functionality requires the library `bamread`. It can be installed with `pip install bamread` or `conda install -c bioconda bamread`. Examples -------- >>> path = pr.get_example_path("control.bam") >>> pr.read_bam(path).sort() +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Flag | | (category) | (int64) | (int64) | (category) | (uint16) | |--------------+-----------+-----------+--------------+------------| | chr1 | 1041102 | 1041127 | + | 0 | | chr1 | 2129359 | 2129384 | + | 0 | | chr1 | 2239108 | 2239133 | + | 0 | | chr1 | 2318805 | 2318830 | + | 0 | | ... | ... | ... | ... | ... | | chrY | 10632456 | 10632481 | - | 16 | | chrY | 11918814 | 11918839 | - | 16 | | chrY | 11936866 | 11936891 | - | 16 | | chrY | 57402214 | 57402239 | - | 16 | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 10,000 rows and 5 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ try: import bamread # type: ignore except ImportError: print( "bamread must be installed to read bam. Use `conda install -c bioconda bamread` or `pip install bamread` to install it." ) sys.exit(1) if bamread.__version__ in [ "0.0.1", "0.0.2", "0.0.3", "0.0.4", "0.0.5", "0.0.6", "0.0.7", "0.0.8", "0.0.9", ]: print( "bamread not recent enough. Must be 0.0.10 or higher. Use `conda install -c bioconda 'bamread>=0.0.10'` or `pip install bamread>=0.0.10` to install it." ) sys.exit(1) if sparse: df = bamread.read_bam(f, mapq, required_flag, filter_flag) else: try: df = bamread.read_bam_full(f, mapq, required_flag, filter_flag) except AttributeError: print("bamread version 0.0.6 or higher is required to read bam non-sparsely.") if as_df: return df else: return PyRanges(df) # return bamread.read_bam(f, mapq, required_flag, filter_flag)
Return bam file as PyRanges. Parameters ---------- f : str Path to bam file sparse : bool, default True Whether to return only. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. mapq : int, default 0 Minimum mapping quality score. required_flag : int, default 0 Flags which must be present for the interval to be read. filter_flag : int, default 1540 Ignore reads with these flags. Default 1540, which means that either the read is unmapped, the read failed vendor or platfrom quality checks, or the read is a PCR or optical duplicate. Notes ----- This functionality requires the library `bamread`. It can be installed with `pip install bamread` or `conda install -c bioconda bamread`. Examples -------- >>> path = pr.get_example_path("control.bam") >>> pr.read_bam(path).sort() +--------------+-----------+-----------+--------------+------------+ | Chromosome | Start | End | Strand | Flag | | (category) | (int64) | (int64) | (category) | (uint16) | |--------------+-----------+-----------+--------------+------------| | chr1 | 1041102 | 1041127 | + | 0 | | chr1 | 2129359 | 2129384 | + | 0 | | chr1 | 2239108 | 2239133 | + | 0 | | chr1 | 2318805 | 2318830 | + | 0 | | ... | ... | ... | ... | ... | | chrY | 10632456 | 10632481 | - | 16 | | chrY | 11918814 | 11918839 | - | 16 | | chrY | 11936866 | 11936891 | - | 16 | | chrY | 57402214 | 57402239 | - | 16 | +--------------+-----------+-----------+--------------+------------+ Stranded PyRanges object has 10,000 rows and 5 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
read_bam
python
pyranges/pyranges
pyranges/readers.py
https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py
MIT
def read_gtf( f, full=True, as_df=False, nrows=None, duplicate_attr=False, rename_attr=False, ignore_bad: bool = False, ): """Read files in the Gene Transfer Format. Parameters ---------- f : str Path to GTF file. full : bool, default True Whether to read and interpret the annotation column. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default None Number of rows to read. Default None, i.e. all. duplicate_attr : bool, default False Whether to handle (potential) duplicate attributes or just keep last one. rename_attr : bool, default False Whether to rename (potential) attributes with reserved column names with the suffix '_attr' or to just raise an error (default) ignore_bad : bool, default False Whether to ignore bad lines or raise an error. Note ---- The GTF format encodes both Start and End as 1-based included. PyRanges (and also the DF returned by this function, if as_df=True), instead encodes intervals as 0-based, Start included and End excluded. See Also -------- pyranges.read_gff3 : read files in the General Feature Format Examples -------- >>> path = pr.get_example_path("ensembl.gtf") >>> gr = pr.read_gtf(path) >>> # +--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------+ >>> # | Chromosome | Source | Feature | Start | End | Score | Strand | Frame | gene_id | gene_version | +18 | >>> # | (category) | (object) | (category) | (int64) | (int64) | (object) | (category) | (object) | (object) | (object) | ... | >>> # |--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------| >>> # | 1 | havana | gene | 11868 | 14409 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | 1 | havana | transcript | 11868 | 14409 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | 1 | havana | exon | 11868 | 12227 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | 1 | havana | exon | 12612 | 12721 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | >>> # | 1 | ensembl | transcript | 120724 | 133723 | . | - | . | ENSG00000238009 | 6 | ... | >>> # | 1 | ensembl | exon | 133373 | 133723 | . | - | . | ENSG00000238009 | 6 | ... | >>> # | 1 | ensembl | exon | 129054 | 129223 | . | - | . | ENSG00000238009 | 6 | ... | >>> # | 1 | ensembl | exon | 120873 | 120932 | . | - | . | ENSG00000238009 | 6 | ... | >>> # +--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------+ >>> # Stranded PyRanges object has 95 rows and 28 columns from 1 chromosomes. >>> # For printing, the PyRanges was sorted on Chromosome and Strand. >>> # 18 hidden columns: gene_name, gene_source, gene_biotype, transcript_id, transcript_version, transcript_name, transcript_source, transcript_biotype, tag, transcript_support_level, ... (+ 8 more.) """ _skiprows = skiprows(f) if full: gr = read_gtf_full( f, as_df, nrows, _skiprows, duplicate_attr, rename_attr, ignore_bad=ignore_bad, ) else: gr = read_gtf_restricted(f, _skiprows, as_df=False, nrows=None) return gr
Read files in the Gene Transfer Format. Parameters ---------- f : str Path to GTF file. full : bool, default True Whether to read and interpret the annotation column. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default None Number of rows to read. Default None, i.e. all. duplicate_attr : bool, default False Whether to handle (potential) duplicate attributes or just keep last one. rename_attr : bool, default False Whether to rename (potential) attributes with reserved column names with the suffix '_attr' or to just raise an error (default) ignore_bad : bool, default False Whether to ignore bad lines or raise an error. Note ---- The GTF format encodes both Start and End as 1-based included. PyRanges (and also the DF returned by this function, if as_df=True), instead encodes intervals as 0-based, Start included and End excluded. See Also -------- pyranges.read_gff3 : read files in the General Feature Format Examples -------- >>> path = pr.get_example_path("ensembl.gtf") >>> gr = pr.read_gtf(path) >>> # +--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------+ >>> # | Chromosome | Source | Feature | Start | End | Score | Strand | Frame | gene_id | gene_version | +18 | >>> # | (category) | (object) | (category) | (int64) | (int64) | (object) | (category) | (object) | (object) | (object) | ... | >>> # |--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------| >>> # | 1 | havana | gene | 11868 | 14409 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | 1 | havana | transcript | 11868 | 14409 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | 1 | havana | exon | 11868 | 12227 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | 1 | havana | exon | 12612 | 12721 | . | + | . | ENSG00000223972 | 5 | ... | >>> # | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | >>> # | 1 | ensembl | transcript | 120724 | 133723 | . | - | . | ENSG00000238009 | 6 | ... | >>> # | 1 | ensembl | exon | 133373 | 133723 | . | - | . | ENSG00000238009 | 6 | ... | >>> # | 1 | ensembl | exon | 129054 | 129223 | . | - | . | ENSG00000238009 | 6 | ... | >>> # | 1 | ensembl | exon | 120873 | 120932 | . | - | . | ENSG00000238009 | 6 | ... | >>> # +--------------+------------+--------------+-----------+-----------+------------+--------------+------------+-----------------+----------------+-------+ >>> # Stranded PyRanges object has 95 rows and 28 columns from 1 chromosomes. >>> # For printing, the PyRanges was sorted on Chromosome and Strand. >>> # 18 hidden columns: gene_name, gene_source, gene_biotype, transcript_id, transcript_version, transcript_name, transcript_source, transcript_biotype, tag, transcript_support_level, ... (+ 8 more.)
read_gtf
python
pyranges/pyranges
pyranges/readers.py
https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py
MIT
def read_gtf_restricted(f, skiprows, as_df=False, nrows=None): """seqname - name of the chromosome or scaffold; chromosome names can be given with or without the 'chr' prefix. Important note: the seqname must be one used within Ensembl, i.e. a standard chromosome name or an Ensembl identifier such as a scaffold ID, without any additional content such as species or assembly. See the example GFF output below. # source - name of the program that generated this feature, or the data source (database or project name) feature - feature type name, e.g. Gene, Variation, Similarity start - Start position of the feature, with sequence numbering starting at 1. end - End position of the feature, with sequence numbering starting at 1. score - A floating point value. strand - defined as + (forward) or - (reverse). # frame - One of '0', '1' or '2'. '0' indicates that the first base of the feature is the first base of a codon, '1' that the second base is the first base of a codon, and so on.. attribute - A semicolon-separated list of tag-value pairs, providing additional information about each feature. """ dtypes = {"Chromosome": "category", "Feature": "category", "Strand": "category"} df_iter = pd.read_csv( f, sep="\t", comment="#", usecols=[0, 2, 3, 4, 5, 6, 8], header=None, names="Chromosome Feature Start End Score Strand Attribute".split(), dtype=dtypes, chunksize=int(1e5), skiprows=skiprows, nrows=nrows, ) dfs = [] for df in df_iter: if sum(df.Score == ".") == len(df): cols_to_concat = "Chromosome Start End Strand Feature".split() else: cols_to_concat = "Chromosome Start End Strand Feature Score".split() extract = _fetch_gene_transcript_exon_id(df.Attribute) extract.columns = "gene_id transcript_id exon_number exon_id".split() extract.exon_number = extract.exon_number.astype(float) extract.set_index(df.index, inplace=True) df = pd.concat([df[cols_to_concat], extract], axis=1, sort=False) dfs.append(df) df = pd.concat(dfs, sort=False) df.loc[:, "Start"] = df.Start - 1 if not as_df: return PyRanges(df) else: return df
seqname - name of the chromosome or scaffold; chromosome names can be given with or without the 'chr' prefix. Important note: the seqname must be one used within Ensembl, i.e. a standard chromosome name or an Ensembl identifier such as a scaffold ID, without any additional content such as species or assembly. See the example GFF output below. # source - name of the program that generated this feature, or the data source (database or project name) feature - feature type name, e.g. Gene, Variation, Similarity start - Start position of the feature, with sequence numbering starting at 1. end - End position of the feature, with sequence numbering starting at 1. score - A floating point value. strand - defined as + (forward) or - (reverse). # frame - One of '0', '1' or '2'. '0' indicates that the first base of the feature is the first base of a codon, '1' that the second base is the first base of a codon, and so on.. attribute - A semicolon-separated list of tag-value pairs, providing additional information about each feature.
read_gtf_restricted
python
pyranges/pyranges
pyranges/readers.py
https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py
MIT
def read_gff3(f, full=True, annotation=None, as_df=False, nrows=None): """Read files in the General Feature Format. Parameters ---------- f : str Path to GFF file. full : bool, default True Whether to read and interpret the annotation column. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default None Number of rows to read. Default None, i.e. all. Notes ----- The gff3 format encodes both Start and End as 1-based included. PyRanges (and also the DF returned by this function, if as_df=True), instead encodes intervals as 0-based, Start included and End excluded. See Also -------- pyranges.read_gtf : read files in the Gene Transfer Format """ _skiprows = skiprows(f) if not full: return read_gtf_restricted(f, _skiprows, as_df=as_df, nrows=nrows) dtypes = {"Chromosome": "category", "Feature": "category", "Strand": "category"} names = "Chromosome Source Feature Start End Score Strand Frame Attribute".split() df_iter = pd.read_csv( f, comment="#", sep="\t", header=None, names=names, dtype=dtypes, chunksize=int(1e5), skiprows=_skiprows, nrows=nrows, ) dfs = [] for df in df_iter: extra = to_rows_gff3(df.Attribute.astype(str)) df = df.drop("Attribute", axis=1) extra.set_index(df.index, inplace=True) ndf = pd.concat([df, extra], axis=1, sort=False) dfs.append(ndf) df = pd.concat(dfs, sort=False) df.loc[:, "Start"] = df.Start - 1 if not as_df: return PyRanges(df) else: return df
Read files in the General Feature Format. Parameters ---------- f : str Path to GFF file. full : bool, default True Whether to read and interpret the annotation column. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default None Number of rows to read. Default None, i.e. all. Notes ----- The gff3 format encodes both Start and End as 1-based included. PyRanges (and also the DF returned by this function, if as_df=True), instead encodes intervals as 0-based, Start included and End excluded. See Also -------- pyranges.read_gtf : read files in the Gene Transfer Format
read_gff3
python
pyranges/pyranges
pyranges/readers.py
https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py
MIT
def fdr(p_vals): """Adjust p-values with Benjamini-Hochberg. Parameters ---------- data : array-like Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> d = {'Chromosome': ['chr3', 'chr6', 'chr13'], 'Start': [146419383, 39800100, 24537618], 'End': [146419483, 39800200, 24537718], 'Strand': ['-', '+', '-'], 'PValue': [0.0039591368855297175, 0.0037600512992788937, 0.0075061166500909205]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-------------+ | Chromosome | Start | End | Strand | PValue | | (category) | (int64) | (int64) | (category) | (float64) | |--------------+-----------+-----------+--------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.00395914 | | chr6 | 39800100 | 39800200 | + | 0.00376005 | | chr13 | 24537618 | 24537718 | - | 0.00750612 | +--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.FDR = pr.stats.fdr(gr.PValue) >>> gr.print(formatting={"PValue": "{:.4f}", "FDR": "{:.4}"}) +--------------+-----------+-----------+--------------+-------------+-------------+ | Chromosome | Start | End | Strand | PValue | FDR | | (category) | (int64) | (int64) | (category) | (float64) | (float64) | |--------------+-----------+-----------+--------------+-------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.004 | 0.005939 | | chr6 | 39800100 | 39800200 | + | 0.0038 | 0.01128 | | chr13 | 24537618 | 24537718 | - | 0.0075 | 0.007506 | +--------------+-----------+-----------+--------------+-------------+-------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from scipy.stats import rankdata # type: ignore ranked_p_values = rankdata(p_vals) fdr = p_vals * len(p_vals) / ranked_p_values fdr[fdr > 1] = 1 return fdr
Adjust p-values with Benjamini-Hochberg. Parameters ---------- data : array-like Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> d = {'Chromosome': ['chr3', 'chr6', 'chr13'], 'Start': [146419383, 39800100, 24537618], 'End': [146419483, 39800200, 24537718], 'Strand': ['-', '+', '-'], 'PValue': [0.0039591368855297175, 0.0037600512992788937, 0.0075061166500909205]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-------------+ | Chromosome | Start | End | Strand | PValue | | (category) | (int64) | (int64) | (category) | (float64) | |--------------+-----------+-----------+--------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.00395914 | | chr6 | 39800100 | 39800200 | + | 0.00376005 | | chr13 | 24537618 | 24537718 | - | 0.00750612 | +--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.FDR = pr.stats.fdr(gr.PValue) >>> gr.print(formatting={"PValue": "{:.4f}", "FDR": "{:.4}"}) +--------------+-----------+-----------+--------------+-------------+-------------+ | Chromosome | Start | End | Strand | PValue | FDR | | (category) | (int64) | (int64) | (category) | (float64) | (float64) | |--------------+-----------+-----------+--------------+-------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.004 | 0.005939 | | chr6 | 39800100 | 39800200 | + | 0.0038 | 0.01128 | | chr13 | 24537618 | 24537718 | - | 0.0075 | 0.007506 | +--------------+-----------+-----------+--------------+-------------+-------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
fdr
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def fisher_exact(tp, fp, fn, tn, pseudocount=0): """Fisher's exact for contingency tables. Computes the hypotheses two-sided, less and greater at the same time. The odds-ratio is Parameters ---------- tp : array-like of int Top left square of contingency table (true positives). fp : array-like of int Top right square of contingency table (false positives). fn : array-like of int Bottom left square of contingency table (false negatives). tn : array-like of int Bottom right square of contingency table (true negatives). pseudocount : float, default 0 Values > 0 allow Odds Ratio to always be a finite number. Notes ----- The odds-ratio is computed thusly: ``((tp + pseudocount) / (fp + pseudocount)) / ((fn + pseudocount) / (tn + pseudocount))`` Returns ------- pandas.DataFrame DataFrame with columns OR and P, PLeft and PRight. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> d = {"TP": [12, 0], "FP": [5, 12], "TN": [29, 10], "FN": [2, 2]} >>> df = pd.DataFrame(d) >>> df TP FP TN FN 0 12 5 29 2 1 0 12 10 2 >>> pr.stats.fisher_exact(df.TP, df.FP, df.TN, df.FN) OR P PLeft PRight 0 0.165517 0.080269 0.044555 0.994525 1 0.000000 0.000067 0.000034 1.000000 """ try: from fisher import pvalue_npy # type: ignore except ImportError: import sys print( "fisher needs to be installed to use fisher exact. pip install fisher or conda install -c bioconda fisher." ) sys.exit(-1) tp = np.array(tp, dtype=np.uint) fp = np.array(fp, dtype=np.uint) fn = np.array(fn, dtype=np.uint) tn = np.array(tn, dtype=np.uint) left, right, twosided = pvalue_npy(tp, fp, fn, tn) OR = ((tp + pseudocount) / (fp + pseudocount)) / ((fn + pseudocount) / (tn + pseudocount)) df = pd.DataFrame({"OR": OR, "P": twosided, "PLeft": left, "PRight": right}) return df
Fisher's exact for contingency tables. Computes the hypotheses two-sided, less and greater at the same time. The odds-ratio is Parameters ---------- tp : array-like of int Top left square of contingency table (true positives). fp : array-like of int Top right square of contingency table (false positives). fn : array-like of int Bottom left square of contingency table (false negatives). tn : array-like of int Bottom right square of contingency table (true negatives). pseudocount : float, default 0 Values > 0 allow Odds Ratio to always be a finite number. Notes ----- The odds-ratio is computed thusly: ``((tp + pseudocount) / (fp + pseudocount)) / ((fn + pseudocount) / (tn + pseudocount))`` Returns ------- pandas.DataFrame DataFrame with columns OR and P, PLeft and PRight. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> d = {"TP": [12, 0], "FP": [5, 12], "TN": [29, 10], "FN": [2, 2]} >>> df = pd.DataFrame(d) >>> df TP FP TN FN 0 12 5 29 2 1 0 12 10 2 >>> pr.stats.fisher_exact(df.TP, df.FP, df.TN, df.FN) OR P PLeft PRight 0 0.165517 0.080269 0.044555 0.994525 1 0.000000 0.000067 0.000034 1.000000
fisher_exact
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def mcc(grs, genome=None, labels=None, strand=False, verbose=False): """Compute Matthew's correlation coefficient for PyRanges overlaps. Parameters ---------- grs : list of PyRanges PyRanges to compare. genome : DataFrame or dict, default None Should contain chromosome sizes. By default, end position of the rightmost intervals are used as proxies for the chromosome size, but it is recommended to use a genome. labels : list of str, default None Names to give the PyRanges in the output. strand : bool, default False Whether to compute correlations per strand. verbose : bool, default False Warn if some chromosomes are in the genome, but not in the PyRanges. Examples -------- >>> grs = [pr.data.aorta(), pr.data.aorta(), pr.data.aorta2()] >>> mcc = pr.stats.mcc(grs, labels="abc", genome={"chr1": 2100000}) >>> mcc T F TP FP TN FN MCC 0 a a 728 0 2099272 0 1.00000 1 a b 728 0 2099272 0 1.00000 3 a c 457 485 2098787 271 0.55168 2 b a 728 0 2099272 0 1.00000 5 b b 728 0 2099272 0 1.00000 6 b c 457 485 2098787 271 0.55168 4 c a 457 271 2098787 485 0.55168 7 c b 457 271 2098787 485 0.55168 8 c c 942 0 2099058 0 1.00000 To create a symmetric matrix (useful for heatmaps of correlations): >>> mcc.set_index(["T", "F"]).MCC.unstack().rename_axis(None, axis=0) F a b c a 1.00000 1.00000 0.55168 b 1.00000 1.00000 0.55168 c 0.55168 0.55168 1.00000 """ import sys from itertools import chain, combinations_with_replacement if labels is None: _labels = list(range(len(grs))) _labels = combinations_with_replacement(_labels, r=2) else: assert len(labels) == len(grs) _labels = combinations_with_replacement(labels, r=2) # remove all non-loc columns before computation grs = [gr.merge(strand=strand) for gr in grs] if genome is not None: if isinstance(genome, (pd.DataFrame, pr.PyRanges)): genome_length = int(genome.End.sum()) else: genome_length = sum(genome.values()) if verbose: # check that genome definition does not have many more # chromosomes than datafiles gr_cs = set(chain(*[gr.chromosomes for gr in grs])) g_cs = set(genome.chromosomes) surplus = g_cs - gr_cs if len(surplus): print( "The following chromosomes are in the genome, but not the PyRanges:", ", ".join(surplus), file=sys.stderr, ) if strand: def make_stranded(df): df = df.copy() df2 = df.copy() df.insert(df.shape[1], "Strand", "+") df2.insert(df2.shape[1], "Strand", "-") return pd.concat([df, df2]) genome = genome.apply(make_stranded) else: d = defaultdict(int) for gr in grs: for k, v in gr: d[k] = max(d[k], v.End.max()) genome_length = sum(d.values()) strandedness = "same" if strand else None rowdicts = [] for (lt, lf), (t, f) in zip(_labels, combinations_with_replacement(grs, r=2)): if verbose: print(lt, lf, file=sys.stderr) if lt == lf: if not strand: tp = t.length fn = 0 tn = genome_length - tp fp = 0 rowdicts.append({"T": lt, "F": lf, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": 1}) else: for strand in "+ -".split(): tp = t[strand].length fn = 0 tn = genome_length - tp fp = 0 rowdicts.append( { "T": lt, "F": lf, "Strand": strand, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": 1, } ) continue else: j = t.join(f, strandedness=strandedness) tp_gr = j.new_position("intersection").merge(strand=strand) if strand: for strand in "+ -".split(): tp = tp_gr[strand].length fp = f[strand].length - tp fn = t[strand].length - tp tn = genome_length - (tp + fp + fn) mcc = _mcc(tp, fp, tn, fn) rowdicts.append( { "T": lt, "F": lf, "Strand": strand, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": mcc, } ) rowdicts.append( { "T": lf, "F": lt, "Strand": strand, "TP": tp, "FP": fn, "TN": tn, "FN": fp, "MCC": mcc, } ) else: tp = tp_gr.length fp = f.length - tp fn = t.length - tp tn = genome_length - (tp + fp + fn) mcc = _mcc(tp, fp, tn, fn) rowdicts.append( { "T": lt, "F": lf, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": mcc, } ) rowdicts.append( { "T": lf, "F": lt, "TP": tp, "FP": fn, "TN": tn, "FN": fp, "MCC": mcc, } ) df = pd.DataFrame.from_dict(rowdicts).sort_values(["T", "F"]) return df
Compute Matthew's correlation coefficient for PyRanges overlaps. Parameters ---------- grs : list of PyRanges PyRanges to compare. genome : DataFrame or dict, default None Should contain chromosome sizes. By default, end position of the rightmost intervals are used as proxies for the chromosome size, but it is recommended to use a genome. labels : list of str, default None Names to give the PyRanges in the output. strand : bool, default False Whether to compute correlations per strand. verbose : bool, default False Warn if some chromosomes are in the genome, but not in the PyRanges. Examples -------- >>> grs = [pr.data.aorta(), pr.data.aorta(), pr.data.aorta2()] >>> mcc = pr.stats.mcc(grs, labels="abc", genome={"chr1": 2100000}) >>> mcc T F TP FP TN FN MCC 0 a a 728 0 2099272 0 1.00000 1 a b 728 0 2099272 0 1.00000 3 a c 457 485 2098787 271 0.55168 2 b a 728 0 2099272 0 1.00000 5 b b 728 0 2099272 0 1.00000 6 b c 457 485 2098787 271 0.55168 4 c a 457 271 2098787 485 0.55168 7 c b 457 271 2098787 485 0.55168 8 c c 942 0 2099058 0 1.00000 To create a symmetric matrix (useful for heatmaps of correlations): >>> mcc.set_index(["T", "F"]).MCC.unstack().rename_axis(None, axis=0) F a b c a 1.00000 1.00000 0.55168 b 1.00000 1.00000 0.55168 c 0.55168 0.55168 1.00000
mcc
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def rowbased_spearman(x, y): """Fast row-based Spearman's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_pearson : fast row-based Pearson's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Spearman's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_spearman(x, y) array([-0.5, 0.5, -1. ]) """ x = np.asarray(x) y = np.asarray(y) rx = rowbased_rankdata(x) ry = rowbased_rankdata(y) return rowbased_pearson(rx, ry)
Fast row-based Spearman's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_pearson : fast row-based Pearson's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Spearman's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_spearman(x, y) array([-0.5, 0.5, -1. ])
rowbased_spearman
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def rowbased_pearson(x, y): """Fast row-based Pearson's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_spearman : fast row-based Spearman's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Pearson's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_pearson(x, y) array([-0.09078413, 0.65465367, -1. ]) """ # Thanks to https://github.com/dengemann def ss(a, axis): return np.sum(a * a, axis=axis) x = np.asarray(x) y = np.asarray(y) mx = x.mean(axis=-1) my = y.mean(axis=-1) xm, ym = x - mx[..., None], y - my[..., None] r_num = np.add.reduce(xm * ym, axis=-1) r_den = np.sqrt(ss(xm, axis=-1) * ss(ym, axis=-1)) with np.errstate(divide="ignore", invalid="ignore"): r = r_num / r_den return r
Fast row-based Pearson's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_spearman : fast row-based Spearman's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Pearson's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_pearson(x, y) array([-0.09078413, 0.65465367, -1. ])
rowbased_pearson
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def rowbased_rankdata(data): """Rank order of entries in each row. Same as SciPy rankdata with method=mean. Parameters ---------- data : matrix-like The data to find order of. Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> x = np.random.randint(10, size=(3, 4)) >>> x = np.array([[3, 7, 6, 0], [1, 3, 8, 9], [5, 9, 3, 5]]) >>> pr.stats.rowbased_rankdata(x) 0 1 2 3 0 2.0 4.0 3.0 1.0 1 1.0 2.0 3.0 4.0 2 2.5 4.0 1.0 2.5 """ dc = np.asarray(data).copy() sorter = np.apply_along_axis(np.argsort, 1, data) inv = np.empty(data.shape, np.intp) ranks = np.tile(np.arange(data.shape[1]), (len(data), 1)) np.put_along_axis(inv, sorter, ranks, axis=1) dc = np.take_along_axis(dc, sorter, 1) res = np.apply_along_axis(lambda r: r[1:] != r[:-1], 1, dc) obs = np.column_stack([np.ones(len(res), dtype=bool), res]) dense = np.take_along_axis(np.apply_along_axis(np.cumsum, 1, obs), inv, 1) len_r = obs.shape[1] nonzero = np.count_nonzero(obs, axis=1) obs = pd.DataFrame(obs) nonzero = pd.Series(nonzero) dense = pd.DataFrame(dense) ranks = [] for _nonzero, nzdf in obs.groupby(nonzero, sort=False, observed=False): nz = np.apply_along_axis(lambda r: np.nonzero(r)[0], 1, nzdf) _count = np.column_stack([nz, np.ones(len(nz)) * len_r]) _dense = dense.reindex(nzdf.index).values _result = 0.5 * (np.take_along_axis(_count, _dense, 1) + np.take_along_axis(_count, _dense - 1, 1) + 1) result = pd.DataFrame(_result, index=nzdf.index) ranks.append(result) final = pd.concat(ranks).sort_index(kind="mergesort") return final
Rank order of entries in each row. Same as SciPy rankdata with method=mean. Parameters ---------- data : matrix-like The data to find order of. Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> x = np.random.randint(10, size=(3, 4)) >>> x = np.array([[3, 7, 6, 0], [1, 3, 8, 9], [5, 9, 3, 5]]) >>> pr.stats.rowbased_rankdata(x) 0 1 2 3 0 2.0 4.0 3.0 1.0 1 1.0 2.0 3.0 4.0 2 2.5 4.0 1.0 2.5
rowbased_rankdata
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def simes(df, groupby, pcol, keep_position=False): """Apply Simes method for giving dependent events a p-value. Parameters ---------- df : pandas.DataFrame Data to analyse with Simes. groupby : str or list of str Features equal in these columns will be merged with Simes. pcol : str Name of column with p-values. keep_position : bool, default False Keep columns "Chromosome", "Start", "End" and "Strand" if they exist. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> s = '''Chromosome Start End Strand Gene PValue ... 1 10 20 + P53 0.0001 ... 1 20 20 + P53 0.0002 ... 1 30 20 + P53 0.0003 ... 2 60 65 - FOX 0.05 ... 2 70 75 - FOX 0.0000001 ... 2 80 90 - FOX 0.0000021''' >>> gr = pr.from_string(s) >>> gr +--------------+-----------+-----------+--------------+------------+-------------+ | Chromosome | Start | End | Strand | Gene | PValue | | (category) | (int64) | (int64) | (category) | (object) | (float64) | |--------------+-----------+-----------+--------------+------------+-------------| | 1 | 10 | 20 | + | P53 | 0.0001 | | 1 | 20 | 20 | + | P53 | 0.0002 | | 1 | 30 | 20 | + | P53 | 0.0003 | | 2 | 60 | 65 | - | FOX | 0.05 | | 2 | 70 | 75 | - | FOX | 1e-07 | | 2 | 80 | 90 | - | FOX | 2.1e-06 | +--------------+-----------+-----------+--------------+------------+-------------+ Stranded PyRanges object has 6 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> simes = pr.stats.simes(gr.df, "Gene", "PValue") >>> simes Gene Simes 0 FOX 3.000000e-07 1 P53 3.000000e-04 >>> gr.apply(lambda df: ... pr.stats.simes(df, "Gene", "PValue", keep_position=True)) +--------------+-----------+-----------+-------------+--------------+------------+ | Chromosome | Start | End | Simes | Strand | Gene | | (category) | (int64) | (int64) | (float64) | (category) | (object) | |--------------+-----------+-----------+-------------+--------------+------------| | 1 | 10 | 20 | 0.0001 | + | P53 | | 2 | 60 | 90 | 1e-07 | - | FOX | +--------------+-----------+-----------+-------------+--------------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if isinstance(groupby, str): groupby = [groupby] positions = [] if "Strand" in df: stranded = True if keep_position: positions += ["Chromosome", "Start", "End"] if stranded: positions += ["Strand"] sorter = groupby + [pcol] sdf = df[positions + sorter].sort_values(sorter) g = sdf.groupby(positions + groupby, observed=False) ranks = g.cumcount().values + 1 size = g.size().values size = np.repeat(size, size) multiplied = sdf[pcol].values * size simes = multiplied / ranks sdf.insert(sdf.shape[1], "Simes", simes) if keep_position: grpby_dict = { "Chromosome": "first", "Start": "min", "End": "max", "Simes": "min", } if stranded: grpby_dict["Strand"] = "first" simes = sdf.groupby(groupby, observed=False).agg(grpby_dict).reset_index() columns = list(simes.columns) columns.append(columns[0]) del columns[0] simes = simes[columns] else: simes = sdf.groupby(groupby, observed=False).Simes.min().reset_index() return simes
Apply Simes method for giving dependent events a p-value. Parameters ---------- df : pandas.DataFrame Data to analyse with Simes. groupby : str or list of str Features equal in these columns will be merged with Simes. pcol : str Name of column with p-values. keep_position : bool, default False Keep columns "Chromosome", "Start", "End" and "Strand" if they exist. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> s = '''Chromosome Start End Strand Gene PValue ... 1 10 20 + P53 0.0001 ... 1 20 20 + P53 0.0002 ... 1 30 20 + P53 0.0003 ... 2 60 65 - FOX 0.05 ... 2 70 75 - FOX 0.0000001 ... 2 80 90 - FOX 0.0000021''' >>> gr = pr.from_string(s) >>> gr +--------------+-----------+-----------+--------------+------------+-------------+ | Chromosome | Start | End | Strand | Gene | PValue | | (category) | (int64) | (int64) | (category) | (object) | (float64) | |--------------+-----------+-----------+--------------+------------+-------------| | 1 | 10 | 20 | + | P53 | 0.0001 | | 1 | 20 | 20 | + | P53 | 0.0002 | | 1 | 30 | 20 | + | P53 | 0.0003 | | 2 | 60 | 65 | - | FOX | 0.05 | | 2 | 70 | 75 | - | FOX | 1e-07 | | 2 | 80 | 90 | - | FOX | 2.1e-06 | +--------------+-----------+-----------+--------------+------------+-------------+ Stranded PyRanges object has 6 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> simes = pr.stats.simes(gr.df, "Gene", "PValue") >>> simes Gene Simes 0 FOX 3.000000e-07 1 P53 3.000000e-04 >>> gr.apply(lambda df: ... pr.stats.simes(df, "Gene", "PValue", keep_position=True)) +--------------+-----------+-----------+-------------+--------------+------------+ | Chromosome | Start | End | Simes | Strand | Gene | | (category) | (int64) | (int64) | (float64) | (category) | (object) | |--------------+-----------+-----------+-------------+--------------+------------| | 1 | 10 | 20 | 0.0001 | + | P53 | | 2 | 60 | 90 | 1e-07 | - | FOX | +--------------+-----------+-----------+-------------+--------------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
simes
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def forbes(self, other, chromsizes, strandedness=None): """Compute Forbes coefficient. Ratio which represents observed versus expected co-occurence. Described in ``Forbes SA (1907): On the local distribution of certain Illinois fishes: an essay in statistical ecology.`` Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of observed versus expected co-occurence. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.forbes(gr2, chromsizes=chromsizes) 1.7168314674978278""" chromsizes = chromsizes_as_int(chromsizes) self = self.pr kwargs = {} kwargs["sparse"] = {"self": True, "other": True} kwargs = pr.pyranges_main.fill_kwargs(kwargs) strand = True if kwargs.get("strandedness") else False reference_length = self.merge(strand=strand).length query_length = other.merge(strand=strand).length intersection_sum = sum( v.sum() for v in self.set_intersect(other, strandedness=strandedness).lengths(as_dict=True).values() ) forbes = chromsizes * intersection_sum / (reference_length * query_length) return forbes
Compute Forbes coefficient. Ratio which represents observed versus expected co-occurence. Described in ``Forbes SA (1907): On the local distribution of certain Illinois fishes: an essay in statistical ecology.`` Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of observed versus expected co-occurence. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.forbes(gr2, chromsizes=chromsizes) 1.7168314674978278
forbes
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def jaccard(self, other, **kwargs): """Compute Jaccards coefficient. Ratio of the intersection and union of two sets. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of the intersection and union of two sets. See Also -------- pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.jaccard(gr2, chromsizes=chromsizes) 6.657941988519211e-05""" self = self.pr kwargs["sparse"] = {"self": True, "other": True} kwargs = pr.pyranges_main.fill_kwargs(kwargs) strand = True if kwargs.get("strandedness") else False intersection_sum = sum(v.sum() for v in self.set_intersect(other).lengths(as_dict=True).values()) union_sum = 0 for gr in [self, other]: union_sum += sum(v.sum() for v in gr.merge(strand=strand).lengths(as_dict=True).values()) denominator = union_sum - intersection_sum if denominator == 0: return 1 else: jc = intersection_sum / denominator return jc
Compute Jaccards coefficient. Ratio of the intersection and union of two sets. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of the intersection and union of two sets. See Also -------- pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.jaccard(gr2, chromsizes=chromsizes) 6.657941988519211e-05
jaccard
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def relative_distance(self, other, **kwargs): """Compute spatial correllation between two sets. Metric which describes relative distance between each interval in one set and two closest intervals in another. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- pandas.DataFrame DataFrame containing the frequency of each relative distance. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.relative_distance(gr2) reldist count total fraction 0 0.00 264 9956 0.026517 1 0.01 226 9956 0.022700 2 0.02 206 9956 0.020691 3 0.03 235 9956 0.023604 4 0.04 194 9956 0.019486 5 0.05 241 9956 0.024207 6 0.06 201 9956 0.020189 7 0.07 191 9956 0.019184 8 0.08 192 9956 0.019285 9 0.09 191 9956 0.019184 10 0.10 186 9956 0.018682 11 0.11 203 9956 0.020390 12 0.12 218 9956 0.021896 13 0.13 209 9956 0.020992 14 0.14 201 9956 0.020189 15 0.15 178 9956 0.017879 16 0.16 202 9956 0.020289 17 0.17 197 9956 0.019787 18 0.18 208 9956 0.020892 19 0.19 202 9956 0.020289 20 0.20 191 9956 0.019184 21 0.21 188 9956 0.018883 22 0.22 213 9956 0.021394 23 0.23 192 9956 0.019285 24 0.24 199 9956 0.019988 25 0.25 181 9956 0.018180 26 0.26 172 9956 0.017276 27 0.27 191 9956 0.019184 28 0.28 190 9956 0.019084 29 0.29 192 9956 0.019285 30 0.30 201 9956 0.020189 31 0.31 212 9956 0.021294 32 0.32 213 9956 0.021394 33 0.33 177 9956 0.017778 34 0.34 197 9956 0.019787 35 0.35 163 9956 0.016372 36 0.36 191 9956 0.019184 37 0.37 198 9956 0.019888 38 0.38 160 9956 0.016071 39 0.39 188 9956 0.018883 40 0.40 200 9956 0.020088 41 0.41 188 9956 0.018883 42 0.42 230 9956 0.023102 43 0.43 197 9956 0.019787 44 0.44 224 9956 0.022499 45 0.45 184 9956 0.018481 46 0.46 198 9956 0.019888 47 0.47 187 9956 0.018783 48 0.48 200 9956 0.020088 49 0.49 194 9956 0.019486 """ self = self.pr kwargs["sparse"] = {"self": True, "other": True} kwargs = pr.pyranges_main.fill_kwargs(kwargs) result = pyrange_apply(_relative_distance, self, other, **kwargs) # pylint: disable=E1132 result = pd.Series(np.concatenate(list(result.values()))) not_nan = ~np.isnan(result) result.loc[not_nan] = np.floor(result[not_nan] * 100) / 100 vc = result.value_counts(dropna=False).to_frame().reset_index() vc.columns = "reldist count".split() vc.insert(vc.shape[1], "total", len(result)) vc.insert(vc.shape[1], "fraction", vc["count"] / len(result)) vc = vc.sort_values("reldist", ascending=True) vc = vc.reset_index(drop=True) return vc
Compute spatial correllation between two sets. Metric which describes relative distance between each interval in one set and two closest intervals in another. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- pandas.DataFrame DataFrame containing the frequency of each relative distance. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.relative_distance(gr2) reldist count total fraction 0 0.00 264 9956 0.026517 1 0.01 226 9956 0.022700 2 0.02 206 9956 0.020691 3 0.03 235 9956 0.023604 4 0.04 194 9956 0.019486 5 0.05 241 9956 0.024207 6 0.06 201 9956 0.020189 7 0.07 191 9956 0.019184 8 0.08 192 9956 0.019285 9 0.09 191 9956 0.019184 10 0.10 186 9956 0.018682 11 0.11 203 9956 0.020390 12 0.12 218 9956 0.021896 13 0.13 209 9956 0.020992 14 0.14 201 9956 0.020189 15 0.15 178 9956 0.017879 16 0.16 202 9956 0.020289 17 0.17 197 9956 0.019787 18 0.18 208 9956 0.020892 19 0.19 202 9956 0.020289 20 0.20 191 9956 0.019184 21 0.21 188 9956 0.018883 22 0.22 213 9956 0.021394 23 0.23 192 9956 0.019285 24 0.24 199 9956 0.019988 25 0.25 181 9956 0.018180 26 0.26 172 9956 0.017276 27 0.27 191 9956 0.019184 28 0.28 190 9956 0.019084 29 0.29 192 9956 0.019285 30 0.30 201 9956 0.020189 31 0.31 212 9956 0.021294 32 0.32 213 9956 0.021394 33 0.33 177 9956 0.017778 34 0.34 197 9956 0.019787 35 0.35 163 9956 0.016372 36 0.36 191 9956 0.019184 37 0.37 198 9956 0.019888 38 0.38 160 9956 0.016071 39 0.39 188 9956 0.018883 40 0.40 200 9956 0.020088 41 0.41 188 9956 0.018883 42 0.42 230 9956 0.023102 43 0.43 197 9956 0.019787 44 0.44 224 9956 0.022499 45 0.45 184 9956 0.018481 46 0.46 198 9956 0.019888 47 0.47 187 9956 0.018783 48 0.48 200 9956 0.020088 49 0.49 194 9956 0.019486
relative_distance
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def from_string(s, int64=False): """Create a PyRanges from multiline string. Parameters ---------- s : str String with data. int64 : bool, default False. Whether to use 64-bit integers for starts and ends. See Also -------- pyranges.from_dict : create a PyRanges from a dictionary. Examples -------- >>> s = '''Chromosome Start End Strand ... chr1 246719402 246719502 + ... chr5 15400908 15401008 + ... chr9 68366534 68366634 + ... chr14 79220091 79220191 + ... chr14 103456471 103456571 -''' >>> pr.from_string(s) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 246719402 | 246719502 | + | | chr5 | 15400908 | 15401008 | + | | chr9 | 68366534 | 68366634 | + | | chr14 | 79220091 | 79220191 | + | | chr14 | 103456471 | 103456571 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 5 rows and 4 columns from 4 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from io import StringIO df = pd.read_csv(StringIO(s), sep=r"\s+", index_col=None) return PyRanges(df, int64=int64)
Create a PyRanges from multiline string. Parameters ---------- s : str String with data. int64 : bool, default False. Whether to use 64-bit integers for starts and ends. See Also -------- pyranges.from_dict : create a PyRanges from a dictionary. Examples -------- >>> s = '''Chromosome Start End Strand ... chr1 246719402 246719502 + ... chr5 15400908 15401008 + ... chr9 68366534 68366634 + ... chr14 79220091 79220191 + ... chr14 103456471 103456571 -''' >>> pr.from_string(s) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 246719402 | 246719502 | + | | chr5 | 15400908 | 15401008 | + | | chr9 | 68366534 | 68366634 | + | | chr14 | 79220091 | 79220191 | + | | chr14 | 103456471 | 103456571 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 5 rows and 4 columns from 4 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
from_string
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def itergrs(prs, strand=None, keys=False): r"""Iterate over multiple PyRanges at once. Parameters ---------- prs : list of PyRanges PyRanges to iterate over. strand : bool, default None, i.e. auto Whether to iterate over strands. If True, all PyRanges must be stranded. keys : bool, default False Return tuple with key and value from iterator. Examples -------- >>> d1 = {"Chromosome": [1, 1, 2], "Start": [1, 2, 3], "End": [4, 9, 12], "Strand": ["+", "+", "-"]} >>> d2 = {"Chromosome": [2, 3, 3], "Start": [5, 9, 21], "End": [81, 42, 25], "Strand": ["-", "+", "-"]} >>> gr1, gr2 = pr.from_dict(d1), pr.from_dict(d2) >>> gr1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 1 | 1 | 4 | + | | 1 | 2 | 9 | + | | 2 | 3 | 12 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 2 | 5 | 81 | - | | 3 | 9 | 42 | + | | 3 | 21 | 25 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> ranges = [gr1, gr2] >>> for key, dfs in pr.itergrs(ranges, keys=True): ... print("-----------\n" + str(key) + "\n-----------") ... for df in dfs: ... print(df) ----------- ('1', '+') ----------- Chromosome Start End Strand 0 1 1 4 + 1 1 2 9 + Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] ----------- ('2', '-') ----------- Chromosome Start End Strand 2 2 3 12 - Chromosome Start End Strand 0 2 5 81 - ----------- ('3', '+') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 1 3 9 42 + ----------- ('3', '-') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 2 3 21 25 - """ if strand is None: strand = all([gr.stranded for gr in prs]) if strand is False and any([gr.stranded for gr in prs]): prs = [gr.unstrand() for gr in prs] grs_per_chromosome = defaultdict(list) set_keys = set() for gr in prs: set_keys.update(gr.dfs.keys()) empty_dfs = [pd.DataFrame(columns=gr.columns) for gr in prs] for gr, empty in zip(prs, empty_dfs): for k in set_keys: df = gr.dfs.get(k, empty) grs_per_chromosome[k].append(df) if not keys: return iter(grs_per_chromosome.values()) else: return iter(natsorted(grs_per_chromosome.items()))
Iterate over multiple PyRanges at once. Parameters ---------- prs : list of PyRanges PyRanges to iterate over. strand : bool, default None, i.e. auto Whether to iterate over strands. If True, all PyRanges must be stranded. keys : bool, default False Return tuple with key and value from iterator. Examples -------- >>> d1 = {"Chromosome": [1, 1, 2], "Start": [1, 2, 3], "End": [4, 9, 12], "Strand": ["+", "+", "-"]} >>> d2 = {"Chromosome": [2, 3, 3], "Start": [5, 9, 21], "End": [81, 42, 25], "Strand": ["-", "+", "-"]} >>> gr1, gr2 = pr.from_dict(d1), pr.from_dict(d2) >>> gr1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 1 | 1 | 4 | + | | 1 | 2 | 9 | + | | 2 | 3 | 12 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 2 | 5 | 81 | - | | 3 | 9 | 42 | + | | 3 | 21 | 25 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> ranges = [gr1, gr2] >>> for key, dfs in pr.itergrs(ranges, keys=True): ... print("-----------\n" + str(key) + "\n-----------") ... for df in dfs: ... print(df) ----------- ('1', '+') ----------- Chromosome Start End Strand 0 1 1 4 + 1 1 2 9 + Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] ----------- ('2', '-') ----------- Chromosome Start End Strand 2 2 3 12 - Chromosome Start End Strand 0 2 5 81 - ----------- ('3', '+') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 1 3 9 42 + ----------- ('3', '-') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 2 3 21 25 -
itergrs
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def random(n=1000, length=100, chromsizes=None, strand=True, int64=False, seed=None): """Return PyRanges with random intervals. Parameters ---------- n : int, default 1000 Number of intervals. length : int, default 100 Length of intervals. chromsizes : dict or DataFrame, default None, i.e. use "hg19" Draw intervals from within these bounds. strand : bool, default True Data should have strand. int64 : bool, default False Use int64 to represent Start and End. Examples -------- # >>> pr.random() # +--------------+-----------+-----------+--------------+ # | Chromosome | Start | End | Strand | # | (category) | (int64) | (int64) | (category) | # |--------------+-----------+-----------+--------------| # | chr1 | 216128004 | 216128104 | + | # | chr1 | 114387955 | 114388055 | + | # | chr1 | 67597551 | 67597651 | + | # | chr1 | 26306616 | 26306716 | + | # | ... | ... | ... | ... | # | chrY | 20811459 | 20811559 | - | # | chrY | 12221362 | 12221462 | - | # | chrY | 8578041 | 8578141 | - | # | chrY | 43259695 | 43259795 | - | # +--------------+-----------+-----------+--------------+ # Stranded PyRanges object has 1,000 rows and 4 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. To have random interval lengths: # >>> gr = pr.random(length=1) # >>> gr.End += np.random.randint(int(1e5), size=len(gr)) # >>> gr.Length = gr.lengths() # >>> gr # +--------------+-----------+-----------+--------------+-----------+ # | Chromosome | Start | End | Strand | Length | # | (category) | (int64) | (int64) | (category) | (int64) | # |--------------+-----------+-----------+--------------+-----------| # | chr1 | 203654331 | 203695380 | + | 41049 | # | chr1 | 46918271 | 46978908 | + | 60637 | # | chr1 | 97355021 | 97391587 | + | 36566 | # | chr1 | 57284999 | 57323542 | + | 38543 | # | ... | ... | ... | ... | ... | # | chrY | 31665821 | 31692660 | - | 26839 | # | chrY | 20236607 | 20253473 | - | 16866 | # | chrY | 33255377 | 33315933 | - | 60556 | # | chrY | 31182964 | 31205467 | - | 22503 | # +--------------+-----------+-----------+--------------+-----------+ # Stranded PyRanges object has 1,000 rows and 5 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. """ if chromsizes is None: chromsizes = data.chromsizes() df = chromsizes.df elif isinstance(chromsizes, dict): df = pd.DataFrame({"Chromosome": list(chromsizes.keys()), "End": list(chromsizes.values())}) else: df = chromsizes.df p = df.End / df.End.sum() n_per_chrom = pd.Series(np.random.choice(df.index, size=n, p=p)).value_counts(sort=False).to_frame() n_per_chrom.insert(1, "Chromosome", df.loc[n_per_chrom.index].Chromosome) n_per_chrom.columns = "Count Chromosome".split() random_dfs = [] for _, (count, chrom) in n_per_chrom.iterrows(): r = np.random.randint(0, df[df.Chromosome == chrom].End - length, size=count) _df = pd.DataFrame({"Chromosome": chrom, "Start": r, "End": r + length}) random_dfs.append(_df) random_df = pd.concat(random_dfs) if strand: s = np.random.choice("+ -".split(), size=n) random_df.insert(3, "Strand", s) return PyRanges(random_df, int64=int64)
Return PyRanges with random intervals. Parameters ---------- n : int, default 1000 Number of intervals. length : int, default 100 Length of intervals. chromsizes : dict or DataFrame, default None, i.e. use "hg19" Draw intervals from within these bounds. strand : bool, default True Data should have strand. int64 : bool, default False Use int64 to represent Start and End. Examples -------- # >>> pr.random() # +--------------+-----------+-----------+--------------+ # | Chromosome | Start | End | Strand | # | (category) | (int64) | (int64) | (category) | # |--------------+-----------+-----------+--------------| # | chr1 | 216128004 | 216128104 | + | # | chr1 | 114387955 | 114388055 | + | # | chr1 | 67597551 | 67597651 | + | # | chr1 | 26306616 | 26306716 | + | # | ... | ... | ... | ... | # | chrY | 20811459 | 20811559 | - | # | chrY | 12221362 | 12221462 | - | # | chrY | 8578041 | 8578141 | - | # | chrY | 43259695 | 43259795 | - | # +--------------+-----------+-----------+--------------+ # Stranded PyRanges object has 1,000 rows and 4 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. To have random interval lengths: # >>> gr = pr.random(length=1) # >>> gr.End += np.random.randint(int(1e5), size=len(gr)) # >>> gr.Length = gr.lengths() # >>> gr # +--------------+-----------+-----------+--------------+-----------+ # | Chromosome | Start | End | Strand | Length | # | (category) | (int64) | (int64) | (category) | (int64) | # |--------------+-----------+-----------+--------------+-----------| # | chr1 | 203654331 | 203695380 | + | 41049 | # | chr1 | 46918271 | 46978908 | + | 60637 | # | chr1 | 97355021 | 97391587 | + | 36566 | # | chr1 | 57284999 | 57323542 | + | 38543 | # | ... | ... | ... | ... | ... | # | chrY | 31665821 | 31692660 | - | 26839 | # | chrY | 20236607 | 20253473 | - | 16866 | # | chrY | 33255377 | 33315933 | - | 60556 | # | chrY | 31182964 | 31205467 | - | 22503 | # +--------------+-----------+-----------+--------------+-----------+ # Stranded PyRanges object has 1,000 rows and 5 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand.
random
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def to_bigwig(gr, path, chromosome_sizes): """Write df to bigwig. Must contain the columns Chromosome, Start, End and Score. All others are ignored. Parameters ---------- path : str Where to write bigwig. chromosome_sizes : PyRanges or dict If dict: map of chromosome names to chromosome length. Examples -------- Extended example with how to prepare your data for writing bigwigs: >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [1, 4, 6], ... 'End': [7, 8, 10], 'Strand': ['+', '-', '-'], ... 'Value': [10, 20, 30]} >>> import pyranges as pr >>> gr = pr.from_dict(d) >>> hg19 = pr.data.chromsizes() >>> print(hg19) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. Overlapping intervals are invalid in bigwigs: >>> to_bigwig(gr, "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Can only write one strand at a time. Use an unstranded PyRanges or subset on strand first. >>> to_bigwig(gr["-"], "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Intervals must not overlap. >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Value | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 7 | + | 10 | | chr1 | 4 | 8 | - | 20 | | chr1 | 6 | 10 | - | 30 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> value = gr.to_rle(rpm=False, value_col="Value") >>> value chr1 + -- +--------+-----+------+ | Runs | 1 | 6 | |--------+-----+------| | Values | 0.0 | 10.0 | +--------+-----+------+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+------+------+------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+------+------+------| | Values | 0.0 | 20.0 | 50.0 | 30.0 | +--------+-----+------+------+------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> raw = gr.to_rle(rpm=False) >>> raw chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | 0.0 | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+-----+-----+-----+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+-----+-----+-----| | Values | 0.0 | 1.0 | 2.0 | 1.0 | +--------+-----+-----+-----+-----+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> result = (value / raw).apply_values(np.log10) >>> result chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | nan | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+--------------------+--------------------+--------------------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+--------------------+--------------------+--------------------| | Values | nan | 1.3010300397872925 | 1.3979400396347046 | 1.4771212339401245 | +--------+-----+--------------------+--------------------+--------------------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> out = result.numbers_only().to_ranges() >>> out +--------------+-----------+-----------+-------------+--------------+ | Chromosome | Start | End | Score | Strand | | (category) | (int64) | (int64) | (float64) | (category) | |--------------+-----------+-----------+-------------+--------------| | chr1 | 1 | 7 | 1 | + | | chr1 | 4 | 6 | 1.30103 | - | | chr1 | 6 | 8 | 1.39794 | - | | chr1 | 8 | 10 | 1.47712 | - | +--------------+-----------+-----------+-------------+--------------+ Stranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> to_bigwig(out["-"], "deleteme_reverse.bw", hg19) >>> to_bigwig(out["+"], "deleteme_forward.bw", hg19) """ try: import pyBigWig # type: ignore except ModuleNotFoundError: print( "pybigwig must be installed to create bigwigs. Use `conda install -c bioconda pybigwig` or `pip install pybigwig` to install it." ) import sys sys.exit(1) assert ( len(gr.strands) <= 1 ), "Can only write one strand at a time. Use an unstranded PyRanges or subset on strand first." assert np.sum(gr.lengths()) == gr.merge().length, "Intervals must not overlap." df = gr.df unique_chromosomes = list(df.Chromosome.drop_duplicates()) if not isinstance(chromosome_sizes, dict): size_df = chromosome_sizes.df chromosome_sizes = {k: v for k, v in zip(size_df.Chromosome, size_df.End)} header = [(c, int(chromosome_sizes[c])) for c in unique_chromosomes] bw = pyBigWig.open(path, "w") bw.addHeader(header) chromosomes = df.Chromosome.tolist() starts = df.Start.tolist() ends = df.End.tolist() values = df.Score.tolist() bw.addEntries(chromosomes, starts, ends=ends, values=values)
Write df to bigwig. Must contain the columns Chromosome, Start, End and Score. All others are ignored. Parameters ---------- path : str Where to write bigwig. chromosome_sizes : PyRanges or dict If dict: map of chromosome names to chromosome length. Examples -------- Extended example with how to prepare your data for writing bigwigs: >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [1, 4, 6], ... 'End': [7, 8, 10], 'Strand': ['+', '-', '-'], ... 'Value': [10, 20, 30]} >>> import pyranges as pr >>> gr = pr.from_dict(d) >>> hg19 = pr.data.chromsizes() >>> print(hg19) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. Overlapping intervals are invalid in bigwigs: >>> to_bigwig(gr, "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Can only write one strand at a time. Use an unstranded PyRanges or subset on strand first. >>> to_bigwig(gr["-"], "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Intervals must not overlap. >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Value | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 7 | + | 10 | | chr1 | 4 | 8 | - | 20 | | chr1 | 6 | 10 | - | 30 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> value = gr.to_rle(rpm=False, value_col="Value") >>> value chr1 + -- +--------+-----+------+ | Runs | 1 | 6 | |--------+-----+------| | Values | 0.0 | 10.0 | +--------+-----+------+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+------+------+------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+------+------+------| | Values | 0.0 | 20.0 | 50.0 | 30.0 | +--------+-----+------+------+------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> raw = gr.to_rle(rpm=False) >>> raw chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | 0.0 | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+-----+-----+-----+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+-----+-----+-----| | Values | 0.0 | 1.0 | 2.0 | 1.0 | +--------+-----+-----+-----+-----+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> result = (value / raw).apply_values(np.log10) >>> result chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | nan | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+--------------------+--------------------+--------------------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+--------------------+--------------------+--------------------| | Values | nan | 1.3010300397872925 | 1.3979400396347046 | 1.4771212339401245 | +--------+-----+--------------------+--------------------+--------------------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> out = result.numbers_only().to_ranges() >>> out +--------------+-----------+-----------+-------------+--------------+ | Chromosome | Start | End | Score | Strand | | (category) | (int64) | (int64) | (float64) | (category) | |--------------+-----------+-----------+-------------+--------------| | chr1 | 1 | 7 | 1 | + | | chr1 | 4 | 6 | 1.30103 | - | | chr1 | 6 | 8 | 1.39794 | - | | chr1 | 8 | 10 | 1.47712 | - | +--------------+-----------+-----------+-------------+--------------+ Stranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> to_bigwig(out["-"], "deleteme_reverse.bw", hg19) >>> to_bigwig(out["+"], "deleteme_forward.bw", hg19)
to_bigwig
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def _handle_eval_return(self, result, col, as_pyranges, subset): """Handle return from eval. If col is set, add/update cols. If subset is True, use return series to subset PyRanges. Otherwise return PyRanges or dict of data.""" if as_pyranges: if not result: return pr.PyRanges() first_hit = list(result.values())[0] if isinstance(first_hit, pd.Series): if first_hit.dtype == bool and subset: return self[result] elif col: self.__setattr__(col, result) return self else: raise Exception("Cannot return PyRanges when function returns a Series! Use as_pyranges=False.") return pr.PyRanges(result) else: return result
Handle return from eval. If col is set, add/update cols. If subset is True, use return series to subset PyRanges. Otherwise return PyRanges or dict of data.
_handle_eval_return
python
pyranges/pyranges
pyranges/methods/call.py
https://github.com/pyranges/pyranges/blob/master/pyranges/methods/call.py
MIT
def sort_one_by_one(d, col1, col2): """ Equivalent to pd.sort_values(by=[col1, col2]), but faster. """ d = d.sort_values(by=[col2]) return d.sort_values(by=[col1], kind="mergesort")
Equivalent to pd.sort_values(by=[col1, col2]), but faster.
sort_one_by_one
python
pyranges/pyranges
pyranges/methods/sort.py
https://github.com/pyranges/pyranges/blob/master/pyranges/methods/sort.py
MIT
def _introns_correct(full, genes, exons, introns, by): """Testing that introns: 1: ends larger than starts 2: the intersection of the computed introns and exons per gene are 0 3: that the number of introns overlapping each gene is the same as number of introns per gene 4 & 5: that the intron positions are the same as the ones computed with the slow, but correct algo """ id_column = by_to_id[by] if len(introns): assert (introns.Start < introns.End).all(), str(introns[(introns.Start >= introns.End)]) expected_results = {} based_on = {} for gene_id, gdf in full.groupby(id_column): # #[full.gene_id.isin(["ENSG00000078808.16"])] # print("gdf " * 10) # print(gdf) if not len(gdf[gdf.Feature == "gene"]) or not len(gdf[gdf.Feature == "transcript"]): continue expected_results[gene_id] = compute_introns_single(gdf, by) based_on[gene_id] = pr.PyRanges(gdf[gdf.Feature.isin([by, "exon"])]).df if not len(introns): for v in expected_results.values(): assert v.empty return # test passed for gene_id, idf in introns.groupby(id_column): idf = idf.sort_values("Start End".split()) if gene_id not in expected_results: continue expected = expected_results[gene_id] exons = pr.PyRanges(based_on[gene_id]).subset(lambda df: df.Feature == "exon").merge(by=id_column) genes = pr.PyRanges(based_on[gene_id]).subset(lambda df: df.Feature == by) print("exons", exons) print("based_on", based_on[gene_id]) print("actual", idf["Chromosome Start End Strand".split()]) print("expected", expected["Chromosome Start End Strand".split()]) _introns = pr.PyRanges(idf) assert len(exons.intersect(_introns)) == 0 assert len(genes.intersect(_introns)) == len(_introns) assert list(idf.Start) == list(expected.Start), "not equal" assert list(idf.End) == list(expected.End), "not equal"
Testing that introns: 1: ends larger than starts 2: the intersection of the computed introns and exons per gene are 0 3: that the number of introns overlapping each gene is the same as number of introns per gene 4 & 5: that the intron positions are the same as the ones computed with the slow, but correct algo
_introns_correct
python
pyranges/pyranges
tests/unit/test_genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/tests/unit/test_genomicfeatures.py
MIT
def test_introns_single(): "Assert that our fast method of computing introns is the same as the slow, correct one in compute_introns_single" gr = pr.data.gencode_gtf()[["gene_id", "Feature"]] exons = gr[gr.Feature == "exon"].merge(by="gene_id") exons.Feature = "exon" exons = exons.df df = pd.concat([gr[gr.Feature == "gene"].df, exons], sort=False) print(df) for gid, gdf in df.groupby("gene_id"): print("-------" * 20) print(gid) print(gdf) print("gdf", len(gdf)) expected = compute_introns_single(gdf, by="gene") print("expected", len(expected)) actual = pr.PyRanges(gdf).features.introns().df print("actual", len(actual)) if actual.empty: assert expected.empty continue assert list(expected.Start) == list(actual.Start) assert list(expected.End) == list(actual.End)
Assert that our fast method of computing introns is the same as the slow, correct one in compute_introns_single
test_introns_single
python
pyranges/pyranges
tests/unit/test_genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/tests/unit/test_genomicfeatures.py
MIT
def makecube(): """ Generate vertices & indices for a filled cube """ vtype = [('a_position', np.float32, 3), ('a_texcoord', np.float32, 2)] itype = np.uint32 # Vertices positions p = np.array([[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]) # Texture coords t = np.array([[0, 0], [0, 1], [1, 1], [1, 0]]) faces_p = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_t = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] vertices = np.zeros(24, vtype) vertices['a_position'] = p[faces_p] vertices['a_texcoord'] = t[faces_t] indices = np.resize( np.array([0, 1, 2, 0, 2, 3], dtype=itype), 6 * (2 * 3)) indices += np.repeat(4 * np.arange(6), 6).astype(np.uint32) return vertices, indices
Generate vertices & indices for a filled cube
makecube
python
timctho/VNect-tensorflow
vispy_test.py
https://github.com/timctho/VNect-tensorflow/blob/master/vispy_test.py
Apache-2.0
def _create_base_cipher(dict_parameters): """This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.""" use_aesni = dict_parameters.pop("use_aesni", True) try: key = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") expect_byte_string(key) if len(key) not in key_size: raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) if use_aesni and _raw_aesni_lib: start_operation = _raw_aesni_lib.AESNI_start_operation stop_operation = _raw_aesni_lib.AESNI_stop_operation else: start_operation = _raw_aes_lib.AES_start_operation stop_operation = _raw_aes_lib.AES_stop_operation cipher = VoidPointer() result = start_operation(key, c_size_t(len(key)), cipher.address_of()) if result: raise ValueError("Error %X while instantiating the AES cipher" % result) return SmartPointer(cipher.get(), stop_operation)
This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.
_create_base_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/AES.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/AES.py
MIT
def new(key, mode, *args, **kwargs): """Create a new AES cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes long. Only in `MODE_SIV`, it needs to be 32, 48, or 64 bytes long. mode : a *MODE_** constant The chaining mode to use for encryption or decryption. If in doubt, use `MODE_EAX`. :Keywords: iv : byte string (*Only* `MODE_CBC`, `MODE_CFB`, `MODE_OFB`, `MODE_OPENPGP`). The initialization vector to use for encryption or decryption. For `MODE_OPENPGP`, it must be 16 bytes long for encryption and 18 bytes for decryption (in the latter case, it is actually the *encrypted* IV which was prefixed to the ciphertext). For all other modes, it must be 16 bytes long. In not provided, a random byte string is used (you must then read its value with the ``iv`` attribute). nonce : byte string (*Only* `MODE_CCM`, `MODE_EAX`, `MODE_GCM`, `MODE_SIV`, `MODE_OCB`, `MODE_CTR`). A value that must never be reused for any other encryption done with this key. For `MODE_CCM`, its length must be in the range ``[7..13]``. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. For `MODE_OCB`, its length must be in the range ``[1..15]``. For `MODE_CTR`, its length must be in the range ``[0..15]``. For the other modes, there are no restrictions on its length. The recommended length depends on the mode: 8 bytes for `MODE_CTR`, 11 bytes for `MODE_CCM`, 15 bytes for `MODE_OCB` and 16 bytes for the remaining modes. In not provided, a random byte string of the recommended length is used (you must then read its value with the ``nonce`` attribute). segment_size : integer (*Only* `MODE_CFB`).The number of **bits** the plaintext and ciphertext are segmented in. It must be a multiple of 8. If not specified, it will be assumed to be 8. mac_len : integer (*Only* `MODE_EAX`, `MODE_GCM`, `MODE_OCB`, `MODE_CCM`) Length of the authentication tag, in bytes. It must be even and in the range ``[4..16]``. The recommended value (and the default, if not specified) is 16. msg_len : integer (*Only* `MODE_CCM`). Length of the message to (de)cipher. If not specified, ``encrypt`` must be called with the entire message. Similarly, ``decrypt`` can only be called once. assoc_len : integer (*Only* `MODE_CCM`). Length of the associated data. If not specified, all associated data is buffered internally, which may represent a problem for very large messages. initial_value : integer (*Only* `MODE_CTR`). The initial value for the counter within the counter block. By default it is 0. use_aesni : boolean Use Intel AES-NI hardware extensions if available. :Return: an AES object, of the applicable mode: - CBC_ mode - CCM_ mode - CFB_ mode - CTR_ mode - EAX_ mode - ECB_ mode - GCM_ mode - OCB_ mode - OFB_ mode - OpenPgp_ mode - SIV_ mode .. _CBC: Cryptodome.Cipher._mode_cbc.CbcMode-class.html .. _CCM: Cryptodome.Cipher._mode_ccm.CcmMode-class.html .. _CFB: Cryptodome.Cipher._mode_cfb.CfbMode-class.html .. _CTR: Cryptodome.Cipher._mode_ctr.CtrMode-class.html .. _EAX: Cryptodome.Cipher._mode_eax.EaxMode-class.html .. _ECB: Cryptodome.Cipher._mode_ecb.EcbMode-class.html .. _GCM: Cryptodome.Cipher._mode_gcm.GcmMode-class.html .. _OCB: Cryptodome.Cipher._mode_ocb.OcbMode-class.html .. _OFB: Cryptodome.Cipher._mode_ofb.OfbMode-class.html .. _OpenPgp: Cryptodome.Cipher._mode_openpgp.OpenPgpMode-class.html .. _SIV: Cryptodome.Cipher._mode_siv.SivMode-class.html """ kwargs["add_aes_modes"] = True return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
Create a new AES cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes long. Only in `MODE_SIV`, it needs to be 32, 48, or 64 bytes long. mode : a *MODE_** constant The chaining mode to use for encryption or decryption. If in doubt, use `MODE_EAX`. :Keywords: iv : byte string (*Only* `MODE_CBC`, `MODE_CFB`, `MODE_OFB`, `MODE_OPENPGP`). The initialization vector to use for encryption or decryption. For `MODE_OPENPGP`, it must be 16 bytes long for encryption and 18 bytes for decryption (in the latter case, it is actually the *encrypted* IV which was prefixed to the ciphertext). For all other modes, it must be 16 bytes long. In not provided, a random byte string is used (you must then read its value with the ``iv`` attribute). nonce : byte string (*Only* `MODE_CCM`, `MODE_EAX`, `MODE_GCM`, `MODE_SIV`, `MODE_OCB`, `MODE_CTR`). A value that must never be reused for any other encryption done with this key. For `MODE_CCM`, its length must be in the range ``[7..13]``. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. For `MODE_OCB`, its length must be in the range ``[1..15]``. For `MODE_CTR`, its length must be in the range ``[0..15]``. For the other modes, there are no restrictions on its length. The recommended length depends on the mode: 8 bytes for `MODE_CTR`, 11 bytes for `MODE_CCM`, 15 bytes for `MODE_OCB` and 16 bytes for the remaining modes. In not provided, a random byte string of the recommended length is used (you must then read its value with the ``nonce`` attribute). segment_size : integer (*Only* `MODE_CFB`).The number of **bits** the plaintext and ciphertext are segmented in. It must be a multiple of 8. If not specified, it will be assumed to be 8. mac_len : integer (*Only* `MODE_EAX`, `MODE_GCM`, `MODE_OCB`, `MODE_CCM`) Length of the authentication tag, in bytes. It must be even and in the range ``[4..16]``. The recommended value (and the default, if not specified) is 16. msg_len : integer (*Only* `MODE_CCM`). Length of the message to (de)cipher. If not specified, ``encrypt`` must be called with the entire message. Similarly, ``decrypt`` can only be called once. assoc_len : integer (*Only* `MODE_CCM`). Length of the associated data. If not specified, all associated data is buffered internally, which may represent a problem for very large messages. initial_value : integer (*Only* `MODE_CTR`). The initial value for the counter within the counter block. By default it is 0. use_aesni : boolean Use Intel AES-NI hardware extensions if available. :Return: an AES object, of the applicable mode: - CBC_ mode - CCM_ mode - CFB_ mode - CTR_ mode - EAX_ mode - ECB_ mode - GCM_ mode - OCB_ mode - OFB_ mode - OpenPgp_ mode - SIV_ mode .. _CBC: Cryptodome.Cipher._mode_cbc.CbcMode-class.html .. _CCM: Cryptodome.Cipher._mode_ccm.CcmMode-class.html .. _CFB: Cryptodome.Cipher._mode_cfb.CfbMode-class.html .. _CTR: Cryptodome.Cipher._mode_ctr.CtrMode-class.html .. _EAX: Cryptodome.Cipher._mode_eax.EaxMode-class.html .. _ECB: Cryptodome.Cipher._mode_ecb.EcbMode-class.html .. _GCM: Cryptodome.Cipher._mode_gcm.GcmMode-class.html .. _OCB: Cryptodome.Cipher._mode_ocb.OcbMode-class.html .. _OFB: Cryptodome.Cipher._mode_ofb.OfbMode-class.html .. _OpenPgp: Cryptodome.Cipher._mode_openpgp.OpenPgpMode-class.html .. _SIV: Cryptodome.Cipher._mode_siv.SivMode-class.html
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/AES.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/AES.py
MIT
def _create_base_cipher(dict_parameters): """This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.""" try: key = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") effective_keylen = dict_parameters.pop("effective_keylen", 1024) expect_byte_string(key) if len(key) not in key_size: raise ValueError("Incorrect ARC2 key length (%d bytes)" % len(key)) if not (40 < effective_keylen <= 1024): raise ValueError("'effective_key_len' must be no larger than 1024 " "(not %d)" % effective_keylen) start_operation = _raw_arc2_lib.ARC2_start_operation stop_operation = _raw_arc2_lib.ARC2_stop_operation cipher = VoidPointer() result = start_operation(key, c_size_t(len(key)), c_size_t(effective_keylen), cipher.address_of()) if result: raise ValueError("Error %X while instantiating the ARC2 cipher" % result) return SmartPointer(cipher.get(), stop_operation)
This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.
_create_base_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ARC2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ARC2.py
MIT
def __init__(self, key, *args, **kwargs): """Initialize an ARC4 cipher object See also `new()` at the module level.""" if len(args) > 0: ndrop = args[0] args = args[1:] else: ndrop = kwargs.pop('drop', 0) if len(key) not in key_size: raise ValueError("Incorrect ARC4 key length (%d bytes)" % len(key)) expect_byte_string(key) self._state = VoidPointer() result = _raw_arc4_lib.ARC4_stream_init(key, c_size_t(len(key)), self._state.address_of()) if result != 0: raise ValueError("Error %d while creating the ARC4 cipher" % result) self._state = SmartPointer(self._state.get(), _raw_arc4_lib.ARC4_stream_destroy) if ndrop > 0: # This is OK even if the cipher is used for decryption, # since encrypt and decrypt are actually the same thing # with ARC4. self.encrypt(b('\x00') * ndrop) self.block_size = 1 self.key_size = len(key)
Initialize an ARC4 cipher object See also `new()` at the module level.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
MIT