Search is not available for this dataset
text stringlengths 75 104k |
|---|
def gseaplot(rank_metric, term, hits_indices, nes, pval, fdr, RES,
pheno_pos='', pheno_neg='', figsize=(6,5.5),
cmap='seismic', ofname=None, **kwargs):
"""This is the main function for reproducing the gsea plot.
:param rank_metric: pd.Series for rankings, rank_metric.values.
:p... |
def dotplot(df, column='Adjusted P-value', title='', cutoff=0.05, top_term=10,
sizes=None, norm=None, legend=True, figsize=(6, 5.5),
cmap='RdBu_r', ofname=None, **kwargs):
"""Visualize enrichr results.
:param df: GSEApy DataFrame results.
:param column: which column of DataFrame t... |
def barplot(df, column='Adjusted P-value', title="", cutoff=0.05, top_term=10,
figsize=(6.5,6), color='salmon', ofname=None, **kwargs):
"""Visualize enrichr results.
:param df: GSEApy DataFrame results.
:param column: which column of DataFrame to show. Default: Adjusted P-value
:param title... |
def adjust_spines(ax, spines):
"""function for removing spines and ticks.
:param ax: axes object
:param spines: a list of spines names to keep. e.g [left, right, top, bottom]
if spines = []. remove all spines and ticks.
"""
for loc, spine in ax.spines.items():
if loc in... |
def main():
"""The Main function/pipeline for GSEApy."""
# Parse options...
argparser = prepare_argparser()
args = argparser.parse_args()
subcommand = args.subcommand_name
if subcommand == "replot":
# reproduce plots using GSEAPY
from .gsea import Replot
rep = Replot(in... |
def prepare_argparser():
"""Prepare argparser object. New options will be added in this function first."""
description = "%(prog)s -- Gene Set Enrichment Analysis in Python"
epilog = "For command line options of each command, type: %(prog)s COMMAND -h"
# top-level parser
argparser = ap.ArgumentPars... |
def add_output_option(parser):
"""output option"""
parser.add_argument("-o", "--outdir", dest="outdir", type=str, default='GSEApy_reports',
metavar='', action="store",
help="The GSEApy output directory. Default: the current working directory")
parser.add_argu... |
def add_output_group(parser, required=True):
"""output group"""
output_group = parser.add_mutually_exclusive_group(required=required)
output_group.add_argument("-o", "--ofile", dest="ofile", type=str, default='GSEApy_reports',
help="Output file name. Mutually exclusive with --... |
def add_gsea_parser(subparsers):
"""Add main function 'gsea' argument parsers."""
argparser_gsea = subparsers.add_parser("gsea", help="Main GSEApy Function: run GSEApy instead of GSEA.")
# group for input files
group_input = argparser_gsea.add_argument_group("Input files arguments")
group_input.ad... |
def add_prerank_parser(subparsers):
"""Add function 'prerank' argument parsers."""
argparser_prerank = subparsers.add_parser("prerank", help="Run GSEApy Prerank tool on preranked gene list.")
# group for input files
prerank_input = argparser_prerank.add_argument_group("Input files arguments")
prer... |
def add_plot_parser(subparsers):
"""Add function 'plot' argument parsers."""
argparser_replot = subparsers.add_parser("replot", help="Reproduce GSEA desktop output figures.")
group_replot = argparser_replot.add_argument_group("Input arguments")
group_replot.add_argument("-i", "--indir", action="store... |
def add_enrichr_parser(subparsers):
"""Add function 'enrichr' argument parsers."""
argparser_enrichr = subparsers.add_parser("enrichr", help="Using Enrichr API to perform GO analysis.")
# group for required options.
enrichr_opt = argparser_enrichr.add_argument_group("Input arguments")
enrichr_opt.... |
def add_biomart_parser(subparsers):
"""Add function 'biomart' argument parsers."""
argparser_biomart = subparsers.add_parser("biomart", help="Using BioMart API to convert gene ids.")
# group for required options.
biomart_opt = argparser_biomart.add_argument_group("Input arguments")
biomart_opt.add... |
def enrichment_score(gene_list, correl_vector, gene_set, weighted_score_type=1,
nperm=1000, rs=np.random.RandomState(), single=False, scale=False):
"""This is the most important function of GSEApy. It has the same algorithm with GSEA and ssGSEA.
:param gene_list: The ordered gene li... |
def enrichment_score_tensor(gene_mat, cor_mat, gene_sets, weighted_score_type, nperm=1000,
rs=np.random.RandomState(), single=False, scale=False):
"""Next generation algorithm of GSEA and ssGSEA.
:param gene_mat: the ordered gene list(vector) with or without gene indices ... |
def ranking_metric_tensor(exprs, method, permutation_num, pos, neg, classes,
ascending, rs=np.random.RandomState()):
"""Build shuffled ranking matrix when permutation_type eq to phenotype.
:param exprs: gene_expression DataFrame, gene_name indexed.
:param str method: calc... |
def ranking_metric(df, method, pos, neg, classes, ascending):
"""The main function to rank an expression table.
:param df: gene_expression DataFrame.
:param method: The method used to calculate a correlation or ranking. Default: 'log2_ratio_of_classes'.
Others methods are... |
def gsea_compute_tensor(data, gmt, n, weighted_score_type, permutation_type,
method, pheno_pos, pheno_neg, classes, ascending,
processes=1, seed=None, single=False, scale=False):
"""compute enrichment scores and enrichment nulls.
:param data: preprocessed expression datafr... |
def gsea_compute(data, gmt, n, weighted_score_type, permutation_type,
method, pheno_pos, pheno_neg, classes, ascending,
processes=1, seed=None, single=False, scale=False):
"""compute enrichment scores and enrichment nulls.
:param data: preprocessed expression dataframe or ... |
def gsea_pval(es, esnull):
"""Compute nominal p-value.
From article (PNAS):
estimate nominal p-value for S from esnull by using the positive
or negative portion of the distribution corresponding to the sign
of the observed ES(S).
"""
# to speed up, using numpy function to compute pval in p... |
def normalize(es, esnull):
"""normalize the ES(S,pi) and the observed ES(S), separately rescaling
the positive and negative scores by dividing the mean of the ES(S,pi).
return: NES, NESnull
"""
nEnrichmentScores =np.zeros(es.shape)
nEnrichmentNulls=np.zeros(esnull.shape)
esnu... |
def gsea_significance(enrichment_scores, enrichment_nulls):
"""Compute nominal pvals, normalized ES, and FDR q value.
For a given NES(S) = NES* >= 0. The FDR is the ratio of the percentage of all (S,pi) with
NES(S,pi) >= 0, whose NES(S,pi) >= NES*, divided by the percentage of
observed S wi... |
def log_init(outlog, log_level=logging.INFO):
"""logging start"""
# clear old root logger handlers
logging.getLogger("gseapy").handlers = []
# init a root logger
logging.basicConfig(level = logging.DEBUG,
format = 'LINE %(lineno)-4d: %(asctime)s [%(levelname)-8s] %(mess... |
def log_stop(logger):
"""log stop"""
handlers = logger.handlers[:]
for handler in handlers:
handler.close()
logger.removeHandler(handler) |
def retry(num=5):
""""retry connection.
define max tries num
if the backoff_factor is 0.1, then sleep() will sleep for
[0.1s, 0.2s, 0.4s, ...] between retries.
It will also force a retry if the status code returned is 500, 502, 503 or 504.
"""
s = requests.Sessi... |
def gsea_cls_parser(cls):
"""Extract class(phenotype) name from .cls file.
:param cls: the a class list instance or .cls file which is identical to GSEA input .
:return: phenotype name and a list of class vector.
"""
if isinstance(cls, list) :
classes = cls
sample_name= unique(clas... |
def gsea_edb_parser(results_path, index=0):
"""Parse results.edb file stored under **edb** file folder.
:param results_path: the .results file located inside edb folder.
:param index: gene_set index of gmt database, used for iterating items.
:return: enrichment_term, hit_index,nes, pval, fdr.
"""
... |
def gsea_gmt_parser(gmt, min_size = 3, max_size = 1000, gene_list=None):
"""Parse gene_sets.gmt(gene set database) file or download from enrichr server.
:param gmt: the gene_sets.gmt file of GSEA input or an enrichr library name.
checkout full enrichr library name here: http://amp.pharm.mssm.ed... |
def get_library_name(database='Human'):
"""return enrichr active enrichr library name.
:param str database: Select one from { 'Human', 'Mouse', 'Yeast', 'Fly', 'Fish', 'Worm' }
"""
# make a get request to get the gmt names and meta data from Enrichr
# old code
# response = requests.get(... |
def get_marts(self):
"""Get available marts and their names."""
mart_names = pd.Series(self.names, name="Name")
mart_descriptions = pd.Series(self.displayNames, name="Description")
return pd.concat([mart_names, mart_descriptions], axis=1) |
def get_datasets(self, mart='ENSEMBL_MART_ENSEMBL'):
"""Get available datasets from mart you've selected"""
datasets = self.datasets(mart, raw=True)
return pd.read_csv(StringIO(datasets), header=None, usecols=[1, 2],
names = ["Name", "Description"],sep="\t") |
def get_attributes(self, dataset):
"""Get available attritbutes from dataset you've selected"""
attributes = self.attributes(dataset)
attr_ = [ (k, v[0]) for k, v in attributes.items()]
return pd.DataFrame(attr_, columns=["Attribute","Description"]) |
def get_filters(self, dataset):
"""Get available filters from dataset you've selected"""
filters = self.filters(dataset)
filt_ = [ (k, v[0]) for k, v in filters.items()]
return pd.DataFrame(filt_, columns=["Filter", "Description"]) |
def query(self, dataset='hsapiens_gene_ensembl', attributes=[],
filters={}, filename=None):
"""mapping ids using BioMart.
:param dataset: str, default: 'hsapiens_gene_ensembl'
:param attributes: str, list, tuple
:param filters: dict, {'filter name': list(filter value)}
... |
def gsea(data, gene_sets, cls, outdir='GSEA_', min_size=15, max_size=500, permutation_num=1000,
weighted_score_type=1,permutation_type='gene_set', method='log2_ratio_of_classes',
ascending=False, processes=1, figsize=(6.5,6), format='pdf',
graph_num=20, no_plot=False, seed=None, verbose=False... |
def ssgsea(data, gene_sets, outdir="ssGSEA_", sample_norm_method='rank', min_size=15, max_size=2000,
permutation_num=0, weighted_score_type=0.25, scale=True, ascending=False, processes=1,
figsize=(7,6), format='pdf', graph_num=20, no_plot=False, seed=None, verbose=False):
"""Run Gene Set Enric... |
def prerank(rnk, gene_sets, outdir='GSEA_Prerank', pheno_pos='Pos', pheno_neg='Neg',
min_size=15, max_size=500, permutation_num=1000, weighted_score_type=1,
ascending=False, processes=1, figsize=(6.5,6), format='pdf',
graph_num=20, no_plot=False, seed=None, verbose=False):
""" Ru... |
def replot(indir, outdir='GSEA_Replot', weighted_score_type=1,
min_size=3, max_size=1000, figsize=(6.5,6), graph_num=20, format='pdf', verbose=False):
"""The main function to reproduce GSEA desktop outputs.
:param indir: GSEA desktop results directory. In the sub folder, you must contain edb file fo... |
def prepare_outdir(self):
"""create temp directory."""
self._outdir = self.outdir
if self._outdir is None:
self._tmpdir = TemporaryDirectory()
self.outdir = self._tmpdir.name
elif isinstance(self.outdir, str):
mkdirs(self.outdir)
else:
... |
def _set_cores(self):
"""set cpu numbers to be used"""
cpu_num = cpu_count()-1
if self._processes > cpu_num:
cores = cpu_num
elif self._processes < 1:
cores = 1
else:
cores = self._processes
# have to be int if user input is float
... |
def _load_ranking(self, rnk):
"""Parse ranking file. This file contains ranking correlation vector( or expression values)
and gene names or ids.
:param rnk: the .rnk file of GSEA input or a Pandas DataFrame, Series instance.
:return: a Pandas Series with gene name indexed ran... |
def load_gmt(self, gene_list, gmt):
"""load gene set dict"""
if isinstance(gmt, dict):
genesets_dict = gmt
elif isinstance(gmt, str):
genesets_dict = self.parse_gmt(gmt)
else:
raise Exception("Error parsing gmt parameter for gene sets")
... |
def parse_gmt(self, gmt):
"""gmt parser"""
if gmt.lower().endswith(".gmt"):
with open(gmt) as genesets:
genesets_dict = { line.strip().split("\t")[0]: line.strip().split("\t")[2:]
for line in genesets.readlines()}
return geneset... |
def get_libraries(self, database=''):
"""return active enrichr library name.Offical API """
lib_url='http://amp.pharm.mssm.edu/%sEnrichr/datasetStatistics'%database
libs_json = json.loads(requests.get(lib_url).text)
libs = [lib['libraryName'] for lib in libs_json['statistics']]
... |
def _download_libraries(self, libname):
""" download enrichr libraries."""
self._logger.info("Downloading and generating Enrichr library gene sets......")
s = retry(5)
# queery string
ENRICHR_URL = 'http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary'
query_string = '?mode=t... |
def _heatmat(self, df, classes, pheno_pos, pheno_neg):
"""only use for gsea heatmap"""
width = len(classes) if len(classes) >= 6 else 5
cls_booA =list(map(lambda x: True if x == pheno_pos else False, classes))
cls_booB =list(map(lambda x: True if x == pheno_neg else False, classes))
... |
def _plotting(self, rank_metric, results, graph_num, outdir,
format, figsize, pheno_pos='', pheno_neg=''):
""" Plotting API.
:param rank_metric: sorted pd.Series with rankings values.
:param results: self.results
:param data: preprocessed expression table
... |
def _save_results(self, zipdata, outdir, module, gmt, rank_metric, permutation_type):
"""reformat gsea results, and save to txt"""
res = OrderedDict()
for gs, gseale, ind, RES in zipdata:
rdict = OrderedDict()
rdict['es'] = gseale[0]
rdict['nes'] = gseale[1]
... |
def load_data(self, cls_vec):
"""pre-processed the data frame.new filtering methods will be implement here.
"""
# read data in
if isinstance(self.data, pd.DataFrame) :
exprs = self.data.copy()
# handle index is gene_names
if exprs.index.dtype == 'O':
... |
def run(self):
"""GSEA main procedure"""
assert self.permutation_type in ["phenotype", "gene_set"]
assert self.min_size <= self.max_size
# Start Analysis
self._logger.info("Parsing data files for GSEA.............................")
# phenotype labels parsing
phe... |
def run(self):
"""GSEA prerank workflow"""
assert self.min_size <= self.max_size
# parsing rankings
dat2 = self._load_ranking(self.rnk)
assert len(dat2) > 1
# cpu numbers
self._set_cores()
# Start Analysis
self._logger.info("Parsing data files f... |
def norm_samples(self, dat):
"""normalization samples
see here: http://rowley.mit.edu/caw_web/ssGSEAProjection/ssGSEAProjection.Library.R
"""
if self.sample_norm_method == 'rank':
data = dat.rank(axis=0, method='average', na_option='bottom')
data = 10000*data ... |
def run(self):
"""run entry"""
self._logger.info("Parsing data files for ssGSEA...........................")
# load data
data = self.load_data()
# normalized samples, and rank
normdat = self.norm_samples(data)
# filtering out gene sets and build gene sets dictiona... |
def runSamplesPermu(self, df, gmt=None):
"""Single Sample GSEA workflow with permutation procedure"""
assert self.min_size <= self.max_size
mkdirs(self.outdir)
self.resultsOnSamples = OrderedDict()
outdir = self.outdir
# iter throught each sample
for name, ser in... |
def runSamples(self, df, gmt=None):
"""Single Sample GSEA workflow.
multiprocessing utility on samples.
"""
# df.index.values are gene_names
# Save each sample results to odict
self.resultsOnSamples = OrderedDict()
outdir = self.outdir
# run ssgsea for... |
def _save(self, outdir):
"""save es and stats"""
# save raw ES to one csv file
samplesRawES = pd.DataFrame(self.resultsOnSamples)
samplesRawES.index.name = 'Term|ES'
# normalize enrichment scores by using the entire data set, as indicated
# by Barbie et al., 2009, online ... |
def run(self):
"""main replot function"""
assert self.min_size <= self.max_size
assert self.fignum > 0
import glob
from bs4 import BeautifulSoup
# parsing files.......
try:
results_path = glob.glob(self.indir+'*/edb/results.edb')[0]
rank_p... |
def enrichr(gene_list, gene_sets, organism='human', description='',
outdir='Enrichr', background='hsapiens_gene_ensembl', cutoff=0.05,
format='pdf', figsize=(8,6), top_term=10, no_plot=False, verbose=False):
"""Enrichr API.
:param gene_list: Flat file with list of genes, one gene id per... |
def prepare_outdir(self):
"""create temp directory."""
self._outdir = self.outdir
if self._outdir is None:
self._tmpdir = TemporaryDirectory()
self.outdir = self._tmpdir.name
elif isinstance(self.outdir, str):
mkdirs(self.outdir)
else:
... |
def parse_genesets(self):
"""parse gene_sets input file type"""
enrichr_library = self.get_libraries()
if isinstance(self.gene_sets, list):
gss = self.gene_sets
elif isinstance(self.gene_sets, str):
gss = [ g.strip() for g in self.gene_sets.strip().split(",") ]
... |
def parse_genelists(self):
"""parse gene list"""
if isinstance(self.gene_list, list):
genes = self.gene_list
elif isinstance(self.gene_list, pd.DataFrame):
# input type is bed file
if self.gene_list.shape[1] >=3:
genes= self.gene_list.iloc[:,:3... |
def send_genes(self, gene_list, url):
""" send gene list to enrichr server"""
payload = {
'list': (None, gene_list),
'description': (None, self.descriptions)
}
# response
response = requests.post(url, files=payload)
if not response.ok:
r... |
def check_genes(self, gene_list, usr_list_id):
'''
Compare the genes sent and received to get successfully recognized genes
'''
response = requests.get('http://amp.pharm.mssm.edu/Enrichr/view?userListId=%s' % usr_list_id)
if not response.ok:
raise Exception('Error get... |
def get_results(self, gene_list):
"""Enrichr API"""
ADDLIST_URL = 'http://amp.pharm.mssm.edu/%sEnrichr/addList'%self._organism
job_id = self.send_genes(gene_list, ADDLIST_URL)
user_list_id = job_id['userListId']
RESULTS_URL = 'http://amp.pharm.mssm.edu/%sEnrichr/export'%self._or... |
def get_background(self):
"""get background gene"""
# input is a file
if os.path.isfile(self.background):
with open(self.background) as b:
bg2 = b.readlines()
bg = [g.strip() for g in bg2]
return set(bg)
# package included ... |
def get_organism(self):
"""Select Enrichr organism from below:
Human & Mouse: H. sapiens & M. musculus
Fly: D. melanogaster
Yeast: S. cerevisiae
Worm: C. elegans
Fish: D. rerio
"""
organism = {'default': ['', 'hs', 'mm', 'human','mouse',
... |
def enrich(self, gmt):
"""use local mode
p = p-value computed using the Fisher exact test (Hypergeometric test)
Not implemented here:
combine score = log(p)·z
see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4
columns contain:
... |
def run(self):
"""run enrichr for one sample gene list but multi-libraries"""
# set organism
self.get_organism()
# read input file
genes_list = self.parse_genelists()
gss = self.parse_genesets()
# if gmt
self._logger.info("Connecting to Enrichr Server to ... |
def cube(script, size=1.0, center=False, color=None):
"""Create a cube primitive
Note that this is made of 6 quads, not triangles
"""
"""# Convert size to list if it isn't already
if not isinstance(size, list):
size = list(size)
# If a single value was supplied use it for all 3 axes
... |
def cylinder(script, up='z', height=1.0, radius=None, radius1=None,
radius2=None, diameter=None, diameter1=None, diameter2=None,
center=False, cir_segments=32, color=None):
"""Create a cylinder or cone primitive. Usage is based on OpenSCAD.
# height = height of the cylinder
# radiu... |
def icosphere(script, radius=1.0, diameter=None, subdivisions=3, color=None):
"""create an icosphere mesh
radius Radius of the sphere
# subdivisions = Subdivision level; Number of the recursive subdivision of the
# surface. Default is 3 (a sphere approximation composed by 1280 faces).
# Admitted va... |
def sphere_cap(script, angle=1.0, subdivisions=3, color=None):
"""# angle = Angle of the cone subtending the cap. It must be <180 less than 180
# subdivisions = Subdivision level; Number of the recursive subdivision of the
# surface. Default is 3 (a sphere approximation composed by 1280 faces).
# Admitt... |
def torus(script, major_radius=3.0, minor_radius=1.0, inner_diameter=None,
outer_diameter=None, major_segments=48, minor_segments=12,
color=None):
"""Create a torus mesh
Args:
major_radius (float, (optional)): radius from the origin to the
center of the cross sections
... |
def grid(script, size=1.0, x_segments=1, y_segments=1, center=False,
color=None):
"""2D square/plane/grid created on XY plane
x_segments # Number of segments in the X direction.
y_segments # Number of segments in the Y direction.
center="false" # If true square will be centered on origin;
... |
def annulus(script, radius=None, radius1=None, radius2=None, diameter=None,
diameter1=None, diameter2=None, cir_segments=32, color=None):
"""Create a 2D (surface) circle or annulus
radius1=1 # Outer radius of the circle
radius2=0 # Inner radius of the circle (if non-zero it creates an annulus)
... |
def cylinder_open_hires(script, height=1.0, radius=1, diameter=None,
cir_segments=48, height_segments=1,
invert_normals=False, center=False, color=None):
""" Creates a round open tube, e.g. a cylinder with no top or bottom.
Useful if you want to wrap it around an... |
def cube_open_hires_old(script, size=1.0, x_segments=1, y_segments=1, z_segments=1,
center=False, color=None):
""" Creates a square open tube, e.g. a box with no top or bottom.
Useful if you want to wrap it around and join the open ends together, forming a torus.
"""
"""# Convert si... |
def cube_open_hires(script, size=1.0, x_segments=1, y_segments=1, z_segments=1,
center=False, color=None):
""" Creates a square open tube, e.g. a box with no top or bottom.
Useful if you want to wrap it around and join the open ends together, forming a torus.
"""
"""# Convert size t... |
def plane_hires_edges(script, size=1.0, x_segments=1, y_segments=1,
center=False, color=None):
""" Creates a plane with a specified number of vertices
on it sides, but no vertices on the interior.
Currently used to create a simpler bottom for cube_hires.
"""
size = util.make_... |
def cube_hires(script, size=1.0, x_segments=1, y_segments=1, z_segments=1,
simple_bottom=True, center=False, color=None):
"""Create a box with user defined number of segments in each direction.
Grid spacing is the same as its dimensions (spacing = 1) and its
thickness is one. Intended to be ... |
def annulus_hires(script, radius=None, radius1=None, radius2=None,
diameter=None, diameter1=None, diameter2=None,
cir_segments=48, rad_segments=1, color=None):
"""Create a cylinder with user defined number of segments
"""
if radius is not None and diameter is None:
... |
def tube_hires(script, height=1.0, radius=None, radius1=None, radius2=None,
diameter=None, diameter1=None, diameter2=None, cir_segments=32,
rad_segments=1, height_segments=1, center=False,
simple_bottom=False, color=None):
"""Create a cylinder with user defined number of... |
def color_values(color):
"""Read color_names.txt and find the red, green, and blue values
for a named color.
"""
# Get the directory where this script file is located:
this_dir = os.path.dirname(
os.path.realpath(
inspect.getsourcefile(
lambda: 0)))
color_... |
def check_list(var, num_terms):
""" Check if a variable is a list and is the correct length.
If variable is not a list it will make it a list of the correct length with
all terms identical.
"""
if not isinstance(var, list):
if isinstance(var, tuple):
var = list(var)
else... |
def make_list(var, num_terms=1):
""" Make a variable a list if it is not already
If variable is not a list it will make it a list of the correct length with
all terms identical.
"""
if not isinstance(var, list):
if isinstance(var, tuple):
var = list(var)
else:
... |
def write_filter(script, filter_xml):
""" Write filter to FilterScript object or filename
Args:
script (FilterScript object or filename str): the FilterScript object
or script filename to write the filter to.
filter_xml (str): the xml filter string
"""
if isinstance(script,... |
def ls3loop(script, iterations=1, loop_weight=0, edge_threshold=0,
selected=False):
""" Apply LS3 Subdivision Surface algorithm using Loop's weights.
This refinement method take normals into account.
See: Boye', S. Guennebaud, G. & Schlick, C.
"Least squares subdivision surfaces"
Comput... |
def merge_vert(script, threshold=0.0):
""" Merge together all the vertices that are nearer than the specified
threshold. Like a unify duplicate vertices but with some tolerance.
Args:
script: the FilterScript object or script filename to write
the filter to.
threshold (float): M... |
def close_holes(script, hole_max_edge=30, selected=False,
sel_new_face=True, self_intersection=True):
""" Close holes smaller than a given threshold
Args:
script: the FilterScript object or script filename to write
the filter to.
hole_max_edge (int): The size is expr... |
def split_vert_on_nonmanifold_face(script, vert_displacement_ratio=0.0):
""" Split non-manifold vertices until it becomes two-manifold.
Args:
script: the FilterScript object or script filename to write
the filter to.
vert_displacement_ratio (float): When a vertex is split it is move... |
def snap_mismatched_borders(script, edge_dist_ratio=0.01, unify_vert=True):
""" Try to snap together adjacent borders that are slightly mismatched.
This situation can happen on badly triangulated adjacent patches defined by
high order surfaces. For each border vertex the filter snaps it onto the
closes... |
def translate(script, value=(0.0, 0.0, 0.0)):
"""An alternative translate implementation that uses a geometric function.
This is more accurate than the built-in version."""
# Convert value to list if it isn't already
if not isinstance(value, list):
value = list(value)
vert_function(script,
... |
def rotate(script, axis='z', angle=0.0):
"""An alternative rotate implementation that uses a geometric function.
This is more accurate than the built-in version."""
angle = math.radians(angle)
if axis.lower() == 'x':
vert_function(script,
x_func='x',
y_func='y*c... |
def scale(script, value=1.0):
"""An alternative scale implementation that uses a geometric function.
This is more accurate than the built-in version."""
"""# Convert value to list if it isn't already
if not isinstance(value, list):
value = list(value)
# If a single value was supplied use it ... |
def freeze_matrix(script, all_layers=False):
""" Freeze the current transformation matrix into the coordinates of the
vertices of the mesh (and set this matrix to the identity).
In other words it applies in a definitive way the current matrix to the
vertex coordinates.
Args:
script: th... |
def function(script, x_func='x', y_func='y', z_func='z'):
"""Geometric function using muparser lib to generate new Coordinates
You can change x, y, z for every vertex according to the function specified.
See help(mlx.muparser_ref) for muparser reference documentation.
It's possible to use the followin... |
def vert_function(script, x_func='x', y_func='y', z_func='z', selected=False):
"""Geometric function using muparser lib to generate new Coordinates
You can change x, y, z for every vertex according to the function specified.
See help(mlx.muparser_ref) for muparser reference documentation.
It's possibl... |
def function_cyl_co(script, r_func='r', theta_func='theta', z_func='z'):
"""Geometric function using cylindrical coordinates.
Define functions in Z up cylindrical coordinates, with radius 'r',
angle 'theta', and height 'z'
See "function" docs for additional usage info and accepted parameters.
Arg... |
def radial_flare2(script, flare_radius=None, start_radius=None, end_radius=None,
end_height=None):
"""
flare_radius must be >= end_height (height)
end_radius max = flare_radius + r
end_radius (num): radius of mesh at end of flare
+15 r= 8.8205
-15 r= 1.1795
z... |
def radial_flare(script, flare_radius=None, start_radius=None, end_radius=None,
end_height=None):
"""
flare_radius must be >= z2 (height)
r2 max = flare_radius + r
r2 (num): radius of mesh at end of flare
+15 r= 8.8205
-15 r= 1.1795
z=10, 5 +/-15 - +/-15*0.745... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.