Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions include/amrexplorer/core/CacheConfig.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#pragma once

#include <charconv>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <optional>
#include <string_view>
#include <system_error>

// The block-cache budget a dataset opens with when its caller names none.
// Qt-free so the viewer and the Python binding share one definition: both read
// AMREXPLORER_CACHE_SIZE_MB, and both fall back to the same 1 GiB. They differ
// only in what an unusable value does -- the viewer opens anyway, with the
// default, while an unattended analysis job refuses to run with a budget it
// did not ask for (see parseCacheSizeMegabytes).

namespace amrvis {

inline constexpr std::uint64_t defaultInitialCacheBudget
= 1ULL * 1024ULL * 1024ULL * 1024ULL;
inline constexpr std::string_view cacheSizeEnvironmentVariable
= "AMREXPLORER_CACHE_SIZE_MB";
inline constexpr std::uint64_t bytesPerMegabyte = 1024ULL * 1024ULL;

// The budget in bytes that a value of AMREXPLORER_CACHE_SIZE_MB names, or
// nullopt when it names none: not a plain decimal count, zero, or too many
// megabytes for a byte count to hold.
[[nodiscard]] inline std::optional<std::uint64_t> parseCacheSizeMegabytes(
std::string_view text) noexcept
{
std::uint64_t megabytes = 0;
const auto [end, error]
= std::from_chars(text.data(), text.data() + text.size(), megabytes);
if (error != std::errc{} || end != text.data() + text.size()
|| megabytes == 0
|| megabytes > std::numeric_limits<std::uint64_t>::max() / bytesPerMegabyte) {
return std::nullopt;
}
return megabytes * bytesPerMegabyte;
}

inline std::uint64_t initialCacheBudget(const char* configuredValue) noexcept
{
if (configuredValue == nullptr) {
return defaultInitialCacheBudget;
}
return parseCacheSizeMegabytes(configuredValue)
.value_or(defaultInitialCacheBudget);
}

// The environment variable's value, or nullopt when it is unset.
[[nodiscard]] inline std::optional<std::string_view>
cacheSizeEnvironmentValue() noexcept
{
#if defined(_MSC_VER)
// _dupenv_s allocates; keep the copy for the process's lifetime so the
// view stays valid. Read once: the variable is configuration, not state.
static const char* const value = [] {
char* configuredValue = nullptr;
std::size_t configuredValueSize = 0;
if (::_dupenv_s(&configuredValue, &configuredValueSize,
cacheSizeEnvironmentVariable.data())
!= 0) {
return static_cast<const char*>(nullptr);
}
return static_cast<const char*>(configuredValue);
}();
#else
const char* const value = std::getenv(cacheSizeEnvironmentVariable.data());
#endif
if (value == nullptr) {
return std::nullopt;
}
return std::string_view(value);
}

inline std::uint64_t initialCacheBudget() noexcept
{
const auto configured = cacheSizeEnvironmentValue();
if (!configured) {
return defaultInitialCacheBudget;
}
return parseCacheSizeMegabytes(*configured)
.value_or(defaultInitialCacheBudget);
}

} // namespace amrvis
6 changes: 6 additions & 0 deletions include/amrexplorer/io/PlotfileBlockReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <cstdint>
#include <filesystem>
#include <memory>
#include <span>
#include <stdexcept>
#include <variant>
#include <vector>
Expand All @@ -33,6 +34,11 @@ class FabValues {
[[nodiscard]] std::size_t elementBytes() const noexcept;
[[nodiscard]] std::uint64_t residentBytes() const noexcept;
[[nodiscard]] double operator[](std::size_t index) const noexcept;
// The payload in its own precision, for a caller copying many values
// that would otherwise dispatch on the precision once per value. Empty
// when the payload has the other precision.
[[nodiscard]] std::span<const float> singleValues() const noexcept;
[[nodiscard]] std::span<const double> doubleValues() const noexcept;

private:
using Storage = std::variant<std::vector<float>, std::vector<double>>;
Expand Down
23 changes: 20 additions & 3 deletions include/amrexplorer/io/PlotfileDataset.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,21 @@ class PlotfileDataset {
// caller of metadata() see one list that never changes. Editing the
// definitions therefore means opening a new dataset, which is what the GUI
// does.
//
// `derivedFieldPolicy` is Skip for the viewer, for the reasons above. An
// unattended analysis passes Strict instead: a definition that does not
// resolve then throws DerivedFieldError here, at open, rather than leaving
// a reduction to run without the field it asked for.
PlotfileDataset(
std::filesystem::path plotfile, DatasetId id,
std::uint64_t cacheBudgetBytes, StopToken cancellation = {},
std::vector<DerivedFieldDefinition> derivedFields = {});
std::vector<DerivedFieldDefinition> derivedFields = {},
DerivedFieldPolicy derivedFieldPolicy = DerivedFieldPolicy::Skip);
PlotfileDataset(std::filesystem::path dataRoot, DatasetId id,
std::uint64_t cacheBudgetBytes, PlotfileMetadataResult metadata,
StopToken cancellation = {},
std::vector<DerivedFieldDefinition> derivedFields = {});
std::vector<DerivedFieldDefinition> derivedFields = {},
DerivedFieldPolicy derivedFieldPolicy = DerivedFieldPolicy::Skip);

