id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
236,400
RJT1990/pyflux
pyflux/families/laplace.py
Laplace.pdf
def pdf(self, mu): """ PDF for Laplace prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - p(mu) """ if self.transform is not None: mu = self.transform(mu) return ss.laplace.pdf(mu, self.loc0, self.scale0)
python
def pdf(self, mu): if self.transform is not None: mu = self.transform(mu) return ss.laplace.pdf(mu, self.loc0, self.scale0)
[ "def", "pdf", "(", "self", ",", "mu", ")", ":", "if", "self", ".", "transform", "is", "not", "None", ":", "mu", "=", "self", ".", "transform", "(", "mu", ")", "return", "ss", ".", "laplace", ".", "pdf", "(", "mu", ",", "self", ".", "loc0", ",",...
PDF for Laplace prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - p(mu)
[ "PDF", "for", "Laplace", "prior" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/laplace.py#L278-L293
236,401
RJT1990/pyflux
pyflux/families/laplace.py
Laplace.second_order_score
def second_order_score(y, mean, scale, shape, skewness): """ GAS Laplace Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the Laplace distribution scale : float scale parameter for the Laplace distribution shape : float tail thickness parameter for the Laplace distribution skewness : float skewness parameter for the Laplace distribution Returns ---------- - Adjusted score of the Laplace family """ return ((y-mean)/float(scale*np.abs(y-mean))) / (-(np.power(y-mean,2) - np.power(np.abs(mean-y),2))/(scale*np.power(np.abs(mean-y),3)))
python
def second_order_score(y, mean, scale, shape, skewness): return ((y-mean)/float(scale*np.abs(y-mean))) / (-(np.power(y-mean,2) - np.power(np.abs(mean-y),2))/(scale*np.power(np.abs(mean-y),3)))
[ "def", "second_order_score", "(", "y", ",", "mean", ",", "scale", ",", "shape", ",", "skewness", ")", ":", "return", "(", "(", "y", "-", "mean", ")", "/", "float", "(", "scale", "*", "np", ".", "abs", "(", "y", "-", "mean", ")", ")", ")", "/", ...
GAS Laplace Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the Laplace distribution scale : float scale parameter for the Laplace distribution shape : float tail thickness parameter for the Laplace distribution skewness : float skewness parameter for the Laplace distribution Returns ---------- - Adjusted score of the Laplace family
[ "GAS", "Laplace", "Update", "term", "potentially", "using", "second", "-", "order", "information", "-", "native", "Python", "function" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/laplace.py#L326-L350
236,402
RJT1990/pyflux
pyflux/data_check.py
data_check
def data_check(data,target): """ Checks data type Parameters ---------- data : pd.DataFrame or np.array Field to specify the time series data that will be used. target : int or str Target column Returns ---------- transformed_data : np.array Raw data array for use in the model data_name : str Name of the data is_pandas : Boolean True if pandas data, else numpy data_index : np.array The time indices for the data """ # Check pandas or numpy if isinstance(data, pd.DataFrame) or isinstance(data, pd.core.frame.DataFrame): data_index = data.index if target is None: transformed_data = data.ix[:,0].values data_name = str(data.columns.values[0]) else: transformed_data = data[target].values data_name = str(target) is_pandas = True elif isinstance(data, np.ndarray): data_name = "Series" is_pandas = False if any(isinstance(i, np.ndarray) for i in data): if target is None: transformed_data = data[0] data_index = list(range(len(data[0]))) else: transformed_data = data[target] data_index = list(range(len(data[target]))) else: transformed_data = data data_index = list(range(len(data))) else: raise Exception("The data input is not pandas or numpy compatible!") return transformed_data, data_name, is_pandas, data_index
python
def data_check(data,target): # Check pandas or numpy if isinstance(data, pd.DataFrame) or isinstance(data, pd.core.frame.DataFrame): data_index = data.index if target is None: transformed_data = data.ix[:,0].values data_name = str(data.columns.values[0]) else: transformed_data = data[target].values data_name = str(target) is_pandas = True elif isinstance(data, np.ndarray): data_name = "Series" is_pandas = False if any(isinstance(i, np.ndarray) for i in data): if target is None: transformed_data = data[0] data_index = list(range(len(data[0]))) else: transformed_data = data[target] data_index = list(range(len(data[target]))) else: transformed_data = data data_index = list(range(len(data))) else: raise Exception("The data input is not pandas or numpy compatible!") return transformed_data, data_name, is_pandas, data_index
[ "def", "data_check", "(", "data", ",", "target", ")", ":", "# Check pandas or numpy", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", "or", "isinstance", "(", "data", ",", "pd", ".", "core", ".", "frame", ".", "DataFrame", ")", ":", ...
Checks data type Parameters ---------- data : pd.DataFrame or np.array Field to specify the time series data that will be used. target : int or str Target column Returns ---------- transformed_data : np.array Raw data array for use in the model data_name : str Name of the data is_pandas : Boolean True if pandas data, else numpy data_index : np.array The time indices for the data
[ "Checks", "data", "type" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/data_check.py#L4-L57
236,403
RJT1990/pyflux
pyflux/latent_variables.py
LatentVariables.add_z
def add_z(self, name, prior, q, index=True): """ Adds latent variable Parameters ---------- name : str Name of the latent variable prior : Prior object Which prior distribution? E.g. Normal(0,1) q : Distribution object Which distribution to use for variational approximation index : boolean Whether to index the variable in the z_indices dictionary Returns ---------- None (changes priors in LatentVariables object) """ self.z_list.append(LatentVariable(name,len(self.z_list),prior,q)) if index is True: self.z_indices[name] = {'start': len(self.z_list)-1, 'end': len(self.z_list)-1}
python
def add_z(self, name, prior, q, index=True): self.z_list.append(LatentVariable(name,len(self.z_list),prior,q)) if index is True: self.z_indices[name] = {'start': len(self.z_list)-1, 'end': len(self.z_list)-1}
[ "def", "add_z", "(", "self", ",", "name", ",", "prior", ",", "q", ",", "index", "=", "True", ")", ":", "self", ".", "z_list", ".", "append", "(", "LatentVariable", "(", "name", ",", "len", "(", "self", ".", "z_list", ")", ",", "prior", ",", "q", ...
Adds latent variable Parameters ---------- name : str Name of the latent variable prior : Prior object Which prior distribution? E.g. Normal(0,1) q : Distribution object Which distribution to use for variational approximation index : boolean Whether to index the variable in the z_indices dictionary Returns ---------- None (changes priors in LatentVariables object)
[ "Adds", "latent", "variable" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/latent_variables.py#L46-L70
236,404
RJT1990/pyflux
pyflux/latent_variables.py
LatentVariables.create
def create(self, name, dim, prior, q): """ Creates multiple latent variables Parameters ---------- name : str Name of the latent variable dim : list Dimension of the latent variable arrays prior : Prior object Which prior distribution? E.g. Normal(0,1) q : Distribution object Which distribution to use for variational approximation Returns ---------- None (changes priors in LatentVariables object) """ def rec(dim, prev=[]): if len(dim) > 0: return [rec(dim[1:], prev + [i]) for i in range(dim[0])] else: return "(" + ",".join([str(j) for j in prev]) + ")" indices = rec(dim) for f_dim in range(1, len(dim)): indices = sum(indices, []) if self.z_list is None: starting_index = 0 else: starting_index = len(self.z_list) self.z_indices[name] = {'start': starting_index, 'end': starting_index+len(indices)-1, 'dim': len(dim)} for index in indices: self.add_z(name + " " + index, prior, q, index=False)
python
def create(self, name, dim, prior, q): def rec(dim, prev=[]): if len(dim) > 0: return [rec(dim[1:], prev + [i]) for i in range(dim[0])] else: return "(" + ",".join([str(j) for j in prev]) + ")" indices = rec(dim) for f_dim in range(1, len(dim)): indices = sum(indices, []) if self.z_list is None: starting_index = 0 else: starting_index = len(self.z_list) self.z_indices[name] = {'start': starting_index, 'end': starting_index+len(indices)-1, 'dim': len(dim)} for index in indices: self.add_z(name + " " + index, prior, q, index=False)
[ "def", "create", "(", "self", ",", "name", ",", "dim", ",", "prior", ",", "q", ")", ":", "def", "rec", "(", "dim", ",", "prev", "=", "[", "]", ")", ":", "if", "len", "(", "dim", ")", ">", "0", ":", "return", "[", "rec", "(", "dim", "[", "...
Creates multiple latent variables Parameters ---------- name : str Name of the latent variable dim : list Dimension of the latent variable arrays prior : Prior object Which prior distribution? E.g. Normal(0,1) q : Distribution object Which distribution to use for variational approximation Returns ---------- None (changes priors in LatentVariables object)
[ "Creates", "multiple", "latent", "variables" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/latent_variables.py#L72-L113
236,405
RJT1990/pyflux
pyflux/gpnarx/kernels.py
ARD.build_latent_variables
def build_latent_variables(self): """ Builds latent variables for this kernel Returns ---------- - A list of lists (each sub-list contains latent variable information) """ lvs_to_build = [] lvs_to_build.append(['Noise Sigma^2', fam.Flat(transform='exp'), fam.Normal(0,3), -1.0]) for lag in range(self.X.shape[1]): lvs_to_build.append(['l lag' + str(lag+1), fam.FLat(transform='exp'), fam.Normal(0,3), -1.0]) lvs_to_build.append(['tau', fam.Flat(transform='exp'), fam.Normal(0,3), -1.0]) return lvs_to_build
python
def build_latent_variables(self): lvs_to_build = [] lvs_to_build.append(['Noise Sigma^2', fam.Flat(transform='exp'), fam.Normal(0,3), -1.0]) for lag in range(self.X.shape[1]): lvs_to_build.append(['l lag' + str(lag+1), fam.FLat(transform='exp'), fam.Normal(0,3), -1.0]) lvs_to_build.append(['tau', fam.Flat(transform='exp'), fam.Normal(0,3), -1.0]) return lvs_to_build
[ "def", "build_latent_variables", "(", "self", ")", ":", "lvs_to_build", "=", "[", "]", "lvs_to_build", ".", "append", "(", "[", "'Noise Sigma^2'", ",", "fam", ".", "Flat", "(", "transform", "=", "'exp'", ")", ",", "fam", ".", "Normal", "(", "0", ",", "...
Builds latent variables for this kernel Returns ---------- - A list of lists (each sub-list contains latent variable information)
[ "Builds", "latent", "variables", "for", "this", "kernel" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gpnarx/kernels.py#L160-L172
236,406
RJT1990/pyflux
pyflux/arma/nnar.py
NNAR._ar_matrix
def _ar_matrix(self): """ Creates Autoregressive matrix Returns ---------- X : np.ndarray Autoregressive Matrix """ Y = np.array(self.data[self.max_lag:self.data.shape[0]]) X = self.data[(self.max_lag-1):-1] if self.ar != 0: for i in range(1, self.ar): X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1])) return X
python
def _ar_matrix(self): Y = np.array(self.data[self.max_lag:self.data.shape[0]]) X = self.data[(self.max_lag-1):-1] if self.ar != 0: for i in range(1, self.ar): X = np.vstack((X,self.data[(self.max_lag-i-1):-i-1])) return X
[ "def", "_ar_matrix", "(", "self", ")", ":", "Y", "=", "np", ".", "array", "(", "self", ".", "data", "[", "self", ".", "max_lag", ":", "self", ".", "data", ".", "shape", "[", "0", "]", "]", ")", "X", "=", "self", ".", "data", "[", "(", "self",...
Creates Autoregressive matrix Returns ---------- X : np.ndarray Autoregressive Matrix
[ "Creates", "Autoregressive", "matrix" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/arma/nnar.py#L118-L134
236,407
RJT1990/pyflux
pyflux/ensembles/mixture_of_experts.py
Aggregate.predict_is
def predict_is(self, h): """ Outputs predictions for the Aggregate algorithm on the in-sample data Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of ensemble predictions """ result = pd.DataFrame([self.run(h=h)[2]]).T result.index = self.index[-h:] return result
python
def predict_is(self, h): result = pd.DataFrame([self.run(h=h)[2]]).T result.index = self.index[-h:] return result
[ "def", "predict_is", "(", "self", ",", "h", ")", ":", "result", "=", "pd", ".", "DataFrame", "(", "[", "self", ".", "run", "(", "h", "=", "h", ")", "[", "2", "]", "]", ")", ".", "T", "result", ".", "index", "=", "self", ".", "index", "[", "...
Outputs predictions for the Aggregate algorithm on the in-sample data Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of ensemble predictions
[ "Outputs", "predictions", "for", "the", "Aggregate", "algorithm", "on", "the", "in", "-", "sample", "data" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ensembles/mixture_of_experts.py#L335-L349
236,408
RJT1990/pyflux
pyflux/ensembles/mixture_of_experts.py
Aggregate.summary
def summary(self, h): """ Summarize the results for each model for h steps of the algorithm Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of losses for each model """ _, losses, _ = self.run(h=h) df = pd.DataFrame(losses) df.index = ['Ensemble'] + self.model_names df.columns = [self.loss_name] return df
python
def summary(self, h): _, losses, _ = self.run(h=h) df = pd.DataFrame(losses) df.index = ['Ensemble'] + self.model_names df.columns = [self.loss_name] return df
[ "def", "summary", "(", "self", ",", "h", ")", ":", "_", ",", "losses", ",", "_", "=", "self", ".", "run", "(", "h", "=", "h", ")", "df", "=", "pd", ".", "DataFrame", "(", "losses", ")", "df", ".", "index", "=", "[", "'Ensemble'", "]", "+", ...
Summarize the results for each model for h steps of the algorithm Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of losses for each model
[ "Summarize", "the", "results", "for", "each", "model", "for", "h", "steps", "of", "the", "algorithm" ]
297f2afc2095acd97c12e827dd500e8ea5da0c0f
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ensembles/mixture_of_experts.py#L351-L368
236,409
vtkiorg/vtki
vtki/container.py
MultiBlock.extract_geometry
def extract_geometry(self): """Combines the geomertry of all blocks into a single ``PolyData`` object. Place this filter at the end of a pipeline before a polydata consumer such as a polydata mapper to extract geometry from all blocks and append them to one polydata object. """ gf = vtk.vtkCompositeDataGeometryFilter() gf.SetInputData(self) gf.Update() return wrap(gf.GetOutputDataObject(0))
python
def extract_geometry(self): gf = vtk.vtkCompositeDataGeometryFilter() gf.SetInputData(self) gf.Update() return wrap(gf.GetOutputDataObject(0))
[ "def", "extract_geometry", "(", "self", ")", ":", "gf", "=", "vtk", ".", "vtkCompositeDataGeometryFilter", "(", ")", "gf", ".", "SetInputData", "(", "self", ")", "gf", ".", "Update", "(", ")", "return", "wrap", "(", "gf", ".", "GetOutputDataObject", "(", ...
Combines the geomertry of all blocks into a single ``PolyData`` object. Place this filter at the end of a pipeline before a polydata consumer such as a polydata mapper to extract geometry from all blocks and append them to one polydata object.
[ "Combines", "the", "geomertry", "of", "all", "blocks", "into", "a", "single", "PolyData", "object", ".", "Place", "this", "filter", "at", "the", "end", "of", "a", "pipeline", "before", "a", "polydata", "consumer", "such", "as", "a", "polydata", "mapper", "...
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L58-L67
236,410
vtkiorg/vtki
vtki/container.py
MultiBlock.combine
def combine(self, merge_points=False): """Appends all blocks into a single unstructured grid. Parameters ---------- merge_points : bool, optional Merge coincidental points. """ alg = vtk.vtkAppendFilter() for block in self: alg.AddInputData(block) alg.SetMergePoints(merge_points) alg.Update() return wrap(alg.GetOutputDataObject(0))
python
def combine(self, merge_points=False): alg = vtk.vtkAppendFilter() for block in self: alg.AddInputData(block) alg.SetMergePoints(merge_points) alg.Update() return wrap(alg.GetOutputDataObject(0))
[ "def", "combine", "(", "self", ",", "merge_points", "=", "False", ")", ":", "alg", "=", "vtk", ".", "vtkAppendFilter", "(", ")", "for", "block", "in", "self", ":", "alg", ".", "AddInputData", "(", "block", ")", "alg", ".", "SetMergePoints", "(", "merge...
Appends all blocks into a single unstructured grid. Parameters ---------- merge_points : bool, optional Merge coincidental points.
[ "Appends", "all", "blocks", "into", "a", "single", "unstructured", "grid", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L69-L83
236,411
vtkiorg/vtki
vtki/container.py
MultiBlock.save
def save(self, filename, binary=True): """ Writes a ``MultiBlock`` dataset to disk. Written file may be an ASCII or binary vtm file. Parameters ---------- filename : str Filename of mesh to be written. File type is inferred from the extension of the filename unless overridden with ftype. Can be one of the following types (.vtm or .vtmb) binary : bool, optional Writes the file as binary when True and ASCII when False. Notes ----- Binary files write much faster than ASCII and have a smaller file size. """ filename = os.path.abspath(os.path.expanduser(filename)) ext = vtki.get_ext(filename) if ext in ['.vtm', '.vtmb']: writer = vtk.vtkXMLMultiBlockDataWriter() else: raise Exception('File extension must be either "vtm" or "vtmb"') writer.SetFileName(filename) writer.SetInputDataObject(self) if binary: writer.SetDataModeToBinary() else: writer.SetDataModeToAscii() writer.Write() return
python
def save(self, filename, binary=True): filename = os.path.abspath(os.path.expanduser(filename)) ext = vtki.get_ext(filename) if ext in ['.vtm', '.vtmb']: writer = vtk.vtkXMLMultiBlockDataWriter() else: raise Exception('File extension must be either "vtm" or "vtmb"') writer.SetFileName(filename) writer.SetInputDataObject(self) if binary: writer.SetDataModeToBinary() else: writer.SetDataModeToAscii() writer.Write() return
[ "def", "save", "(", "self", ",", "filename", ",", "binary", "=", "True", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")", "ext", "=", "vtki", ".", "get_ext", "(", ...
Writes a ``MultiBlock`` dataset to disk. Written file may be an ASCII or binary vtm file. Parameters ---------- filename : str Filename of mesh to be written. File type is inferred from the extension of the filename unless overridden with ftype. Can be one of the following types (.vtm or .vtmb) binary : bool, optional Writes the file as binary when True and ASCII when False. Notes ----- Binary files write much faster than ASCII and have a smaller file size.
[ "Writes", "a", "MultiBlock", "dataset", "to", "disk", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L111-L146
236,412
vtkiorg/vtki
vtki/container.py
MultiBlock.get_index_by_name
def get_index_by_name(self, name): """Find the index number by block name""" for i in range(self.n_blocks): if self.get_block_name(i) == name: return i raise KeyError('Block name ({}) not found'.format(name))
python
def get_index_by_name(self, name): for i in range(self.n_blocks): if self.get_block_name(i) == name: return i raise KeyError('Block name ({}) not found'.format(name))
[ "def", "get_index_by_name", "(", "self", ",", "name", ")", ":", "for", "i", "in", "range", "(", "self", ".", "n_blocks", ")", ":", "if", "self", ".", "get_block_name", "(", "i", ")", "==", "name", ":", "return", "i", "raise", "KeyError", "(", "'Block...
Find the index number by block name
[ "Find", "the", "index", "number", "by", "block", "name" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L211-L216
236,413
vtkiorg/vtki
vtki/container.py
MultiBlock.append
def append(self, data): """Add a data set to the next block index""" index = self.n_blocks # note off by one so use as index self[index] = data self.refs.append(data)
python
def append(self, data): index = self.n_blocks # note off by one so use as index self[index] = data self.refs.append(data)
[ "def", "append", "(", "self", ",", "data", ")", ":", "index", "=", "self", ".", "n_blocks", "# note off by one so use as index", "self", "[", "index", "]", "=", "data", "self", ".", "refs", ".", "append", "(", "data", ")" ]
Add a data set to the next block index
[ "Add", "a", "data", "set", "to", "the", "next", "block", "index" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L234-L238
236,414
vtkiorg/vtki
vtki/container.py
MultiBlock.set_block_name
def set_block_name(self, index, name): """Set a block's string name at the specified index""" if name is None: return self.GetMetaData(index).Set(vtk.vtkCompositeDataSet.NAME(), name) self.Modified()
python
def set_block_name(self, index, name): if name is None: return self.GetMetaData(index).Set(vtk.vtkCompositeDataSet.NAME(), name) self.Modified()
[ "def", "set_block_name", "(", "self", ",", "index", ",", "name", ")", ":", "if", "name", "is", "None", ":", "return", "self", ".", "GetMetaData", "(", "index", ")", ".", "Set", "(", "vtk", ".", "vtkCompositeDataSet", ".", "NAME", "(", ")", ",", "name...
Set a block's string name at the specified index
[ "Set", "a", "block", "s", "string", "name", "at", "the", "specified", "index" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L247-L252
236,415
vtkiorg/vtki
vtki/container.py
MultiBlock.get_block_name
def get_block_name(self, index): """Returns the string name of the block at the given index""" meta = self.GetMetaData(index) if meta is not None: return meta.Get(vtk.vtkCompositeDataSet.NAME()) return None
python
def get_block_name(self, index): meta = self.GetMetaData(index) if meta is not None: return meta.Get(vtk.vtkCompositeDataSet.NAME()) return None
[ "def", "get_block_name", "(", "self", ",", "index", ")", ":", "meta", "=", "self", ".", "GetMetaData", "(", "index", ")", "if", "meta", "is", "not", "None", ":", "return", "meta", ".", "Get", "(", "vtk", ".", "vtkCompositeDataSet", ".", "NAME", "(", ...
Returns the string name of the block at the given index
[ "Returns", "the", "string", "name", "of", "the", "block", "at", "the", "given", "index" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L255-L260
236,416
vtkiorg/vtki
vtki/container.py
MultiBlock.keys
def keys(self): """Get all the block names in the dataset""" names = [] for i in range(self.n_blocks): names.append(self.get_block_name(i)) return names
python
def keys(self): names = [] for i in range(self.n_blocks): names.append(self.get_block_name(i)) return names
[ "def", "keys", "(", "self", ")", ":", "names", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "n_blocks", ")", ":", "names", ".", "append", "(", "self", ".", "get_block_name", "(", "i", ")", ")", "return", "names" ]
Get all the block names in the dataset
[ "Get", "all", "the", "block", "names", "in", "the", "dataset" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L263-L268
236,417
vtkiorg/vtki
vtki/container.py
MultiBlock.next
def next(self): """Get the next block from the iterator""" if self._iter_n < self.n_blocks: result = self[self._iter_n] self._iter_n += 1 return result else: raise StopIteration
python
def next(self): if self._iter_n < self.n_blocks: result = self[self._iter_n] self._iter_n += 1 return result else: raise StopIteration
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_iter_n", "<", "self", ".", "n_blocks", ":", "result", "=", "self", "[", "self", ".", "_iter_n", "]", "self", ".", "_iter_n", "+=", "1", "return", "result", "else", ":", "raise", "StopIteratio...
Get the next block from the iterator
[ "Get", "the", "next", "block", "from", "the", "iterator" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L321-L328
236,418
vtkiorg/vtki
vtki/container.py
MultiBlock._repr_html_
def _repr_html_(self): """A pretty representation for Jupyter notebooks""" fmt = "" fmt += "<table>" fmt += "<tr><th>Information</th><th>Blocks</th></tr>" fmt += "<tr><td>" fmt += "\n" fmt += "<table>\n" fmt += "<tr><th>{}</th><th>Values</th></tr>\n".format(type(self).__name__) row = "<tr><td>{}</td><td>{}</td></tr>\n" # now make a call on the object to get its attributes as a list of len 2 tuples for attr in self._get_attrs(): try: fmt += row.format(attr[0], attr[2].format(*attr[1])) except: fmt += row.format(attr[0], attr[2].format(attr[1])) fmt += "</table>\n" fmt += "\n" fmt += "</td><td>" fmt += "\n" fmt += "<table>\n" row = "<tr><th>{}</th><th>{}</th><th>{}</th></tr>\n" fmt += row.format("Index", "Name", "Type") for i in range(self.n_blocks): data = self[i] fmt += row.format(i, self.get_block_name(i), type(data).__name__) fmt += "</table>\n" fmt += "\n" fmt += "</td></tr> </table>" return fmt
python
def _repr_html_(self): fmt = "" fmt += "<table>" fmt += "<tr><th>Information</th><th>Blocks</th></tr>" fmt += "<tr><td>" fmt += "\n" fmt += "<table>\n" fmt += "<tr><th>{}</th><th>Values</th></tr>\n".format(type(self).__name__) row = "<tr><td>{}</td><td>{}</td></tr>\n" # now make a call on the object to get its attributes as a list of len 2 tuples for attr in self._get_attrs(): try: fmt += row.format(attr[0], attr[2].format(*attr[1])) except: fmt += row.format(attr[0], attr[2].format(attr[1])) fmt += "</table>\n" fmt += "\n" fmt += "</td><td>" fmt += "\n" fmt += "<table>\n" row = "<tr><th>{}</th><th>{}</th><th>{}</th></tr>\n" fmt += row.format("Index", "Name", "Type") for i in range(self.n_blocks): data = self[i] fmt += row.format(i, self.get_block_name(i), type(data).__name__) fmt += "</table>\n" fmt += "\n" fmt += "</td></tr> </table>" return fmt
[ "def", "_repr_html_", "(", "self", ")", ":", "fmt", "=", "\"\"", "fmt", "+=", "\"<table>\"", "fmt", "+=", "\"<tr><th>Information</th><th>Blocks</th></tr>\"", "fmt", "+=", "\"<tr><td>\"", "fmt", "+=", "\"\\n\"", "fmt", "+=", "\"<table>\\n\"", "fmt", "+=", "\"<tr><t...
A pretty representation for Jupyter notebooks
[ "A", "pretty", "representation", "for", "Jupyter", "notebooks" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/container.py#L367-L400
236,419
vtkiorg/vtki
vtki/geometric_objects.py
translate
def translate(surf, center, direction): """ Translates and orientates a mesh centered at the origin and facing in the x direction to a new center and direction """ normx = np.array(direction)/np.linalg.norm(direction) normz = np.cross(normx, [0, 1.0, 0.0000001]) normz /= np.linalg.norm(normz) normy = np.cross(normz, normx) trans = np.zeros((4, 4)) trans[:3, 0] = normx trans[:3, 1] = normy trans[:3, 2] = normz trans[3, 3] = 1 surf.transform(trans) surf.points += np.array(center)
python
def translate(surf, center, direction): normx = np.array(direction)/np.linalg.norm(direction) normz = np.cross(normx, [0, 1.0, 0.0000001]) normz /= np.linalg.norm(normz) normy = np.cross(normz, normx) trans = np.zeros((4, 4)) trans[:3, 0] = normx trans[:3, 1] = normy trans[:3, 2] = normz trans[3, 3] = 1 surf.transform(trans) surf.points += np.array(center)
[ "def", "translate", "(", "surf", ",", "center", ",", "direction", ")", ":", "normx", "=", "np", ".", "array", "(", "direction", ")", "/", "np", ".", "linalg", ".", "norm", "(", "direction", ")", "normz", "=", "np", ".", "cross", "(", "normx", ",", ...
Translates and orientates a mesh centered at the origin and facing in the x direction to a new center and direction
[ "Translates", "and", "orientates", "a", "mesh", "centered", "at", "the", "origin", "and", "facing", "in", "the", "x", "direction", "to", "a", "new", "center", "and", "direction" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L24-L41
236,420
vtkiorg/vtki
vtki/geometric_objects.py
Cylinder
def Cylinder(center=(0.,0.,0.), direction=(1.,0.,0.), radius=0.5, height=1.0, resolution=100, **kwargs): """ Create the surface of a cylinder. Parameters ---------- center : list or np.ndarray Location of the centroid in [x, y, z] direction : list or np.ndarray Direction cylinder points to in [x, y, z] radius : float Radius of the cylinder. height : float Height of the cylinder. resolution : int Number of points on the circular face of the cylinder. capping : bool, optional Cap cylinder ends with polygons. Default True Returns ------- cylinder : vtki.PolyData Cylinder surface. Examples -------- >>> import vtki >>> import numpy as np >>> cylinder = vtki.Cylinder(np.array([1, 2, 3]), np.array([1, 1, 1]), 1, 1) >>> cylinder.plot() # doctest:+SKIP """ capping = kwargs.get('capping', kwargs.get('cap_ends', True)) cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetRadius(radius) cylinderSource.SetHeight(height) cylinderSource.SetCapping(capping) cylinderSource.SetResolution(resolution) cylinderSource.Update() surf = PolyData(cylinderSource.GetOutput()) surf.rotate_z(-90) translate(surf, center, direction) return surf
python
def Cylinder(center=(0.,0.,0.), direction=(1.,0.,0.), radius=0.5, height=1.0, resolution=100, **kwargs): capping = kwargs.get('capping', kwargs.get('cap_ends', True)) cylinderSource = vtk.vtkCylinderSource() cylinderSource.SetRadius(radius) cylinderSource.SetHeight(height) cylinderSource.SetCapping(capping) cylinderSource.SetResolution(resolution) cylinderSource.Update() surf = PolyData(cylinderSource.GetOutput()) surf.rotate_z(-90) translate(surf, center, direction) return surf
[ "def", "Cylinder", "(", "center", "=", "(", "0.", ",", "0.", ",", "0.", ")", ",", "direction", "=", "(", "1.", ",", "0.", ",", "0.", ")", ",", "radius", "=", "0.5", ",", "height", "=", "1.0", ",", "resolution", "=", "100", ",", "*", "*", "kwa...
Create the surface of a cylinder. Parameters ---------- center : list or np.ndarray Location of the centroid in [x, y, z] direction : list or np.ndarray Direction cylinder points to in [x, y, z] radius : float Radius of the cylinder. height : float Height of the cylinder. resolution : int Number of points on the circular face of the cylinder. capping : bool, optional Cap cylinder ends with polygons. Default True Returns ------- cylinder : vtki.PolyData Cylinder surface. Examples -------- >>> import vtki >>> import numpy as np >>> cylinder = vtki.Cylinder(np.array([1, 2, 3]), np.array([1, 1, 1]), 1, 1) >>> cylinder.plot() # doctest:+SKIP
[ "Create", "the", "surface", "of", "a", "cylinder", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L44-L93
236,421
vtkiorg/vtki
vtki/geometric_objects.py
Arrow
def Arrow(start=(0.,0.,0.), direction=(1.,0.,0.), tip_length=0.25, tip_radius=0.1, shaft_radius=0.05, shaft_resolution=20): """ Create a vtk Arrow Parameters ---------- start : np.ndarray Start location in [x, y, z] direction : list or np.ndarray Direction the arrow points to in [x, y, z] tip_length : float, optional Length of the tip. tip_radius : float, optional Radius of the tip. shaft_radius : float, optional Radius of the shaft. shaft_resolution : int, optional Number of faces around the shaft Returns ------- arrow : vtki.PolyData Arrow surface. """ # Create arrow object arrow = vtk.vtkArrowSource() arrow.SetTipLength(tip_length) arrow.SetTipRadius(tip_radius) arrow.SetShaftRadius(shaft_radius) arrow.SetShaftResolution(shaft_resolution) arrow.Update() surf = PolyData(arrow.GetOutput()) translate(surf, start, direction) return surf
python
def Arrow(start=(0.,0.,0.), direction=(1.,0.,0.), tip_length=0.25, tip_radius=0.1, shaft_radius=0.05, shaft_resolution=20): # Create arrow object arrow = vtk.vtkArrowSource() arrow.SetTipLength(tip_length) arrow.SetTipRadius(tip_radius) arrow.SetShaftRadius(shaft_radius) arrow.SetShaftResolution(shaft_resolution) arrow.Update() surf = PolyData(arrow.GetOutput()) translate(surf, start, direction) return surf
[ "def", "Arrow", "(", "start", "=", "(", "0.", ",", "0.", ",", "0.", ")", ",", "direction", "=", "(", "1.", ",", "0.", ",", "0.", ")", ",", "tip_length", "=", "0.25", ",", "tip_radius", "=", "0.1", ",", "shaft_radius", "=", "0.05", ",", "shaft_res...
Create a vtk Arrow Parameters ---------- start : np.ndarray Start location in [x, y, z] direction : list or np.ndarray Direction the arrow points to in [x, y, z] tip_length : float, optional Length of the tip. tip_radius : float, optional Radius of the tip. shaft_radius : float, optional Radius of the shaft. shaft_resolution : int, optional Number of faces around the shaft Returns ------- arrow : vtki.PolyData Arrow surface.
[ "Create", "a", "vtk", "Arrow" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L96-L135
236,422
vtkiorg/vtki
vtki/geometric_objects.py
Sphere
def Sphere(radius=0.5, center=(0, 0, 0), direction=(0, 0, 1), theta_resolution=30, phi_resolution=30, start_theta=0, end_theta=360, start_phi=0, end_phi=180): """ Create a vtk Sphere Parameters ---------- radius : float, optional Sphere radius center : np.ndarray or list, optional Center in [x, y, z] direction : list or np.ndarray Direction the top of the sphere points to in [x, y, z] theta_resolution: int , optional Set the number of points in the longitude direction (ranging from start_theta to end theta). phi_resolution : int, optional Set the number of points in the latitude direction (ranging from start_phi to end_phi). start_theta : float, optional Starting longitude angle. end_theta : float, optional Ending longitude angle. start_phi : float, optional Starting latitude angle. end_phi : float, optional Ending latitude angle. Returns ------- sphere : vtki.PolyData Sphere mesh. """ sphere = vtk.vtkSphereSource() sphere.SetRadius(radius) sphere.SetThetaResolution(theta_resolution) sphere.SetPhiResolution(phi_resolution) sphere.SetStartTheta(start_theta) sphere.SetEndTheta(end_theta) sphere.SetStartPhi(start_phi) sphere.SetEndPhi(end_phi) sphere.Update() surf = PolyData(sphere.GetOutput()) surf.rotate_y(-90) translate(surf, center, direction) return surf
python
def Sphere(radius=0.5, center=(0, 0, 0), direction=(0, 0, 1), theta_resolution=30, phi_resolution=30, start_theta=0, end_theta=360, start_phi=0, end_phi=180): sphere = vtk.vtkSphereSource() sphere.SetRadius(radius) sphere.SetThetaResolution(theta_resolution) sphere.SetPhiResolution(phi_resolution) sphere.SetStartTheta(start_theta) sphere.SetEndTheta(end_theta) sphere.SetStartPhi(start_phi) sphere.SetEndPhi(end_phi) sphere.Update() surf = PolyData(sphere.GetOutput()) surf.rotate_y(-90) translate(surf, center, direction) return surf
[ "def", "Sphere", "(", "radius", "=", "0.5", ",", "center", "=", "(", "0", ",", "0", ",", "0", ")", ",", "direction", "=", "(", "0", ",", "0", ",", "1", ")", ",", "theta_resolution", "=", "30", ",", "phi_resolution", "=", "30", ",", "start_theta",...
Create a vtk Sphere Parameters ---------- radius : float, optional Sphere radius center : np.ndarray or list, optional Center in [x, y, z] direction : list or np.ndarray Direction the top of the sphere points to in [x, y, z] theta_resolution: int , optional Set the number of points in the longitude direction (ranging from start_theta to end theta). phi_resolution : int, optional Set the number of points in the latitude direction (ranging from start_phi to end_phi). start_theta : float, optional Starting longitude angle. end_theta : float, optional Ending longitude angle. start_phi : float, optional Starting latitude angle. end_phi : float, optional Ending latitude angle. Returns ------- sphere : vtki.PolyData Sphere mesh.
[ "Create", "a", "vtk", "Sphere" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L138-L191
236,423
vtkiorg/vtki
vtki/geometric_objects.py
Plane
def Plane(center=(0, 0, 0), direction=(0, 0, 1), i_size=1, j_size=1, i_resolution=10, j_resolution=10): """ Create a plane Parameters ---------- center : list or np.ndarray Location of the centroid in [x, y, z] direction : list or np.ndarray Direction cylinder points to in [x, y, z] i_size : float Size of the plane in the i direction. j_size : float Size of the plane in the i direction. i_resolution : int Number of points on the plane in the i direction. j_resolution : int Number of points on the plane in the j direction. Returns ------- plane : vtki.PolyData Plane mesh """ planeSource = vtk.vtkPlaneSource() planeSource.SetXResolution(i_resolution) planeSource.SetYResolution(j_resolution) planeSource.Update() surf = PolyData(planeSource.GetOutput()) surf.points[:, 0] *= i_size surf.points[:, 1] *= j_size surf.rotate_y(-90) translate(surf, center, direction) return surf
python
def Plane(center=(0, 0, 0), direction=(0, 0, 1), i_size=1, j_size=1, i_resolution=10, j_resolution=10): planeSource = vtk.vtkPlaneSource() planeSource.SetXResolution(i_resolution) planeSource.SetYResolution(j_resolution) planeSource.Update() surf = PolyData(planeSource.GetOutput()) surf.points[:, 0] *= i_size surf.points[:, 1] *= j_size surf.rotate_y(-90) translate(surf, center, direction) return surf
[ "def", "Plane", "(", "center", "=", "(", "0", ",", "0", ",", "0", ")", ",", "direction", "=", "(", "0", ",", "0", ",", "1", ")", ",", "i_size", "=", "1", ",", "j_size", "=", "1", ",", "i_resolution", "=", "10", ",", "j_resolution", "=", "10",...
Create a plane Parameters ---------- center : list or np.ndarray Location of the centroid in [x, y, z] direction : list or np.ndarray Direction cylinder points to in [x, y, z] i_size : float Size of the plane in the i direction. j_size : float Size of the plane in the i direction. i_resolution : int Number of points on the plane in the i direction. j_resolution : int Number of points on the plane in the j direction. Returns ------- plane : vtki.PolyData Plane mesh
[ "Create", "a", "plane" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L194-L236
236,424
vtkiorg/vtki
vtki/geometric_objects.py
Line
def Line(pointa=(-0.5, 0., 0.), pointb=(0.5, 0., 0.), resolution=1): """Create a line Parameters ---------- pointa : np.ndarray or list Location in [x, y, z]. pointb : np.ndarray or list Location in [x, y, z]. resolution : int number of pieces to divide line into """ if np.array(pointa).size != 3: raise TypeError('Point A must be a length three tuple of floats.') if np.array(pointb).size != 3: raise TypeError('Point B must be a length three tuple of floats.') src = vtk.vtkLineSource() src.SetPoint1(*pointa) src.SetPoint2(*pointb) src.SetResolution(resolution) src.Update() return vtki.wrap(src.GetOutput())
python
def Line(pointa=(-0.5, 0., 0.), pointb=(0.5, 0., 0.), resolution=1): if np.array(pointa).size != 3: raise TypeError('Point A must be a length three tuple of floats.') if np.array(pointb).size != 3: raise TypeError('Point B must be a length three tuple of floats.') src = vtk.vtkLineSource() src.SetPoint1(*pointa) src.SetPoint2(*pointb) src.SetResolution(resolution) src.Update() return vtki.wrap(src.GetOutput())
[ "def", "Line", "(", "pointa", "=", "(", "-", "0.5", ",", "0.", ",", "0.", ")", ",", "pointb", "=", "(", "0.5", ",", "0.", ",", "0.", ")", ",", "resolution", "=", "1", ")", ":", "if", "np", ".", "array", "(", "pointa", ")", ".", "size", "!="...
Create a line Parameters ---------- pointa : np.ndarray or list Location in [x, y, z]. pointb : np.ndarray or list Location in [x, y, z]. resolution : int number of pieces to divide line into
[ "Create", "a", "line" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L239-L262
236,425
vtkiorg/vtki
vtki/geometric_objects.py
Cube
def Cube(center=(0., 0., 0.), x_length=1.0, y_length=1.0, z_length=1.0, bounds=None): """Create a cube by either specifying the center and side lengths or just the bounds of the cube. If ``bounds`` are given, all other arguments are ignored. Parameters ---------- center : np.ndarray or list Center in [x, y, z]. x_length : float length of the cube in the x-direction. y_length : float length of the cube in the y-direction. z_length : float length of the cube in the z-direction. bounds : np.ndarray or list Specify the bounding box of the cube. If given, all other arguments are ignored. ``(xMin,xMax, yMin,yMax, zMin,zMax)`` """ src = vtk.vtkCubeSource() if bounds is not None: if np.array(bounds).size != 6: raise TypeError('Bounds must be given as length 6 tuple: (xMin,xMax, yMin,yMax, zMin,zMax)') src.SetBounds(bounds) else: src.SetCenter(center) src.SetXLength(x_length) src.SetYLength(y_length) src.SetZLength(z_length) src.Update() return vtki.wrap(src.GetOutput())
python
def Cube(center=(0., 0., 0.), x_length=1.0, y_length=1.0, z_length=1.0, bounds=None): src = vtk.vtkCubeSource() if bounds is not None: if np.array(bounds).size != 6: raise TypeError('Bounds must be given as length 6 tuple: (xMin,xMax, yMin,yMax, zMin,zMax)') src.SetBounds(bounds) else: src.SetCenter(center) src.SetXLength(x_length) src.SetYLength(y_length) src.SetZLength(z_length) src.Update() return vtki.wrap(src.GetOutput())
[ "def", "Cube", "(", "center", "=", "(", "0.", ",", "0.", ",", "0.", ")", ",", "x_length", "=", "1.0", ",", "y_length", "=", "1.0", ",", "z_length", "=", "1.0", ",", "bounds", "=", "None", ")", ":", "src", "=", "vtk", ".", "vtkCubeSource", "(", ...
Create a cube by either specifying the center and side lengths or just the bounds of the cube. If ``bounds`` are given, all other arguments are ignored. Parameters ---------- center : np.ndarray or list Center in [x, y, z]. x_length : float length of the cube in the x-direction. y_length : float length of the cube in the y-direction. z_length : float length of the cube in the z-direction. bounds : np.ndarray or list Specify the bounding box of the cube. If given, all other arguments are ignored. ``(xMin,xMax, yMin,yMax, zMin,zMax)``
[ "Create", "a", "cube", "by", "either", "specifying", "the", "center", "and", "side", "lengths", "or", "just", "the", "bounds", "of", "the", "cube", ".", "If", "bounds", "are", "given", "all", "other", "arguments", "are", "ignored", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/geometric_objects.py#L265-L299
236,426
vtkiorg/vtki
vtki/readers.py
standard_reader_routine
def standard_reader_routine(reader, filename, attrs=None): """Use a given reader from the ``READERS`` mapping in the common VTK reading pipeline routine. Parameters ---------- reader : vtkReader Any instantiated VTK reader class filename : str The string filename to the data file to read. attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value. """ if attrs is None: attrs = {} if not isinstance(attrs, dict): raise TypeError('Attributes must be a dictionary of name and arguments.') reader.SetFileName(filename) # Apply any attributes listed for name, args in attrs.items(): attr = getattr(reader, name) if args is not None: if not isinstance(args, (list, tuple)): args = [args] attr(*args) else: attr() # Perform the read reader.Update() return vtki.wrap(reader.GetOutputDataObject(0))
python
def standard_reader_routine(reader, filename, attrs=None): if attrs is None: attrs = {} if not isinstance(attrs, dict): raise TypeError('Attributes must be a dictionary of name and arguments.') reader.SetFileName(filename) # Apply any attributes listed for name, args in attrs.items(): attr = getattr(reader, name) if args is not None: if not isinstance(args, (list, tuple)): args = [args] attr(*args) else: attr() # Perform the read reader.Update() return vtki.wrap(reader.GetOutputDataObject(0))
[ "def", "standard_reader_routine", "(", "reader", ",", "filename", ",", "attrs", "=", "None", ")", ":", "if", "attrs", "is", "None", ":", "attrs", "=", "{", "}", "if", "not", "isinstance", "(", "attrs", ",", "dict", ")", ":", "raise", "TypeError", "(", ...
Use a given reader from the ``READERS`` mapping in the common VTK reading pipeline routine. Parameters ---------- reader : vtkReader Any instantiated VTK reader class filename : str The string filename to the data file to read. attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value.
[ "Use", "a", "given", "reader", "from", "the", "READERS", "mapping", "in", "the", "common", "VTK", "reading", "pipeline", "routine", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/readers.py#L85-L119
236,427
vtkiorg/vtki
vtki/readers.py
read_legacy
def read_legacy(filename): """Use VTK's legacy reader to read a file""" reader = vtk.vtkDataSetReader() reader.SetFileName(filename) # Ensure all data is fetched with poorly formated legacy files reader.ReadAllScalarsOn() reader.ReadAllColorScalarsOn() reader.ReadAllNormalsOn() reader.ReadAllTCoordsOn() reader.ReadAllVectorsOn() # Perform the read reader.Update() output = reader.GetOutputDataObject(0) if output is None: raise AssertionError('No output when using VTKs legacy reader') return vtki.wrap(output)
python
def read_legacy(filename): reader = vtk.vtkDataSetReader() reader.SetFileName(filename) # Ensure all data is fetched with poorly formated legacy files reader.ReadAllScalarsOn() reader.ReadAllColorScalarsOn() reader.ReadAllNormalsOn() reader.ReadAllTCoordsOn() reader.ReadAllVectorsOn() # Perform the read reader.Update() output = reader.GetOutputDataObject(0) if output is None: raise AssertionError('No output when using VTKs legacy reader') return vtki.wrap(output)
[ "def", "read_legacy", "(", "filename", ")", ":", "reader", "=", "vtk", ".", "vtkDataSetReader", "(", ")", "reader", ".", "SetFileName", "(", "filename", ")", "# Ensure all data is fetched with poorly formated legacy files", "reader", ".", "ReadAllScalarsOn", "(", ")",...
Use VTK's legacy reader to read a file
[ "Use", "VTK", "s", "legacy", "reader", "to", "read", "a", "file" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/readers.py#L122-L137
236,428
vtkiorg/vtki
vtki/readers.py
read
def read(filename, attrs=None): """This will read any VTK file! It will figure out what reader to use then wrap the VTK object for use in ``vtki``. Parameters ---------- attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value. """ filename = os.path.abspath(os.path.expanduser(filename)) ext = get_ext(filename) # From the extension, decide which reader to use if attrs is not None: reader = get_reader(filename) return standard_reader_routine(reader, filename, attrs=attrs) elif ext in '.vti': # ImageData return vtki.UniformGrid(filename) elif ext in '.vtr': # RectilinearGrid return vtki.RectilinearGrid(filename) elif ext in '.vtu': # UnstructuredGrid return vtki.UnstructuredGrid(filename) elif ext in ['.ply', '.obj', '.stl']: # PolyData return vtki.PolyData(filename) elif ext in '.vts': # StructuredGrid return vtki.StructuredGrid(filename) elif ext in ['.vtm', '.vtmb']: return vtki.MultiBlock(filename) elif ext in ['.e', '.exo']: return read_exodus(filename) elif ext in ['.vtk']: # Attempt to use the legacy reader... return read_legacy(filename) else: # Attempt find a reader in the readers mapping try: reader = get_reader(filename) return standard_reader_routine(reader, filename) except KeyError: pass raise IOError("This file was not able to be automatically read by vtki.")
python
def read(filename, attrs=None): filename = os.path.abspath(os.path.expanduser(filename)) ext = get_ext(filename) # From the extension, decide which reader to use if attrs is not None: reader = get_reader(filename) return standard_reader_routine(reader, filename, attrs=attrs) elif ext in '.vti': # ImageData return vtki.UniformGrid(filename) elif ext in '.vtr': # RectilinearGrid return vtki.RectilinearGrid(filename) elif ext in '.vtu': # UnstructuredGrid return vtki.UnstructuredGrid(filename) elif ext in ['.ply', '.obj', '.stl']: # PolyData return vtki.PolyData(filename) elif ext in '.vts': # StructuredGrid return vtki.StructuredGrid(filename) elif ext in ['.vtm', '.vtmb']: return vtki.MultiBlock(filename) elif ext in ['.e', '.exo']: return read_exodus(filename) elif ext in ['.vtk']: # Attempt to use the legacy reader... return read_legacy(filename) else: # Attempt find a reader in the readers mapping try: reader = get_reader(filename) return standard_reader_routine(reader, filename) except KeyError: pass raise IOError("This file was not able to be automatically read by vtki.")
[ "def", "read", "(", "filename", ",", "attrs", "=", "None", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")", "ext", "=", "get_ext", "(", "filename", ")", "# From the ex...
This will read any VTK file! It will figure out what reader to use then wrap the VTK object for use in ``vtki``. Parameters ---------- attrs : dict, optional A dictionary of attributes to call on the reader. Keys of dictionary are the attribute/method names and values are the arguments passed to those calls. If you do not have any attributes to call, pass ``None`` as the value.
[ "This", "will", "read", "any", "VTK", "file!", "It", "will", "figure", "out", "what", "reader", "to", "use", "then", "wrap", "the", "VTK", "object", "for", "use", "in", "vtki", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/readers.py#L140-L183
236,429
vtkiorg/vtki
vtki/readers.py
read_texture
def read_texture(filename, attrs=None): """Loads a ``vtkTexture`` from an image file.""" filename = os.path.abspath(os.path.expanduser(filename)) try: # intitialize the reader using the extnesion to find it reader = get_reader(filename) image = standard_reader_routine(reader, filename, attrs=attrs) return vtki.image_to_texture(image) except KeyError: # Otherwise, use the imageio reader pass return vtki.numpy_to_texture(imageio.imread(filename))
python
def read_texture(filename, attrs=None): filename = os.path.abspath(os.path.expanduser(filename)) try: # intitialize the reader using the extnesion to find it reader = get_reader(filename) image = standard_reader_routine(reader, filename, attrs=attrs) return vtki.image_to_texture(image) except KeyError: # Otherwise, use the imageio reader pass return vtki.numpy_to_texture(imageio.imread(filename))
[ "def", "read_texture", "(", "filename", ",", "attrs", "=", "None", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ")", "try", ":", "# intitialize the reader using the extnesion t...
Loads a ``vtkTexture`` from an image file.
[ "Loads", "a", "vtkTexture", "from", "an", "image", "file", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/readers.py#L186-L197
236,430
vtkiorg/vtki
vtki/examples/downloads.py
delete_downloads
def delete_downloads(): """Delete all downloaded examples to free space or update the files""" shutil.rmtree(vtki.EXAMPLES_PATH) os.makedirs(vtki.EXAMPLES_PATH) return True
python
def delete_downloads(): shutil.rmtree(vtki.EXAMPLES_PATH) os.makedirs(vtki.EXAMPLES_PATH) return True
[ "def", "delete_downloads", "(", ")", ":", "shutil", ".", "rmtree", "(", "vtki", ".", "EXAMPLES_PATH", ")", "os", ".", "makedirs", "(", "vtki", ".", "EXAMPLES_PATH", ")", "return", "True" ]
Delete all downloaded examples to free space or update the files
[ "Delete", "all", "downloaded", "examples", "to", "free", "space", "or", "update", "the", "files" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/downloads.py#L13-L17
236,431
vtkiorg/vtki
vtki/examples/downloads.py
download_blood_vessels
def download_blood_vessels(): """data representing the bifurcation of blood vessels.""" local_path, _ = _download_file('pvtu_blood_vessels/blood_vessels.zip') filename = os.path.join(local_path, 'T0000000500.pvtu') mesh = vtki.read(filename) mesh.set_active_vectors('velocity') return mesh
python
def download_blood_vessels(): local_path, _ = _download_file('pvtu_blood_vessels/blood_vessels.zip') filename = os.path.join(local_path, 'T0000000500.pvtu') mesh = vtki.read(filename) mesh.set_active_vectors('velocity') return mesh
[ "def", "download_blood_vessels", "(", ")", ":", "local_path", ",", "_", "=", "_download_file", "(", "'pvtu_blood_vessels/blood_vessels.zip'", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "local_path", ",", "'T0000000500.pvtu'", ")", "mesh", "=", "v...
data representing the bifurcation of blood vessels.
[ "data", "representing", "the", "bifurcation", "of", "blood", "vessels", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/downloads.py#L137-L143
236,432
vtkiorg/vtki
vtki/examples/downloads.py
download_sparse_points
def download_sparse_points(): """Used with ``download_saddle_surface``""" saved_file, _ = _download_file('sparsePoints.txt') points_reader = vtk.vtkDelimitedTextReader() points_reader.SetFileName(saved_file) points_reader.DetectNumericColumnsOn() points_reader.SetFieldDelimiterCharacters('\t') points_reader.SetHaveHeaders(True) table_points = vtk.vtkTableToPolyData() table_points.SetInputConnection(points_reader.GetOutputPort()) table_points.SetXColumn('x') table_points.SetYColumn('y') table_points.SetZColumn('z') table_points.Update() return vtki.wrap(table_points.GetOutput())
python
def download_sparse_points(): saved_file, _ = _download_file('sparsePoints.txt') points_reader = vtk.vtkDelimitedTextReader() points_reader.SetFileName(saved_file) points_reader.DetectNumericColumnsOn() points_reader.SetFieldDelimiterCharacters('\t') points_reader.SetHaveHeaders(True) table_points = vtk.vtkTableToPolyData() table_points.SetInputConnection(points_reader.GetOutputPort()) table_points.SetXColumn('x') table_points.SetYColumn('y') table_points.SetZColumn('z') table_points.Update() return vtki.wrap(table_points.GetOutput())
[ "def", "download_sparse_points", "(", ")", ":", "saved_file", ",", "_", "=", "_download_file", "(", "'sparsePoints.txt'", ")", "points_reader", "=", "vtk", ".", "vtkDelimitedTextReader", "(", ")", "points_reader", ".", "SetFileName", "(", "saved_file", ")", "point...
Used with ``download_saddle_surface``
[ "Used", "with", "download_saddle_surface" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/downloads.py#L154-L168
236,433
vtkiorg/vtki
vtki/examples/downloads.py
download_kitchen
def download_kitchen(split=False): """Download structured grid of kitchen with velocity field. Use the ``split`` argument to extract all of the furniture in the kitchen. """ mesh = _download_and_read('kitchen.vtk') if not split: return mesh extents = { 'door' : (27, 27, 14, 18, 0, 11), 'window1' : (0, 0, 9, 18, 6, 12), 'window2' : (5, 12, 23, 23, 6, 12), 'klower1' : (17, 17, 0, 11, 0, 6), 'klower2' : (19, 19, 0, 11, 0, 6), 'klower3' : (17, 19, 0, 0, 0, 6), 'klower4' : (17, 19, 11, 11, 0, 6), 'klower5' : (17, 19, 0, 11, 0, 0), 'klower6' : (17, 19, 0, 7, 6, 6), 'klower7' : (17, 19, 9, 11, 6, 6), 'hood1' : (17, 17, 0, 11, 11, 16), 'hood2' : (19, 19, 0, 11, 11, 16), 'hood3' : (17, 19, 0, 0, 11, 16), 'hood4' : (17, 19, 11, 11, 11, 16), 'hood5' : (17, 19, 0, 11, 16, 16), 'cookingPlate' : (17, 19, 7, 9, 6, 6), 'furniture' : (17, 19, 7, 9, 11, 11), } kitchen = vtki.MultiBlock() for key, extent in extents.items(): alg = vtk.vtkStructuredGridGeometryFilter() alg.SetInputDataObject(mesh) alg.SetExtent(extent) alg.Update() result = vtki.filters._get_output(alg) kitchen[key] = result return kitchen
python
def download_kitchen(split=False): mesh = _download_and_read('kitchen.vtk') if not split: return mesh extents = { 'door' : (27, 27, 14, 18, 0, 11), 'window1' : (0, 0, 9, 18, 6, 12), 'window2' : (5, 12, 23, 23, 6, 12), 'klower1' : (17, 17, 0, 11, 0, 6), 'klower2' : (19, 19, 0, 11, 0, 6), 'klower3' : (17, 19, 0, 0, 0, 6), 'klower4' : (17, 19, 11, 11, 0, 6), 'klower5' : (17, 19, 0, 11, 0, 0), 'klower6' : (17, 19, 0, 7, 6, 6), 'klower7' : (17, 19, 9, 11, 6, 6), 'hood1' : (17, 17, 0, 11, 11, 16), 'hood2' : (19, 19, 0, 11, 11, 16), 'hood3' : (17, 19, 0, 0, 11, 16), 'hood4' : (17, 19, 11, 11, 11, 16), 'hood5' : (17, 19, 0, 11, 16, 16), 'cookingPlate' : (17, 19, 7, 9, 6, 6), 'furniture' : (17, 19, 7, 9, 11, 11), } kitchen = vtki.MultiBlock() for key, extent in extents.items(): alg = vtk.vtkStructuredGridGeometryFilter() alg.SetInputDataObject(mesh) alg.SetExtent(extent) alg.Update() result = vtki.filters._get_output(alg) kitchen[key] = result return kitchen
[ "def", "download_kitchen", "(", "split", "=", "False", ")", ":", "mesh", "=", "_download_and_read", "(", "'kitchen.vtk'", ")", "if", "not", "split", ":", "return", "mesh", "extents", "=", "{", "'door'", ":", "(", "27", ",", "27", ",", "14", ",", "18", ...
Download structured grid of kitchen with velocity field. Use the ``split`` argument to extract all of the furniture in the kitchen.
[ "Download", "structured", "grid", "of", "kitchen", "with", "velocity", "field", ".", "Use", "the", "split", "argument", "to", "extract", "all", "of", "the", "furniture", "in", "the", "kitchen", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/downloads.py#L324-L358
236,434
vtkiorg/vtki
vtki/ipy_tools.py
InteractiveTool._get_scalar_names
def _get_scalar_names(self, limit=None): """Only give scalar options that have a varying range""" names = [] if limit == 'point': inpnames = list(self.input_dataset.point_arrays.keys()) elif limit == 'cell': inpnames = list(self.input_dataset.cell_arrays.keys()) else: inpnames = self.input_dataset.scalar_names for name in inpnames: arr = self.input_dataset.get_scalar(name) rng = self.input_dataset.get_data_range(name) if arr is not None and arr.size > 0 and (rng[1]-rng[0] > 0.0): names.append(name) try: self._last_scalars = names[0] except IndexError: pass return names
python
def _get_scalar_names(self, limit=None): names = [] if limit == 'point': inpnames = list(self.input_dataset.point_arrays.keys()) elif limit == 'cell': inpnames = list(self.input_dataset.cell_arrays.keys()) else: inpnames = self.input_dataset.scalar_names for name in inpnames: arr = self.input_dataset.get_scalar(name) rng = self.input_dataset.get_data_range(name) if arr is not None and arr.size > 0 and (rng[1]-rng[0] > 0.0): names.append(name) try: self._last_scalars = names[0] except IndexError: pass return names
[ "def", "_get_scalar_names", "(", "self", ",", "limit", "=", "None", ")", ":", "names", "=", "[", "]", "if", "limit", "==", "'point'", ":", "inpnames", "=", "list", "(", "self", ".", "input_dataset", ".", "point_arrays", ".", "keys", "(", ")", ")", "e...
Only give scalar options that have a varying range
[ "Only", "give", "scalar", "options", "that", "have", "a", "varying", "range" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/ipy_tools.py#L133-L151
236,435
vtkiorg/vtki
vtki/ipy_tools.py
InteractiveTool._initialize
def _initialize(self, show_bounds, reset_camera, outline): """Outlines the input dataset and sets up the scene""" self.plotter.subplot(*self.loc) if outline is None: self.plotter.add_mesh(self.input_dataset.outline_corners(), reset_camera=False, color=vtki.rcParams['outline_color'], loc=self.loc) elif outline: self.plotter.add_mesh(self.input_dataset.outline(), reset_camera=False, color=vtki.rcParams['outline_color'], loc=self.loc) # add the axis labels if show_bounds: self.plotter.show_bounds(reset_camera=False, loc=loc) if reset_camera: cpos = self.plotter.get_default_cam_pos() self.plotter.camera_position = cpos self.plotter.reset_camera() self.plotter.camera_set = False
python
def _initialize(self, show_bounds, reset_camera, outline): self.plotter.subplot(*self.loc) if outline is None: self.plotter.add_mesh(self.input_dataset.outline_corners(), reset_camera=False, color=vtki.rcParams['outline_color'], loc=self.loc) elif outline: self.plotter.add_mesh(self.input_dataset.outline(), reset_camera=False, color=vtki.rcParams['outline_color'], loc=self.loc) # add the axis labels if show_bounds: self.plotter.show_bounds(reset_camera=False, loc=loc) if reset_camera: cpos = self.plotter.get_default_cam_pos() self.plotter.camera_position = cpos self.plotter.reset_camera() self.plotter.camera_set = False
[ "def", "_initialize", "(", "self", ",", "show_bounds", ",", "reset_camera", ",", "outline", ")", ":", "self", ".", "plotter", ".", "subplot", "(", "*", "self", ".", "loc", ")", "if", "outline", "is", "None", ":", "self", ".", "plotter", ".", "add_mesh"...
Outlines the input dataset and sets up the scene
[ "Outlines", "the", "input", "dataset", "and", "sets", "up", "the", "scene" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/ipy_tools.py#L160-L178
236,436
vtkiorg/vtki
vtki/ipy_tools.py
InteractiveTool._update_plotting_params
def _update_plotting_params(self, **kwargs): """Some plotting parameters can be changed through the tool; this updataes those plotting parameters. """ scalars = kwargs.get('scalars', None) if scalars is not None: old = self.display_params['scalars'] self.display_params['scalars'] = scalars if old != scalars: self.plotter.subplot(*self.loc) self.plotter.remove_actor(self._data_to_update, reset_camera=False) self._need_to_update = True self.valid_range = self.input_dataset.get_data_range(scalars) # self.display_params['rng'] = self.valid_range cmap = kwargs.get('cmap', None) if cmap is not None: self.display_params['cmap'] = cmap
python
def _update_plotting_params(self, **kwargs): scalars = kwargs.get('scalars', None) if scalars is not None: old = self.display_params['scalars'] self.display_params['scalars'] = scalars if old != scalars: self.plotter.subplot(*self.loc) self.plotter.remove_actor(self._data_to_update, reset_camera=False) self._need_to_update = True self.valid_range = self.input_dataset.get_data_range(scalars) # self.display_params['rng'] = self.valid_range cmap = kwargs.get('cmap', None) if cmap is not None: self.display_params['cmap'] = cmap
[ "def", "_update_plotting_params", "(", "self", ",", "*", "*", "kwargs", ")", ":", "scalars", "=", "kwargs", ".", "get", "(", "'scalars'", ",", "None", ")", "if", "scalars", "is", "not", "None", ":", "old", "=", "self", ".", "display_params", "[", "'sca...
Some plotting parameters can be changed through the tool; this updataes those plotting parameters.
[ "Some", "plotting", "parameters", "can", "be", "changed", "through", "the", "tool", ";", "this", "updataes", "those", "plotting", "parameters", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/ipy_tools.py#L181-L197
236,437
vtkiorg/vtki
vtki/renderer.py
_remove_mapper_from_plotter
def _remove_mapper_from_plotter(plotter, actor, reset_camera): """removes this actor's mapper from the given plotter's _scalar_bar_mappers""" try: mapper = actor.GetMapper() except AttributeError: return for name in list(plotter._scalar_bar_mappers.keys()): try: plotter._scalar_bar_mappers[name].remove(mapper) except ValueError: pass if len(plotter._scalar_bar_mappers[name]) < 1: slot = plotter._scalar_bar_slot_lookup.pop(name) plotter._scalar_bar_mappers.pop(name) plotter._scalar_bar_ranges.pop(name) plotter.remove_actor(plotter._scalar_bar_actors.pop(name), reset_camera=reset_camera) plotter._scalar_bar_slots.add(slot) return
python
def _remove_mapper_from_plotter(plotter, actor, reset_camera): try: mapper = actor.GetMapper() except AttributeError: return for name in list(plotter._scalar_bar_mappers.keys()): try: plotter._scalar_bar_mappers[name].remove(mapper) except ValueError: pass if len(plotter._scalar_bar_mappers[name]) < 1: slot = plotter._scalar_bar_slot_lookup.pop(name) plotter._scalar_bar_mappers.pop(name) plotter._scalar_bar_ranges.pop(name) plotter.remove_actor(plotter._scalar_bar_actors.pop(name), reset_camera=reset_camera) plotter._scalar_bar_slots.add(slot) return
[ "def", "_remove_mapper_from_plotter", "(", "plotter", ",", "actor", ",", "reset_camera", ")", ":", "try", ":", "mapper", "=", "actor", ".", "GetMapper", "(", ")", "except", "AttributeError", ":", "return", "for", "name", "in", "list", "(", "plotter", ".", ...
removes this actor's mapper from the given plotter's _scalar_bar_mappers
[ "removes", "this", "actor", "s", "mapper", "from", "the", "given", "plotter", "s", "_scalar_bar_mappers" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L774-L791
236,438
vtkiorg/vtki
vtki/renderer.py
Renderer.add_axes_at_origin
def add_axes_at_origin(self): """ Add axes actor at origin Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor """ self.marker_actor = vtk.vtkAxesActor() # renderer = self.renderers[self.loc_to_index(loc)] self.AddActor(self.marker_actor) self.parent._actors[str(hex(id(self.marker_actor)))] = self.marker_actor return self.marker_actor
python
def add_axes_at_origin(self): self.marker_actor = vtk.vtkAxesActor() # renderer = self.renderers[self.loc_to_index(loc)] self.AddActor(self.marker_actor) self.parent._actors[str(hex(id(self.marker_actor)))] = self.marker_actor return self.marker_actor
[ "def", "add_axes_at_origin", "(", "self", ")", ":", "self", ".", "marker_actor", "=", "vtk", ".", "vtkAxesActor", "(", ")", "# renderer = self.renderers[self.loc_to_index(loc)]", "self", ".", "AddActor", "(", "self", ".", "marker_actor", ")", "self", ".", "parent"...
Add axes actor at origin Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor
[ "Add", "axes", "actor", "at", "origin" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L128-L141
236,439
vtkiorg/vtki
vtki/renderer.py
Renderer.remove_bounding_box
def remove_bounding_box(self): """ Removes bounding box """ if hasattr(self, '_box_object'): actor = self.bounding_box_actor self.bounding_box_actor = None del self._box_object self.remove_actor(actor, reset_camera=False)
python
def remove_bounding_box(self): if hasattr(self, '_box_object'): actor = self.bounding_box_actor self.bounding_box_actor = None del self._box_object self.remove_actor(actor, reset_camera=False)
[ "def", "remove_bounding_box", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_box_object'", ")", ":", "actor", "=", "self", ".", "bounding_box_actor", "self", ".", "bounding_box_actor", "=", "None", "del", "self", ".", "_box_object", "self", "."...
Removes bounding box
[ "Removes", "bounding", "box" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L433-L439
236,440
vtkiorg/vtki
vtki/renderer.py
Renderer.camera_position
def camera_position(self): """ Returns camera position of active render window """ return [self.camera.GetPosition(), self.camera.GetFocalPoint(), self.camera.GetViewUp()]
python
def camera_position(self): return [self.camera.GetPosition(), self.camera.GetFocalPoint(), self.camera.GetViewUp()]
[ "def", "camera_position", "(", "self", ")", ":", "return", "[", "self", ".", "camera", ".", "GetPosition", "(", ")", ",", "self", ".", "camera", ".", "GetFocalPoint", "(", ")", ",", "self", ".", "camera", ".", "GetViewUp", "(", ")", "]" ]
Returns camera position of active render window
[ "Returns", "camera", "position", "of", "active", "render", "window" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L499-L503
236,441
vtkiorg/vtki
vtki/renderer.py
Renderer.camera_position
def camera_position(self, camera_location): """ Set camera position of all active render windows """ if camera_location is None: return if isinstance(camera_location, str): camera_location = camera_location.lower() if camera_location == 'xy': self.view_xy() elif camera_location == 'xz': self.view_xz() elif camera_location == 'yz': self.view_yz() elif camera_location == 'yx': self.view_xy(True) elif camera_location == 'zx': self.view_xz(True) elif camera_location == 'zy': self.view_yz(True) return if isinstance(camera_location[0], (int, float)): return self.view_vector(camera_location) # everything is set explicitly self.camera.SetPosition(camera_location[0]) self.camera.SetFocalPoint(camera_location[1]) self.camera.SetViewUp(camera_location[2]) # reset clipping range self.ResetCameraClippingRange() self.camera_set = True
python
def camera_position(self, camera_location): if camera_location is None: return if isinstance(camera_location, str): camera_location = camera_location.lower() if camera_location == 'xy': self.view_xy() elif camera_location == 'xz': self.view_xz() elif camera_location == 'yz': self.view_yz() elif camera_location == 'yx': self.view_xy(True) elif camera_location == 'zx': self.view_xz(True) elif camera_location == 'zy': self.view_yz(True) return if isinstance(camera_location[0], (int, float)): return self.view_vector(camera_location) # everything is set explicitly self.camera.SetPosition(camera_location[0]) self.camera.SetFocalPoint(camera_location[1]) self.camera.SetViewUp(camera_location[2]) # reset clipping range self.ResetCameraClippingRange() self.camera_set = True
[ "def", "camera_position", "(", "self", ",", "camera_location", ")", ":", "if", "camera_location", "is", "None", ":", "return", "if", "isinstance", "(", "camera_location", ",", "str", ")", ":", "camera_location", "=", "camera_location", ".", "lower", "(", ")", ...
Set camera position of all active render windows
[ "Set", "camera", "position", "of", "all", "active", "render", "windows" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L506-L537
236,442
vtkiorg/vtki
vtki/renderer.py
Renderer.remove_actor
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Renderer. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed. """ name = None if isinstance(actor, str): name = actor keys = list(self._actors.keys()) names = [] for k in keys: if k.startswith('{}-'.format(name)): names.append(k) if len(names) > 0: self.remove_actor(names, reset_camera=reset_camera) try: actor = self._actors[name] except KeyError: # If actor of that name is not present then return success return False if isinstance(actor, collections.Iterable): success = False for a in actor: rv = self.remove_actor(a, reset_camera=reset_camera) if rv or success: success = True return success if actor is None: return False # First remove this actor's mapper from _scalar_bar_mappers _remove_mapper_from_plotter(self.parent, actor, False) self.RemoveActor(actor) if name is None: for k, v in self._actors.items(): if v == actor: name = k self._actors.pop(name, None) self.update_bounds_axes() if reset_camera: self.reset_camera() elif not self.camera_set and reset_camera is None: self.reset_camera() else: self.parent._render() return True
python
def remove_actor(self, actor, reset_camera=False): name = None if isinstance(actor, str): name = actor keys = list(self._actors.keys()) names = [] for k in keys: if k.startswith('{}-'.format(name)): names.append(k) if len(names) > 0: self.remove_actor(names, reset_camera=reset_camera) try: actor = self._actors[name] except KeyError: # If actor of that name is not present then return success return False if isinstance(actor, collections.Iterable): success = False for a in actor: rv = self.remove_actor(a, reset_camera=reset_camera) if rv or success: success = True return success if actor is None: return False # First remove this actor's mapper from _scalar_bar_mappers _remove_mapper_from_plotter(self.parent, actor, False) self.RemoveActor(actor) if name is None: for k, v in self._actors.items(): if v == actor: name = k self._actors.pop(name, None) self.update_bounds_axes() if reset_camera: self.reset_camera() elif not self.camera_set and reset_camera is None: self.reset_camera() else: self.parent._render() return True
[ "def", "remove_actor", "(", "self", ",", "actor", ",", "reset_camera", "=", "False", ")", ":", "name", "=", "None", "if", "isinstance", "(", "actor", ",", "str", ")", ":", "name", "=", "actor", "keys", "=", "list", "(", "self", ".", "_actors", ".", ...
Removes an actor from the Renderer. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed.
[ "Removes", "an", "actor", "from", "the", "Renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L544-L603
236,443
vtkiorg/vtki
vtki/renderer.py
Renderer.set_scale
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. """ if xscale is None: xscale = self.scale[0] if yscale is None: yscale = self.scale[1] if zscale is None: zscale = self.scale[2] self.scale = [xscale, yscale, zscale] # Update the camera's coordinate system transform = vtk.vtkTransform() transform.Scale(xscale, yscale, zscale) self.camera.SetModelTransformMatrix(transform.GetMatrix()) self.parent._render() if reset_camera: self.update_bounds_axes() self.reset_camera()
python
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): if xscale is None: xscale = self.scale[0] if yscale is None: yscale = self.scale[1] if zscale is None: zscale = self.scale[2] self.scale = [xscale, yscale, zscale] # Update the camera's coordinate system transform = vtk.vtkTransform() transform.Scale(xscale, yscale, zscale) self.camera.SetModelTransformMatrix(transform.GetMatrix()) self.parent._render() if reset_camera: self.update_bounds_axes() self.reset_camera()
[ "def", "set_scale", "(", "self", ",", "xscale", "=", "None", ",", "yscale", "=", "None", ",", "zscale", "=", "None", ",", "reset_camera", "=", "True", ")", ":", "if", "xscale", "is", "None", ":", "xscale", "=", "self", ".", "scale", "[", "0", "]", ...
Scale all the datasets in the scene. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one.
[ "Scale", "all", "the", "datasets", "in", "the", "scene", ".", "Scaling", "in", "performed", "independently", "on", "the", "X", "Y", "and", "Z", "axis", ".", "A", "scale", "of", "zero", "is", "illegal", "and", "will", "be", "replaced", "with", "one", "....
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L605-L626
236,444
vtkiorg/vtki
vtki/renderer.py
Renderer.bounds
def bounds(self): """ Bounds of all actors present in the rendering window """ the_bounds = [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf] def _update_bounds(bounds): def update_axis(ax): if bounds[ax*2] < the_bounds[ax*2]: the_bounds[ax*2] = bounds[ax*2] if bounds[ax*2+1] > the_bounds[ax*2+1]: the_bounds[ax*2+1] = bounds[ax*2+1] for ax in range(3): update_axis(ax) return for actor in self._actors.values(): if isinstance(actor, vtk.vtkCubeAxesActor): continue if ( hasattr(actor, 'GetBounds') and actor.GetBounds() is not None and id(actor) != id(self.bounding_box_actor)): _update_bounds(actor.GetBounds()) return the_bounds
python
def bounds(self): the_bounds = [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf] def _update_bounds(bounds): def update_axis(ax): if bounds[ax*2] < the_bounds[ax*2]: the_bounds[ax*2] = bounds[ax*2] if bounds[ax*2+1] > the_bounds[ax*2+1]: the_bounds[ax*2+1] = bounds[ax*2+1] for ax in range(3): update_axis(ax) return for actor in self._actors.values(): if isinstance(actor, vtk.vtkCubeAxesActor): continue if ( hasattr(actor, 'GetBounds') and actor.GetBounds() is not None and id(actor) != id(self.bounding_box_actor)): _update_bounds(actor.GetBounds()) return the_bounds
[ "def", "bounds", "(", "self", ")", ":", "the_bounds", "=", "[", "np", ".", "inf", ",", "-", "np", ".", "inf", ",", "np", ".", "inf", ",", "-", "np", ".", "inf", ",", "np", ".", "inf", ",", "-", "np", ".", "inf", "]", "def", "_update_bounds", ...
Bounds of all actors present in the rendering window
[ "Bounds", "of", "all", "actors", "present", "in", "the", "rendering", "window" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L629-L650
236,445
vtkiorg/vtki
vtki/renderer.py
Renderer.center
def center(self): """Center of the bounding box around all data present in the scene""" bounds = self.bounds x = (bounds[1] + bounds[0])/2 y = (bounds[3] + bounds[2])/2 z = (bounds[5] + bounds[4])/2 return [x, y, z]
python
def center(self): bounds = self.bounds x = (bounds[1] + bounds[0])/2 y = (bounds[3] + bounds[2])/2 z = (bounds[5] + bounds[4])/2 return [x, y, z]
[ "def", "center", "(", "self", ")", ":", "bounds", "=", "self", ".", "bounds", "x", "=", "(", "bounds", "[", "1", "]", "+", "bounds", "[", "0", "]", ")", "/", "2", "y", "=", "(", "bounds", "[", "3", "]", "+", "bounds", "[", "2", "]", ")", ...
Center of the bounding box around all data present in the scene
[ "Center", "of", "the", "bounding", "box", "around", "all", "data", "present", "in", "the", "scene" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L653-L659
236,446
vtkiorg/vtki
vtki/renderer.py
Renderer.get_default_cam_pos
def get_default_cam_pos(self): """ Returns the default focal points and viewup. Uses ResetCamera to make a useful view. """ focal_pt = self.center return [np.array(rcParams['camera']['position']) + np.array(focal_pt), focal_pt, rcParams['camera']['viewup']]
python
def get_default_cam_pos(self): focal_pt = self.center return [np.array(rcParams['camera']['position']) + np.array(focal_pt), focal_pt, rcParams['camera']['viewup']]
[ "def", "get_default_cam_pos", "(", "self", ")", ":", "focal_pt", "=", "self", ".", "center", "return", "[", "np", ".", "array", "(", "rcParams", "[", "'camera'", "]", "[", "'position'", "]", ")", "+", "np", ".", "array", "(", "focal_pt", ")", ",", "f...
Returns the default focal points and viewup. Uses ResetCamera to make a useful view.
[ "Returns", "the", "default", "focal", "points", "and", "viewup", ".", "Uses", "ResetCamera", "to", "make", "a", "useful", "view", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L661-L668
236,447
vtkiorg/vtki
vtki/renderer.py
Renderer.update_bounds_axes
def update_bounds_axes(self): """Update the bounds axes of the render window """ if (hasattr(self, '_box_object') and self._box_object is not None and self.bounding_box_actor is not None): if not np.allclose(self._box_object.bounds, self.bounds): color = self.bounding_box_actor.GetProperty().GetColor() self.remove_bounding_box() self.add_bounding_box(color=color) if hasattr(self, 'cube_axes_actor'): self.cube_axes_actor.SetBounds(self.bounds) if not np.allclose(self.scale, [1.0, 1.0, 1.0]): self.cube_axes_actor.SetUse2DMode(True) else: self.cube_axes_actor.SetUse2DMode(False)
python
def update_bounds_axes(self): if (hasattr(self, '_box_object') and self._box_object is not None and self.bounding_box_actor is not None): if not np.allclose(self._box_object.bounds, self.bounds): color = self.bounding_box_actor.GetProperty().GetColor() self.remove_bounding_box() self.add_bounding_box(color=color) if hasattr(self, 'cube_axes_actor'): self.cube_axes_actor.SetBounds(self.bounds) if not np.allclose(self.scale, [1.0, 1.0, 1.0]): self.cube_axes_actor.SetUse2DMode(True) else: self.cube_axes_actor.SetUse2DMode(False)
[ "def", "update_bounds_axes", "(", "self", ")", ":", "if", "(", "hasattr", "(", "self", ",", "'_box_object'", ")", "and", "self", ".", "_box_object", "is", "not", "None", "and", "self", ".", "bounding_box_actor", "is", "not", "None", ")", ":", "if", "not"...
Update the bounds axes of the render window
[ "Update", "the", "bounds", "axes", "of", "the", "render", "window" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L670-L683
236,448
vtkiorg/vtki
vtki/renderer.py
Renderer.view_isometric
def view_isometric(self): """ Resets the camera to a default isometric view showing all the actors in the scene. """ self.camera_position = self.get_default_cam_pos() self.camera_set = False return self.reset_camera()
python
def view_isometric(self): self.camera_position = self.get_default_cam_pos() self.camera_set = False return self.reset_camera()
[ "def", "view_isometric", "(", "self", ")", ":", "self", ".", "camera_position", "=", "self", ".", "get_default_cam_pos", "(", ")", "self", ".", "camera_set", "=", "False", "return", "self", ".", "reset_camera", "(", ")" ]
Resets the camera to a default isometric view showing all the actors in the scene.
[ "Resets", "the", "camera", "to", "a", "default", "isometric", "view", "showing", "all", "the", "actors", "in", "the", "scene", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L697-L704
236,449
vtkiorg/vtki
vtki/renderer.py
Renderer.view_vector
def view_vector(self, vector, viewup=None): """Point the camera in the direction of the given vector""" focal_pt = self.center if viewup is None: viewup = rcParams['camera']['viewup'] cpos = [vector + np.array(focal_pt), focal_pt, viewup] self.camera_position = cpos return self.reset_camera()
python
def view_vector(self, vector, viewup=None): focal_pt = self.center if viewup is None: viewup = rcParams['camera']['viewup'] cpos = [vector + np.array(focal_pt), focal_pt, viewup] self.camera_position = cpos return self.reset_camera()
[ "def", "view_vector", "(", "self", ",", "vector", ",", "viewup", "=", "None", ")", ":", "focal_pt", "=", "self", ".", "center", "if", "viewup", "is", "None", ":", "viewup", "=", "rcParams", "[", "'camera'", "]", "[", "'viewup'", "]", "cpos", "=", "["...
Point the camera in the direction of the given vector
[ "Point", "the", "camera", "in", "the", "direction", "of", "the", "given", "vector" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L706-L714
236,450
vtkiorg/vtki
vtki/renderer.py
Renderer.view_xy
def view_xy(self, negative=False): """View the XY plane""" vec = np.array([0,0,1]) viewup = np.array([0,1,0]) if negative: vec = np.array([0,0,-1]) return self.view_vector(vec, viewup)
python
def view_xy(self, negative=False): vec = np.array([0,0,1]) viewup = np.array([0,1,0]) if negative: vec = np.array([0,0,-1]) return self.view_vector(vec, viewup)
[ "def", "view_xy", "(", "self", ",", "negative", "=", "False", ")", ":", "vec", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "1", "]", ")", "viewup", "=", "np", ".", "array", "(", "[", "0", ",", "1", ",", "0", "]", ")", "if", "ne...
View the XY plane
[ "View", "the", "XY", "plane" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/renderer.py#L716-L722
236,451
vtkiorg/vtki
vtki/utilities.py
cell_scalar
def cell_scalar(mesh, name): """ Returns cell scalars of a vtk object """ vtkarr = mesh.GetCellData().GetArray(name) if vtkarr: if isinstance(vtkarr, vtk.vtkBitArray): vtkarr = vtk_bit_array_to_char(vtkarr) return vtk_to_numpy(vtkarr)
python
def cell_scalar(mesh, name): vtkarr = mesh.GetCellData().GetArray(name) if vtkarr: if isinstance(vtkarr, vtk.vtkBitArray): vtkarr = vtk_bit_array_to_char(vtkarr) return vtk_to_numpy(vtkarr)
[ "def", "cell_scalar", "(", "mesh", ",", "name", ")", ":", "vtkarr", "=", "mesh", ".", "GetCellData", "(", ")", ".", "GetArray", "(", "name", ")", "if", "vtkarr", ":", "if", "isinstance", "(", "vtkarr", ",", "vtk", ".", "vtkBitArray", ")", ":", "vtkar...
Returns cell scalars of a vtk object
[ "Returns", "cell", "scalars", "of", "a", "vtk", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L44-L50
236,452
vtkiorg/vtki
vtki/utilities.py
vtk_points
def vtk_points(points, deep=True): """ Convert numpy points to a vtkPoints object """ if not points.flags['C_CONTIGUOUS']: points = np.ascontiguousarray(points) vtkpts = vtk.vtkPoints() vtkpts.SetData(numpy_to_vtk(points, deep=deep)) return vtkpts
python
def vtk_points(points, deep=True): if not points.flags['C_CONTIGUOUS']: points = np.ascontiguousarray(points) vtkpts = vtk.vtkPoints() vtkpts.SetData(numpy_to_vtk(points, deep=deep)) return vtkpts
[ "def", "vtk_points", "(", "points", ",", "deep", "=", "True", ")", ":", "if", "not", "points", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ":", "points", "=", "np", ".", "ascontiguousarray", "(", "points", ")", "vtkpts", "=", "vtk", ".", "vtkPoints", "("...
Convert numpy points to a vtkPoints object
[ "Convert", "numpy", "points", "to", "a", "vtkPoints", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L109-L115
236,453
vtkiorg/vtki
vtki/utilities.py
lines_from_points
def lines_from_points(points): """ Generates line from points. Assumes points are ordered as line segments. Parameters ---------- points : np.ndarray Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) Returns ------- lines : vtki.PolyData PolyData with lines and cells. Examples -------- This example plots two line segments at right angles to each other line. >>> import vtki >>> import numpy as np >>> points = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) >>> lines = vtki.lines_from_points(points) >>> lines.plot() # doctest:+SKIP """ # Assuming ordered points, create array defining line order npoints = points.shape[0] - 1 lines = np.vstack((2 * np.ones(npoints, np.int), np.arange(npoints), np.arange(1, npoints + 1))).T.ravel() return vtki.PolyData(points, lines)
python
def lines_from_points(points): # Assuming ordered points, create array defining line order npoints = points.shape[0] - 1 lines = np.vstack((2 * np.ones(npoints, np.int), np.arange(npoints), np.arange(1, npoints + 1))).T.ravel() return vtki.PolyData(points, lines)
[ "def", "lines_from_points", "(", "points", ")", ":", "# Assuming ordered points, create array defining line order", "npoints", "=", "points", ".", "shape", "[", "0", "]", "-", "1", "lines", "=", "np", ".", "vstack", "(", "(", "2", "*", "np", ".", "ones", "("...
Generates line from points. Assumes points are ordered as line segments. Parameters ---------- points : np.ndarray Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) Returns ------- lines : vtki.PolyData PolyData with lines and cells. Examples -------- This example plots two line segments at right angles to each other line. >>> import vtki >>> import numpy as np >>> points = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) >>> lines = vtki.lines_from_points(points) >>> lines.plot() # doctest:+SKIP
[ "Generates", "line", "from", "points", ".", "Assumes", "points", "are", "ordered", "as", "line", "segments", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L118-L152
236,454
vtkiorg/vtki
vtki/utilities.py
vector_poly_data
def vector_poly_data(orig, vec): """ Creates a vtkPolyData object composed of vectors """ # shape, dimention checking if not isinstance(orig, np.ndarray): orig = np.asarray(orig) if not isinstance(vec, np.ndarray): vec = np.asarray(vec) if orig.ndim != 2: orig = orig.reshape((-1, 3)) elif orig.shape[1] != 3: raise Exception('orig array must be 3D') if vec.ndim != 2: vec = vec.reshape((-1, 3)) elif vec.shape[1] != 3: raise Exception('vec array must be 3D') # Create vtk points and cells objects vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(np.ascontiguousarray(orig), deep=True)) npts = orig.shape[0] cells = np.hstack((np.ones((npts, 1), 'int'), np.arange(npts).reshape((-1, 1)))) if cells.dtype != ctypes.c_int64 or cells.flags.c_contiguous: cells = np.ascontiguousarray(cells, ctypes.c_int64) cells = np.reshape(cells, (2*npts)) vcells = vtk.vtkCellArray() vcells.SetCells(npts, numpy_to_vtkIdTypeArray(cells, deep=True)) # Create vtkPolyData object pdata = vtk.vtkPolyData() pdata.SetPoints(vpts) pdata.SetVerts(vcells) # Add vectors to polydata name = 'vectors' vtkfloat = numpy_to_vtk(np.ascontiguousarray(vec), deep=True) vtkfloat.SetName(name) pdata.GetPointData().AddArray(vtkfloat) pdata.GetPointData().SetActiveVectors(name) # Add magnitude of vectors to polydata name = 'mag' scalars = (vec * vec).sum(1)**0.5 vtkfloat = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) vtkfloat.SetName(name) pdata.GetPointData().AddArray(vtkfloat) pdata.GetPointData().SetActiveScalars(name) return vtki.PolyData(pdata)
python
def vector_poly_data(orig, vec): # shape, dimention checking if not isinstance(orig, np.ndarray): orig = np.asarray(orig) if not isinstance(vec, np.ndarray): vec = np.asarray(vec) if orig.ndim != 2: orig = orig.reshape((-1, 3)) elif orig.shape[1] != 3: raise Exception('orig array must be 3D') if vec.ndim != 2: vec = vec.reshape((-1, 3)) elif vec.shape[1] != 3: raise Exception('vec array must be 3D') # Create vtk points and cells objects vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(np.ascontiguousarray(orig), deep=True)) npts = orig.shape[0] cells = np.hstack((np.ones((npts, 1), 'int'), np.arange(npts).reshape((-1, 1)))) if cells.dtype != ctypes.c_int64 or cells.flags.c_contiguous: cells = np.ascontiguousarray(cells, ctypes.c_int64) cells = np.reshape(cells, (2*npts)) vcells = vtk.vtkCellArray() vcells.SetCells(npts, numpy_to_vtkIdTypeArray(cells, deep=True)) # Create vtkPolyData object pdata = vtk.vtkPolyData() pdata.SetPoints(vpts) pdata.SetVerts(vcells) # Add vectors to polydata name = 'vectors' vtkfloat = numpy_to_vtk(np.ascontiguousarray(vec), deep=True) vtkfloat.SetName(name) pdata.GetPointData().AddArray(vtkfloat) pdata.GetPointData().SetActiveVectors(name) # Add magnitude of vectors to polydata name = 'mag' scalars = (vec * vec).sum(1)**0.5 vtkfloat = numpy_to_vtk(np.ascontiguousarray(scalars), deep=True) vtkfloat.SetName(name) pdata.GetPointData().AddArray(vtkfloat) pdata.GetPointData().SetActiveScalars(name) return vtki.PolyData(pdata)
[ "def", "vector_poly_data", "(", "orig", ",", "vec", ")", ":", "# shape, dimention checking", "if", "not", "isinstance", "(", "orig", ",", "np", ".", "ndarray", ")", ":", "orig", "=", "np", ".", "asarray", "(", "orig", ")", "if", "not", "isinstance", "(",...
Creates a vtkPolyData object composed of vectors
[ "Creates", "a", "vtkPolyData", "object", "composed", "of", "vectors" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L155-L209
236,455
vtkiorg/vtki
vtki/utilities.py
trans_from_matrix
def trans_from_matrix(matrix): """ Convert a vtk matrix to a numpy.ndarray """ t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
python
def trans_from_matrix(matrix): t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
[ "def", "trans_from_matrix", "(", "matrix", ")", ":", "t", "=", "np", ".", "zeros", "(", "(", "4", ",", "4", ")", ")", "for", "i", "in", "range", "(", "4", ")", ":", "for", "j", "in", "range", "(", "4", ")", ":", "t", "[", "i", ",", "j", "...
Convert a vtk matrix to a numpy.ndarray
[ "Convert", "a", "vtk", "matrix", "to", "a", "numpy", ".", "ndarray" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L212-L218
236,456
vtkiorg/vtki
vtki/utilities.py
wrap
def wrap(vtkdataset): """This is a convenience method to safely wrap any given VTK data object to its appropriate ``vtki`` data object. """ wrappers = { 'vtkUnstructuredGrid' : vtki.UnstructuredGrid, 'vtkRectilinearGrid' : vtki.RectilinearGrid, 'vtkStructuredGrid' : vtki.StructuredGrid, 'vtkPolyData' : vtki.PolyData, 'vtkImageData' : vtki.UniformGrid, 'vtkStructuredPoints' : vtki.UniformGrid, 'vtkMultiBlockDataSet' : vtki.MultiBlock, } key = vtkdataset.GetClassName() try: wrapped = wrappers[key](vtkdataset) except: logging.warning('VTK data type ({}) is not currently supported by vtki.'.format(key)) return vtkdataset # if not supported just passes the VTK data object return wrapped
python
def wrap(vtkdataset): wrappers = { 'vtkUnstructuredGrid' : vtki.UnstructuredGrid, 'vtkRectilinearGrid' : vtki.RectilinearGrid, 'vtkStructuredGrid' : vtki.StructuredGrid, 'vtkPolyData' : vtki.PolyData, 'vtkImageData' : vtki.UniformGrid, 'vtkStructuredPoints' : vtki.UniformGrid, 'vtkMultiBlockDataSet' : vtki.MultiBlock, } key = vtkdataset.GetClassName() try: wrapped = wrappers[key](vtkdataset) except: logging.warning('VTK data type ({}) is not currently supported by vtki.'.format(key)) return vtkdataset # if not supported just passes the VTK data object return wrapped
[ "def", "wrap", "(", "vtkdataset", ")", ":", "wrappers", "=", "{", "'vtkUnstructuredGrid'", ":", "vtki", ".", "UnstructuredGrid", ",", "'vtkRectilinearGrid'", ":", "vtki", ".", "RectilinearGrid", ",", "'vtkStructuredGrid'", ":", "vtki", ".", "StructuredGrid", ",", ...
This is a convenience method to safely wrap any given VTK data object to its appropriate ``vtki`` data object.
[ "This", "is", "a", "convenience", "method", "to", "safely", "wrap", "any", "given", "VTK", "data", "object", "to", "its", "appropriate", "vtki", "data", "object", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L221-L240
236,457
vtkiorg/vtki
vtki/utilities.py
image_to_texture
def image_to_texture(image): """Converts ``vtkImageData`` to a ``vtkTexture``""" vtex = vtk.vtkTexture() vtex.SetInputDataObject(image) vtex.Update() return vtex
python
def image_to_texture(image): vtex = vtk.vtkTexture() vtex.SetInputDataObject(image) vtex.Update() return vtex
[ "def", "image_to_texture", "(", "image", ")", ":", "vtex", "=", "vtk", ".", "vtkTexture", "(", ")", "vtex", ".", "SetInputDataObject", "(", "image", ")", "vtex", ".", "Update", "(", ")", "return", "vtex" ]
Converts ``vtkImageData`` to a ``vtkTexture``
[ "Converts", "vtkImageData", "to", "a", "vtkTexture" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L243-L248
236,458
vtkiorg/vtki
vtki/utilities.py
numpy_to_texture
def numpy_to_texture(image): """Convert a NumPy image array to a vtk.vtkTexture""" if not isinstance(image, np.ndarray): raise TypeError('Unknown input type ({})'.format(type(image))) if image.ndim != 3 or image.shape[2] != 3: raise AssertionError('Input image must be nn by nm by RGB') grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1)) grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F') grid.set_active_scalar('Image') return image_to_texture(grid)
python
def numpy_to_texture(image): if not isinstance(image, np.ndarray): raise TypeError('Unknown input type ({})'.format(type(image))) if image.ndim != 3 or image.shape[2] != 3: raise AssertionError('Input image must be nn by nm by RGB') grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1)) grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F') grid.set_active_scalar('Image') return image_to_texture(grid)
[ "def", "numpy_to_texture", "(", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Unknown input type ({})'", ".", "format", "(", "type", "(", "image", ")", ")", ")", "if", "image...
Convert a NumPy image array to a vtk.vtkTexture
[ "Convert", "a", "NumPy", "image", "array", "to", "a", "vtk", ".", "vtkTexture" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L251-L260
236,459
vtkiorg/vtki
vtki/utilities.py
is_inside_bounds
def is_inside_bounds(point, bounds): """ Checks if a point is inside a set of bounds. This is implemented through recursion so that this is N-dimensional. """ if isinstance(point, (int, float)): point = [point] if isinstance(point, collections.Iterable) and not isinstance(point, collections.deque): if len(bounds) < 2 * len(point) or len(bounds) % 2 != 0: raise AssertionError('Bounds mismatch point dimensionality') point = collections.deque(point) bounds = collections.deque(bounds) return is_inside_bounds(point, bounds) if not isinstance(point, collections.deque): raise TypeError('Unknown input data type ({}).'.format(type(point))) if len(point) < 1: return True p = point.popleft() lower, upper = bounds.popleft(), bounds.popleft() if lower <= p <= upper: return is_inside_bounds(point, bounds) return False
python
def is_inside_bounds(point, bounds): if isinstance(point, (int, float)): point = [point] if isinstance(point, collections.Iterable) and not isinstance(point, collections.deque): if len(bounds) < 2 * len(point) or len(bounds) % 2 != 0: raise AssertionError('Bounds mismatch point dimensionality') point = collections.deque(point) bounds = collections.deque(bounds) return is_inside_bounds(point, bounds) if not isinstance(point, collections.deque): raise TypeError('Unknown input data type ({}).'.format(type(point))) if len(point) < 1: return True p = point.popleft() lower, upper = bounds.popleft(), bounds.popleft() if lower <= p <= upper: return is_inside_bounds(point, bounds) return False
[ "def", "is_inside_bounds", "(", "point", ",", "bounds", ")", ":", "if", "isinstance", "(", "point", ",", "(", "int", ",", "float", ")", ")", ":", "point", "=", "[", "point", "]", "if", "isinstance", "(", "point", ",", "collections", ".", "Iterable", ...
Checks if a point is inside a set of bounds. This is implemented through recursion so that this is N-dimensional.
[ "Checks", "if", "a", "point", "is", "inside", "a", "set", "of", "bounds", ".", "This", "is", "implemented", "through", "recursion", "so", "that", "this", "is", "N", "-", "dimensional", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L263-L283
236,460
vtkiorg/vtki
vtki/utilities.py
fit_plane_to_points
def fit_plane_to_points(points, return_meta=False): """ Fits a plane to a set of points Parameters ---------- points : np.ndarray Size n by 3 array of points to fit a plane through return_meta : bool If true, also returns the center and normal used to generate the plane """ data = np.array(points) center = data.mean(axis=0) result = np.linalg.svd(data - center) normal = np.cross(result[2][0], result[2][1]) plane = vtki.Plane(center=center, direction=normal) if return_meta: return plane, center, normal return plane
python
def fit_plane_to_points(points, return_meta=False): data = np.array(points) center = data.mean(axis=0) result = np.linalg.svd(data - center) normal = np.cross(result[2][0], result[2][1]) plane = vtki.Plane(center=center, direction=normal) if return_meta: return plane, center, normal return plane
[ "def", "fit_plane_to_points", "(", "points", ",", "return_meta", "=", "False", ")", ":", "data", "=", "np", ".", "array", "(", "points", ")", "center", "=", "data", ".", "mean", "(", "axis", "=", "0", ")", "result", "=", "np", ".", "linalg", ".", "...
Fits a plane to a set of points Parameters ---------- points : np.ndarray Size n by 3 array of points to fit a plane through return_meta : bool If true, also returns the center and normal used to generate the plane
[ "Fits", "a", "plane", "to", "a", "set", "of", "points" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/utilities.py#L286-L305
236,461
vtkiorg/vtki
vtki/plotting.py
set_plot_theme
def set_plot_theme(theme): """Set the plotting parameters to a predefined theme""" if theme.lower() in ['paraview', 'pv']: rcParams['background'] = PV_BACKGROUND rcParams['cmap'] = 'coolwarm' rcParams['font']['family'] = 'arial' rcParams['font']['label_size'] = 16 rcParams['show_edges'] = False elif theme.lower() in ['document', 'doc', 'paper', 'report']: rcParams['background'] = 'white' rcParams['cmap'] = 'viridis' rcParams['font']['size'] = 18 rcParams['font']['title_size'] = 18 rcParams['font']['label_size'] = 18 rcParams['font']['color'] = 'black' rcParams['show_edges'] = False rcParams['color'] = 'tan' rcParams['outline_color'] = 'black' elif theme.lower() in ['night', 'dark']: rcParams['background'] = 'black' rcParams['cmap'] = 'viridis' rcParams['font']['color'] = 'white' rcParams['show_edges'] = False rcParams['color'] = 'tan' rcParams['outline_color'] = 'white' elif theme.lower() in ['default']: for k,v in DEFAULT_THEME.items(): rcParams[k] = v
python
def set_plot_theme(theme): if theme.lower() in ['paraview', 'pv']: rcParams['background'] = PV_BACKGROUND rcParams['cmap'] = 'coolwarm' rcParams['font']['family'] = 'arial' rcParams['font']['label_size'] = 16 rcParams['show_edges'] = False elif theme.lower() in ['document', 'doc', 'paper', 'report']: rcParams['background'] = 'white' rcParams['cmap'] = 'viridis' rcParams['font']['size'] = 18 rcParams['font']['title_size'] = 18 rcParams['font']['label_size'] = 18 rcParams['font']['color'] = 'black' rcParams['show_edges'] = False rcParams['color'] = 'tan' rcParams['outline_color'] = 'black' elif theme.lower() in ['night', 'dark']: rcParams['background'] = 'black' rcParams['cmap'] = 'viridis' rcParams['font']['color'] = 'white' rcParams['show_edges'] = False rcParams['color'] = 'tan' rcParams['outline_color'] = 'white' elif theme.lower() in ['default']: for k,v in DEFAULT_THEME.items(): rcParams[k] = v
[ "def", "set_plot_theme", "(", "theme", ")", ":", "if", "theme", ".", "lower", "(", ")", "in", "[", "'paraview'", ",", "'pv'", "]", ":", "rcParams", "[", "'background'", "]", "=", "PV_BACKGROUND", "rcParams", "[", "'cmap'", "]", "=", "'coolwarm'", "rcPara...
Set the plotting parameters to a predefined theme
[ "Set", "the", "plotting", "parameters", "to", "a", "predefined", "theme" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L85-L112
236,462
vtkiorg/vtki
vtki/plotting.py
plot
def plot(var_item, off_screen=None, full_screen=False, screenshot=None, interactive=True, cpos=None, window_size=None, show_bounds=False, show_axes=True, notebook=None, background=None, text='', return_img=False, eye_dome_lighting=False, use_panel=None, **kwargs): """ Convenience plotting function for a vtk or numpy object. Parameters ---------- item : vtk or numpy object VTK object or numpy array to be plotted. off_screen : bool Plots off screen when True. Helpful for saving screenshots without a window popping up. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. screenshot : str or bool, optional Saves screenshot to file when enabled. See: help(vtkinterface.Plotter.screenshot). Default disabled. When True, takes screenshot and returns numpy array of image. window_size : list, optional Window size in pixels. Defaults to [1024, 768] show_bounds : bool, optional Shows mesh bounds when True. Default False. Alias ``show_grid`` also accepted. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. show_axes : bool, optional Shows a vtk axes widget. Enabled by default. text : str, optional Adds text at the bottom of the plot. **kwargs : optional keyword arguments See help(Plotter.add_mesh) for additional options. Returns ------- cpos : list List of camera position, focal point, and view up. img : numpy.ndarray Array containing pixel RGB and alpha. Sized: [Window height x Window width x 3] for transparent_background=False [Window height x Window width x 4] for transparent_background=True Returned only when screenshot enabled """ if notebook is None: if run_from_ipython(): try: notebook = type(get_ipython()).__module__.startswith('ipykernel.') except NameError: pass if notebook: off_screen = notebook plotter = Plotter(off_screen=off_screen, notebook=notebook) if show_axes: plotter.add_axes() plotter.set_background(background) if isinstance(var_item, list): if len(var_item) == 2: # might be arrows isarr_0 = isinstance(var_item[0], np.ndarray) isarr_1 = isinstance(var_item[1], np.ndarray) if isarr_0 and isarr_1: plotter.add_arrows(var_item[0], var_item[1]) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: plotter.add_mesh(var_item, **kwargs) if text: plotter.add_text(text) if show_bounds or kwargs.get('show_grid', False): if kwargs.get('show_grid', False): plotter.show_grid() else: plotter.show_bounds() if cpos is None: cpos = plotter.get_default_cam_pos() plotter.camera_position = cpos plotter.camera_set = False else: plotter.camera_position = cpos if eye_dome_lighting: plotter.enable_eye_dome_lighting() result = plotter.show(window_size=window_size, auto_close=False, interactive=interactive, full_screen=full_screen, screenshot=screenshot, return_img=return_img, use_panel=use_panel) # close and return camera position and maybe image plotter.close() # Result will be handled by plotter.show(): cpos or [cpos, img] return result
python
def plot(var_item, off_screen=None, full_screen=False, screenshot=None, interactive=True, cpos=None, window_size=None, show_bounds=False, show_axes=True, notebook=None, background=None, text='', return_img=False, eye_dome_lighting=False, use_panel=None, **kwargs): if notebook is None: if run_from_ipython(): try: notebook = type(get_ipython()).__module__.startswith('ipykernel.') except NameError: pass if notebook: off_screen = notebook plotter = Plotter(off_screen=off_screen, notebook=notebook) if show_axes: plotter.add_axes() plotter.set_background(background) if isinstance(var_item, list): if len(var_item) == 2: # might be arrows isarr_0 = isinstance(var_item[0], np.ndarray) isarr_1 = isinstance(var_item[1], np.ndarray) if isarr_0 and isarr_1: plotter.add_arrows(var_item[0], var_item[1]) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: plotter.add_mesh(var_item, **kwargs) if text: plotter.add_text(text) if show_bounds or kwargs.get('show_grid', False): if kwargs.get('show_grid', False): plotter.show_grid() else: plotter.show_bounds() if cpos is None: cpos = plotter.get_default_cam_pos() plotter.camera_position = cpos plotter.camera_set = False else: plotter.camera_position = cpos if eye_dome_lighting: plotter.enable_eye_dome_lighting() result = plotter.show(window_size=window_size, auto_close=False, interactive=interactive, full_screen=full_screen, screenshot=screenshot, return_img=return_img, use_panel=use_panel) # close and return camera position and maybe image plotter.close() # Result will be handled by plotter.show(): cpos or [cpos, img] return result
[ "def", "plot", "(", "var_item", ",", "off_screen", "=", "None", ",", "full_screen", "=", "False", ",", "screenshot", "=", "None", ",", "interactive", "=", "True", ",", "cpos", "=", "None", ",", "window_size", "=", "None", ",", "show_bounds", "=", "False"...
Convenience plotting function for a vtk or numpy object. Parameters ---------- item : vtk or numpy object VTK object or numpy array to be plotted. off_screen : bool Plots off screen when True. Helpful for saving screenshots without a window popping up. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. screenshot : str or bool, optional Saves screenshot to file when enabled. See: help(vtkinterface.Plotter.screenshot). Default disabled. When True, takes screenshot and returns numpy array of image. window_size : list, optional Window size in pixels. Defaults to [1024, 768] show_bounds : bool, optional Shows mesh bounds when True. Default False. Alias ``show_grid`` also accepted. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. show_axes : bool, optional Shows a vtk axes widget. Enabled by default. text : str, optional Adds text at the bottom of the plot. **kwargs : optional keyword arguments See help(Plotter.add_mesh) for additional options. Returns ------- cpos : list List of camera position, focal point, and view up. img : numpy.ndarray Array containing pixel RGB and alpha. Sized: [Window height x Window width x 3] for transparent_background=False [Window height x Window width x 4] for transparent_background=True Returned only when screenshot enabled
[ "Convenience", "plotting", "function", "for", "a", "vtk", "or", "numpy", "object", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L140-L260
236,463
vtkiorg/vtki
vtki/plotting.py
system_supports_plotting
def system_supports_plotting(): """ Check if x server is running Returns ------- system_supports_plotting : bool True when on Linux and running an xserver. Returns None when on a non-linux platform. """ try: if os.environ['ALLOW_PLOTTING'].lower() == 'true': return True except KeyError: pass try: p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE) p.communicate() return p.returncode == 0 except: return False
python
def system_supports_plotting(): try: if os.environ['ALLOW_PLOTTING'].lower() == 'true': return True except KeyError: pass try: p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE) p.communicate() return p.returncode == 0 except: return False
[ "def", "system_supports_plotting", "(", ")", ":", "try", ":", "if", "os", ".", "environ", "[", "'ALLOW_PLOTTING'", "]", ".", "lower", "(", ")", "==", "'true'", ":", "return", "True", "except", "KeyError", ":", "pass", "try", ":", "p", "=", "Popen", "("...
Check if x server is running Returns ------- system_supports_plotting : bool True when on Linux and running an xserver. Returns None when on a non-linux platform.
[ "Check", "if", "x", "server", "is", "running" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L287-L308
236,464
vtkiorg/vtki
vtki/plotting.py
single_triangle
def single_triangle(): """ A single PolyData triangle """ points = np.zeros((3, 3)) points[1] = [1, 0, 0] points[2] = [0.5, 0.707, 0] cells = np.array([[3, 0, 1, 2]], ctypes.c_long) return vtki.PolyData(points, cells)
python
def single_triangle(): points = np.zeros((3, 3)) points[1] = [1, 0, 0] points[2] = [0.5, 0.707, 0] cells = np.array([[3, 0, 1, 2]], ctypes.c_long) return vtki.PolyData(points, cells)
[ "def", "single_triangle", "(", ")", ":", "points", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ")", ")", "points", "[", "1", "]", "=", "[", "1", ",", "0", ",", "0", "]", "points", "[", "2", "]", "=", "[", "0.5", ",", "0.707", ",", "...
A single PolyData triangle
[ "A", "single", "PolyData", "triangle" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2970-L2976
236,465
vtkiorg/vtki
vtki/plotting.py
parse_color
def parse_color(color): """ Parses color into a vtk friendly rgb list """ if color is None: color = rcParams['color'] if isinstance(color, str): return vtki.string_to_rgb(color) elif len(color) == 3: return color else: raise Exception(""" Invalid color input Must ba string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF'""")
python
def parse_color(color): if color is None: color = rcParams['color'] if isinstance(color, str): return vtki.string_to_rgb(color) elif len(color) == 3: return color else: raise Exception(""" Invalid color input Must ba string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF'""")
[ "def", "parse_color", "(", "color", ")", ":", "if", "color", "is", "None", ":", "color", "=", "rcParams", "[", "'color'", "]", "if", "isinstance", "(", "color", ",", "str", ")", ":", "return", "vtki", ".", "string_to_rgb", "(", "color", ")", "elif", ...
Parses color into a vtk friendly rgb list
[ "Parses", "color", "into", "a", "vtk", "friendly", "rgb", "list" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2979-L2994
236,466
vtkiorg/vtki
vtki/plotting.py
plot_compare_four
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None, plotter_kwargs=None, show_kwargs=None, screenshot=None, camera_position=None, outline=None, outline_color='k', labels=('A', 'B', 'C', 'D')): """Plot a 2 by 2 comparison of data objects. Plotting parameters and camera positions will all be the same. """ datasets = [[data_a, data_b], [data_c, data_d]] labels = [labels[0:2], labels[2:4]] if plotter_kwargs is None: plotter_kwargs = {} if disply_kwargs is None: disply_kwargs = {} if show_kwargs is None: show_kwargs = {} p = vtki.Plotter(shape=(2,2), **plotter_kwargs) for i in range(2): for j in range(2): p.subplot(i, j) p.add_mesh(datasets[i][j], **disply_kwargs) p.add_text(labels[i][j]) if is_vtki_obj(outline): p.add_mesh(outline, color=outline_color) if camera_position is not None: p.camera_position = camera_position return p.show(screenshot=screenshot, **show_kwargs)
python
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None, plotter_kwargs=None, show_kwargs=None, screenshot=None, camera_position=None, outline=None, outline_color='k', labels=('A', 'B', 'C', 'D')): datasets = [[data_a, data_b], [data_c, data_d]] labels = [labels[0:2], labels[2:4]] if plotter_kwargs is None: plotter_kwargs = {} if disply_kwargs is None: disply_kwargs = {} if show_kwargs is None: show_kwargs = {} p = vtki.Plotter(shape=(2,2), **plotter_kwargs) for i in range(2): for j in range(2): p.subplot(i, j) p.add_mesh(datasets[i][j], **disply_kwargs) p.add_text(labels[i][j]) if is_vtki_obj(outline): p.add_mesh(outline, color=outline_color) if camera_position is not None: p.camera_position = camera_position return p.show(screenshot=screenshot, **show_kwargs)
[ "def", "plot_compare_four", "(", "data_a", ",", "data_b", ",", "data_c", ",", "data_d", ",", "disply_kwargs", "=", "None", ",", "plotter_kwargs", "=", "None", ",", "show_kwargs", "=", "None", ",", "screenshot", "=", "None", ",", "camera_position", "=", "None...
Plot a 2 by 2 comparison of data objects. Plotting parameters and camera positions will all be the same.
[ "Plot", "a", "2", "by", "2", "comparison", "of", "data", "objects", ".", "Plotting", "parameters", "and", "camera", "positions", "will", "all", "be", "the", "same", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L3008-L3037
236,467
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_focus
def set_focus(self, point): """ sets focus to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetFocalPoint(point) self._render()
python
def set_focus(self, point): if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetFocalPoint(point) self._render()
[ "def", "set_focus", "(", "self", ",", "point", ")", ":", "if", "isinstance", "(", "point", ",", "np", ".", "ndarray", ")", ":", "if", "point", ".", "ndim", "!=", "1", ":", "point", "=", "point", ".", "ravel", "(", ")", "self", ".", "camera", ".",...
sets focus to a point
[ "sets", "focus", "to", "a", "point" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L480-L486
236,468
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_position
def set_position(self, point, reset=False): """ sets camera position to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetPosition(point) if reset: self.reset_camera() self.camera_set = True self._render()
python
def set_position(self, point, reset=False): if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetPosition(point) if reset: self.reset_camera() self.camera_set = True self._render()
[ "def", "set_position", "(", "self", ",", "point", ",", "reset", "=", "False", ")", ":", "if", "isinstance", "(", "point", ",", "np", ".", "ndarray", ")", ":", "if", "point", ".", "ndim", "!=", "1", ":", "point", "=", "point", ".", "ravel", "(", "...
sets camera position to a point
[ "sets", "camera", "position", "to", "a", "point" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L488-L497
236,469
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_viewup
def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render()
python
def set_viewup(self, vector): if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render()
[ "def", "set_viewup", "(", "self", ",", "vector", ")", ":", "if", "isinstance", "(", "vector", ",", "np", ".", "ndarray", ")", ":", "if", "vector", ".", "ndim", "!=", "1", ":", "vector", "=", "vector", ".", "ravel", "(", ")", "self", ".", "camera", ...
sets camera viewup vector
[ "sets", "camera", "viewup", "vector" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L499-L505
236,470
vtkiorg/vtki
vtki/plotting.py
BasePlotter._render
def _render(self): """ redraws render window if the render window exists """ if hasattr(self, 'ren_win'): if hasattr(self, 'render_trigger'): self.render_trigger.emit() elif not self._first_time: self.render()
python
def _render(self): if hasattr(self, 'ren_win'): if hasattr(self, 'render_trigger'): self.render_trigger.emit() elif not self._first_time: self.render()
[ "def", "_render", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'ren_win'", ")", ":", "if", "hasattr", "(", "self", ",", "'render_trigger'", ")", ":", "self", ".", "render_trigger", ".", "emit", "(", ")", "elif", "not", "self", ".", "_fi...
redraws render window if the render window exists
[ "redraws", "render", "window", "if", "the", "render", "window", "exists" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L507-L513
236,471
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_axes
def add_axes(self, interactive=None, color=None): """ Add an interactive axes widget """ if interactive is None: interactive = rcParams['interactive'] if hasattr(self, 'axes_widget'): self.axes_widget.SetInteractive(interactive) self._update_axes_color(color) return self.axes_actor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(self.axes_actor) if hasattr(self, 'iren'): self.axes_widget.SetInteractor(self.iren) self.axes_widget.SetEnabled(1) self.axes_widget.SetInteractive(interactive) # Set the color self._update_axes_color(color)
python
def add_axes(self, interactive=None, color=None): if interactive is None: interactive = rcParams['interactive'] if hasattr(self, 'axes_widget'): self.axes_widget.SetInteractive(interactive) self._update_axes_color(color) return self.axes_actor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(self.axes_actor) if hasattr(self, 'iren'): self.axes_widget.SetInteractor(self.iren) self.axes_widget.SetEnabled(1) self.axes_widget.SetInteractive(interactive) # Set the color self._update_axes_color(color)
[ "def", "add_axes", "(", "self", ",", "interactive", "=", "None", ",", "color", "=", "None", ")", ":", "if", "interactive", "is", "None", ":", "interactive", "=", "rcParams", "[", "'interactive'", "]", "if", "hasattr", "(", "self", ",", "'axes_widget'", "...
Add an interactive axes widget
[ "Add", "an", "interactive", "axes", "widget" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L515-L531
236,472
vtkiorg/vtki
vtki/plotting.py
BasePlotter.key_press_event
def key_press_event(self, obj, event): """ Listens for key press event """ key = self.iren.GetKeySym() log.debug('Key %s pressed' % key) if key == 'q': self.q_pressed = True # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) elif key == 'b': self.observer = self.iren.AddObserver('LeftButtonPressEvent', self.left_button_down) elif key == 'v': self.isometric_view_interactive()
python
def key_press_event(self, obj, event): key = self.iren.GetKeySym() log.debug('Key %s pressed' % key) if key == 'q': self.q_pressed = True # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) elif key == 'b': self.observer = self.iren.AddObserver('LeftButtonPressEvent', self.left_button_down) elif key == 'v': self.isometric_view_interactive()
[ "def", "key_press_event", "(", "self", ",", "obj", ",", "event", ")", ":", "key", "=", "self", ".", "iren", ".", "GetKeySym", "(", ")", "log", ".", "debug", "(", "'Key %s pressed'", "%", "key", ")", "if", "key", "==", "'q'", ":", "self", ".", "q_pr...
Listens for key press event
[ "Listens", "for", "key", "press", "event" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L545-L557
236,473
vtkiorg/vtki
vtki/plotting.py
BasePlotter.left_button_down
def left_button_down(self, obj, event_type): """Register the event for a left button down click""" # Get 2D click location on window click_pos = self.iren.GetEventPosition() # Get corresponding click location in the 3D plot picker = vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0
python
def left_button_down(self, obj, event_type): # Get 2D click location on window click_pos = self.iren.GetEventPosition() # Get corresponding click location in the 3D plot picker = vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0
[ "def", "left_button_down", "(", "self", ",", "obj", ",", "event_type", ")", ":", "# Get 2D click location on window", "click_pos", "=", "self", ".", "iren", ".", "GetEventPosition", "(", ")", "# Get corresponding click location in the 3D plot", "picker", "=", "vtk", "...
Register the event for a left button down click
[ "Register", "the", "event", "for", "a", "left", "button", "down", "click" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L559-L569
236,474
vtkiorg/vtki
vtki/plotting.py
BasePlotter.isometric_view_interactive
def isometric_view_interactive(self): """ sets the current interactive render window to isometric view """ interactor = self.iren.GetInteractorStyle() renderer = interactor.GetCurrentRenderer() renderer.view_isometric()
python
def isometric_view_interactive(self): interactor = self.iren.GetInteractorStyle() renderer = interactor.GetCurrentRenderer() renderer.view_isometric()
[ "def", "isometric_view_interactive", "(", "self", ")", ":", "interactor", "=", "self", ".", "iren", ".", "GetInteractorStyle", "(", ")", "renderer", "=", "interactor", ".", "GetCurrentRenderer", "(", ")", "renderer", ".", "view_isometric", "(", ")" ]
sets the current interactive render window to isometric view
[ "sets", "the", "current", "interactive", "render", "window", "to", "isometric", "view" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L571-L575
236,475
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update
def update(self, stime=1, force_redraw=True): """ Update window, redraw, process messages query Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call vtkRenderWindowInteractor.Render() immediately. """ if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if not hasattr(self, 'iren'): return update_rate = self.iren.GetDesiredUpdateRate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.CreateRepeatingTimer(stime) self.iren.Start() self.iren.DestroyTimer(self.right_timer_id) self._render() Plotter.last_update_time = curr_time else: if force_redraw: self.iren.Render()
python
def update(self, stime=1, force_redraw=True): if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if not hasattr(self, 'iren'): return update_rate = self.iren.GetDesiredUpdateRate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.CreateRepeatingTimer(stime) self.iren.Start() self.iren.DestroyTimer(self.right_timer_id) self._render() Plotter.last_update_time = curr_time else: if force_redraw: self.iren.Render()
[ "def", "update", "(", "self", ",", "stime", "=", "1", ",", "force_redraw", "=", "True", ")", ":", "if", "stime", "<=", "0", ":", "stime", "=", "1", "curr_time", "=", "time", ".", "time", "(", ")", "if", "Plotter", ".", "last_update_time", ">", "cur...
Update window, redraw, process messages query Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call vtkRenderWindowInteractor.Render() immediately.
[ "Update", "window", "redraw", "process", "messages", "query" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L577-L612
236,476
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update_scalar_bar_range
def update_scalar_bar_range(self, clim, name=None): """Update the value range of the active or named scalar bar. Parameters ---------- 2 item list The new range of scalar bar. Example: ``[-1, 2]``. name : str, optional The title of the scalar bar to update """ if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise RuntimeError('This plotter does not have an active mapper.') return self.mapper.SetScalarRange(*clim) # Use the name to find the desired actor def update_mapper(mapper): return mapper.SetScalarRange(*clim) try: for m in self._scalar_bar_mappers[name]: update_mapper(m) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return
python
def update_scalar_bar_range(self, clim, name=None): if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise RuntimeError('This plotter does not have an active mapper.') return self.mapper.SetScalarRange(*clim) # Use the name to find the desired actor def update_mapper(mapper): return mapper.SetScalarRange(*clim) try: for m in self._scalar_bar_mappers[name]: update_mapper(m) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return
[ "def", "update_scalar_bar_range", "(", "self", ",", "clim", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "clim", ",", "float", ")", "or", "isinstance", "(", "clim", ",", "int", ")", ":", "clim", "=", "[", "-", "clim", ",", "clim", "...
Update the value range of the active or named scalar bar. Parameters ---------- 2 item list The new range of scalar bar. Example: ``[-1, 2]``. name : str, optional The title of the scalar bar to update
[ "Update", "the", "value", "range", "of", "the", "active", "or", "named", "scalar", "bar", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1087-L1114
236,477
vtkiorg/vtki
vtki/plotting.py
BasePlotter.clear
def clear(self): """ Clears plot by removing all actors and properties """ for renderer in self.renderers: renderer.RemoveAllViewProps() self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} self._scalar_bar_actors = {} self._scalar_bar_widgets = {}
python
def clear(self): for renderer in self.renderers: renderer.RemoveAllViewProps() self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} self._scalar_bar_actors = {} self._scalar_bar_widgets = {}
[ "def", "clear", "(", "self", ")", ":", "for", "renderer", "in", "self", ".", "renderers", ":", "renderer", ".", "RemoveAllViewProps", "(", ")", "self", ".", "_scalar_bar_slots", "=", "set", "(", "range", "(", "MAX_N_COLOR_BARS", ")", ")", "self", ".", "_...
Clears plot by removing all actors and properties
[ "Clears", "plot", "by", "removing", "all", "actors", "and", "properties" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1150-L1159
236,478
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_actor
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed. """ for renderer in self.renderers: renderer.remove_actor(actor, reset_camera) return True
python
def remove_actor(self, actor, reset_camera=False): for renderer in self.renderers: renderer.remove_actor(actor, reset_camera) return True
[ "def", "remove_actor", "(", "self", ",", "actor", ",", "reset_camera", "=", "False", ")", ":", "for", "renderer", "in", "self", ".", "renderers", ":", "renderer", ".", "remove_actor", "(", "actor", ",", "reset_camera", ")", "return", "True" ]
Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed.
[ "Removes", "an", "actor", "from", "the", "Plotter", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1161-L1181
236,479
vtkiorg/vtki
vtki/plotting.py
BasePlotter.loc_to_index
def loc_to_index(self, loc): """ Return index of the render window given a location index. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- idx : int Index of the render window. """ if loc is None: return self._active_renderer_index elif isinstance(loc, int): return loc elif isinstance(loc, collections.Iterable): assert len(loc) == 2, '"loc" must contain two items' return loc[0]*self.shape[0] + loc[1]
python
def loc_to_index(self, loc): if loc is None: return self._active_renderer_index elif isinstance(loc, int): return loc elif isinstance(loc, collections.Iterable): assert len(loc) == 2, '"loc" must contain two items' return loc[0]*self.shape[0] + loc[1]
[ "def", "loc_to_index", "(", "self", ",", "loc", ")", ":", "if", "loc", "is", "None", ":", "return", "self", ".", "_active_renderer_index", "elif", "isinstance", "(", "loc", ",", "int", ")", ":", "return", "loc", "elif", "isinstance", "(", "loc", ",", "...
Return index of the render window given a location index. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- idx : int Index of the render window.
[ "Return", "index", "of", "the", "render", "window", "given", "a", "location", "index", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1222-L1244
236,480
vtkiorg/vtki
vtki/plotting.py
BasePlotter.index_to_loc
def index_to_loc(self, index): """Convert a 1D index location to the 2D location on the plotting grid """ sz = int(self.shape[0] * self.shape[1]) idxs = np.array([i for i in range(sz)], dtype=int).reshape(self.shape) args = np.argwhere(idxs == index) if len(args) < 1: raise RuntimeError('Index ({}) is out of range.') return args[0]
python
def index_to_loc(self, index): sz = int(self.shape[0] * self.shape[1]) idxs = np.array([i for i in range(sz)], dtype=int).reshape(self.shape) args = np.argwhere(idxs == index) if len(args) < 1: raise RuntimeError('Index ({}) is out of range.') return args[0]
[ "def", "index_to_loc", "(", "self", ",", "index", ")", ":", "sz", "=", "int", "(", "self", ".", "shape", "[", "0", "]", "*", "self", ".", "shape", "[", "1", "]", ")", "idxs", "=", "np", ".", "array", "(", "[", "i", "for", "i", "in", "range", ...
Convert a 1D index location to the 2D location on the plotting grid
[ "Convert", "a", "1D", "index", "location", "to", "the", "2D", "location", "on", "the", "plotting", "grid" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1246-L1254
236,481
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_axes_at_origin
def add_axes_at_origin(self, loc=None): """ Add axes actor at the origin of a render window. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. When None, defaults to the active render window. Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor """ self._active_renderer_index = self.loc_to_index(loc) return self.renderers[self._active_renderer_index].add_axes_at_origin()
python
def add_axes_at_origin(self, loc=None): self._active_renderer_index = self.loc_to_index(loc) return self.renderers[self._active_renderer_index].add_axes_at_origin()
[ "def", "add_axes_at_origin", "(", "self", ",", "loc", "=", "None", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "loc", ")", "return", "self", ".", "renderers", "[", "self", ".", "_active_renderer_index", "]", ".", ...
Add axes actor at the origin of a render window. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. When None, defaults to the active render window. Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor
[ "Add", "axes", "actor", "at", "the", "origin", "of", "a", "render", "window", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1262-L1279
236,482
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_bounding_box
def remove_bounding_box(self, loc=None): """ Removes bounding box from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounding_box()
python
def remove_bounding_box(self, loc=None): self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounding_box()
[ "def", "remove_bounding_box", "(", "self", ",", "loc", "=", "None", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "loc", ")", "renderer", "=", "self", ".", "renderers", "[", "self", ".", "_active_renderer_index", "]"...
Removes bounding box from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer.
[ "Removes", "bounding", "box", "from", "the", "active", "renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1460-L1473
236,483
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_bounds_axes
def remove_bounds_axes(self, loc=None): """ Removes bounds axes from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounds_axes()
python
def remove_bounds_axes(self, loc=None): self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounds_axes()
[ "def", "remove_bounds_axes", "(", "self", ",", "loc", "=", "None", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "loc", ")", "renderer", "=", "self", ".", "renderers", "[", "self", ".", "_active_renderer_index", "]",...
Removes bounds axes from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer.
[ "Removes", "bounds", "axes", "from", "the", "active", "renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1475-L1488
236,484
vtkiorg/vtki
vtki/plotting.py
BasePlotter.subplot
def subplot(self, index_x, index_y): """ Sets the active subplot. Parameters ---------- index_x : int Index of the subplot to activate in the x direction. index_y : int Index of the subplot to activate in the y direction. """ self._active_renderer_index = self.loc_to_index((index_x, index_y))
python
def subplot(self, index_x, index_y): self._active_renderer_index = self.loc_to_index((index_x, index_y))
[ "def", "subplot", "(", "self", ",", "index_x", ",", "index_y", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "(", "index_x", ",", "index_y", ")", ")" ]
Sets the active subplot. Parameters ---------- index_x : int Index of the subplot to activate in the x direction. index_y : int Index of the subplot to activate in the y direction.
[ "Sets", "the", "active", "subplot", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1490-L1503
236,485
vtkiorg/vtki
vtki/plotting.py
BasePlotter.show_grid
def show_grid(self, **kwargs): """ A wrapped implementation of ``show_bounds`` to change default behaviour to use gridlines and showing the axes labels on the outer edges. This is intended to be silimar to ``matplotlib``'s ``grid`` function. """ kwargs.setdefault('grid', 'back') kwargs.setdefault('location', 'outer') kwargs.setdefault('ticks', 'both') return self.show_bounds(**kwargs)
python
def show_grid(self, **kwargs): kwargs.setdefault('grid', 'back') kwargs.setdefault('location', 'outer') kwargs.setdefault('ticks', 'both') return self.show_bounds(**kwargs)
[ "def", "show_grid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'grid'", ",", "'back'", ")", "kwargs", ".", "setdefault", "(", "'location'", ",", "'outer'", ")", "kwargs", ".", "setdefault", "(", "'ticks'", ",", "...
A wrapped implementation of ``show_bounds`` to change default behaviour to use gridlines and showing the axes labels on the outer edges. This is intended to be silimar to ``matplotlib``'s ``grid`` function.
[ "A", "wrapped", "implementation", "of", "show_bounds", "to", "change", "default", "behaviour", "to", "use", "gridlines", "and", "showing", "the", "axes", "labels", "on", "the", "outer", "edges", ".", "This", "is", "intended", "to", "be", "silimar", "to", "ma...
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1505-L1515
236,486
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_scale
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater than zero. yscale : float, optional Scaling of the y axis. Must be greater than zero. zscale : float, optional Scaling of the z axis. Must be greater than zero. reset_camera : bool, optional Resets camera so all actors can be seen. """ self.renderer.set_scale(xscale, yscale, zscale, reset_camera)
python
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): self.renderer.set_scale(xscale, yscale, zscale, reset_camera)
[ "def", "set_scale", "(", "self", ",", "xscale", "=", "None", ",", "yscale", "=", "None", ",", "zscale", "=", "None", ",", "reset_camera", "=", "True", ")", ":", "self", ".", "renderer", ".", "set_scale", "(", "xscale", ",", "yscale", ",", "zscale", "...
Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater than zero. yscale : float, optional Scaling of the y axis. Must be greater than zero. zscale : float, optional Scaling of the z axis. Must be greater than zero. reset_camera : bool, optional Resets camera so all actors can be seen.
[ "Scale", "all", "the", "datasets", "in", "the", "scene", "of", "the", "active", "renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1517-L1539
236,487
vtkiorg/vtki
vtki/plotting.py
BasePlotter._update_axes_color
def _update_axes_color(self, color): """Internal helper to set the axes label color""" prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() prop_z = self.axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty() if color is None: color = rcParams['font']['color'] color = parse_color(color) for prop in [prop_x, prop_y, prop_z]: prop.SetColor(color[0], color[1], color[2]) prop.SetShadow(False) return
python
def _update_axes_color(self, color): prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() prop_z = self.axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty() if color is None: color = rcParams['font']['color'] color = parse_color(color) for prop in [prop_x, prop_y, prop_z]: prop.SetColor(color[0], color[1], color[2]) prop.SetShadow(False) return
[ "def", "_update_axes_color", "(", "self", ",", "color", ")", ":", "prop_x", "=", "self", ".", "axes_actor", ".", "GetXAxisCaptionActor2D", "(", ")", ".", "GetCaptionTextProperty", "(", ")", "prop_y", "=", "self", ".", "axes_actor", ".", "GetYAxisCaptionActor2D",...
Internal helper to set the axes label color
[ "Internal", "helper", "to", "set", "the", "axes", "label", "color" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1546-L1557
236,488
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update_scalars
def update_scalars(self, scalars, mesh=None, render=True): """ Updates scalars of the an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.Iterable, vtki.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.ren_win.Render() return if isinstance(scalars, str): # Grab scalar array if name given scalars = get_scalar(mesh, scalars) if scalars is None: if render: self.ren_win.Render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: _raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise Exception('No active scalars') s = VN.vtk_to_numpy(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalar array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.ren_win.Render()
python
def update_scalars(self, scalars, mesh=None, render=True): if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.Iterable, vtki.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.ren_win.Render() return if isinstance(scalars, str): # Grab scalar array if name given scalars = get_scalar(mesh, scalars) if scalars is None: if render: self.ren_win.Render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: _raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise Exception('No active scalars') s = VN.vtk_to_numpy(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalar array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.ren_win.Render()
[ "def", "update_scalars", "(", "self", ",", "scalars", ",", "mesh", "=", "None", ",", "render", "=", "True", ")", ":", "if", "mesh", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "if", "isinstance", "(", "mesh", ",", "(", "collections", ".", ...
Updates scalars of the an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True.
[ "Updates", "scalars", "of", "the", "an", "object", "in", "the", "plotter", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1809-L1867
236,489
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update_coordinates
def update_coordinates(self, points, mesh=None, render=True): """ Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh mesh.points = points if render: self._render()
python
def update_coordinates(self, points, mesh=None, render=True): if mesh is None: mesh = self.mesh mesh.points = points if render: self._render()
[ "def", "update_coordinates", "(", "self", ",", "points", ",", "mesh", "=", "None", ",", "render", "=", "True", ")", ":", "if", "mesh", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "mesh", ".", "points", "=", "points", "if", "render", ":", "...
Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True.
[ "Updates", "the", "points", "of", "the", "an", "object", "in", "the", "plotter", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1869-L1892
236,490
vtkiorg/vtki
vtki/plotting.py
BasePlotter.close
def close(self): """ closes render window """ # must close out axes marker if hasattr(self, 'axes_widget'): del self.axes_widget # reset scalar bar stuff self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win if hasattr(self, '_style'): del self._style if hasattr(self, 'iren'): self.iren.RemoveAllObservers() del self.iren if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass
python
def close(self): # must close out axes marker if hasattr(self, 'axes_widget'): del self.axes_widget # reset scalar bar stuff self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win if hasattr(self, '_style'): del self._style if hasattr(self, 'iren'): self.iren.RemoveAllObservers() del self.iren if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass
[ "def", "close", "(", "self", ")", ":", "# must close out axes marker", "if", "hasattr", "(", "self", ",", "'axes_widget'", ")", ":", "del", "self", ".", "axes_widget", "# reset scalar bar stuff", "self", ".", "_scalar_bar_slots", "=", "set", "(", "range", "(", ...
closes render window
[ "closes", "render", "window" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1894-L1925
236,491
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_text
def add_text(self, text, position=None, font_size=50, color=None, font=None, shadow=False, name=None, loc=None): """ Adds text to plot object in the top left corner by default Parameters ---------- text : str The text to add the the rendering position : tuple(float) Length 2 tuple of the pixelwise position to place the bottom left corner of the text box. Default is to find the top left corner of the renderering window and place text box up there. font : string, optional Font name may be courier, times, or arial shadow : bool, optional Adds a black shadow to the text. Defaults to False name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- textActor : vtk.vtkTextActor Text actor added to plot """ if font is None: font = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if color is None: color = rcParams['font']['color'] if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] self.textActor = vtk.vtkTextActor() self.textActor.SetPosition(position) self.textActor.GetTextProperty().SetFontSize(font_size) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONT_KEYS[font]) self.textActor.GetTextProperty().SetShadow(shadow) self.textActor.SetInput(text) self.add_actor(self.textActor, reset_camera=False, name=name, loc=loc) return self.textActor
python
def add_text(self, text, position=None, font_size=50, color=None, font=None, shadow=False, name=None, loc=None): if font is None: font = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if color is None: color = rcParams['font']['color'] if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] self.textActor = vtk.vtkTextActor() self.textActor.SetPosition(position) self.textActor.GetTextProperty().SetFontSize(font_size) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONT_KEYS[font]) self.textActor.GetTextProperty().SetShadow(shadow) self.textActor.SetInput(text) self.add_actor(self.textActor, reset_camera=False, name=name, loc=loc) return self.textActor
[ "def", "add_text", "(", "self", ",", "text", ",", "position", "=", "None", ",", "font_size", "=", "50", ",", "color", "=", "None", ",", "font", "=", "None", ",", "shadow", "=", "False", ",", "name", "=", "None", ",", "loc", "=", "None", ")", ":",...
Adds text to plot object in the top left corner by default Parameters ---------- text : str The text to add the the rendering position : tuple(float) Length 2 tuple of the pixelwise position to place the bottom left corner of the text box. Default is to find the top left corner of the renderering window and place text box up there. font : string, optional Font name may be courier, times, or arial shadow : bool, optional Adds a black shadow to the text. Defaults to False name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- textActor : vtk.vtkTextActor Text actor added to plot
[ "Adds", "text", "to", "plot", "object", "in", "the", "top", "left", "corner", "by", "default" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1927-L1984
236,492
vtkiorg/vtki
vtki/plotting.py
BasePlotter.open_movie
def open_movie(self, filename, framerate=24): """ Establishes a connection to the ffmpeg writer Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See "imagio.get_writer" framerate : int, optional Frames per second. """ if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self.mwriter = imageio.get_writer(filename, fps=framerate)
python
def open_movie(self, filename, framerate=24): if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self.mwriter = imageio.get_writer(filename, fps=framerate)
[ "def", "open_movie", "(", "self", ",", "filename", ",", "framerate", "=", "24", ")", ":", "if", "isinstance", "(", "vtki", ".", "FIGURE_PATH", ",", "str", ")", "and", "not", "os", ".", "path", ".", "isabs", "(", "filename", ")", ":", "filename", "=",...
Establishes a connection to the ffmpeg writer Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See "imagio.get_writer" framerate : int, optional Frames per second.
[ "Establishes", "a", "connection", "to", "the", "ffmpeg", "writer" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1986-L2002
236,493
vtkiorg/vtki
vtki/plotting.py
BasePlotter.open_gif
def open_gif(self, filename): """ Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in gif. """ if filename[-3:] != 'gif': raise Exception('Unsupported filetype. Must end in .gif') if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = imageio.get_writer(filename, mode='I')
python
def open_gif(self, filename): if filename[-3:] != 'gif': raise Exception('Unsupported filetype. Must end in .gif') if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = imageio.get_writer(filename, mode='I')
[ "def", "open_gif", "(", "self", ",", "filename", ")", ":", "if", "filename", "[", "-", "3", ":", "]", "!=", "'gif'", ":", "raise", "Exception", "(", "'Unsupported filetype. Must end in .gif'", ")", "if", "isinstance", "(", "vtki", ".", "FIGURE_PATH", ",", ...
Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in gif.
[ "Open", "a", "gif", "file", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2004-L2019
236,494
vtkiorg/vtki
vtki/plotting.py
BasePlotter.write_frame
def write_frame(self): """ Writes a single frame to the movie file """ if not hasattr(self, 'mwriter'): raise AssertionError('This plotter has not opened a movie or GIF file.') self.mwriter.append_data(self.image)
python
def write_frame(self): if not hasattr(self, 'mwriter'): raise AssertionError('This plotter has not opened a movie or GIF file.') self.mwriter.append_data(self.image)
[ "def", "write_frame", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'mwriter'", ")", ":", "raise", "AssertionError", "(", "'This plotter has not opened a movie or GIF file.'", ")", "self", ".", "mwriter", ".", "append_data", "(", "self", ".",...
Writes a single frame to the movie file
[ "Writes", "a", "single", "frame", "to", "the", "movie", "file" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2021-L2025
236,495
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_lines
def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): """ Adds lines to the plotting object. Parameters ---------- lines : np.ndarray or vtki.PolyData Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' width : float, optional Thickness of lines name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- actor : vtk.vtkActor Lines actor. """ if not isinstance(lines, np.ndarray): raise Exception('Input should be an array of point segments') lines = vtki.lines_from_points(lines) # Create mapper and add lines mapper = vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise AssertionError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor self.scalar_bar = vtk.vtkActor() self.scalar_bar.SetMapper(mapper) self.scalar_bar.GetProperty().SetLineWidth(width) self.scalar_bar.GetProperty().EdgeVisibilityOn() self.scalar_bar.GetProperty().SetEdgeColor(rgb_color) self.scalar_bar.GetProperty().SetColor(rgb_color) self.scalar_bar.GetProperty().LightingOff() # Add to renderer self.add_actor(self.scalar_bar, reset_camera=False, name=name) return self.scalar_bar
python
def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): if not isinstance(lines, np.ndarray): raise Exception('Input should be an array of point segments') lines = vtki.lines_from_points(lines) # Create mapper and add lines mapper = vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise AssertionError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor self.scalar_bar = vtk.vtkActor() self.scalar_bar.SetMapper(mapper) self.scalar_bar.GetProperty().SetLineWidth(width) self.scalar_bar.GetProperty().EdgeVisibilityOn() self.scalar_bar.GetProperty().SetEdgeColor(rgb_color) self.scalar_bar.GetProperty().SetColor(rgb_color) self.scalar_bar.GetProperty().LightingOff() # Add to renderer self.add_actor(self.scalar_bar, reset_camera=False, name=name) return self.scalar_bar
[ "def", "add_lines", "(", "self", ",", "lines", ",", "color", "=", "(", "1", ",", "1", ",", "1", ")", ",", "width", "=", "5", ",", "label", "=", "None", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "lines", ",", "np", "....
Adds lines to the plotting object. Parameters ---------- lines : np.ndarray or vtki.PolyData Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' width : float, optional Thickness of lines name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- actor : vtk.vtkActor Lines actor.
[ "Adds", "lines", "to", "the", "plotting", "object", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2081-L2142
236,496
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_scalar_bar
def remove_scalar_bar(self): """ Removes scalar bar """ if hasattr(self, 'scalar_bar'): self.remove_actor(self.scalar_bar, reset_camera=False)
python
def remove_scalar_bar(self): if hasattr(self, 'scalar_bar'): self.remove_actor(self.scalar_bar, reset_camera=False)
[ "def", "remove_scalar_bar", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'scalar_bar'", ")", ":", "self", ".", "remove_actor", "(", "self", ".", "scalar_bar", ",", "reset_camera", "=", "False", ")" ]
Removes scalar bar
[ "Removes", "scalar", "bar" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2144-L2147
236,497
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_point_labels
def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color='k', font_family=None, shadow=False, show_points=True, point_color='k', point_size=5, name=None): """ Creates a point actor with one label from list labels assigned to each point. Parameters ---------- points : np.ndarray n x 3 numpy array of points. labels : list List of labels. Must be the same length as points. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : string or 3 item list, optional, defaults to black Color of text. Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False show_points : bool, optional Controls if points are visible. Default True point_color : string or 3 item list, optional, defaults to black Color of points (if visible). Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' point_size : float, optional Size of points (if visible) name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- labelMapper : vtk.vtkvtkLabeledDataMapper VTK label mapper. Can be used to change properties of the labels. """ if font_family is None: font_family = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if len(points) != len(labels): raise Exception('There must be one label for each point') vtkpoints = vtki.PolyData(points) vtklabels = vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # create label mapper labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputData(vtkpoints) textprop = labelMapper.GetLabelTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName('labels') labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # add points if show_points: style = 'points' else: style = 'surface' self.add_mesh(vtkpoints, style=style, color=point_color, point_size=point_size) self.add_actor(labelActor, reset_camera=False, name=name) return labelMapper
python
def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color='k', font_family=None, shadow=False, show_points=True, point_color='k', point_size=5, name=None): if font_family is None: font_family = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if len(points) != len(labels): raise Exception('There must be one label for each point') vtkpoints = vtki.PolyData(points) vtklabels = vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # create label mapper labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputData(vtkpoints) textprop = labelMapper.GetLabelTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName('labels') labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # add points if show_points: style = 'points' else: style = 'surface' self.add_mesh(vtkpoints, style=style, color=point_color, point_size=point_size) self.add_actor(labelActor, reset_camera=False, name=name) return labelMapper
[ "def", "add_point_labels", "(", "self", ",", "points", ",", "labels", ",", "italic", "=", "False", ",", "bold", "=", "True", ",", "font_size", "=", "None", ",", "text_color", "=", "'k'", ",", "font_family", "=", "None", ",", "shadow", "=", "False", ","...
Creates a point actor with one label from list labels assigned to each point. Parameters ---------- points : np.ndarray n x 3 numpy array of points. labels : list List of labels. Must be the same length as points. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : string or 3 item list, optional, defaults to black Color of text. Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False show_points : bool, optional Controls if points are visible. Default True point_color : string or 3 item list, optional, defaults to black Color of points (if visible). Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' point_size : float, optional Size of points (if visible) name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- labelMapper : vtk.vtkvtkLabeledDataMapper VTK label mapper. Can be used to change properties of the labels.
[ "Creates", "a", "point", "actor", "with", "one", "label", "from", "list", "labels", "assigned", "to", "each", "point", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2149-L2257
236,498
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_arrows
def add_arrows(self, cent, direction, mag=1, **kwargs): """ Adds arrows to plotting object """ direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) direction[:,0] *= mag direction[:,1] *= mag direction[:,2] *= mag pdata = vtki.vector_poly_data(cent, direction) # Create arrow object arrow = vtk.vtkArrowSource() arrow.Update() glyph3D = vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs)
python
def add_arrows(self, cent, direction, mag=1, **kwargs): direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) direction[:,0] *= mag direction[:,1] *= mag direction[:,2] *= mag pdata = vtki.vector_poly_data(cent, direction) # Create arrow object arrow = vtk.vtkArrowSource() arrow.Update() glyph3D = vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs)
[ "def", "add_arrows", "(", "self", ",", "cent", ",", "direction", ",", "mag", "=", "1", ",", "*", "*", "kwargs", ")", ":", "direction", "=", "direction", ".", "copy", "(", ")", "if", "cent", ".", "ndim", "!=", "2", ":", "cent", "=", "cent", ".", ...
Adds arrows to plotting object
[ "Adds", "arrows", "to", "plotting", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2264-L2289
236,499
vtkiorg/vtki
vtki/plotting.py
BasePlotter._save_image
def _save_image(image, filename, return_img=None): """Internal helper for saving a NumPy image array""" if not image.size: raise Exception('Empty image. Have you run plot() first?') # write screenshot to file if isinstance(filename, str): if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) if not return_img: return imageio.imwrite(filename, image) imageio.imwrite(filename, image) return image
python
def _save_image(image, filename, return_img=None): if not image.size: raise Exception('Empty image. Have you run plot() first?') # write screenshot to file if isinstance(filename, str): if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) if not return_img: return imageio.imwrite(filename, image) imageio.imwrite(filename, image) return image
[ "def", "_save_image", "(", "image", ",", "filename", ",", "return_img", "=", "None", ")", ":", "if", "not", "image", ".", "size", ":", "raise", "Exception", "(", "'Empty image. Have you run plot() first?'", ")", "# write screenshot to file", "if", "isinstance", "...
Internal helper for saving a NumPy image array
[ "Internal", "helper", "for", "saving", "a", "NumPy", "image", "array" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2293-L2306