yt.funcs module¶
- exception yt.funcs.NoCUDAException[source]¶
Bases:
Exception
- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- 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.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 preferred 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_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.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:
- Returns:
hash – The hash of the file.
- Return type:
Examples
>>> from tempfile import NamedTemporaryFile >>> with NamedTemporaryFile() as file: ... get_hash(file.name) 'd41d8cd98f00b204e9800998ecf8427e'
- 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:
if name is None, the filename will be the keyword plus the suffix.
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.
if name does not end in the suffix, add the suffix.
- Parameters:
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.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.
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.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:
- 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='yt.default', after_reset=False)[source]¶
Returns a context manager for controlling matplotlib style.
Arguments are passed to matplotlib.style.context() if specified. Defaults to setting yt’s “yt.default” style, after resetting to the default config parameters.
- 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.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.rootonly(func)[source]¶
This is a decorator that, when used, will only call the function on the root processor.
This can be used like so:
@rootonly def some_root_only_function(*args, **kwargs): ...
- yt.funcs.setdefault_mpl_metadata(save_kwargs: dict[str, Any], name: str) None [source]¶
Set a default Software metadata entry for use with Matplotlib outputs.
- 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.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.validate_float(obj)[source]¶
Validates if the passed argument is a float value.
Raises an exception if obj is not 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