gurudesh/pytracebugs huggingface dataset:
# Buggy code
def can_add(self, dist):
    filename, ext = os.path.splitext(os.path.basename(dist.location))
    if ext.lower() != ".whl":
        # This supports resolving pex's own vendored distributions which are vendored in directory
        # directory with the project name (`pip/` for pip) and not the corresponding wheel name
        # (`pip-19.3.1-py2.py3-none-any.whl/` for pip). Pex only vendors universal wheels for all
        # platforms it supports at buildtime and runtime so this is always safe.
        return True

    try:
        wheel_name_, wheel_raw_version_, wheel_tags = filename.split("-", 2)
    except ValueError:
        return False

    if self._supported_tags.isdisjoint(tags.parse_tag(wheel_tags)):
        return False

    python_requires = dist_metadata.requires_python(dist)
    if not python_requires:
        return True

    return self._interpreter.identity.version_str in python_requires


# Traceback (ValueError)
(nwpy-ml-clustering_linux-x86-64_cp3.7) app@8bceeea547ee:/srv/nerdwallet/nwpy-ml-clustering$ ./build/nwpy-ml-clustering.pex
Traceback (most recent call last):
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/pex.py", line 391, in execute
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/pex.py", line 89, in _activate
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/environment.py", line 232, in activate
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/environment.py", line 375, in _activate
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/environment.py", line 209, in _update_candidate_distributions
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/environment.py", line 227, in can_add
File "/srv/nerdwallet/nwpy-ml-clustering/build/nwpy-ml-clustering.pex/.bootstrap/pex/vendor/_vendored/packaging/packaging/tags.py", line 75, in parse_tag
ValueError: too many values to unpack (expected 3)

# Fixed code
def can_add(self, dist):
    filename, ext = os.path.splitext(os.path.basename(dist.location))
    if ext.lower() != ".whl":
        # This supports resolving pex's own vendored distributions which are vendored in directory
        # directory with the project name (`pip/` for pip) and not the corresponding wheel name
        # (`pip-19.3.1-py2.py3-none-any.whl/` for pip). Pex only vendors universal wheels for all
        # platforms it supports at buildtime and runtime so this is always safe.
        return True

    # Wheel filename format: https://www.python.org/dev/peps/pep-0427/#file-name-convention
    # `{distribution}-{version}(-{build tag})?-{python tag}-{abi tag}-{platform tag}.whl`
    wheel_tags = "-".join(
        filename.split("-")[-3:]
    )  # `{python tag}-{abi tag}-{platform tag}`
    if self._supported_tags.isdisjoint(tags.parse_tag(wheel_tags)):
        return False

    python_requires = dist_metadata.requires_python(dist)
    if not python_requires:
        return True

    return self._interpreter.identity.version_str in python_requires
# Buggy code
def force_local(cls, pex, pex_info):
    if pex_info.code_hash is None:
        # Do not support force_local if code_hash is not set. (It should always be set.)
        return pex
    explode_dir = os.path.join(pex_info.zip_unsafe_cache, pex_info.code_hash)
    TRACER.log("PEX is not zip safe, exploding to %s" % explode_dir)
    if not os.path.exists(explode_dir):
        explode_tmp = explode_dir + "." + uuid.uuid4().hex
        with TRACER.timed("Unzipping %s" % pex):
            try:
                safe_mkdir(explode_tmp)
                with open_zip(pex) as pex_zip:
                    pex_files = (
                        x
                        for x in pex_zip.namelist()
                        if not x.startswith(pex_builder.BOOTSTRAP_DIR)
                        and not x.startswith(PexInfo.INTERNAL_CACHE)
                    )
                    pex_zip.extractall(explode_tmp, pex_files)
            except:  # noqa: T803
                safe_rmtree(explode_tmp)
                raise
        TRACER.log("Renaming %s to %s" % (explode_tmp, explode_dir))
        rename_if_empty(explode_tmp, explode_dir)
    return explode_dir


# Traceback (AttributeError)
Traceback (most recent call last):
File ".bootstrap/_pex/pex.py", line 364, in execute
File ".bootstrap/_pex/pex.py", line 90, in _activate
File ".bootstrap/_pex/environment.py", line 147, in activate
File ".bootstrap/_pex/environment.py", line 198, in _activate
File ".bootstrap/_pex/environment.py", line 64, in update_module_paths
AttributeError: '_NamespacePath' object has no attribute 'insert'

