Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing dll tests #30

Merged
merged 5 commits into from
Dec 3, 2024
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
14 changes: 7 additions & 7 deletions cadet/cadet_dll.py
Original file line number Diff line number Diff line change
Expand Up @@ -2055,35 +2055,35 @@ def _load_solution_io(
if nPort == 1:
if single_as_multi_port:
for comp in range(nComp):
comp_out = numpy.squeeze(out[..., comp])
comp_out = out[..., 0, comp]
solution[f'{solution_str}_port_000_comp_{comp:03d}'] = comp_out
else:
for comp in range(nComp):
comp_out = numpy.squeeze(out[..., comp])
comp_out = out[..., comp]
solution[f'{solution_str}_comp_{comp:03d}'] = comp_out
else:
for port in range(nPort):
for comp in range(nComp):
comp_out = numpy.squeeze(out[..., port, comp])
comp_out = out[..., port, comp]
solution[f'{solution_str}_port_{port:03d}_comp_{comp:03d}'] = comp_out
else:
for comp in range(nComp):
comp_out = numpy.squeeze(out[..., comp])
comp_out = out[..., comp]
solution[f'{solution_str}_comp_{comp:03d}'] = comp_out
else:
if split_ports_data:
if nPort == 1:
if single_as_multi_port:
solution[f'{solution_str}_port_000'] = out
else:
solution[solution_str] = numpy.squeeze(out[..., 0, :])
solution[solution_str] = out[..., 0, :]
else:
for port in range(nPort):
port_out = numpy.squeeze(out[..., port, :])
port_out = out[..., port, :]
solution[f'{solution_str}_port_{port:03d}'] = port_out
else:
if nPort == 1 and nPort_idx is not None:
solution[solution_str] = numpy.squeeze(out[..., 0, :])
solution[solution_str] = out[..., 0, :]
else:
solution[solution_str] = out

Expand Down
67 changes: 43 additions & 24 deletions cadet/h5.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,42 +254,47 @@ def __setitem__(self, key: str, value: Any) -> None:
obj[parts[-1]] = value


def convert_from_numpy(data: Dict, func: callable) -> Dict:
def convert_from_numpy(data: Dict, func: Optional[callable]=None) -> Dict:
"""
Convert numpy objects to native Python types.
Convert a dictionary with NumPy objects into native Python types.

Parameters
----------
data : Dict
Input dictionary potentially containing numpy objects.
data : dict
The input dictionary with potential NumPy types.
func : callable
Transformation function for dictionary keys.
A function to transform the keys.

Returns
-------
Dict
Dictionary with converted data.
dict
A dictionary with transformed keys and native Python types.
"""
ans = Dict()
for key_original, item in data.items():
key = func(key_original)
ans = {}
for key, item in data.items():
if func is not None:
key = func(key)

# Handle NumPy-specific types
if isinstance(item, numpy.ndarray):
item = item.tolist()

if isinstance(item, numpy.generic):
elif isinstance(item, numpy.generic):
item = item.item()

if isinstance(item, bytes):
item = item.decode('ascii')
# Handle bytes
elif isinstance(item, bytes):
item = item.decode('utf-8')

if isinstance(item, Dict):
ans[key_original] = convert_from_numpy(item, func)
# Recursive handling of nested dictionaries
if isinstance(item, dict): # Assuming Dict is replaced with dict
ans[key] = convert_from_numpy(item, func)
else:
ans[key] = item

return ans


def recursively_load_dict(data: dict, func: callable) -> Dict:
def recursively_load_dict(data: dict, func: Optional[callable]=None) -> Dict:
"""
Recursively load data from a dictionary.

Expand All @@ -306,32 +311,46 @@ def recursively_load_dict(data: dict, func: callable) -> Dict:
Dictionary with loaded data.
"""
ans = Dict()
for key_original, item in data.items():
key = func(key_original)
for key, item in data.items():
if func is not None:
key = func(key)

if isinstance(item, dict):
ans[key] = recursively_load_dict(item, func)
else:
# Handle bytes
if isinstance(item, numpy.int32):
item = int(item)
elif isinstance(item, bytes):
item = item.decode('utf-8')

ans[key] = item
return ans


def set_path(obj: Dict, path: str, value: Any) -> None:
def set_path(obj: Dict[str, Any], path: str, value: Any) -> None:
"""
Set a value within a nested dictionary given a path.
Set a value within a nested dictionary given a slash-separated path.

Parameters
----------
obj : Dict
obj : Dict[str, Any]
Dictionary to set the value in.
path : str
Slash-separated path indicating where to set the value.
value : Any
Value to be set at the specified path.
"""
path_parts = [i for i in path.split('/') if i]

temp = obj
for part in path_parts[:-1]:
if part not in temp or not isinstance(temp[part], dict):
temp[part] = {} # Create intermediate dictionaries as needed
temp = temp[part]

value = recursively_load_dict(value)

temp[path_parts[-1]] = value


Expand Down Expand Up @@ -413,9 +432,9 @@ def recursively_save(h5file: h5py.File, path: str, dic: Dict, func: callable) ->
if isinstance(item, dict):
recursively_save(h5file, path + key + '/', item, func)
elif isinstance(item, str):
value = numpy.array(item.encode('ascii'))
value = numpy.array(item.encode('utf-8'))
elif isinstance(item, list) and all(isinstance(i, str) for i in item):
value = numpy.array([i.encode('ascii') for i in item])
value = numpy.array([i.encode('utf-8') for i in item])
else:
try:
value = numpy.array(item)
Expand Down
89 changes: 87 additions & 2 deletions tests/test_dll.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ def setup_model(
n_partypes=1,
include_sensitivity=False,
file_name='LWE.h5',
n_components=4
):
"""
Set up and initialize a CADET model template.
Expand Down Expand Up @@ -44,6 +45,8 @@ def setup_model(
file_name : str, optional
The name of the file to which the CADET model is written.
The default is 'LWE.h5'.
n_components : int, optional
Number of components for the simulation. The default is 4.

Returns
-------
Expand Down Expand Up @@ -83,7 +86,7 @@ def setup_model(
interface.
"""

cadet_model = Cadet(install_path=cadet_root, use_dll=True)
cadet_model = Cadet(install_path=cadet_root, use_dll=use_dll)

args = [
cadet_model.cadet_create_lwe_path,
Expand Down Expand Up @@ -113,6 +116,37 @@ def setup_model(

cadet_model.filename = file_name
cadet_model.load()
if n_components < 4:
unit_000 = cadet_model.root.input.model.unit_000
unit_000.update({
'adsorption_model': 'LINEAR', 'col_dispersion': 5.75e-08,
'col_length': 0.014, 'col_porosity': 0.37,
'cross_section_area': 0.0003141592653589793,
'film_diffusion': [6.9e-06, ] * n_components,
'film_diffusion_multiplex': 0, 'init_c': [0., ] * n_components,
'init_q': [0., ] * n_components, 'nbound': [1, ] * n_components,
'ncomp': 1, 'npartype': 1, 'par_coreradius': 0.0,
'par_diffusion': [7.00e-10, ] * n_components, 'par_geom': 'SPHERE',
'par_porosity': 0.75, 'par_radius': 4.5e-05,
'par_surfdiffusion': [0., ] * n_components, 'unit_type': 'GENERAL_RATE_MODEL',
'velocity': 1.0,
'adsorption': {'is_kinetic': 0, 'lin_ka': [0.] * n_components, 'lin_kd': [1.] * n_components},
})
cadet_model.root.input.model.unit_001.update(
{'inlet_type': b'PIECEWISE_CUBIC_POLY', 'ncomp': 1, 'unit_type': b'INLET',
'sec_000': {'const_coeff': [50., ], 'cube_coeff': [0., ],
'lin_coeff': [0., ], 'quad_coeff': [0., ]},
'sec_001': {'const_coeff': [50., ], 'cube_coeff': [0., ],
'lin_coeff': [0., ], 'quad_coeff': [0., ]},
'sec_002': {'const_coeff': [100., ], 'cube_coeff': [0., ],
'lin_coeff': [0.2], 'quad_coeff': [0., ]}}
)
# if we don't save and re-load the model we get windows access violations.
# Interesting case for future tests, not what I want to test now.
cadet_model.save()
cadet_model = Cadet(install_path=cadet_root, use_dll=use_dll)
cadet_model.filename = file_name
cadet_model.load()

return cadet_model

Expand Down Expand Up @@ -254,7 +288,10 @@ def run_simulation_with_options(use_dll, model_options, solution_recorder_option
model = setup_model(cadet_root, use_dll, **model_options)
setup_solution_recorder(model, **solution_recorder_options)

model.run_load()
return_info = model.run_load()

if return_info.return_code != 0:
raise RuntimeError(return_info)

return model

Expand Down Expand Up @@ -285,6 +322,13 @@ def run_simulation_with_options(use_dll, model_options, solution_recorder_option
'include_sensitivity': False,
}

grm_template_1_comp = {
'model': 'GENERAL_RATE_MODEL',
'n_partypes': 1,
'include_sensitivity': False,
'n_components': 1,
}

grm_template_sens = {
'model': 'GENERAL_RATE_MODEL',
'n_partypes': 1,
Expand Down Expand Up @@ -497,6 +541,46 @@ def __repr__(self):
},
},
)
# %% GRM 1 Comp

grm_1_comp = Case(
name='grm_1_comp',
model_options=grm_template_1_comp,
solution_recorder_options=no_split_options,
expected_results={
'last_state_y': (103,),
'last_state_ydot': (103,),
'coordinates_unit_000': {
'axial_coordinates': (10,),
'particle_coordinates_000': (4,),
},
'solution_times': (1501,),
'solution_unit_000': {
'last_state_y': (101,),
'last_state_ydot': (101,),
'soldot_bulk': (1501, 10, 1),
'soldot_flux': (1501, 1, 10, 1),
'soldot_inlet': (1501, 1),
'soldot_outlet': (1501, 1),
'soldot_particle': (1501, 10, 4, 1),
'soldot_solid': (1501, 10, 4, 1),
'solution_bulk': (1501, 10, 1),
'solution_flux': (1501, 1, 10, 1),
'solution_inlet': (1501, 1),
'solution_outlet': (1501, 1),
'solution_particle': (1501, 10, 4, 1),
'solution_solid': (1501, 10, 4, 1),
},
'solution_unit_001': {
'last_state_y': (1,),
'last_state_ydot': (1,),
'soldot_inlet': (1501, 1),
'soldot_outlet': (1501, 1),
'solution_inlet': (1501, 1),
'solution_outlet': (1501, 1),
},
},
)

# %% GRM Split

Expand Down Expand Up @@ -867,6 +951,7 @@ def __repr__(self):
lrm,
lrmp,
grm,
grm_1_comp,
grm_split,
grm_sens,
grm_par_types,
Expand Down
Loading