#! /usr/bin/env python
"""Rectangle mesh convergence workflow

Requires the following ``SConscript(..., exports=[])``

* ``env`` - The SCons construction environment with the following required keys

  * ``abaqus_source_abspath`` - String absolute path to the EABM's Abaqus journal files
  * ``python_source_abspath`` - String absolute path to the EABM's Python 3 files
  * ``datacheck_alias`` - String for the alias collecting the datacheck workflow targets
  * ``unconditional_build`` - Boolean flag to force building of conditionally ignored targets
  * ``abaqus`` - String path for the Abaqus executable
"""

import pathlib

import waves

from eabm_package.python.rectangle_compression_mesh_convergence import parameter_schema

# Inherit the parent construction environment
Import('env')

# Comment used in tutorial code snippets: marker-1

# Set project-wide paths with os-agnostic path separators
abaqus_source_abspath = pathlib.Path(env["abaqus_source_abspath"])
python_source_abspath = pathlib.Path(env["python_source_abspath"])

# Simulation variables
build_directory = pathlib.Path(Dir('.').abspath)
workflow_name = build_directory.name
output_file_type = "h5"
parameter_study_file = build_directory / f"parameter_study.{output_file_type}"
previous_parameter_study = str(parameter_study_file) if parameter_study_file.exists() else None
model = "rectangle"
simulation_constants = {
    'width': 1.0,
    'height': 1.0,
    'displacement': -0.01
}

# Collect the target nodes to build a concise alias for all targets
workflow = []
datacheck = []

# Comment used in tutorial code snippets: marker-2

# Parameter Study with Cartesian Product
parameter_generator = waves.parameter_generators.CartesianProduct(
    parameter_schema,
    output_file=parameter_study_file,
    output_file_type=output_file_type,
    previous_parameter_study=previous_parameter_study)
parameter_generator.write()

# Comment used in tutorial code snippets: marker-3

# Geometry
journal_file = f"{model}_geometry"
journal_options = "--width ${width} --height ${height}"
workflow.extend(env.AbaqusJournal(
    target=[f"{journal_file}.cae", f"{journal_file}.jnl"],
    source=[f"{abaqus_source_abspath / journal_file}.py"],
    journal_options=journal_options,
    width=simulation_constants['width'],
    height=simulation_constants['height']))

# Partition
journal_file = f"{model}_partition"
journal_options = "--width ${width} --height ${height}"
partition_targets = env.AbaqusJournal(
    target=[f"{journal_file}.cae", f"{journal_file}.jnl"],
    source=[f"{abaqus_source_abspath / journal_file}.py", f"{model}_geometry.cae"],
    journal_options=journal_options,
    width=simulation_constants['width'],
    height=simulation_constants['height'])
workflow.extend(partition_targets)
partition_cae_object = partition_targets[0]
partition_cae_file = pathlib.Path(partition_cae_object.abspath)

# Parameterized targets must live inside current simulation_variables for loop
for set_name, parameters in parameter_generator.parameter_study_to_dict().items():
    set_name = pathlib.Path(set_name)
    simulation_variables = {**parameters, **simulation_constants}

    # Comment used in tutorial code snippets: marker-4

    # Mesh
    journal_file = f"{model}_mesh"
    journal_options = "--global-seed ${global_seed} --input-file ${input_file} --output-file ${output_file}"
    workflow.extend(env.AbaqusJournal(
        target=[f"{set_name / journal_file}.inp",
                f"{set_name / journal_file}.cae",
                f"{set_name / journal_file}.jnl"],
        source=[f"{abaqus_source_abspath / journal_file}.py",
                partition_cae_object],
        journal_options=journal_options,
        global_seed=simulation_variables['global_seed'],
        input_file=partition_cae_file.with_suffix(''),
        output_file=journal_file))

    # SolverPrep
    abaqus_source_list = [
        abaqus_source_abspath / f"{model}_compression.inp.in",
        abaqus_source_abspath / "assembly.inp",
        abaqus_source_abspath / "boundary.inp",
        abaqus_source_abspath / "field_output.inp",
        abaqus_source_abspath / "materials.inp",
        abaqus_source_abspath / "parts.inp",
        abaqus_source_abspath / "history_output.inp"
    ]
    abaqus_source_list = [pathlib.Path(source_file) for source_file in abaqus_source_list]
    workflow.extend(waves.scons_extensions.copy_substitute(
        abaqus_source_list,
        substitution_dictionary=waves.scons_extensions.substitution_syntax(simulation_variables),
        build_subdirectory=set_name))

# Comment used in tutorial code snippets: marker-5

    # Abaqus Solve
    solve_source_list = [f"{set_name / source_file.name.rstrip('.in')}" for source_file in abaqus_source_list]
    solve_source_list.append([f"{set_name / journal_file}.inp"])
    job_name = pathlib.Path(solve_source_list[0]).stem
    datacheck_name = f"{job_name}_DATACHECK"
    datacheck_suffixes = ('023', 'mdl', 'sim', 'stt')
    abaqus_options='-double both'
    datacheck.extend(env.AbaqusSolver(
        target=[f"{set_name / datacheck_name}.{suffix}" for suffix in datacheck_suffixes],
        source=solve_source_list,
        job_name=datacheck_name,
        abaqus_options=f'{abaqus_options} -datacheck'))

    workflow.extend(env.AbaqusSolver(
        target=[f"{set_name / job_name}.sta"],
        source=solve_source_list,
        job_name=job_name,
        abaqus_options=abaqus_options))

    # Extract Abaqus
    extract_source_list = [f"{set_name / job_name}.odb"]
    workflow.extend(env.AbaqusExtract(
        target=[f"{set_name / job_name}.h5"],
        source=extract_source_list))

# Comment used in tutorial code snippets: marker-6

# Post-processing
plot_name = "stress_strain_comparison"
post_processing_source = [f"{pathlib.Path(set_name) / job_name}_datasets.h5" for set_name in
                          parameter_generator.parameter_study.parameter_sets.values]
script_options = "--input-file ${SOURCES[2:].abspath}"
script_options += " --output-file ${TARGET.file} --x-units 'mm/mm' --y-units 'MPa'"
script_options += " --parameter-study-file ${SOURCES[1].abspath}"
workflow.extend(env.PythonScript(
    target=[f"{plot_name}.pdf", f"{plot_name}.csv"],
    source=[f"{python_source_abspath}/post_processing.py", parameter_study_file.name] + post_processing_source,
    script_options=script_options))

plot_name = "mesh_convergence_stress"
selection_dict = python_source_abspath / f"{plot_name}.yaml"
script_options = "--input-file " + " ".join(str(path) for path in post_processing_source)
script_options += " --output-file ${TARGET.file} --x-units 'mm' --y-units 'MPa' --x-var 'global_seed' --y-var 'S'"
script_options += f" --parameter-study-file {parameter_study_file.name}"
script_options += f" --selection-dict {selection_dict}"
workflow.extend(env.PythonScript(
    target=[f"{plot_name}.pdf", f"{plot_name}.csv"],
    source=[f"{python_source_abspath}/post_processing.py", parameter_study_file.name] + post_processing_source,
    script_options=script_options))

# Collector alias based on parent directory name
env.Alias(workflow_name, workflow)
env.Alias(f"{workflow_name}_datacheck", datacheck)
env.Alias(env['datacheck_alias'], datacheck)

if not env['unconditional_build'] and not env['abaqus']:
    print(f"Program 'abaqus' was not found in construction environment. Ignoring '{workflow_name}' target(s)")
    Ignore(['.', workflow_name], workflow)
    Ignore(['.', model], datacheck)
