Skip to content

Commit 27bf3ea

Browse files
authored
Merge pull request #13315 from KratosMultiphysics/core/deprecate-parameters-iter
[Core] Remove deprecated iteration over `Parameters`
2 parents 7c5b35f + 7ee5d62 commit 27bf3ea

13 files changed

Lines changed: 46 additions & 64 deletions

File tree

applications/CoSimulationApplication/python_scripts/convergence_criteria/absolute_norm_energy_conjugate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(self, settings, solvers):
2929
# Determine if we are looking at the energy difference between two domains (solvers), or just one
3030
self.solver_vec = [solvers[settings["solver"].GetString()]]
3131
is_dual_domain = False
32-
for criteria_option in settings["criteria_options"]:
32+
for criteria_option in settings["criteria_options"].values():
3333
if criteria_option.GetString() == "domain_difference":
3434
is_dual_domain = True
3535
break

applications/DEMApplication/python_scripts/materials_assignation_utility.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def AssignPropertiesToEntities(self):
6969
if pair[1].IsString():
7070
material_name_in_assignation_table = pair[1].GetString()
7171
material_id = None
72-
for material in list_of_materials:
72+
for material in list_of_materials.values():
7373
material_name_in_materials_list = material["material_name"].GetString()
7474
if material_name_in_assignation_table == material_name_in_materials_list:
7575
material_id = material["material_id"].GetInt()

applications/FluidDynamicsHydraulicsApplication/python_scripts/navier_stokes_two_fluid_hydraulic_fractional_solver.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def GetDefaultParameters(cls):
7979
"dynamic_tau" : 1.0,
8080
"tau_nodal":true
8181
}
82-
},
82+
},
8383
"distance_reinitialization_type" :"variational",
8484
"distance_reinitialization_settings":{
8585
},
@@ -105,7 +105,7 @@ def __init__(self, model, custom_settings):
105105
self.condition_name = "TwoFluidNavierStokesWallCondition"
106106
self.element_integrates_in_time = True
107107
self.element_has_nodal_properties = True
108-
108+
109109
# Set the levelset characteristic variables and add them to the convection settings
110110
# These are required to be set as some of the auxiliary processes admit user-defined variables
111111
self._levelset_variable = KratosMultiphysics.DISTANCE
@@ -115,10 +115,10 @@ def __init__(self, model, custom_settings):
115115
self.settings["levelset_convection_settings"].AddEmptyValue("levelset_gradient_variable_name").SetString("DISTANCE_GRADIENT")
116116
self.settings["levelset_convection_settings"].AddEmptyValue("levelset_convection_variable_name").SetString("VELOCITY")
117117
self.settings["levelset_convection_settings"].AddEmptyValue("convection_model_part_name").SetString("LevelSetConvectionModelPart")
118-
118+
119119
self.settings["fractional_splitting_settings"].AddEmptyValue("model_part_name").SetString(self.main_model_part.Name )
120-
121-
120+
121+
122122
dynamic_tau = self.settings["formulation"]["dynamic_tau"].GetDouble()
123123
self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.DYNAMIC_TAU, dynamic_tau)
124124

@@ -220,25 +220,25 @@ def InitializeSolutionStep(self):
220220
# Inlet and outlet water discharge is calculated for current time step, first discharge and the considering the time step inlet and outlet volume is calculated
221221
if self.mass_source:
222222
self._ComputeStepInitialWaterVolume()
223-
223+
224224
# Recompute the BDF2 coefficients
225225
(self.time_discretization).ComputeAndSaveBDFCoefficients(self.GetComputingModelPart().ProcessInfo)
226226

