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 convert_github_url_to_raw(path_or_url: str) -> str:
"""Convert a GitHub URL to a raw URL if it's a GitHub URL, otherwise return the original path or URL."""
github_pattern = r"https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(?:blob|raw)/([^/]+)/(.+)"
github_match = re.match(github_pattern, path_or_url)
... | Convert a GitHub URL to a raw URL if it's a GitHub URL, otherwise return the original path or URL. | convert_github_url_to_raw | python | mckinsey/vizro | vizro-mcp/src/vizro_mcp/_utils/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py | Apache-2.0 |
def load_dataframe_by_format(
path_or_url: Union[str, Path], mime_type: Optional[str] = None
) -> tuple[pd.DataFrame, Literal["pd.read_csv", "pd.read_json", "pd.read_html", "pd.read_excel", "pd.read_parquet"]]:
"""Load a dataframe based on file format determined by MIME type or file extension."""
file_path_... | Load a dataframe based on file format determined by MIME type or file extension. | load_dataframe_by_format | python | mckinsey/vizro | vizro-mcp/src/vizro_mcp/_utils/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py | Apache-2.0 |
def path_or_url_check(string: str) -> str:
"""Check if a string is a link or a file path."""
if string.startswith(("http://", "https://", "www.")):
return "remote"
if Path(string).is_file():
return "local"
return "invalid" | Check if a string is a link or a file path. | path_or_url_check | python | mckinsey/vizro | vizro-mcp/src/vizro_mcp/_utils/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py | Apache-2.0 |
def create_pycafe_url(python_code: str) -> str:
"""Create a PyCafe URL for a given Python code."""
# Create JSON object for py.cafe
json_object = {
"code": python_code,
"requirements": "vizro==0.1.38",
"files": [],
}
# Convert to compressed base64 URL
json_text = json.du... | Create a PyCafe URL for a given Python code. | create_pycafe_url | python | mckinsey/vizro | vizro-mcp/src/vizro_mcp/_utils/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py | Apache-2.0 |
def get_python_code_and_preview_link(
model_object: vm.VizroBaseModel, data_infos: list[DFMetaData]
) -> VizroCodeAndPreviewLink:
"""Get the Python code and preview link for a Vizro model object."""
# Get the Python code
python_code = model_object._to_python()
# Add imports after the first empty li... | Get the Python code and preview link for a Vizro model object. | get_python_code_and_preview_link | python | mckinsey/vizro | vizro-mcp/src/vizro_mcp/_utils/utils.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/src/vizro_mcp/_utils/utils.py | Apache-2.0 |
def dashboard_config_validation_result() -> ValidationResults:
"""Fixture for a dashboard configuration validation result."""
return ValidationResults(
valid=True,
message="Configuration is valid for Dashboard!",
python_code="""############ Imports ##############
import vizro.models as v... | Fixture for a dashboard configuration validation result. | dashboard_config_validation_result | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def graph_dashboard_config() -> dict[str, Any]:
"""Fixture for a dashboard configuration with a scatter graph."""
return {
"title": "Graph Dashboard",
"pages": [
{
"id": "graph_page",
"title": "Scatter Graph Page",
"components": [
... | Fixture for a dashboard configuration with a scatter graph. | graph_dashboard_config | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def graph_dashboard_validation_result() -> ValidationResults:
"""Fixture for a dashboard configuration with graph validation result."""
return ValidationResults(
valid=True,
message="Configuration is valid for Dashboard!",
python_code="""############ Imports ##############
import vizro.p... | Fixture for a dashboard configuration with graph validation result. | graph_dashboard_validation_result | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def invalid_chart_plan() -> dict[str, Any]:
"""Fixture for an invalid chart plan."""
return {
"chart_type": "scatter",
"imports": ["import pandas as pd", "import plotly.express as px"],
"chart_code": """def scatter_chart(data_frame):
return px.scatter(data_frame, x="sepal_length"... | Fixture for an invalid chart plan. | invalid_chart_plan | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def chart_plan_validation_result() -> ValidationResults:
"""Fixture for a chart plan validation result."""
return ValidationResults(
valid=True,
message="Chart only dashboard created successfully!",
python_code="""@capture('graph')
def custom_chart(data_frame):
return px.scatter(... | Fixture for a chart plan validation result. | chart_plan_validation_result | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_successful_validation(
self, valid_dashboard_config: dict[str, Any], dashboard_config_validation_result: ValidationResults
) -> None:
"""Test successful validation of a dashboard configuration."""
result = validate_model_config(dashboard_config=valid_dashboard_config, data_infos=[],... | Test successful validation of a dashboard configuration. | test_successful_validation | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_graph_dashboard_validation(
self,
graph_dashboard_config: dict[str, Any],
graph_dashboard_validation_result: ValidationResults,
iris_metadata: DFMetaData,
) -> None:
"""Test validation of a dashboard with a scatter graph component."""
result = validate_model_... | Test validation of a dashboard with a scatter graph component. | test_graph_dashboard_validation | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_validation_error(self, valid_dashboard_config: dict[str, Any], iris_metadata: DFMetaData) -> None:
"""Test validation error for an invalid dashboard configuration."""
# Create an invalid config by removing a required field
invalid_config = valid_dashboard_config.copy()
invalid_c... | Test validation error for an invalid dashboard configuration. | test_validation_error | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_successful_validation(
self,
valid_chart_plan: dict[str, Any],
iris_metadata: DFMetaData,
chart_plan_validation_result: ValidationResults,
) -> None:
"""Test successful validation of chart code."""
result = validate_chart_code(chart_config=valid_chart_plan, d... | Test successful validation of chart code. | test_successful_validation | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_validation_error(
self,
invalid_chart_plan: dict[str, Any],
iris_metadata: DFMetaData,
) -> None:
"""Test validation error for an invalid chart plan."""
result = validate_chart_code(chart_config=invalid_chart_plan, data_info=iris_metadata, auto_open=False)
a... | Test validation error for an invalid chart plan. | test_validation_error | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_model_json_schema(self, model_name: str, model_class: type) -> None:
"""Test getting JSON schema for various models."""
schema = get_model_json_schema(model_name=model_name)
# Get the schema directly from the model class
expected_schema = model_class.model_json_schema()
... | Test getting JSON schema for various models. | test_model_json_schema | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def test_nonexistent_model(self) -> None:
"""Test getting schema for a nonexistent model."""
schema = get_model_json_schema("NonExistentModel")
assert isinstance(schema, dict)
assert "error" in schema
assert "not found" in schema["error"] | Test getting schema for a nonexistent model. | test_nonexistent_model | python | mckinsey/vizro | vizro-mcp/tests/unit/vizro_mcp/test_server.py | https://github.com/mckinsey/vizro/blob/master/vizro-mcp/tests/unit/vizro_mcp/test_server.py | Apache-2.0 |
def resnet50_backbone(lda_out_channels, in_chn, pretrained=False, **kwargs):
"""Constructs a ResNet-50 model_hyper.
Args:
pretrained (bool): If True, returns a model_hyper pre-trained on ImageNet
"""
model = ResNetBackbone(lda_out_channels, in_chn, Bottleneck, [3, 4, 6, 3], **kwargs)
if pre... | Constructs a ResNet-50 model_hyper.
Args:
pretrained (bool): If True, returns a model_hyper pre-trained on ImageNet
| resnet50_backbone | python | bytedance/LatentSync | eval/hyper_iqa.py | https://github.com/bytedance/LatentSync/blob/master/eval/hyper_iqa.py | Apache-2.0 |
def get_random_clip_from_video(self, idx: int) -> tuple:
'''
Sample a random clip starting index from the video.
Args:
idx: Index of the video.
'''
# Note that some videos may not contain enough frames, we skip those videos here.
while self._clips.clips[idx].... |
Sample a random clip starting index from the video.
Args:
idx: Index of the video.
| get_random_clip_from_video | python | bytedance/LatentSync | latentsync/trepa/utils/data_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/data_utils.py | Apache-2.0 |
def load_video_frames(self, dataroot: str) -> list:
'''
Loads all the video frames under the dataroot and returns a list of all the video frames.
Args:
dataroot: The root directory containing the video frames.
Returns:
A list of all the video frames.
''... |
Loads all the video frames under the dataroot and returns a list of all the video frames.
Args:
dataroot: The root directory containing the video frames.
Returns:
A list of all the video frames.
| load_video_frames | python | bytedance/LatentSync | latentsync/trepa/utils/data_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/data_utils.py | Apache-2.0 |
def getTensor(self, index: int) -> torch.Tensor:
'''
Returns a tensor of the video frames at the given index.
Args:
index: The index of the video frames to return.
Returns:
A BCTHW tensor in the range `[0, 1]` of the video frames at the given index.
'''... |
Returns a tensor of the video frames at the given index.
Args:
index: The index of the video frames to return.
Returns:
A BCTHW tensor in the range `[0, 1]` of the video frames at the given index.
| getTensor | python | bytedance/LatentSync | latentsync/trepa/utils/data_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/data_utils.py | Apache-2.0 |
def set_num_features(self, num_features: int):
'''
Set the number of features diminsions.
Args:
num_features: Number of features diminsions.
'''
if self.num_features is not None:
assert num_features == self.num_features
else:
self.num_... |
Set the number of features diminsions.
Args:
num_features: Number of features diminsions.
| set_num_features | python | bytedance/LatentSync | latentsync/trepa/utils/metric_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py | Apache-2.0 |
def append(self, x: np.ndarray):
'''
Add the newly computed features to the list. Update the mean and covariance.
Args:
x: New features to record.
'''
x = np.asarray(x, dtype=np.float32)
assert x.ndim == 2
if (self.max_items is not None) and (self.num... |
Add the newly computed features to the list. Update the mean and covariance.
Args:
x: New features to record.
| append | python | bytedance/LatentSync | latentsync/trepa/utils/metric_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py | Apache-2.0 |
def append_torch(self, x: torch.Tensor, rank: int, num_gpus: int):
'''
Add the newly computed PyTorch features to the list. Update the mean and covariance.
Args:
x: New features to record.
rank: Rank of the current GPU.
num_gpus: Total number of GPUs.
... |
Add the newly computed PyTorch features to the list. Update the mean and covariance.
Args:
x: New features to record.
rank: Rank of the current GPU.
num_gpus: Total number of GPUs.
| append_torch | python | bytedance/LatentSync | latentsync/trepa/utils/metric_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py | Apache-2.0 |
def get_all(self) -> np.ndarray:
'''
Get all the stored features as NumPy Array.
Returns:
Concatenation of the stored features.
'''
assert self.capture_all
return np.concatenate(self.all_features, axis=0) |
Get all the stored features as NumPy Array.
Returns:
Concatenation of the stored features.
| get_all | python | bytedance/LatentSync | latentsync/trepa/utils/metric_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py | Apache-2.0 |
def get_mean_cov(self) -> Tuple[np.ndarray, np.ndarray]:
'''
Get the mean and covariance of the stored features.
Returns:
Mean and covariance of the stored features.
'''
assert self.capture_mean_cov
mean = self.raw_mean / self.num_items
cov = self.raw... |
Get the mean and covariance of the stored features.
Returns:
Mean and covariance of the stored features.
| get_mean_cov | python | bytedance/LatentSync | latentsync/trepa/utils/metric_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py | Apache-2.0 |
def load(pkl_file: str) -> 'FeatureStats':
'''
Load the features and statistics from a pickle file.
Args:
pkl_file: Path to the pickle file.
'''
with open(pkl_file, 'rb') as f:
s = pickle.load(f)
obj = FeatureStats(capture_all=s['capture_all'], ma... |
Load the features and statistics from a pickle file.
Args:
pkl_file: Path to the pickle file.
| load | python | bytedance/LatentSync | latentsync/trepa/utils/metric_utils.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/trepa/utils/metric_utils.py | Apache-2.0 |
def num_frames(length, fsize, fshift):
"""Compute number of time frames of spectrogram"""
pad = fsize - fshift
if length % fshift == 0:
M = (length + pad * 2 - fsize) // fshift + 1
else:
M = (length + pad * 2 - fsize) // fshift + 2
return M | Compute number of time frames of spectrogram | num_frames | python | bytedance/LatentSync | latentsync/utils/audio.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/audio.py | Apache-2.0 |
def __getitem__(self, idx):
"""Get audio samples and video frame at `idx`.
Parameters
----------
idx : int or slice
The frame index, can be negative which means it will index backwards,
or slice of frame indices.
Returns
-------
(ndarray/... | Get audio samples and video frame at `idx`.
Parameters
----------
idx : int or slice
The frame index, can be negative which means it will index backwards,
or slice of frame indices.
Returns
-------
(ndarray/list of ndarray, ndarray)
F... | __getitem__ | python | bytedance/LatentSync | latentsync/utils/av_reader.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/av_reader.py | Apache-2.0 |
def get_batch(self, indices):
"""Get entire batch of audio samples and video frames.
Parameters
----------
indices : list of integers
A list of frame indices. If negative indices detected, the indices will be indexed from backward
Returns
-------
(lis... | Get entire batch of audio samples and video frames.
Parameters
----------
indices : list of integers
A list of frame indices. If negative indices detected, the indices will be indexed from backward
Returns
-------
(list of ndarray, ndarray)
First ... | get_batch | python | bytedance/LatentSync | latentsync/utils/av_reader.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/av_reader.py | Apache-2.0 |
def _validate_indices(self, indices):
"""Validate int64 integers and convert negative integers to positive by backward search"""
assert self.__video_reader is not None and self.__audio_reader is not None
indices = np.array(indices, dtype=np.int64)
# process negative indices
indic... | Validate int64 integers and convert negative integers to positive by backward search | _validate_indices | python | bytedance/LatentSync | latentsync/utils/av_reader.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/av_reader.py | Apache-2.0 |
def cuda_to_int(cuda_str: str) -> int:
"""
Convert the string with format "cuda:X" to integer X.
"""
if cuda_str == "cuda":
return 0
device = torch.device(cuda_str)
if device.type != "cuda":
raise ValueError(f"Device type must be 'cuda', got: {device.type}")
return device.ind... |
Convert the string with format "cuda:X" to integer X.
| cuda_to_int | python | bytedance/LatentSync | latentsync/utils/face_detector.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/utils/face_detector.py | Apache-2.0 |
def get_sliced_feature(self, feature_array, vid_idx, fps=25):
"""
Get sliced features based on a given index
:param feature_array:
:param start_idx: the start index of the feature
:param audio_feat_length:
:return:
"""
length = len(feature_array)
s... |
Get sliced features based on a given index
:param feature_array:
:param start_idx: the start index of the feature
:param audio_feat_length:
:return:
| get_sliced_feature | python | bytedance/LatentSync | latentsync/whisper/audio2feature.py | https://github.com/bytedance/LatentSync/blob/master/latentsync/whisper/audio2feature.py | Apache-2.0 |
def cpg():
"""
>>> # +--------------+-----------+-----------+-----------+
>>> # | Chromosome | Start | End | CpG |
>>> # | (category) | (int64) | (int64) | (int64) |
>>> # |--------------+-----------+-----------+-----------|
>>> # | chrX | 64181 | 64793 ... |
>>> # +--------------+-----------+-----------+-----------+
>>> # | Chromosome | Start | End | CpG |
>>> # | (category) | (int64) | (int64) | (int64) |
>>> # |--------------+-----------+-----------+-----------|
>>> # | chrX | 64181 | 64793 | 62 |
... | 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 |
... |
>>> # +--------------+-----------+-----------+------------+------------+-----------------+--------------+---------------+-------------------+
>>> # | Chromosome | Start | End | Feature | gene_id | transcript_id | Strand | exon_number | transcript_name |
>>> # | (category) | ... | 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 = p... | 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()[["Sou... | 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
--------
>... | 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()[["Sou... | 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 chro... | 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... | 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.
... | 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... | 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 gen... | 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
--------
... | 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... | 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 p... | 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 thi... | 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 : st... | 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 No... | 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", "o... | 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": Fal... | 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
--------
... | 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], "Star... | __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": [... | 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
... | __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 = ... | 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... | __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 retu... | 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.
... | __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 operati... | 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
chrom... | 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.
... | 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-b... | 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
... | 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... | 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 Py... | 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.
... | 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, d... | 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 chromo... | 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 metada... | 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 col... | 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.
Res... | 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... | 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 ... | 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... | 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
... | 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
+--------------+-----------+--... | 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
----------
... | 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 Fal... | 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 o... | 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... | 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 N... | 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 | 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 : ... | 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 ... | 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 ... | 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, ... | 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... | 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 A... | 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 la... | 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 ... | 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 la... | 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 i... | 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.
... | 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
W... | 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
-----... | 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
info... | 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 : PyRan... | 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", "diffe... | 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... | 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
---... | 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 in... | 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.
Retu... | 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... | 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"
Na... | 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 nea... | 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
... | 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... | 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... | 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.
stran... | 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 ... | 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 sav... | 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 ... | 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.
... | 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 ... | 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... | 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 PyR... | 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 PyR... | 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
... | 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 as... | 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 - st... | 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 t... | 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 ... | 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
Inc... | 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
... | 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
--------
... | 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': ['ch... | 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', 'c... | 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],
... | 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/str... | 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
... | 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
interval... | 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 ... | 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
informati... | 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 strand... | 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 ... | 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 aft... | 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 firs... | 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 :... | 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 ... | 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... | 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
--------
Py... | 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... | 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 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
... | 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... | 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.
c... | 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, subse... | 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 na... | 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.
... | 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... | 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': ['chr... | 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],
... | 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... | 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. ... | 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... | 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... | 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 ... | 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 qua... | 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 r... | 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... | 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,... | 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 e... | read_gtf_restricted | python | pyranges/pyranges | pyranges/readers.py | https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.