yt.funcs module

class yt.funcs.DummyProgressBar(*args, **kwargs)[source]

Bases: object

finish(*args, **kwargs)[source]
update(*args, **kwargs)[source]
exception yt.funcs.NoCUDAException[source]

Bases: Exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class yt.funcs.TqdmProgressBar(title, maxval)[source]

Bases: object

finish()[source]
update(i=None)[source]
class yt.funcs.YTEmptyClass[source]

Bases: object

yt.funcs.array_like_field(data, x, field)[source]
yt.funcs.bb_apicall(endpoint, data, use_pass=True)[source]
yt.funcs.camelcase_to_underscore(name)[source]
yt.funcs.compare_dicts(dict1, dict2)[source]
yt.funcs.dictWithFactory(factory: Callable[[Any], Any]) → Type[source]

Create a dictionary class with a default factory function. Contrary to collections.defaultdict, the factory takes the missing key as input parameter.

Parameters

factory (callable(key) -> value) – The factory to call when hitting a missing key

Returns

A class to create new dictionaries handling missing keys.

Return type

DictWithFactory class

yt.funcs.download_file(url, filename)[source]
yt.funcs.dummy_context_manager(*args, **kwargs)[source]
yt.funcs.enable_plugins(plugin_filename=None)[source]

Forces a plugin file to be parsed.

A plugin file is a means of creating custom fields, quantities, data objects, colormaps, and other code classes and objects to be used in yt scripts without modifying the yt source directly.

If plugin_filename is omitted, this function will look for a plugin file at $HOME/.config/yt/my_plugins.py, which is the prefered behaviour for a system-level configuration.

Warning: a script using this function will only be reproducible if your plugin file is shared with it.

yt.funcs.ensure_dir(path)[source]

Parallel safe directory maker.

yt.funcs.ensure_dir_exists(path)[source]

Create all directories in path recursively in a parallel safe manner

yt.funcs.ensure_numpy_array(obj)[source]

This function ensures that obj is a numpy array. Typically used to convert scalar, list or tuple argument passed to functions using Cython.

yt.funcs.fancy_download_file(url, filename, requests=None)[source]
yt.funcs.fix_axis(axis, ds)[source]
yt.funcs.fix_length(length, ds)[source]
yt.funcs.fix_unitary(u)[source]
yt.funcs.get_brewer_cmap(cmap)[source]

Returns a colorbrewer colormap from palettable

yt.funcs.get_git_version(path)[source]
yt.funcs.get_hash(infile, algorithm='md5', BLOCKSIZE=65536)[source]

Generate file hash without reading in the entire file at once.

Original code licensed under MIT. Source: https://www.pythoncentral.io/hashing-files-with-python/

Parameters
  • infile (str) – File of interest (including the path).

  • algorithm (str (optional)) – Hash algorithm of choice. Defaults to ‘md5’.

  • BLOCKSIZE (int (optional)) – How much data in bytes to read in at once.

Returns

hash – The hash of the file.

Return type

str

Examples

>>> from tempfile import NamedTemporaryFile
>>> with NamedTemporaryFile() as file:
...     get_hash(file.name)
'd41d8cd98f00b204e9800998ecf8427e'
yt.funcs.get_interactivity()[source]
yt.funcs.get_memory_usage(subtract_share=False)[source]

Returning resident size in megabytes

yt.funcs.get_num_threads()[source]
yt.funcs.get_output_filename(name, keyword, suffix)[source]

Return an appropriate filename for output.