# Fixed code
def force_local(cls, pex_file, pex_info):
    if pex_info.code_hash is None:
        # Do not support force_local if code_hash is not set. (It should always be set.)
        return pex_file
    explode_dir = os.path.join(pex_info.zip_unsafe_cache, pex_info.code_hash)
    TRACER.log("PEX is not zip safe, exploding to %s" % explode_dir)
    if not os.path.exists(explode_dir):
        explode_tmp = explode_dir + "." + uuid.uuid4().hex
        with TRACER.timed("Unzipping %s" % pex_file):
            try:
                safe_mkdir(explode_tmp)
                with open_zip(pex_file) as pex_zip:
                    pex_files = (
                        x
                        for x in pex_zip.namelist()
                        if not x.startswith(pex_builder.BOOTSTRAP_DIR)
                        and not x.startswith(PexInfo.INTERNAL_CACHE)
                    )
                    pex_zip.extractall(explode_tmp, pex_files)
            except:  # noqa: T803
                safe_rmtree(explode_tmp)
                raise
        TRACER.log("Renaming %s to %s" % (explode_tmp, explode_dir))
        rename_if_empty(explode_tmp, explode_dir)
    return explode_dir
# Buggy code
def __init__(self, pex, pex_info, interpreter=None, **kw):
    self._internal_cache = os.path.join(pex, pex_info.internal_cache)
    self._pex = pex
    self._pex_info = pex_info
    self._activated = False
    self._working_set = None
    self._interpreter = interpreter or PythonInterpreter.get()
    self._inherit_path = pex_info.inherit_path
    self._supported_tags = []

    platform = Platform.current()
    platform_name = platform.platform
    super(PEXEnvironment, self).__init__(
        search_path=[] if pex_info.inherit_path == "false" else sys.path,
        # NB: Our pkg_resources.Environment base-class wants the platform name string and not the
        # pex.platform.Platform object.
        platform=platform_name,
        **kw,
    )
    self._target_interpreter_env = self._interpreter.identity.pkg_resources_env(
        platform_name
    )
    self._supported_tags.extend(platform.supported_tags(self._interpreter))
    TRACER.log(
        "E: tags for %r x %r -> %s"
        % (self.platform, self._interpreter, self._supported_tags),
        V=9,
    )


# Traceback (AttributeError)
Traceback (most recent call last):
File ".bootstrap/_pex/pex.py", line 364, in execute
File ".bootstrap/_pex/pex.py", line 90, in _activate
File ".bootstrap/_pex/environment.py", line 147, in activate
File ".bootstrap/_pex/environment.py", line 198, in _activate
File ".bootstrap/_pex/environment.py", line 64, in update_module_paths
AttributeError: '_NamespacePath' object has no attribute 'insert'

# Fixed code
def __init__(self, delegate):
    self._delegate = delegate
# Buggy code
def update_module_paths(cls, new_code_path):
    # Force subsequent imports to come from the .pex directory rather than the .pex file.
    TRACER.log("Adding to the head of sys.path: %s" % new_code_path)
    sys.path.insert(0, new_code_path)
    for name, module in sys.modules.items():
        if hasattr(module, "__path__"):
            module_dir = os.path.join(new_code_path, *name.split("."))
            TRACER.log(
                "Adding to the head of %s.__path__: %s" % (module.__name__, module_dir)
            )
            module.__path__.insert(0, module_dir)


# Traceback (AttributeError)
Traceback (most recent call last):
File ".bootstrap/_pex/pex.py", line 364, in execute
File ".bootstrap/_pex/pex.py", line 90, in _activate
File ".bootstrap/_pex/environment.py", line 147, in activate
File ".bootstrap/_pex/environment.py", line 198, in _activate
File ".bootstrap/_pex/environment.py", line 64, in update_module_paths
AttributeError: '_NamespacePath' object has no attribute 'insert'

# Fixed code
def update_module_paths(cls, new_code_path):
    # Force subsequent imports to come from the .pex directory rather than the .pex file.
    TRACER.log("Adding to the head of sys.path: %s" % new_code_path)
    sys.path.insert(0, new_code_path)
    for name, module in sys.modules.items():
        if hasattr(module, "__path__"):
            module_dir = os.path.join(new_code_path, *name.split("."))
            TRACER.log(
                "Adding to the head of %s.__path__: %s" % (module.__name__, module_dir)
            )
            try:
                module.__path__.insert(0, module_dir)
            except AttributeError:
                # TODO: This is a temporary bandaid for an unhandled AttributeError which results
                # in a startup crash. See https://github.com/pantsbuild/pex/issues/598 for more info.
                TRACER.log(
                    "Failed to insert %s: %s.__path__ of type %s does not support insertion!"
                    % (module_dir, module.__name__, type(module.__path__))
                )