[[nodiscard]] const DatasetMetadata& metadata() const noexcept;
[[nodiscard]] const MetadataReadMetrics& metadataReadMetrics() const noexcept;
Expand Down Expand Up @@ -74,6 +81,11 @@ class PlotfileDataset {
// How many of metadata().fields this dataset stores; the derived ones
// follow them, in the order their definitions were given.
[[nodiscard]] std::size_t storedFieldCount() const noexcept;
// The program that computes a derived field, or null for a stored one --
// what a caller bounding a read in advance walks to find every block the
// evaluation would pin.
[[nodiscard]] const DerivedFieldProgram* derivedFieldProgram(
FieldId field) const noexcept;
// The definitions this dataset could not install, with the reason. A
// definition written for another plotfile does not stop this one from
// opening (DerivedFieldPolicy::Skip); it lands here instead, for whoever
Expand Down Expand Up @@ -105,6 +117,10 @@ class PlotfileDataset {
// The block pool this dataset reports; the mapped grid's pool follows the
// budget (setCacheBudget) and the clear, but is not part of the metrics.
[[nodiscard]] CacheMetrics cacheMetrics() const;
// False when pinned blocks already exceed the new budget. The new budget
// is stored either way (ByteLruCache::setBudget), on this pool and the
// mapped grid's; a caller that must not keep a budget it could not honour
// restores the previous one itself.
[[nodiscard]] bool setCacheBudget(std::uint64_t bytes);
void clearUnpinnedCache();

Expand Down Expand Up @@ -137,7 +153,8 @@ class PlotfileDataset {
};
[[nodiscard]] static Fields installFields(
const PlotfileMetadataResult& source,
std::span<const DerivedFieldDefinition> definitions);
std::span<const DerivedFieldDefinition> definitions,
DerivedFieldPolicy policy);
[[nodiscard]] BlockReadResult readDerivedBlock(const BlockRequest& request,
const DerivedFieldProgram& program, StopToken cancellation);

Expand Down
16 changes: 16 additions & 0 deletions src/io/plotfile/PlotfileBlockReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,22 @@ double FabValues::operator[](std::size_t index) const noexcept
}, m_storage);
}

std::span<const float> FabValues::singleValues() const noexcept
{
if (const auto* values = std::get_if<std::vector<float>>(&m_storage)) {
return *values;
}
return {};
}

std::span<const double> FabValues::doubleValues() const noexcept
{
if (const auto* values = std::get_if<std::vector<double>>(&m_storage)) {
return *values;
}
return {};
}

