15#include <boost/algorithm/string.hpp>
41namespace PhreeqcIOData
48 using Ts::operator()...;
53template <
typename DataBlock>
55 std::vector<DataBlock>
const& data_blocks)
57 std::copy(data_blocks.begin(), data_blocks.end(),
58 std::ostream_iterator<DataBlock>(os));
70 auto& components = aqueous_solution.
components;
71 for (
unsigned component_id = 0; component_id < components.size();
75 *components[component_id].amount);
76 components[component_id].amount->set(global_index,
77 concentrations[component_id]);
82 aqueous_solution.
pH->set(global_index, concentrations.back());
85template <
typename Reactant>
94 auto const& solid_constituent = solid_phase.
component(reactant.name);
96 if (solid_constituent.hasProperty(
101 .template initialValue<double>(pos, t);
103 (*reactant.molality)[chemical_system_id] = molality;
104 (*reactant.molality_prev)[chemical_system_id] = molality;
108 auto const volume_fraction =
111 .template initialValue<double>(pos, t);
113 (*reactant.volume_fraction)[chemical_system_id] = volume_fraction;
115 (*reactant.volume_fraction_prev)[chemical_system_id] = volume_fraction;
117 auto const fluid_density =
119 .template initialValue<double>(pos, t);
121 auto const porosity =
123 .template initialValue<double>(pos, t);
125 auto const molar_volume =
127 .template initialValue<double>(pos, t);
129 (*reactant.molality)[chemical_system_id] =
130 volume_fraction / fluid_density / porosity / molar_volume;
132 (*reactant.molality_prev)[chemical_system_id] =
133 (*reactant.molality)[chemical_system_id];
137template <
typename Reactant>
144 double const t,
double const dt)
146 auto const& solid_constituent = solid_phase.
component(reactant.name);
148 if (solid_constituent.hasProperty(
151 (*reactant.molality_prev)[chemical_system_id] =
152 (*reactant.molality)[chemical_system_id];
157 auto const volume_fraction =
158 (*reactant.volume_fraction)[chemical_system_id];
160 (*reactant.volume_fraction_prev)[chemical_system_id] =
161 (*reactant.volume_fraction)[chemical_system_id];
163 auto const fluid_density =
165 .template value<double>(vars, pos, t, dt);
167 auto const molar_volume =
169 .template value<double>(vars, pos, t, dt);
171 (*reactant.molality)[chemical_system_id] =
172 volume_fraction / fluid_density / vars.
porosity / molar_volume;
174 (*reactant.molality_prev)[chemical_system_id] =
175 (*reactant.molality)[chemical_system_id];
178template <
typename Site>
185 auto const& solid_constituent = solid_phase.
component(site.name);
187 auto const molality =
189 .template initialValue<double>(pos, t);
191 (*site.molality)[chemical_system_id] = molality;
194template <
typename Reactant>
199 double const porosity,
double const t,
202 auto const& solid_phase = medium.
phase(
"Solid");
203 auto const& liquid_phase = medium.
phase(
"AqueousLiquid");
207 auto const liquid_density =
209 .template value<double>(vars, pos, t, dt);
211 auto const& solid_constituent = solid_phase.component(reactant.name);
213 if (solid_constituent.hasProperty(
219 auto const molar_volume =
221 .template value<double>(vars, pos, t, dt);
223 (*reactant.volume_fraction)[chemical_system_id] +=
224 ((*reactant.molality)[chemical_system_id] -
225 (*reactant.molality_prev)[chemical_system_id]) *
226 liquid_density * porosity * molar_volume;
229template <
typename Reactant>
235 auto const& solid_phase = medium.
phase(
"Solid");
237 auto const& solid_constituent = solid_phase.
component(reactant.name);
239 if (solid_constituent.hasProperty(
245 porosity -= ((*reactant.volume_fraction)[chemical_system_id] -
246 (*reactant.volume_fraction_prev)[chemical_system_id]);
249template <
typename Reactant>
251 Reactant
const& reactant,
252 std::vector<GlobalIndexType>
const& chemical_system_indices)
254 double const sum = std::accumulate(
255 chemical_system_indices.begin(), chemical_system_indices.end(), 0.0,
257 { return s + (*reactant.molality)[id]; });
258 return sum / chemical_system_indices.size();
262extern std::string
specifyFileName(std::string
const& project_file_name,
263 std::string
const& file_extension);
267 std::string
const& project_file_name,
268 std::string&& database,
269 std::unique_ptr<ChemicalSystem>&& chemical_system,
270 std::vector<ReactionRate>&& reaction_rates,
271 std::unique_ptr<UserPunch>&& user_punch,
272 std::unique_ptr<Output>&& output,
273 std::unique_ptr<Dump>&& dump,
277 _database(std::move(database)),
278 _chemical_system(std::move(chemical_system)),
279 _reaction_rates(std::move(reaction_rates)),
280 _user_punch(std::move(user_punch)),
281 _output(std::move(output)),
282 _dump(std::move(dump)),
283 _knobs(std::move(knobs))
289 "Failed to initialize phreeqc instance, due to lack of memory.");
296 "Failed in loading the specified thermodynamic database file: "
304 "Failed to fly the flag for the specified file {:s} where phreeqc "
305 "will write output.",
306 _output->basic_output_setups.output_file);
336 std::vector<double>
const& concentrations,
342 setAqueousSolution(concentrations, chemical_system_id,
345 auto const& solid_phase = medium.
phase(
"Solid");
346 auto const& liquid_phase = medium.
phase(
"AqueousLiquid");
350 initializeReactantMolality(kinetic_reactant, chemical_system_id,
351 solid_phase, liquid_phase, medium, pos, t);
356 initializeReactantMolality(equilibrium_reactant, chemical_system_id,
357 solid_phase, liquid_phase, medium, pos, t);
362 initializeSiteMolality(exchanger, chemical_system_id, solid_phase, pos,
368 if (
auto const surface_site_ptr =
369 std::get_if<MoleBasedSurfaceSite>(&surface_site))
371 initializeSiteMolality(*surface_site_ptr, chemical_system_id,
372 solid_phase, pos, t);
378 std::vector<double>
const& concentrations,
384 setAqueousSolution(concentrations, chemical_system_id,
387 auto const& solid_phase = medium->
phase(
"Solid");
388 auto const& liquid_phase = medium->
phase(
"AqueousLiquid");
392 setReactantMolality(kinetic_reactant, chemical_system_id, solid_phase,
393 liquid_phase, vars, pos, t, dt);
398 setReactantMolality(equilibrium_reactant, chemical_system_id,
399 solid_phase, liquid_phase, vars, pos, t, dt);
413 int const component_id,
GlobalIndexType const chemical_system_id)
const
416 auto& components = aqueous_solution.components;
417 auto const&
pH = *aqueous_solution.pH;
419 if (component_id <
static_cast<int>(components.size()))
422 *components[component_id].amount);
424 return components[component_id].amount->get(chemical_system_id);
430 return pH.get(chemical_system_id);
440 auto const& dump_file =
_dump->dump_file;
441 std::ifstream in(dump_file);
453 OGS_FATAL(
"Error when reading phreeqc dump file '{:s}'", dump_file);
466 OGS_FATAL(
"Could not open file '{:s}' for writing phreeqc inputs.",
470 out << std::scientific
471 << std::setprecision(std::numeric_limits<double>::max_digits10);
472 out << (*
this << dt);
476 OGS_FATAL(
"Failed in generating phreeqc input file '{:s}'.",
485 bool const fixing_pe =
495 os << phreeqc_io.
_knobs <<
"\n";
497 os << *phreeqc_io.
_output <<
"\n";
502 os << *user_punch <<
"\n";
506 if (!reaction_rates.empty())
509 os << reaction_rates <<
"\n";
512 for (std::size_t chemical_system_id = 0;
514 ++chemical_system_id)
516 os <<
"SOLUTION " << chemical_system_id + 1 <<
"\n";
518 os, chemical_system_id);
520 auto const& dump = phreeqc_io.
_dump;
523 auto const& aqueous_solutions_prev = dump->aqueous_solutions_prev;
524 if (!aqueous_solutions_prev.empty())
526 os << aqueous_solutions_prev[chemical_system_id] <<
"\n\n";
530 os <<
"USE solution none\n";
533 os <<
"USE solution " << chemical_system_id + 1 <<
"\n\n";
535 auto const& equilibrium_reactants =
537 if (!equilibrium_reactants.empty() || fixing_pe)
539 os <<
"EQUILIBRIUM_PHASES " << chemical_system_id + 1 <<
"\n";
540 for (
auto const& equilibrium_reactant : equilibrium_reactants)
542 equilibrium_reactant.print(os, chemical_system_id);
551 auto const& kinetic_reactants =
553 if (!kinetic_reactants.empty())
555 os <<
"KINETICS " << chemical_system_id + 1 <<
"\n";
556 for (
auto const& kinetic_reactant : kinetic_reactants)
558 kinetic_reactant.print(os, chemical_system_id);
560 os <<
"-steps " << phreeqc_io.
_dt <<
"\n\n";
564 if (!surface.empty())
566 os <<
"SURFACE " << chemical_system_id + 1 <<
"\n";
567 std::size_t aqueous_solution_id =
568 dump->aqueous_solutions_prev.empty()
569 ? chemical_system_id + 1
571 os <<
"-equilibrate with solution " << aqueous_solution_id <<
"\n";
574 if (std::holds_alternative<DensityBasedSurfaceSite>(
577 os <<
"-sites_units density\n";
581 os <<
"-sites_units absolute\n";
584 for (
auto const& surface_site : surface)
589 os << s.name <<
" " << s.site_density <<
" "
590 << s.specific_surface_area <<
" "
593 [&os, chemical_system_id](
596 << (*s.molality)[chemical_system_id]
603 if (std::holds_alternative<MoleBasedSurfaceSite>(surface.front()))
608 os <<
"SAVE solution " << chemical_system_id + 1 <<
"\n";
612 if (!exchangers.empty())
614 os <<
"EXCHANGE " << chemical_system_id + 1 <<
"\n";
615 std::size_t
const aqueous_solution_id =
616 dump->aqueous_solutions_prev.empty()
617 ? chemical_system_id + 1
619 os <<
"-equilibrate with solution " << aqueous_solution_id <<
"\n";
620 for (
auto const& exchanger : exchangers)
622 exchanger.print(os, chemical_system_id);
624 os <<
"SAVE solution " << chemical_system_id + 1 <<
"\n";
630 auto const& dump = phreeqc_io.
_dump;
641 INFO(
"Phreeqc: Executing chemical calculation.");
646 "Failed in performing speciation calculation with the generated "
647 "phreeqc input file '{:s}'.",
654 auto const& basic_output_setups =
_output->basic_output_setups;
655 auto const& phreeqc_result_file = basic_output_setups.output_file;
656 DBUG(
"Reading phreeqc results from file '{:s}'.", phreeqc_result_file);
657 std::ifstream in(phreeqc_result_file);
661 OGS_FATAL(
"Could not open phreeqc result file '{:s}'.",
662 phreeqc_result_file);
669 OGS_FATAL(
"Error when reading phreeqc result file '{:s}'",
670 phreeqc_result_file);
679 in.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
682 auto const& output = *phreeqc_io.
_output;
683 auto const& dropped_item_ids = output.dropped_item_ids;
688 int const num_skipped_lines =
689 1 + (!surface.empty() ? 1 : 0) + (!exchangers.empty() ? 1 : 0);
691 auto& equilibrium_reactants =
695 for (std::size_t chemical_system_id = 0;
697 ++chemical_system_id)
700 for (
int i = 0; i < num_skipped_lines; ++i)
702 in.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
706 if (!std::getline(in, line))
709 "Error when reading calculation result of Solution {:d} "
710 "after the reaction.",
714 std::vector<double> accepted_items;
715 std::vector<std::string> items;
716 boost::trim_if(line, boost::is_any_of(
"\t "));
717 boost::algorithm::split(items, line, boost::is_any_of(
"\t "),
718 boost::token_compress_on);
719 for (
int item_id = 0; item_id < static_cast<int>(items.size());
722 if (std::find(dropped_item_ids.begin(), dropped_item_ids.end(),
723 item_id) == dropped_item_ids.end())
728 value = std::stod(items[item_id]);
730 catch (
const std::invalid_argument& e)
733 "Invalid argument. Could not convert string '{:s}' to "
734 "double for chemical system {:d}, column {:d}. "
735 "Exception '{:s}' was thrown.",
736 items[item_id], chemical_system_id + 1, item_id,
739 catch (
const std::out_of_range& e)
742 "Out of range error. Could not convert string "
743 "'{:s}' to double for chemical system {:d}, column "
744 "{:d}. Exception '{:s}' was thrown.",
745 items[item_id], chemical_system_id + 1, item_id,
748 accepted_items.push_back(value);
751 assert(accepted_items.size() == output.accepted_items.size());
754 auto& components = aqueous_solution->components;
760 for (
int item_id = 0; item_id < static_cast<int>(accepted_items.size());
763 auto const& accepted_item = output.accepted_items[item_id];
764 auto const& item_name = accepted_item.name;
766 auto compare_by_name = [&item_name](
auto const& item)
767 {
return item.name == item_name; };
769 switch (accepted_item.item_type)
775 *aqueous_solution->pH);
776 aqueous_solution->pH->set(
777 global_index, std::pow(10, -accepted_items[item_id]));
783 (*aqueous_solution->pe)[chemical_system_id] =
784 accepted_items[item_id];
791 components, compare_by_name,
793 OGS_FATAL(
"Could not find component '{:s}'.",
798 component.amount->set(global_index,
799 accepted_items[item_id]);
805 auto const& equilibrium_reactant =
807 equilibrium_reactants, compare_by_name,
811 "Could not find equilibrium reactant "
815 (*equilibrium_reactant.molality)[chemical_system_id] =
816 accepted_items[item_id];
823 kinetic_reactants, compare_by_name,
825 OGS_FATAL(
"Could not find kinetic reactant '{:s}'.",
828 (*kinetic_reactant.molality)[chemical_system_id] =
829 accepted_items[item_id];
835 auto const& secondary_variables =
836 user_punch->secondary_variables;
838 auto const& secondary_variable =
840 secondary_variables, compare_by_name,
843 "Could not find secondary variable '{:s}'.",
846 (*secondary_variable.value)[chemical_system_id] =
847 accepted_items[item_id];
859 std::vector<std::string> component_names;
861 std::transform(components.begin(), components.end(),
862 std::back_inserter(component_names),
863 [](
auto const& c) { return c.name; });
865 component_names.push_back(
"H");
867 return component_names;
874 double const t,
double const dt)
878 updateReactantVolumeFraction(kinetic_reactant, chemical_system_id,
879 medium, pos, porosity, t, dt);
884 updateReactantVolumeFraction(equilibrium_reactant, chemical_system_id,
885 medium, pos, porosity, t, dt);
896 setPorosityPostReaction(kinetic_reactant, chemical_system_id, medium,
902 setPorosityPostReaction(equilibrium_reactant, chemical_system_id,
908 std::size_t
const ele_id,
909 std::vector<GlobalIndexType>
const& chemical_system_indices)
913 (*kinetic_reactant.mesh_prop_molality)[ele_id] =
914 averageReactantMolality(kinetic_reactant, chemical_system_indices);
917 for (
auto const& equilibrium_reactant :
920 (*equilibrium_reactant.mesh_prop_molality)[ele_id] =
921 averageReactantMolality(equilibrium_reactant,
922 chemical_system_indices);
GlobalMatrix::IndexType GlobalIndexType
void INFO(fmt::format_string< Args... > fmt, Args &&... args)
void DBUG(fmt::format_string< Args... > fmt, Args &&... args)
Definition of the Mesh class.
std::vector< GlobalIndexType > chemical_system_index_map
std::string const _phreeqc_input_file
double getConcentration(int const component_id, GlobalIndexType const chemical_system_id) const override
PhreeqcIO(MeshLib::Mesh const &mesh, GlobalLinearSolver &linear_solver, std::string const &project_file_name, std::string &&database, std::unique_ptr< ChemicalSystem > &&chemical_system, std::vector< ReactionRate > &&reaction_rates, std::unique_ptr< UserPunch > &&user_punch, std::unique_ptr< Output > &&output, std::unique_ptr< Dump > &&dump, Knobs &&knobs)
void setAqueousSolutionsPrevFromDumpFile() override
std::unique_ptr< ChemicalSystem > _chemical_system
std::vector< ReactionRate > const _reaction_rates
std::unique_ptr< UserPunch > _user_punch
const int phreeqc_instance_id
void writeInputsToFile(double const dt)
void setChemicalSystemConcrete(std::vector< double > const &concentrations, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Medium const *medium, MaterialPropertyLib::VariableArray const &vars, ParameterLib::SpatialPosition const &pos, double const t, double const dt) override
std::unique_ptr< Dump > const _dump
void initialize() override
std::unique_ptr< Output > const _output
void readOutputsFromFile()
std::size_t _num_chemical_systems
void computeSecondaryVariable(std::size_t const ele_id, std::vector< GlobalIndexType > const &chemical_system_indices) override
void initializeChemicalSystemConcrete(std::vector< double > const &concentrations, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Medium const &medium, ParameterLib::SpatialPosition const &pos, double const t) override
void updateVolumeFractionPostReaction(GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Medium const &medium, ParameterLib::SpatialPosition const &pos, double const porosity, double const t, double const dt) override
void executeSpeciationCalculation(double const dt) override
std::string const _database
std::vector< std::string > const getComponentList() const override
void updatePorosityPostReaction(GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Medium const &medium, double &porosity) override
Phase const & phase(std::size_t index) const
Component const & component(std::size_t const &index) const
ranges::range_reference_t< Range > findElementOrError(Range &range, std::predicate< ranges::range_reference_t< Range > > auto &&predicate, std::invocable auto error_callback)
void initializeSiteMolality(Site &site, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Phase const &solid_phase, ParameterLib::SpatialPosition const &pos, double const t)
void initializeReactantMolality(Reactant &reactant, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Phase const &solid_phase, MaterialPropertyLib::Phase const &liquid_phase, MaterialPropertyLib::Medium const &medium, ParameterLib::SpatialPosition const &pos, double const t)
void setPorosityPostReaction(Reactant &reactant, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Medium const &medium, double &porosity)
void setReactantMolality(Reactant &reactant, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Phase const &solid_phase, MaterialPropertyLib::Phase const &liquid_phase, MaterialPropertyLib::VariableArray const &vars, ParameterLib::SpatialPosition const &pos, double const t, double const dt)
void setAqueousSolution(std::vector< double > const &concentrations, GlobalIndexType const &chemical_system_id, AqueousSolution &aqueous_solution)
static double averageReactantMolality(Reactant const &reactant, std::vector< GlobalIndexType > const &chemical_system_indices)
void updateReactantVolumeFraction(Reactant &reactant, GlobalIndexType const &chemical_system_id, MaterialPropertyLib::Medium const &medium, ParameterLib::SpatialPosition const &pos, double const porosity, double const t, double const dt)
std::ostream & operator<<(std::ostream &os, PhreeqcIO const &phreeqc_io)
std::string specifyFileName(std::string const &project_file_name, std::string const &file_extension)
std::istream & operator>>(std::istream &in, PhreeqcIO &phreeqc_io)
void setLocalAccessibleVector(PETScVector const &x)
std::vector< Component > components
std::unique_ptr< GlobalVector > pH