# Buggy code
def open_zip(path, *args, **kwargs):
    """A contextmanager for zip files.  Passes through positional and kwargs to zipfile.ZipFile."""
    with contextlib.closing(zipfile.ZipFile(path, *args, **kwargs)) as zip:
        yield zip


# Traceback (RuntimeError)
$ pex torch numpy -- test.py
Traceback (most recent call last):
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.bootstrap/_pex/pex.py", line 367, in execute
self._wrap_coverage(self._wrap_profiling, self._execute)
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.bootstrap/_pex/pex.py", line 293, in _wrap_coverage
runner(*args)
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.bootstrap/_pex/pex.py", line 325, in _wrap_profiling
runner(*args)
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.bootstrap/_pex/pex.py", line 413, in _execute
return self.execute_interpreter()
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.bootstrap/_pex/pex.py", line 423, in execute_interpreter
self.execute_content(name, content)
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.bootstrap/_pex/pex.py", line 453, in execute_content
exec_function(ast, globals())
File "<exec_function>", line 4, in exec_function
File "test_dl.py", line 18, in <module>
for item in train_loader:
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.deps/torch-0.4.0-cp27-none-macosx_10_6_x86_64.whl/torch/utils/data/dataloader.py", line 286, in __next__
return self._process_next_batch(batch)
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.deps/torch-0.4.0-cp27-none-macosx_10_6_x86_64.whl/torch/utils/data/dataloader.py", line 307, in _process_next_batch
raise batch.exc_type(batch.exc_msg)
RuntimeError: Traceback (most recent call last):
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.deps/torch-0.4.0-cp27-none-macosx_10_6_x86_64.whl/torch/utils/data/dataloader.py", line 57, in _worker_loop
samples = collate_fn([dataset[i] for i in batch_indices])
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.deps/torch-0.4.0-cp27-none-macosx_10_6_x86_64.whl/torch/utils/data/dataloader.py", line 113, in default_collate
storage = batch[0].storage()._new_shared(numel)
File "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.deps/torch-0.4.0-cp27-none-macosx_10_6_x86_64.whl/torch/storage.py", line 114, in _new_shared
return cls._new_using_filename(size)
RuntimeError: error executing torch_shm_manager at "/private/var/folders/b5/hgpy98310bg_g3hfqngl759m0000gn/T/tmpxYzeas/.deps/torch-0.4.0-cp27-none-macosx_10_6_x86_64.whl/torch/lib/torch_shm_manager" at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/libshm/core.cpp:125

# Fixed code
def open_zip(path, *args, **kwargs):
    """A contextmanager for zip files.  Passes through positional and kwargs to zipfile.ZipFile."""
    with contextlib.closing(PermPreservingZipFile(path, *args, **kwargs)) as zip:
        yield zip
# Buggy code
def cache_distribution(cls, zf, source, target_dir):
    """Possibly cache an egg from within a zipfile into target_cache.

    Given a zipfile handle and a filename corresponding to an egg distribution within
    that zip, maybe write to the target cache and return a Distribution."""
    dependency_basename = os.path.basename(source)
    if not os.path.exists(target_dir):
        target_dir_tmp = target_dir + "." + uuid.uuid4().hex
        for name in zf.namelist():
            if name.startswith(source) and not name.endswith("/"):
                # strip off prefix + '/'
                target_name = os.path.join(dependency_basename, name[len(source) + 1 :])
                with contextlib.closing(zf.open(name)) as zi:
                    with safe_open(
                        os.path.join(target_dir_tmp, target_name), "wb"
                    ) as fp:
                        shutil.copyfileobj(zi, fp)
        try:
            os.rename(target_dir_tmp, target_dir)
        except OSError as e:
            if e.errno == errno.ENOTEMPTY:
                safe_rmtree(target_dir_tmp)
            else:
                raise

    dist = DistributionHelper.distribution_from_path(target_dir)
    assert dist is not None, "Failed to cache distribution %s" % source
    return dist


# Traceback (OSError)
Traceback (most recent call last):
File ".bootstrap/_pex/pex.py", line 309, in execute
File ".bootstrap/_pex/pex.py", line 78, in _activate
File ".bootstrap/_pex/environment.py", line 132, in activate
File ".bootstrap/_pex/environment.py", line 176, in _activate
File ".bootstrap/_pex/environment.py", line 121, in update_candidate_distributions
File ".bootstrap/_pex/environment.py", line 107, in load_internal_cache
File ".bootstrap/_pex/environment.py", line 95, in write_zipped_internal_cache
File ".bootstrap/_pex/util.py", line 177, in cache_distribution
OSError: [Errno 17] File exists