227227
# STEP I: NS Fractional part 1
228-
# Perform the pure convection of the fractional velocity which corresponds to the first part of the NS fractional splitting.
228+
# Perform the pure convection of the fractional velocity which corresponds to the first part of the NS fractional splitting.
229229
self.__PerformNSFractionalSplitting()
230230
KratosMultiphysics.Logger.PrintInfo(self.__class__.__name__, "Navier Stokes fractional convection part is performed.")
231-
232-
# STEP II: Convect the free surface according to the fractional velocity
233-
# Before doing this second step, the fractional velocity data is copied to the velocity data since the level set convection process takes velocity variable as convection variable.
231+
232+
# STEP II: Convect the free surface according to the fractional velocity
233+
# Before doing this second step, the fractional velocity data is copied to the velocity data since the level set convection process takes velocity variable as convection variable.
234234
# And the previous previous velocity is copied in an auxiliar variable
235235
KratosMultiphysics.VariableUtils().CopyModelPartNodalVar(KratosCFD.FRACTIONAL_VELOCITY,KratosMultiphysics.VELOCITY, self.main_model_part, self.main_model_part, 0, 0)
236236
KratosMultiphysics.VariableUtils().CopyModelPartNodalVar(KratosMultiphysics.VELOCITY,KratosCFD.AUXILIAR_VECTOR_VELOCITY, self.main_model_part, self.main_model_part, 0, 0)
237237

238238
self.__PerformLevelSetConvection()
239239
KratosMultiphysics.Logger.PrintInfo(self.__class__.__name__, "Level-set convection is performed.")
240240

241-
# After the convection process, the velocity is copied back to the original state.
241+
# After the convection process, the velocity is copied back to the original state.
242242
KratosMultiphysics.VariableUtils().CopyModelPartNodalVar(KratosCFD.AUXILIAR_VECTOR_VELOCITY,KratosMultiphysics.VELOCITY, self.main_model_part, self.main_model_part, 0, 0)
243243

244244
# Perform distance correction to prevent ill-conditioned cuts
@@ -272,14 +272,14 @@ def FinalizeSolutionStep(self):
272272

273273
# Prepare distance correction for next step
274274
self._GetDistanceModificationProcess().ExecuteFinalizeSolutionStep()
275-
276-
# FinalizeSolutionStep of Navier-Stokes strategy
275+
276+
# FinalizeSolutionStep of Navier-Stokes strategy
277277
self._GetSolutionStrategy().FinalizeSolutionStep()
278278

279279
def _ComputeStepInitialWaterVolume(self):
280-
281-
# This function calculates the theoretical water volume at each time step.
282-
# Reminder: Despite adding the source term to both air and water, the absolute volume error
280+
281+
# This function calculates the theoretical water volume at each time step.
282+
# Reminder: Despite adding the source term to both air and water, the absolute volume error
283283
# is referenced to the water volume, since what is lost from water is gained by air and vice versa.
284284

285285
# Here the initial water volume of the system is calculated without considering inlet and outlet flow rate
@@ -299,8 +299,8 @@ def _ComputeStepInitialWaterVolume(self):
299299
self.__initial_water_system_volume = system_water_volume
300300

301301
def _ComputeVolumeError(self):
302-
# In this function, the volume of the cut elements is calculated,
303-
# corresponding to the portions of water and air volumes, as this is the domain where the source term will be added.
302+
# In this function, the volume of the cut elements is calculated,
303+
# corresponding to the portions of water and air volumes, as this is the domain where the source term will be added.
304304
# Meanwhile, the absolute error is calculated within the water domain
305305