PlotfileBlockReader::PlotfileBlockReader(
std::filesystem::path plotfile, std::shared_ptr<const DatasetMetadata> metadata)
: m_plotfile(std::move(plotfile))
Expand Down
29 changes: 22 additions & 7 deletions src/io/plotfile/PlotfileDataset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ constexpr std::size_t derivedChunkPoints = 512;

PlotfileDataset::Fields PlotfileDataset::installFields(
const PlotfileMetadataResult& source,
std::span<const DerivedFieldDefinition> definitions)
std::span<const DerivedFieldDefinition> definitions,
DerivedFieldPolicy policy)
{
if (!source.metadata) {
throw std::invalid_argument("dataset metadata is unavailable");
Expand All @@ -71,7 +72,7 @@ PlotfileDataset::Fields PlotfileDataset::installFields(
auto metadata = std::make_shared<DatasetMetadata>(*source.metadata);
const auto storedCount = metadata->fields.size();
auto installation = installDerivedFields(
*metadata, definitions, DerivedFieldPolicy::Skip);
*metadata, definitions, policy);
return {std::move(metadata), std::move(installation.programs), storedCount,
std::move(installation.skipped),
{definitions.begin(), definitions.end()}};
Expand All @@ -80,11 +81,13 @@ PlotfileDataset::Fields PlotfileDataset::installFields(
PlotfileDataset::PlotfileDataset(
std::filesystem::path plotfile, DatasetId id,
std::uint64_t cacheBudgetBytes, StopToken cancellation,
std::vector<DerivedFieldDefinition> derivedFields)
std::vector<DerivedFieldDefinition> derivedFields,
DerivedFieldPolicy derivedFieldPolicy)
: m_plotfile(sourceDataRoot(plotfile))
, m_id(id)
, m_metadataResult(readDatasetMetadata(plotfile, cancellation))
, m_fields(installFields(m_metadataResult, derivedFields))
, m_fields(installFields(
m_metadataResult, derivedFields, derivedFieldPolicy))
, m_particleSpecies(std::filesystem::is_directory(plotfile)
? discoverParticleSpecies(m_plotfile, cancellation)
: std::vector<ParticleSpeciesMetadata>{})
Expand All @@ -99,14 +102,16 @@ PlotfileDataset::PlotfileDataset(

PlotfileDataset::PlotfileDataset(std::filesystem::path root, DatasetId id,
std::uint64_t cacheBudgetBytes, PlotfileMetadataResult metadata,
StopToken cancellation, std::vector<DerivedFieldDefinition> derivedFields)
StopToken cancellation, std::vector<DerivedFieldDefinition> derivedFields,
DerivedFieldPolicy derivedFieldPolicy)
: m_plotfile(std::move(root))
, m_id(id)
, m_metadataResult(std::move(metadata))
// Rejects a missing metadata result, which used to be the constructor
// body's job -- the field list has to be built before the block reader is
// constructed, so the check has to happen there too.
, m_fields(installFields(m_metadataResult, derivedFields))
, m_fields(installFields(
m_metadataResult, derivedFields, derivedFieldPolicy))
, m_particleSpecies(
discoverParticlesForPlotfileRoot(m_plotfile, cancellation))
, m_blockReader(m_plotfile, m_fields.metadata)
Expand All @@ -124,7 +129,7 @@ PlotfileDataset::PlotfileDataset(MappedGridTag, std::filesystem::path root,
: m_plotfile(std::move(root))
, m_id(id)
, m_metadataResult{std::move(metadata), {}, {}, {}}
, m_fields(installFields(m_metadataResult, {}))
, m_fields(installFields(m_metadataResult, {}, DerivedFieldPolicy::Skip))
, m_blockReader(m_plotfile, m_fields.metadata)
, m_cache(cacheBudgetBytes)
{
Expand Down Expand Up @@ -179,6 +184,16 @@ std::size_t PlotfileDataset::storedFieldCount() const noexcept
return m_fields.storedCount;
}

const DerivedFieldProgram* PlotfileDataset::derivedFieldProgram(
FieldId field) const noexcept
{
if (!isDerivedField(field)) {
return nullptr;
}
return &m_fields.programs[static_cast<std::size_t>(field.value)
- m_fields.storedCount];
}

const std::vector<DerivedFieldSkip>& PlotfileDataset::skippedDerivedFields()
const noexcept
{
Expand Down
54 changes: 7 additions & 47 deletions src/qt/CacheConfig.hpp
Original file line number Diff line number Diff line change
@@ -1,54 +1,14 @@
#pragma once

#include <charconv>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <string_view>
#include <system_error>
// The viewer's initial cache budget now lives below Qt, shared with the
// analysis binding; these names keep the GUI's spelling of it.
#include <amrexplorer/core/CacheConfig.hpp>

namespace amrvis::qt {

inline constexpr std::uint64_t defaultInitialCacheBudget
= 1ULL * 1024ULL * 1024ULL * 1024ULL;
inline constexpr std::string_view cacheSizeEnvironmentVariable
= "AMREXPLORER_CACHE_SIZE_MB";
inline constexpr std::uint64_t bytesPerMegabyte = 1024ULL * 1024ULL;

inline std::uint64_t initialCacheBudget(const char* configuredValue) noexcept
{
if (configuredValue == nullptr) {
return defaultInitialCacheBudget;
}

const std::string_view text(configuredValue);
std::uint64_t megabytes = 0;
const auto [end, error]
= std::from_chars(text.data(), text.data() + text.size(), megabytes);
if (error != std::errc{} || end != text.data() + text.size()
|| megabytes == 0
|| megabytes > std::numeric_limits<std::uint64_t>::max() / bytesPerMegabyte) {
return defaultInitialCacheBudget;
}
return megabytes * bytesPerMegabyte;
}

inline std::uint64_t initialCacheBudget() noexcept
{
#if defined(_MSC_VER)
char* configuredValue = nullptr;
std::size_t configuredValueSize = 0;
const auto readError = ::_dupenv_s(&configuredValue,
&configuredValueSize, cacheSizeEnvironmentVariable.data());
const auto budget = readError == 0
? initialCacheBudget(configuredValue) : defaultInitialCacheBudget;
std::free(configuredValue);
return budget;
#else
return initialCacheBudget(
std::getenv(cacheSizeEnvironmentVariable.data()));
#endif
}
using amrvis::bytesPerMegabyte;
using amrvis::cacheSizeEnvironmentVariable;
using amrvis::defaultInitialCacheBudget;
using amrvis::initialCacheBudget;

} // namespace amrvis::qt
6 changes: 5 additions & 1 deletion tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ add_test(NAME byte_lru_cache COMMAND test_byte_lru_cache)

add_executable(test_cache_config unit/test_cache_config.cpp)
target_include_directories(test_cache_config PRIVATE "${CMAKE_SOURCE_DIR}/src/qt")
target_link_libraries(test_cache_config PRIVATE amrexplorer::warnings)
target_link_libraries(test_cache_config PRIVATE amrexplorer::core amrexplorer::warnings)
add_test(NAME cache_config COMMAND test_cache_config)
set_tests_properties(cache_config PROPERTIES
ENVIRONMENT "AMREXPLORER_CACHE_SIZE_MB=768"
Expand Down Expand Up @@ -515,6 +515,10 @@ target_link_libraries(
)
add_test(NAME single_precision_plotfile COMMAND test_single_precision_plotfile)

add_executable(test_derived_field_policy integration/test_derived_field_policy.cpp)
target_link_libraries(test_derived_field_policy PRIVATE amrexplorer::io amrexplorer::warnings)
add_test(NAME derived_field_policy COMMAND test_derived_field_policy)

add_executable(
test_near_degenerate_field
integration/test_near_degenerate_field.cpp
Expand Down
Loading
Loading