# Fixed code
def cache_distribution(cls, zf, source, target_dir):
    """Possibly cache an egg from within a zipfile into target_cache.

    Given a zipfile handle and a filename corresponding to an egg distribution within
    that zip, maybe write to the target cache and return a Distribution."""
    dependency_basename = os.path.basename(source)
    if not os.path.exists(target_dir):
        target_dir_tmp = target_dir + "." + uuid.uuid4().hex
        for name in zf.namelist():
            if name.startswith(source) and not name.endswith("/"):
                # strip off prefix + '/'
                target_name = os.path.join(dependency_basename, name[len(source) + 1 :])
                with contextlib.closing(zf.open(name)) as zi:
                    with safe_open(
                        os.path.join(target_dir_tmp, target_name), "wb"
                    ) as fp:
                        shutil.copyfileobj(zi, fp)

        rename_if_empty(target_dir_tmp, target_dir)

    dist = DistributionHelper.distribution_from_path(target_dir)
    assert dist is not None, "Failed to cache distribution %s" % source
    return dist
# Buggy code
def process_disable_cache(option, option_str, option_value, parser):
    setattr(parser.values, option.dest, [])


# Traceback (AttributeError)
Traceback (most recent call last):
File ".tox/package/bin/pex", line 11, in <module>
sys.exit(main())
File ".../lib/python3.4/site-packages/pex/bin/pex.py", line 533, in main
options.cache_dir = make_relative_to_root(options.cache_dir)
File ".../.tox/package/lib/python3.4/site-packages/pex/bin/pex.py", line 514, in make_relative_to_root
return os.path.normpath(path.format(pex_root=ENV.PEX_ROOT))
AttributeError: 'list' object has no attribute 'format'

# Fixed code
def process_disable_cache(option, option_str, option_value, parser):
    setattr(parser.values, option.dest, None)
# Buggy code
def deserialize(collection, topological=True):
    """
    Load a collection from file system.

    :param collection: The collection type the deserialize
    :param topological: If the dict/list should be sorted or not.
    :type topological: bool
    """

    datastruct = deserialize_raw(collection.collection_types())
    if topological and type(datastruct) == list:
        # FIXME
        # datastruct.sort(key=__depth_cmp)
        pass
    if type(datastruct) == dict:
        collection.from_dict(datastruct)
    elif type(datastruct) == list:
        collection.from_list(datastruct)


# Traceback (cobbler.cexceptions.CX)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/manager.py", line 185, in deserialize
serializer.deserialize(collection)
File "/usr/local/lib/python3.7/dist-packages/cobbler/serializer.py", line 124, in deserialize
storage_module.deserialize(collection, topological)
File "/usr/local/lib/python3.7/dist-packages/cobbler/modules/serializers/file.py", line 187, in deserialize
collection.from_list(datastruct)
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/collection.py", line 179, in from_list
self.add(item)
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/collection.py", line 299, in add
ref.check_if_valid()
File "/usr/local/lib/python3.7/dist-packages/cobbler/items/profile.py", line 126, in check_if_valid
raise CX("Error with profile %s - distro is required" % (self.name))
cobbler.cexceptions.CX: 'Error with profile testSP - distro is required'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/bin/cobblerd", line 75, in main
api = cobbler_api.CobblerAPI(is_cobblerd=True)
File "/usr/local/lib/python3.7/dist-packages/cobbler/api.py", line 109, in __init__
self.deserialize()
File "/usr/local/lib/python3.7/dist-packages/cobbler/api.py", line 893, in deserialize
return self._collection_mgr.deserialize()
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/manager.py", line 187, in deserialize
raise CX("serializer: error loading collection %s: %s. Check /etc/cobbler/modules.conf" % (collection.collection_type(), e))
cobbler.cexceptions.CX: "serializer: error loading collection profile: 'Error with profile testSP - distro is required'. Check /etc/cobbler/modules.conf"

# Fixed code
def deserialize(collection, topological=True):
    """
    Load a collection from file system.

    :param collection: The collection to deserialize.
    :param topological: If the collection list should be sorted by the
                        collection dict depth value or not.
    :type topological: bool
    """

    datastruct = deserialize_raw(collection.collection_types())
    if topological and type(datastruct) == list:
        datastruct.sort(key=lambda x: x["depth"])
    if type(datastruct) == dict:
        collection.from_dict(datastruct)
    elif type(datastruct) == list:
        collection.from_list(datastruct)