306306
if self.mass_source:
@@ -336,7 +336,7 @@ def __PerformNSFractionalSplitting(self):
336336
self._GetNSFractionalSplittingProcess().Execute()
337337
# Trasfer velocity slip condition to fractional velocity
338338
self.__SlipConditonFractionalFixity()
339-
# TODO: Remove those methods as soon as a new hydraulic slip process is done.
339+
# TODO: Remove those methods as soon as a new hydraulic slip process is done.
340340
def __SlipConditonFractionalFixity(self):
341341
for node in self.GetComputingModelPart().Nodes:
342342
if node.Is(KratosMultiphysics.SLIP):
@@ -345,7 +345,7 @@ def __SlipConditonFractionalFixity(self):
345345
v= node.GetSolutionStepValue(KratosCFD.FRACTIONAL_VELOCITY)
346346
v_prooj = self.DotProduct(v,n)
347347
v-= v_prooj*n
348-
node.SetSolutionStepValue(KratosCFD.FRACTIONAL_VELOCITY,v)
348+
node.SetSolutionStepValue(KratosCFD.FRACTIONAL_VELOCITY,v)
349349
def VelocityBoundaryConditionFractional(self, fractional_velocity_componentes, velocity_components):
350350
for node in self.GetComputingModelPart().Nodes:
351351
if node.IsFixed(velocity_components):
@@ -381,7 +381,7 @@ def GetAuxMaterialsFileName(mat_file_name, prop_id):
381381

382382
if data_comm.Rank() == 0:
383383
# Create and read an auxiliary materials file for each one of the fields (only on one rank)
384-
for i_material in materials["properties"]:
384+
for i_material in materials["properties"].values():
385385
aux_materials = KratosMultiphysics.Parameters()
386386
aux_materials.AddEmptyArray("properties")
387387
aux_materials["properties"].Append(i_material)
@@ -393,7 +393,7 @@ def GetAuxMaterialsFileName(mat_file_name, prop_id):
393393
data_comm.Barrier()
394394

395395
# read the files on all ranks
396-
for i_material in materials["properties"]:
396+
for i_material in materials["properties"].values():
397397
aux_materials_filename = GetAuxMaterialsFileName(materials_filename, i_material["properties_id"].GetInt())
398398
aux_material_settings = KratosMultiphysics.Parameters("""{"Parameters": {"materials_filename": ""}} """)
399399
aux_material_settings["Parameters"]["materials_filename"].SetString(aux_materials_filename)
@@ -403,7 +403,7 @@ def GetAuxMaterialsFileName(mat_file_name, prop_id):
403403

404404
if data_comm.Rank() == 0:
405405
# remove aux files after every rank read them
406-
for i_material in materials["properties"]:
406+
for i_material in materials["properties"].values():
407407
aux_materials_filename = GetAuxMaterialsFileName(materials_filename, i_material["properties_id"].GetInt())
408408
KratosUtilities.DeleteFileIfExisting(aux_materials_filename)
409409

applications/FluidDynamicsHydraulicsApplication/python_scripts/navier_stokes_two_fluid_hydraulic_solver.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ def GetAuxMaterialsFileName(mat_file_name, prop_id):
466466

467467
if data_comm.Rank() == 0:
468468
# Create and read an auxiliary materials file for each one of the fields (only on one rank)
469-
for i_material in materials["properties"]:
469+
for i_material in materials["properties"].values():
470470
aux_materials = KratosMultiphysics.Parameters()
471471
aux_materials.AddEmptyArray("properties")
472472
aux_materials["properties"].Append(i_material)
@@ -478,7 +478,7 @@ def GetAuxMaterialsFileName(mat_file_name, prop_id):
478478
data_comm.Barrier()
479479

480480
# read the files on all ranks
481-
for i_material in materials["properties"]:
481+
for i_material in materials["properties"].values():
482482
aux_materials_filename = GetAuxMaterialsFileName(materials_filename, i_material["properties_id"].GetInt())
483483
aux_material_settings = KratosMultiphysics.Parameters("""{"Parameters": {"materials_filename": ""}} """)
484484
aux_material_settings["Parameters"]["materials_filename"].SetString(aux_materials_filename)
@@ -488,7 +488,7 @@ def GetAuxMaterialsFileName(mat_file_name, prop_id):
488488

