Page MenuHomec4science

migration.cpp
No OneTemporary

File Metadata

Created
Fri, Sep 13, 20:37

migration.cpp

/* =============================================================================
Copyright (c) 2014-2017 F. Georget <fabieng@princeton.edu> Princeton University
Copyright (c) 2017 F. Georget <fabien.georget@epfl.ch> EPFL
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
============================================================================= */
#include "reactmicp/systems/chloride/variables.hpp"
#include "reactmicp/systems/chloride/variables_interface.hpp"
#include "reactmicp/systems/chloride/transport_stagger.hpp"
#include "reactmicp/systems/chloride/boundary_conditions.hpp"
#include "specmicp_common/log.hpp"
#include "specmicp_database/io/configuration.hpp"
#include "specmicp/adimensional/adimensional_system_solver.hpp"
#include "specmicp/problem_solver/smart_solver.hpp"
#include "specmicp/problem_solver/reactant_box.hpp"
#include "specmicp/adimensional/adimensional_system_solver_structs.hpp"
#include "reactmicp/systems/chloride/transport_program_struct.hpp"
#include "reactmicp/solver/staggers_base/stagger_structs.hpp"
#include "dfpm/solver/parabolic_structs.hpp"
#include "specmicp_common/log.hpp"
#include <vector>
#include <iostream>
#include <fstream>
using namespace specmicp;
using namespace specmicp::reactmicp::systems::chloride;
mesh::Mesh1DPtr get_mesh(scalar_t thickness, scalar_t dx)
{
mesh::Uniform1DMeshGeometry amesh;
amesh.dx = dx;
amesh.section = (121.0)*3.14;
amesh.nb_nodes = std::floor(thickness/dx)+1;
return mesh::uniform_mesh1d(amesh);
}
specmicp::database::RawDatabasePtr get_database()
{
static database::RawDatabasePtr raw_data {nullptr};
if (raw_data == nullptr)
{
specmicp::database::Database thedatabase(CEMDATA_PATH);
//thedatabase.keep_only_components({"H2O","H[+]", "Na[+]", "Cl[-]", "Ca[2+]", "SO4[2-]"});
thedatabase.keep_only_components({"H2O","H[+]", "Na[+]", "Cl[-]", "Ca[2+]"});
thedatabase.swap_components({{"H[+]", "HO[-]"}});
thedatabase.remove_half_cell_reactions();
raw_data = thedatabase.get_database();
raw_data->freeze_db();
}
return raw_data;
}
specmicp::AdimensionalSystemSolution initial_conditions(database::RawDatabasePtr data, units::UnitsSet tunits)
{
ReactantBox box(data, tunits);
box.set_solution(0.3, "L/L");
box.set_saturated_system();
box.set_inert_volume_fraction(0.7);
box.add_aqueous_species("NaCl", 0.001, "mol/kg");
box.add_aqueous_species("NaOH", 0.3, "mol/kg");
box.add_aqueous_species("Ca(OH)2", 0.02, "mol/kg");
//box.add_aqueous_species("CaSO4", 0.01, "mol/kg");
SmartAdimSolver solver(data, box, false);
if (! solver.solve()) {
throw std::runtime_error("Cannot solve init cond");
}
return solver.get_solution();
}
static specmicp::AdimensionalSystemSolution boundary_conditions(database::RawDatabasePtr data, units::UnitsSet tunits)
{
ReactantBox box(data, tunits);
box.set_solution(0.3, "L/L");
box.set_saturated_system();
box.set_inert_volume_fraction(0.7);
box.add_aqueous_species("NaOH", 0.3, "mol/kg");
box.add_aqueous_species("NaCl", 0.5, "mol/kg");
//box.add_aqueous_species("Ca(OH)2", 0.01, "mol/kg");
//box.add_aqueous_species("CaSO4", 0.01, "mol/kg");
SmartAdimSolver solver(data, box, false);
if (! solver.solve()) {
throw std::runtime_error("Cannot solve bound cond");
}
return solver.get_solution();
}
static void chemitry_step(ChlorideVariables* vars)
{
RawDatabasePtr data = vars->get_database();
for (int node=1; node<vars->get_mesh()->nb_nodes(); ++node) {
AdimensionalSystemConstraints constraints;
Vector total_conc = Vector::Zero(data->nb_component());
for (auto i: data->range_aqueous_component())
{
total_conc(i) = vars->porosity(node)*vars->main_variables()(vars->dof_component(node, i));
}
constraints.set_total_concentrations(total_conc);
constraints.set_saturated_system();
constraints.set_inert_volume_fraction(0.7);
AdimensionalSystemSolution sol = vars->adim_solution(node);
Vector x = sol.main_variables;
AdimensionalSystemSolver solver(data, constraints, vars->adim_solution(node));
solver.get_options().units_set = vars->get_units();
solver.get_options().system_options.cutoff_total_concentration = 1e-14;
solver.get_options().solver_options.set_tolerance(1e-6,1e-14);
micpsolver::MiCPPerformance perf = solver.solve(x, false);
if (perf.return_code < micpsolver::MiCPSolverReturnCode::Success) {
std::cout << "\n === \n" << total_conc << "\n === \n" << std::endl;
throw std::runtime_error("Failed to solve chemistry step");
}
auto adim_sol = solver.get_raw_solution(x);
vars->set_adim_solution(node, adim_sol);
}
}
int main()
{
std::cerr.flush();
specmicp::logger::ErrFile::stream() = &std::cout;
specmicp::stdlog::ReportLevel() = specmicp::logger::Warning;
auto tunits = units::SI_units;
tunits.length = units::LengthUnit::centimeter;
mesh::Mesh1DPtr amesh = get_mesh(3.0, 0.1);
const index_t nb_nodes = amesh->nb_nodes();
std::cout << "nb nodes : " << nb_nodes << std::endl;
auto data = get_database();
index_t i_na = data->get_id_component("Na[+]");
index_t i_cl = data->get_id_component("Cl[-]");
index_t i_ca = data->get_id_component("Ca[2+]");
index_t i_h = data->get_id_component("H[+]");
index_t i_ho = data->get_id_component("HO[-]");
ChlorideVariablesInterface interface(data, amesh, tunits);
std::vector<AdimensionalSystemSolution> sols = {
initial_conditions(data, tunits), boundary_conditions(data, tunits)};
std::vector<index_t> indices(nb_nodes, 0);
indices[0] = 1;
interface.set_adim_solutions(indices, sols);
interface.set_diffusion_coefficient_component(i_na, 1.334e-5);
interface.set_default_diffusion_coefficient_component(1.0e-5);
interface.set_default_diffusion_coefficient_aqueous(1.0e-5);
interface.set_diffusion_coefficient_component("Cl[-]", 2.032e-5);
interface.set_diffusion_coefficient_aqueous("H[+]", 9.311e-5);
interface.set_diffusion_coefficient_component("HO[-]", 5.273e-5);
//interface.set_diffusion_coefficient_aqueous("HSO4[-]", 1.385e-5);
//interface.set_diffusion_coefficient_component("SO4[2-]", 1.065e-5);
interface.set_default_diffusion_resistance_factor(5.0e-2);
interface.set_potential(0, 0.0);
interface.set_potential(nb_nodes-1, 1.0);
auto variables = interface.get_variables();
std::shared_ptr<BoundaryConditions> bcs = BoundaryConditions::make(amesh, data);
bcs->fix_concentrations_node(0);
bcs->fix_potential_node(0);
bcs->fix_concentrations_node(nb_nodes-1);
bcs->fix_potential_node(nb_nodes-1);
ChlorideTransportStagger stagger(variables, bcs);
stagger.initialize(variables.get());
stagger.set_approximation_method(AdimSolutionPerturbationMethod::component);
auto& opts = stagger.get_options();
opts.absolute_tolerance = 1e-12;
opts.residuals_tolerance = 1e-6;
opts.step_tolerance = 1e-14;
opts.quasi_newton = 1;
opts.maximum_step_length = 1e3;
opts.maximum_iterations = 500;
opts.alpha = 1;
index_t nb_iter = 10000;
index_t dt = 50;
std::vector<scalar_t> currents(nb_iter);
std::ofstream cur_file("migration_current.csv");
cur_file << "Time(s)\tCurrent\n";
for (int i=0; i<nb_iter; ++i) {
std::cout << "timestep : " << i << std::endl;
stagger.initialize_timestep(dt, variables.get());
auto res_0 = stagger.get_residual_0(variables.get());
auto retcode = stagger.restart_timestep(variables.get());
std::cout << "Return code : " << static_cast<int>(retcode) << std::endl;
auto res = stagger.get_residual(variables.get());
//std::cout << res << " - " << res/res_0 << std::endl;
if (retcode < reactmicp::solver::StaggerReturnCode::NotConvergedYet) {
throw std::runtime_error("Failed to solve iteration "+ std::to_string(i) +". Retcode : "+std::to_string(static_cast<int>(retcode)));
}
if (i%2==0) {
cur_file << (i+1)*dt << "\t" << variables->current()(0) << "\n";
}
}
cur_file.close();
//std::cout << " ======= \n" << current << std::endl;
//std::cout << "[\n";
//for (index_t i=0; i<nb_iter; ++i) {
// std::cout << "[" << i*dt/3600 << ", " << current(i) << "],\n";
//}
//std::cout << "]" << std::endl;
std::ofstream outfile("migration_end.csv");
outfile << "Coords\tNa[+]\tCl[-]\tCa[2+]\tpH\tPotential\tCharge\n";
for (index_t node: range(amesh->nb_nodes()))
{
AdimensionalSystemSolutionExtractor extr(variables->adim_solution(node), data, tunits);
auto rho_w = extr.density_water()*1000.;
auto cl = extr.molality_component(i_cl)*rho_w;
auto na = extr.molality_component(i_na)*rho_w;
auto ca = extr.molality_component(i_ca)*rho_w;
auto ph = extr.pH();
outfile << amesh->get_position(node) << "\t"
<< na << "\t"
<< cl << "\t"
<< ca << "\t"
<< ph << "\t"
<< variables->main_variables()(variables->dof_potential(node)) << "\t"
<< extr.charge_balance()*rho_w << "\t"
<< "\n";
}
outfile.close();
}

Event Timeline