# Buggy code
def deserialize(collection, topological=True):
    """
    Load a collection from the database.

    :param collection: The collection to deserialize.
    :param topological: This sorts the returned dict.
    :type topological: bool
    """

    datastruct = deserialize_raw(collection.collection_type())
    if topological and type(datastruct) == list:
        datastruct.sort(__depth_cmp)
    if type(datastruct) == dict:
        collection.from_dict(datastruct)
    elif type(datastruct) == list:
        collection.from_list(datastruct)


# Traceback (cobbler.cexceptions.CX)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/manager.py", line 185, in deserialize
serializer.deserialize(collection)
File "/usr/local/lib/python3.7/dist-packages/cobbler/serializer.py", line 124, in deserialize
storage_module.deserialize(collection, topological)
File "/usr/local/lib/python3.7/dist-packages/cobbler/modules/serializers/file.py", line 187, in deserialize
collection.from_list(datastruct)
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/collection.py", line 179, in from_list
self.add(item)
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/collection.py", line 299, in add
ref.check_if_valid()
File "/usr/local/lib/python3.7/dist-packages/cobbler/items/profile.py", line 126, in check_if_valid
raise CX("Error with profile %s - distro is required" % (self.name))
cobbler.cexceptions.CX: 'Error with profile testSP - distro is required'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/bin/cobblerd", line 75, in main
api = cobbler_api.CobblerAPI(is_cobblerd=True)
File "/usr/local/lib/python3.7/dist-packages/cobbler/api.py", line 109, in __init__
self.deserialize()
File "/usr/local/lib/python3.7/dist-packages/cobbler/api.py", line 893, in deserialize
return self._collection_mgr.deserialize()
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/manager.py", line 187, in deserialize
raise CX("serializer: error loading collection %s: %s. Check /etc/cobbler/modules.conf" % (collection.collection_type(), e))
cobbler.cexceptions.CX: "serializer: error loading collection profile: 'Error with profile testSP - distro is required'. Check /etc/cobbler/modules.conf"

# Fixed code
def deserialize(collection, topological=True):
    """
    Load a collection from the database.

    :param collection: The collection to deserialize.
    :param topological: If the collection list should be sorted by the
                        collection dict depth value or not.
    :type topological: bool
    """

    datastruct = deserialize_raw(collection.collection_type())
    if topological and type(datastruct) == list:
        datastruct.sort(key=lambda x: x["depth"])
    if type(datastruct) == dict:
        collection.from_dict(datastruct)
    elif type(datastruct) == list:
        collection.from_list(datastruct)
# Buggy code
def deserialize(collection, topological=True):
    """
    Load a collection from disk.

    :param collection: The Cobbler collection to know the type of the item.
    :param topological: Unkown parameter.
    :type topological: bool
    """
    __grab_lock()
    storage_module = __get_storage_module(collection.collection_type())
    storage_module.deserialize(collection, topological)
    __release_lock()


# Traceback (cobbler.cexceptions.CX)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/manager.py", line 185, in deserialize
serializer.deserialize(collection)
File "/usr/local/lib/python3.7/dist-packages/cobbler/serializer.py", line 124, in deserialize
storage_module.deserialize(collection, topological)
File "/usr/local/lib/python3.7/dist-packages/cobbler/modules/serializers/file.py", line 187, in deserialize
collection.from_list(datastruct)
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/collection.py", line 179, in from_list
self.add(item)
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/collection.py", line 299, in add
ref.check_if_valid()
File "/usr/local/lib/python3.7/dist-packages/cobbler/items/profile.py", line 126, in check_if_valid
raise CX("Error with profile %s - distro is required" % (self.name))
cobbler.cexceptions.CX: 'Error with profile testSP - distro is required'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/bin/cobblerd", line 75, in main
api = cobbler_api.CobblerAPI(is_cobblerd=True)
File "/usr/local/lib/python3.7/dist-packages/cobbler/api.py", line 109, in __init__
self.deserialize()
File "/usr/local/lib/python3.7/dist-packages/cobbler/api.py", line 893, in deserialize
return self._collection_mgr.deserialize()
File "/usr/local/lib/python3.7/dist-packages/cobbler/cobbler_collections/manager.py", line 187, in deserialize
raise CX("serializer: error loading collection %s: %s. Check /etc/cobbler/modules.conf" % (collection.collection_type(), e))
cobbler.cexceptions.CX: "serializer: error loading collection profile: 'Error with profile testSP - distro is required'. Check /etc/cobbler/modules.conf"

# Fixed code
def deserialize(collection, topological=True):
    """
    Load a collection from disk.

    :param collection: The Cobbler collection to know the type of the item.
    :param topological: Sort collection based on each items' depth attribute
                        in the list of collection items.  This ensures
                        properly ordered object loading from disk with
                        objects having parent/child relationships, i.e.
                        profiles/subprofiles.  See cobbler/items/item.py
    :type topological: bool
    """
    __grab_lock()
    storage_module = __get_storage_module(collection.collection_type())
    storage_module.deserialize(collection, topological)
    __release_lock()