489489
if data_comm.Rank() == 0:
490490
# remove aux files after every rank read them
491-
for i_material in materials["properties"]:
491+
for i_material in materials["properties"].values():
492492
aux_materials_filename = GetAuxMaterialsFileName(materials_filename, i_material["properties_id"].GetInt())
493493
KratosUtilities.DeleteFileIfExisting(aux_materials_filename)
494494

applications/GeoMechanicsApplication/python_scripts/geomechanics_solver.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,10 @@ def PrepareModelPart(self):
207207
self.main_model_part.ProcessInfo.SetValue(KratosMultiphysics.STEP, 0)
208208
self.computing_model_part_name = "porous_computational_model_part"
209209

210-
sub_model_part_names = [f"sub_{name.GetString()}" for name in self.settings["body_domain_sub_model_part_list"]]
210+
sub_model_part_names = [f"sub_{name.GetString()}" for name in self.settings["body_domain_sub_model_part_list"].values()]
211211
self.body_domain_sub_sub_model_part_list = KratosMultiphysics.Parameters(json.dumps(sub_model_part_names))
212212

213-
sub_model_part_names = [f"sub_{name.GetString()}" for name in self.settings["loads_sub_model_part_list"]]
213+
sub_model_part_names = [f"sub_{name.GetString()}" for name in self.settings["loads_sub_model_part_list"].values()]
214214
self.loads_sub_sub_model_part_list = KratosMultiphysics.Parameters(json.dumps(sub_model_part_names))
215215

216216
if not self.main_model_part.ProcessInfo[KratosMultiphysics.IS_RESTARTED]:
@@ -357,7 +357,7 @@ def _add_water_variables(self):
357357
self.main_model_part.AddNodalSolutionStepVariable(GeoMechanicsApplication.NORMAL_FLUID_FLUX)
358358
# Add variables for the water conditions
359359
self.main_model_part.AddNodalSolutionStepVariable(GeoMechanicsApplication.HYDRAULIC_DISCHARGE)
360-
360+
361361
# Add integration \ gauss point values that will likely need extrapolating to node
362362
self.main_model_part.AddNodalSolutionStepVariable(GeoMechanicsApplication.HYDRAULIC_HEAD)
363363
self.main_model_part.AddNodalSolutionStepVariable(KratosMultiphysics.CAUCHY_STRESS_TENSOR)

applications/MPMApplication/python_scripts/mpm_analysis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def _AddFrictionAuxiliaryVariables(self, project_parameters):
4444
friction_active = False
4545

4646
for proc_list in project_parameters["processes"].values():
47-
for proc in proc_list:
47+
for proc in proc_list.values():
4848
if proc.Has("process_name") and proc["process_name"].GetString() == "ApplyMPMSlipBoundaryProcess":
4949
proc_params = proc["Parameters"]
5050

applications/RomApplication/python_scripts/rom_analysis.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def _CreateSolver(self):
2828
for name in self.project_parameters["output_processes"].keys():
2929
if name=="rom_output":
3030
rom_output_parameters = self.project_parameters["output_processes"]["rom_output"]
31-
for parameter_set in rom_output_parameters:
31+
for parameter_set in rom_output_parameters.values():
3232
if parameter_set["python_module"].GetString() == "calculate_rom_basis_output_process":
3333
if parameter_set["Parameters"].Has("rom_basis_output_name"):
3434
self.rom_basis_output_name = parameter_set["Parameters"]["rom_basis_output_name"].GetString()
@@ -261,7 +261,7 @@ def ModifyAfterSolverInitialize(self):
261261
self.__petrov_galerkin_training_utility = PetrovGalerkinTrainingUtility(
262262
self._GetSolver(),
263263
self.rom_parameters)
264-
264+
265265