With a name provided by the user, this will decide how to appropriately name the output file by the following rules:

  1. if name is None, the filename will be the keyword plus the suffix.

  2. if name ends with “/” (resp “" on Windows), assume name is a directory and the file will be named name/(keyword+suffix). If the directory does not exist, first try to create it and raise an exception if an error occurs.

  3. if name does not end in the suffix, add the suffix.

Parameters
  • name (str) – A filename given by the user.

  • keyword (str) – A default filename prefix if name is None.

  • suffix (str) – Suffix that must appear at end of the filename. This will be added if not present.

Examples

>>> get_output_filename(None, "Projection_x", ".png")
'Projection_x.png'
>>> get_output_filename("my_file", "Projection_x", ".png")
'my_file.png'
>>> get_output_filename("my_dir/", "Projection_x", ".png")
'my_dir/Projection_x.png'
yt.funcs.get_pbar(title, maxval)[source]

This returns a progressbar of the most appropriate type, given a title and a maxval.

yt.funcs.get_script_contents()[source]
yt.funcs.get_version_stack()[source]
yt.funcs.get_yt_version()[source]
yt.funcs.humanize_time(secs)[source]

Takes secs and returns a nicely formatted string

yt.funcs.insert_ipython(num_up=1)[source]

Placed inside a function, this will insert an IPython interpreter at that current location. This will enabled detailed inspection of the current execution environment, as well as (optional) modification of that environment. num_up refers to how many frames of the stack get stripped off, and defaults to 1 so that this function itself is stripped off.

yt.funcs.interactivity = False

Sets the condition that interactive backends can be used.

yt.funcs.is_root()[source]

This function returns True if it is on the root processor of the topcomm and False otherwise.

yt.funcs.is_sequence(obj)[source]

Grabbed from Python Cookbook / matplotlib.cbook. Returns true/false for

Parameters

obj (iterable) –

yt.funcs.iter_fields(field_or_fields)[source]

Create an iterator for field names, specified as single strings or tuples(fname, ftype) alike. This can safely be used in places where we accept a single field or a list as input.

Parameters

field_or_fields (str, tuple(str, str), or any iterable of the previous types.) –

Examples

>>> fields = ("gas", "density")
>>> for field in iter_fields(fields):
...     print(field)
density
>>> fields = ("gas", "density")
>>> for field in iter_fields(fields):
...     print(field)
('gas', 'density')
>>> fields = [("gas", "density"), ("gas", "temperature"), ("index", "dx")]
>>> for field in iter_fields(fields):
...     print(field)
density
temperature
('index', 'dx')
yt.funcs.just_one(obj)[source]
yt.funcs.levenshtein_distance(seq1, seq2, max_dist=None)[source]

Compute the levenshtein distance between seq1 and seq2. From https://stackabuse.com/levenshtein-distance-and-text-similarity-in-python/

Parameters
  • seq1 (str) –

  • seq2 (str) – The strings to compute the distance between

  • max_dist (integer) – If not None, maximum distance returned (see notes).

Returns

Return type

The Levenshtein distance as an integer.

Notes

This computes the Levenshtein distance, i.e. the number of edits to change seq1 into seq2. If a maximum distance is passed, the algorithm will stop as soon as the number of edits goes above the value. This allows for an earlier break and speeds calculations up.

yt.funcs.matplotlib_style_context(style_name=None, after_reset=False)[source]

Returns a context manager for controlling matplotlib style.

Arguments are passed to matplotlib.style.context() if specified. Defaults to setting “classic” style, after resetting to the default config parameters.

On older matplotlib versions (<=1.5.0) where matplotlib.style isn’t available, returns a dummy context manager.

yt.funcs.memory_checker(interval=15, dest=None)[source]

This is a context manager that monitors memory usage.

Parameters

interval (int) – The number of seconds between printing the current memory usage in gigabytes of the current Python interpreter.

Examples

>>> with memory_checker(10):
...     arr = np.zeros(1024 * 1024 * 1024, dtype="float64")
...     time.sleep(15)
...     del arr
MEMORY: -1.000e+00 gb
yt.funcs.obj_length(v)[source]
yt.funcs.only_on_root(func, *args, **kwargs)[source]

This function accepts a func, a set of args and kwargs and then only on the root processor calls the function. All other processors get “None” handed back.

yt.funcs.parallel_profile(prefix)[source]

A context manager for profiling parallel code execution using cProfile

This is a simple context manager that automatically profiles the execution of a snippet of code.

Parameters

prefix (string) – A string name to prefix outputs with.

Examples

>>> from yt import PhasePlot
>>> from yt.testing import fake_random_ds
>>> fields = ("density", "temperature", "cell_mass")
>>> units = ("g/cm**3", "K", "g")
>>> ds = fake_random_ds(16, fields=fields, units=units)
>>> with parallel_profile("my_profile"):
...     plot = PhasePlot(ds.all_data(), *fields)
yt.funcs.parse_h5_attr(f, attr)[source]

A Python3-safe function for getting hdf5 attributes.

If an attribute is supposed to be a string, this will return it as such.

yt.funcs.paste_traceback(exc_type, exc, tb)[source]

This is a traceback handler that knows how to paste to the pastebin. Should only be used in sys.excepthook.

yt.funcs.paste_traceback_detailed(exc_type, exc, tb)[source]

This is a traceback handler that knows how to paste to the pastebin. Should only be used in sys.excepthook.

yt.funcs.pdb_run(func)[source]

This decorator inserts a pdb session on top of the call-stack into a function.

This can be used like so:

>>> @pdb_run
... def some_function_to_debug(*args, **kwargs):
...     ...
yt.funcs.print_tb(func)[source]

This function is used as a decorate on a function to have the calling stack printed whenever that function is entered.

This can be used like so:

>>> @print_tb
... def some_deeply_nested_function(*args, **kwargs):
...     ...
yt.funcs.read_struct(f, fmt)[source]

This reads a struct, and only that struct, from an open file.

yt.funcs.rebuild_modules(path, f)[source]
yt.funcs.rootonly(func)[source]

This is a decorator that, when used, will only call the function on the root processor and then broadcast the results of the function to all other processors.

This can be used like so:

@rootonly
def some_root_only_function(*args, **kwargs):
    ...
yt.funcs.set_intersection(some_list)[source]
yt.funcs.setdefaultattr(obj, name, value)[source]

Set attribute with name on obj with value if it doesn’t exist yet

Analogous to dict.setdefault

yt.funcs.sglob(pattern)[source]

Return the results of a glob through the sorted() function.

yt.funcs.signal_ipython(signo, frame)[source]
yt.funcs.signal_print_traceback(signo, frame)[source]
yt.funcs.signal_problem(signo, frame)[source]
yt.funcs.simple_download_file(url, filename)[source]
yt.funcs.subchunk_count(n_total, chunk_size)[source]
yt.funcs.time_execution(func)[source]

Decorator for seeing how long a given function takes, depending on whether or not the global ‘yt.time_functions’ config parameter is set.

yt.funcs.toggle_interactivity()[source]
yt.funcs.update_git(path)[source]
yt.funcs.validate_3d_array(obj)[source]
yt.funcs.validate_axis(ds, axis)[source]
yt.funcs.validate_center(center)[source]
yt.funcs.validate_float(obj)[source]

Validates if the passed argument is a float value.

Raises an exception if obj is a single float value or a YTQuantity of size 1.

Parameters

obj (Any) – Any argument which needs to be checked for a single float value.

Raises

TypeError – Raised if obj is not a single float value or YTQunatity

Examples

>>> validate_float(1)
>>> validate_float(1.50)
>>> validate_float(YTQuantity(1, "cm"))
>>> validate_float((1, "cm"))
>>> validate_float([1, 1, 1])
Traceback (most recent call last):
...
TypeError: Expected a numeric value (or size-1 array), received 'list' of length 3
>>> validate_float([YTQuantity(1, "cm"), YTQuantity(2, "cm")])
Traceback (most recent call last):
...
TypeError: Expected a numeric value (or size-1 array), received 'list' of length 2
yt.funcs.validate_object(obj, data_type)[source]
yt.funcs.validate_sequence(obj)[source]
yt.funcs.validate_width_tuple(width)[source]