# Buggy code
def heats(diagrams, sampling, step_size, sigma):
    heats_ = np.zeros((diagrams.shape[0], sampling.shape[0], sampling.shape[0]))

    diagrams[diagrams < sampling[0, 0]] = sampling[0, 0]
    diagrams[diagrams > sampling[-1, 0]] = sampling[-1, 0]
    diagrams = np.array((diagrams - sampling[0, 0]) / step_size, dtype=int)

    [_heat(heats_[i], sampled_diag, sigma) for i, sampled_diag in enumerate(diagrams)]

    heats_ = heats_ - np.transpose(heats_, (0, 2, 1))
    heats_ = np.rot90(heats_, k=1, axes=(1, 2))
    return heats_


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def heats(diagrams, sampling, step_size, sigma):
    # WARNING: modifies `diagrams` in place
    heats_ = np.zeros((len(diagrams), len(sampling), len(sampling)), dtype=float)
    # If the step size is zero, we return a trivial image
    if step_size == 0:
        return heats_

    # Set the values outside of the sampling range
    first_sampling, last_sampling = sampling[0, 0, 0], sampling[-1, 0, 0]
    diagrams[diagrams < first_sampling] = first_sampling
    diagrams[diagrams > last_sampling] = last_sampling

    # Calculate the value of `sigma` in pixel units
    sigma_pixel = sigma / step_size

    for i, diagram in enumerate(diagrams):
        nontrivial_points_idx = np.flatnonzero(diagram[:, 1] != diagram[:, 0])
        diagram_nontrivial_pixel_coords = np.array(
            (diagram - first_sampling) / step_size, dtype=int
        )[nontrivial_points_idx]
        image = heats_[i]
        _sample_image(image, diagram_nontrivial_pixel_coords)
        gaussian_filter(image, sigma_pixel, mode="constant", output=image)

    heats_ -= np.transpose(heats_, (0, 2, 1))
    heats_ /= step_size**2
    heats_ = np.rot90(heats_, k=1, axes=(1, 2))
    return heats_
# Buggy code
def silhouettes(diagrams, sampling, power, **kwargs):
    """Input: a batch of persistence diagrams with a sampling (3d array
    returned by _bin) of a one-dimensional range.
    """
    sampling = np.transpose(sampling, axes=(1, 2, 0))
    weights = np.diff(diagrams, axis=2)[:, :, [0]]
    if power > 8.0:
        weights = weights / np.max(weights, axis=1, keepdims=True)
    weights = weights**power
    total_weights = np.sum(weights, axis=1)
    midpoints = (diagrams[:, :, [1]] + diagrams[:, :, [0]]) / 2.0
    heights = (diagrams[:, :, [1]] - diagrams[:, :, [0]]) / 2.0
    fibers = np.maximum(-np.abs(sampling - midpoints) + heights, 0)
    fibers_weighted_sum = np.sum(weights * fibers, axis=1) / total_weights
    return fibers_weighted_sum


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def silhouettes(diagrams, sampling, power, **kwargs):
    """Input: a batch of persistence diagrams with a sampling (3d array
    returned by _bin) of a one-dimensional range.
    """
    sampling = np.transpose(sampling, axes=(1, 2, 0))
    weights = np.diff(diagrams, axis=2)
    if power > 8.0:
        weights = weights / np.max(weights, axis=1, keepdims=True)
    weights = weights**power
    total_weights = np.sum(weights, axis=1)
    # Next line is a trick to avoid NaNs when computing `fibers_weighted_sum`
    total_weights[total_weights == 0.0] = np.inf
    midpoints = (diagrams[:, :, [1]] + diagrams[:, :, [0]]) / 2.0
    heights = (diagrams[:, :, [1]] - diagrams[:, :, [0]]) / 2.0
    fibers = np.maximum(-np.abs(sampling - midpoints) + heights, 0)
    fibers_weighted_sum = np.sum(weights * fibers, axis=1) / total_weights
    return fibers_weighted_sum