266266
def ModifyInitialGeometry(self):
267267
super().ModifyInitialGeometry()
@@ -277,7 +277,7 @@ def ModifyInitialGeometry(self):
277277
self._GetSolver()._GetBuilderAndSolver().SetDecoderParameters(computing_model_part, len(NNLayers), SVDPhiMatrices[0], SVDPhiMatrices[1], SVDPhiMatrices[2], refSnapshot)
278278
for i, layer in enumerate(NNLayers):
279279
self._GetSolver()._GetBuilderAndSolver().SetNNLayer(computing_model_part, i, layer)
280-
280+
281281
nodal_unknown_names= self.project_parameters["solver_settings"]["rom_settings"]["nodal_unknowns"].GetStringArray()
282282
nodal_dofs = len(nodal_unknown_names)
283283
nodal_unknowns=[]
@@ -302,7 +302,7 @@ def ModifyInitialGeometry(self):
302302
computing_model_part.SetValue(KratosROM.ROM_SOLUTION_BASE, KratosMultiphysics.Vector(q))
303303
computing_model_part.SetValue(KratosROM.ROM_SOLUTION_TOTAL, KratosMultiphysics.Vector(q))
304304
computing_model_part.SetValue(KratosROM.ROM_SOLUTION_INCREMENT, KratosMultiphysics.Vector(np.zeros_like(q)))
305-
305+
306306
s_init = np.array(self._GetSolver()._GetBuilderAndSolver().RunDecoder(computing_model_part, q))
307307
print(s_init.shape)
308308

@@ -311,7 +311,7 @@ def ModifyInitialGeometry(self):
311311
for nodal_var in nodal_unknowns:
312312
node.SetSolutionStepValue(nodal_var, s_init[i])
313313
i+=1
314-
314+
315315
computing_model_part.SetValue(KratosROM.SOLUTION_BASE, KratosMultiphysics.Vector(s_init))
316316

317317
# Initialize nodal ROM_BASIS to zeros

applications/SwimmingDEMApplication/python_scripts/swimming_sphere_strategy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def GetRotationalSchemeInstance(self, class_name):
7474

7575
def GetHydrodynamicLawParametersIfItExists(self, properties):
7676
if self.project_parameters.Has('properties'):
77-
for p in self.project_parameters["properties"]:
77+
for p in self.project_parameters["properties"].values():
7878
return p['hydrodynamic_law_parameters']
7979
return None
8080

applications/SystemIdentificationApplication/python_scripts/responses/damage_detection_response.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def __init__(self, name: str, model: Kratos.Model, parameters: Kratos.Parameters
5858

5959
# reading test analsis list
6060
self.list_of_test_analysis_data: 'list[tuple[ExecutionPolicyDecorator, DataIO, str, float]]' = []
61-
for params in parameters["test_analysis_list"]:
61+
for params in parameters["test_analysis_list"].values():
6262
params.ValidateAndAssignDefaults(default_settings["test_analysis_list"][0])
6363
primal_analysis_name = params["primal_analysis_name"].GetString()
6464
sensor_measurement_data_file_name = params["sensor_measurement_csv_file"].GetString()
@@ -92,7 +92,7 @@ def Initialize(self) -> None:
9292

9393
def Check(self) -> None:
9494
pass
95-
95+
9696
def Finalize(self) -> None:
9797
self.adjoint_analysis.Finalize()
9898

kratos/python/add_kratos_parameters_to_python.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,10 @@ void AddKratosParametersToPython(pybind11::module& m)
127127
.def("__getitem__", GetValue)
128128
.def("__setitem__", &Parameters::SetArrayItem)
129129
.def("__getitem__", GetArrayItem)
130-
.def("__iter__", [](Parameters& self){ return py::make_iterator(self.begin(), self.end()); } , py::keep_alive<0,1>())
130+
.def("__iter__", [](Parameters& self){
131+
KRATOS_ERROR << "iterating through Parameters is ambiguous. Use \"keys\", \"values\" or \"items\" instead.";
132+
return py::make_iterator(self.begin(), self.end());
133+
} , py::keep_alive<0,1>())
131134
.def("items", &items )
132135
.def("keys", &keys )
133136
.def("values", &values )

0 commit comments

Comments
 (0)