# Buggy code
def betti_distances(diagrams_1, diagrams_2, sampling, step_size, p=2.0, **kwargs):
    betti_curves_1 = betti_curves(diagrams_1, sampling)
    if np.array_equal(diagrams_1, diagrams_2):
        unnorm_dist = squareform(pdist(betti_curves_1, "minkowski", p=p))
        return (step_size ** (1 / p)) * unnorm_dist
    betti_curves_2 = betti_curves(diagrams_2, sampling)
    unnorm_dist = cdist(betti_curves_1, betti_curves_2, "minkowski", p=p)
    return (step_size ** (1 / p)) * unnorm_dist


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def betti_distances(diagrams_1, diagrams_2, sampling, step_size, p=2.0, **kwargs):
    step_size_factor = step_size ** (1 / p)
    are_arrays_equal = np.array_equal(diagrams_1, diagrams_2)
    betti_curves_1 = betti_curves(diagrams_1, sampling)
    if are_arrays_equal:
        distances = pdist(betti_curves_1, "minkowski", p=p)
        distances *= step_size_factor
        return squareform(distances)
    betti_curves_2 = betti_curves(diagrams_2, sampling)
    distances = cdist(betti_curves_1, betti_curves_2, "minkowski", p=p)
    distances *= step_size_factor
    return distances
# Buggy code
def landscape_distances(
    diagrams_1, diagrams_2, sampling, step_size, p=2.0, n_layers=1, **kwargs
):
    n_samples_1, n_points_1 = diagrams_1.shape[:2]
    n_layers_1 = min(n_layers, n_points_1)
    if np.array_equal(diagrams_1, diagrams_2):
        ls_1 = landscapes(diagrams_1, sampling, n_layers_1).reshape(n_samples_1, -1)
        unnorm_dist = squareform(pdist(ls_1, "minkowski", p=p))
        return (step_size ** (1 / p)) * unnorm_dist
    n_samples_2, n_points_2 = diagrams_2.shape[:2]
    n_layers_2 = min(n_layers, n_points_2)
    n_layers = max(n_layers_1, n_layers_2)
    ls_1 = landscapes(diagrams_1, sampling, n_layers).reshape(n_samples_1, -1)
    ls_2 = landscapes(diagrams_2, sampling, n_layers).reshape(n_samples_2, -1)
    unnorm_dist = cdist(ls_1, ls_2, "minkowski", p=p)
    return (step_size ** (1 / p)) * unnorm_dist


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def landscape_distances(
    diagrams_1, diagrams_2, sampling, step_size, p=2.0, n_layers=1, **kwargs
):
    step_size_factor = step_size ** (1 / p)
    n_samples_1, n_points_1 = diagrams_1.shape[:2]
    n_layers_1 = min(n_layers, n_points_1)
    if np.array_equal(diagrams_1, diagrams_2):
        ls_1 = landscapes(diagrams_1, sampling, n_layers_1).reshape(n_samples_1, -1)
        distances = pdist(ls_1, "minkowski", p=p)
        distances *= step_size_factor
        return squareform(distances)
    n_samples_2, n_points_2 = diagrams_2.shape[:2]
    n_layers_2 = min(n_layers, n_points_2)
    n_layers = max(n_layers_1, n_layers_2)
    ls_1 = landscapes(diagrams_1, sampling, n_layers).reshape(n_samples_1, -1)
    ls_2 = landscapes(diagrams_2, sampling, n_layers).reshape(n_samples_2, -1)
    distances = cdist(ls_1, ls_2, "minkowski", p=p)
    distances *= step_size_factor
    return distances
# Buggy code
def heat_distances(
    diagrams_1, diagrams_2, sampling, step_size, sigma=1.0, p=2.0, **kwargs
):
    heat_1 = heats(diagrams_1, sampling, step_size, sigma).reshape(
        diagrams_1.shape[0], -1
    )
    if np.array_equal(diagrams_1, diagrams_2):
        unnorm_dist = squareform(pdist(heat_1, "minkowski", p=p))
        return (step_size ** (1 / p)) * unnorm_dist
    heat_2 = heats(diagrams_2, sampling, step_size, sigma).reshape(
        diagrams_2.shape[0], -1
    )
    unnorm_dist = cdist(heat_1, heat_2, "minkowski", p=p)
    return (step_size ** (1 / p)) * unnorm_dist


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def heat_distances(
    diagrams_1, diagrams_2, sampling, step_size, sigma=0.1, p=2.0, **kwargs
):
    # WARNING: `heats` modifies `diagrams` in place
    step_size_factor = step_size ** (2 / p)
    are_arrays_equal = np.array_equal(diagrams_1, diagrams_2)
    heats_1 = heats(diagrams_1, sampling, step_size, sigma).reshape(len(diagrams_1), -1)
    if are_arrays_equal:
        distances = pdist(heats_1, "minkowski", p=p)
        distances *= step_size_factor
        return squareform(distances)
    heats_2 = heats(diagrams_2, sampling, step_size, sigma).reshape(len(diagrams_2), -1)
    distances = cdist(heats_1, heats_2, "minkowski", p=p)
    distances *= step_size_factor
    return distances
# Buggy code
def silhouette_distances(
    diagrams_1, diagrams_2, sampling, step_size, power=2.0, p=2.0, **kwargs
):
    silhouette_1 = silhouettes(diagrams_1, sampling, power)
    if np.array_equal(diagrams_1, diagrams_2):
        unnorm_dist = squareform(pdist(silhouette_1, "minkowski", p=p))
    else:
        silhouette_2 = silhouettes(diagrams_2, sampling, power)
        unnorm_dist = cdist(silhouette_1, silhouette_2, "minkowski", p=p)
    return (step_size ** (1 / p)) * unnorm_dist


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def silhouette_distances(
    diagrams_1, diagrams_2, sampling, step_size, power=1.0, p=2.0, **kwargs
):
    step_size_factor = step_size ** (1 / p)
    are_arrays_equal = np.array_equal(diagrams_1, diagrams_2)
    silhouettes_1 = silhouettes(diagrams_1, sampling, power)
    if are_arrays_equal:
        distances = pdist(silhouettes_1, "minkowski", p=p)
        distances *= step_size_factor
        return squareform(distances)
    silhouettes_2 = silhouettes(diagrams_2, sampling, power)
    distances = cdist(silhouettes_1, silhouettes_2, "minkowski", p=p)
    distances *= step_size_factor
    return distances
# Buggy code
def betti_amplitudes(diagrams, sampling, step_size, p=2.0, **kwargs):
    bcs = betti_curves(diagrams, sampling)
    return (step_size ** (1 / p)) * np.linalg.norm(bcs, axis=1, ord=p)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def betti_amplitudes(diagrams, sampling, step_size, p=2.0, **kwargs):
    step_size_factor = step_size ** (1 / p)
    bcs = betti_curves(diagrams, sampling)
    amplitudes = np.linalg.norm(bcs, axis=1, ord=p)
    amplitudes *= step_size_factor
    return amplitudes
# Buggy code
def landscape_amplitudes(diagrams, sampling, step_size, p=2.0, n_layers=1, **kwargs):
    ls = landscapes(diagrams, sampling, n_layers).reshape(len(diagrams), -1)
    return (step_size ** (1 / p)) * np.linalg.norm(ls, axis=1, ord=p)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def landscape_amplitudes(diagrams, sampling, step_size, p=2.0, n_layers=1, **kwargs):
    step_size_factor = step_size ** (1 / p)
    ls = landscapes(diagrams, sampling, n_layers).reshape(len(diagrams), -1)
    amplitudes = np.linalg.norm(ls, axis=1, ord=p)
    amplitudes *= step_size_factor
    return amplitudes
# Buggy code
def heat_amplitudes(diagrams, sampling, step_size, sigma=1.0, p=2.0, **kwargs):
    heat = heats(diagrams, sampling, step_size, sigma)
    return np.linalg.norm(heat, axis=(1, 2), ord=p)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-5e233492b878> in <module>
----> 1 Amplitude(metric="persistence_image").fit_transform(Xd)

~\Workspace\giotto-tda_ulupo\gtda\utils\_docs.py in fit_transform_wrapper(*args, **kwargs)
104         @wraps(original_fit_transform)
105         def fit_transform_wrapper(*args, **kwargs):
--> 106             return original_fit_transform(*args, **kwargs)
107         fit_transform_wrapper.__doc__ = \
108             make_fit_transform_docs(fit_docs, transform_docs)

~\Anaconda3\envs\gtda-ulupo-py38\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params)
688         if y is None:
689             # fit method of arity 1 (unsupervised transformation)
--> 690             return self.fit(X, **fit_params).transform(X)
691         else:
692             # fit method of arity 2 (supervised transformation)

~\Workspace\giotto-tda_ulupo\gtda\diagrams\features.py in fit(self, X, y)
273         if self.metric == 'persistence_image':
274             self.effective_metric_params_['weights'] = \
--> 275                 _calculate_weights(X, **self.effective_metric_params_)
276
277         return self

TypeError: _calculate_weights() missing 1 required positional argument: 'weight_function'

# Fixed code
def heat_amplitudes(diagrams, sampling, step_size, sigma=0.1, p=2.0, **kwargs):
    # WARNING: `heats` modifies `diagrams` in place
    step_size_factor = step_size ** (2 / p)
    heats_ = heats(diagrams, sampling, step_size, sigma).reshape(len(diagrams), -1)
    amplitudes = np.linalg.norm(heats_, axis=1, ord=p)
    amplitudes *= step_size_factor
    return amplitudes