Skip to content

Commit

Permalink
Fix/read write modes (#122)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
chrpetre and pre-commit-ci[bot] authored Oct 6, 2023
1 parent 4897685 commit bfe9283
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 80 deletions.
16 changes: 4 additions & 12 deletions examples/evaluate/04-TBROM_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@
# files.

import os
import struct

import ansys.fluent.core as pyfluent
from ansys.fluent.visualization import set_config
from ansys.fluent.visualization.pyvista import Graphics
import matplotlib.image as img
import matplotlib.pyplot as plt
import numpy as np
from pytwin import TwinModel, download_file

twin_file = download_file("ThermalTBROM_23R1_other.twin", "twin_files", force_download=True)
Expand Down Expand Up @@ -80,17 +80,9 @@ def snapshot_to_cfd(snapshot_file, geometry_file, field_name, outputFilePath):
field of scalar data (temperature field).
"""

with open(geometry_file, "rb") as geo, open(snapshot_file, "rb") as snp:
nb = struct.unpack("Q", snp.read(8))[0]
struct.unpack("Q", geo.read(8))
res_list = []
for i in range(nb):
res_line = []
res_line.append(struct.unpack("d", geo.read(8))[0])
res_line.append(struct.unpack("d", geo.read(8))[0])
res_line.append(struct.unpack("d", geo.read(8))[0])
res_line.append(struct.unpack("d", snp.read(8))[0])
res_list.append(res_line)
geometry_data = np.fromfile(geometry_file, dtype=np.double, offset=8).reshape(-1, 3)
snapshot_data = np.fromfile(snapshot_file, dtype=np.double, offset=8).reshape(-1, 1)
res_list = np.hstack((geometry_data, snapshot_data))

with open(outputFilePath, "w") as ipfile:
ipfile.write("3\n") # IP file format
Expand Down
16 changes: 3 additions & 13 deletions examples/evaluate/05-TBROM_coSimulation_pyMAPDL.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@
# Perform required imports, which include downloading and importing the input
# files, and launch an instance of MAPDL.

import struct

from ansys.mapdl.core import launch_mapdl
import numpy as np
import pandas as pd
Expand Down Expand Up @@ -72,17 +70,9 @@ def snapshot_to_fea(snapshot_file, geometry_file):
"""Create a Pandas dataframe containing the x, y, z coordinates for the ROM
and snapshot file results."""

with open(geometry_file, "rb") as geo, open(snapshot_file, "rb") as snp:
nb = struct.unpack("Q", snp.read(8))[0]
struct.unpack("Q", geo.read(8))
res_list = []
for i in range(nb):
res_line = []
res_line.append(struct.unpack("d", geo.read(8))[0])
res_line.append(struct.unpack("d", geo.read(8))[0])
res_line.append(struct.unpack("d", geo.read(8))[0])
res_line.append(struct.unpack("d", snp.read(8))[0])
res_list.append(res_line)
geometry_data = np.fromfile(geometry_file, dtype=np.double, offset=8).reshape(-1, 3)
snapshot_data = np.fromfile(snapshot_file, dtype=np.double, offset=8).reshape(-1, 1)
res_list = np.hstack((geometry_data, snapshot_data))

return pd.DataFrame(res_list)

Expand Down
32 changes: 12 additions & 20 deletions examples/evaluate/06-TBROM_input_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@
# ~~~~~~~~~~~~~~~~~~~~~~~~
# Perform required imports, which include downloading and importing the input
# files.
import math

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pytwin import TwinModel, download_file

Expand Down Expand Up @@ -129,16 +129,10 @@ def plot_result_comparison(results: pd.DataFrame):
plt.show()


def norm_vector_field(field: list):
def norm_vector_field(field: np.ndarray):
"""Compute the norm of a vector field."""

norm = []
for i in range(0, int(len(field) / 3)):
x = field[i * 3]
y = field[i * 3 + 1]
z = field[i * 3 + 2]
norm.append(math.sqrt(x * x + y * y + z * z))
return norm
vec = field.reshape((-1, 3))
return np.sqrt((vec * vec).sum(axis=1))


###############################################################################
Expand Down Expand Up @@ -195,9 +189,7 @@ def norm_vector_field(field: list):
outputs.append(twin_model.outputs[item])
outfield = twin_model.generate_snapshot(romname, False) # generating the field output on the entire domain
outputs.append(max(norm_vector_field(outfield)))
outfieldns = twin_model.generate_snapshot(
romname, False, ns
) # generating the field output on "Group_2" outputs.append(max(norm_vector_field(outfield)))
outfieldns = twin_model.generate_snapshot(romname, False, ns) # generating the field output on "Group_2"
outputs.append(max(norm_vector_field(outfieldns)))
results.append(outputs)
points_path = twin_model.generate_points(romname, True) # generating the points file on whole domain
Expand All @@ -208,13 +200,6 @@ def norm_vector_field(field: list):
results, columns=[input_name] + output_name_without_mcs + ["MaxDefSnapshot", "MaxDefSnapshotNs"], dtype=float
)

###############################################################################
# Plot results
# ~~~~~~~~~~~~
# Plot the results and save the image on disk.

plot_result_comparison(sim_results)

###############################################################################
# Simulate the twin in batch mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -231,3 +216,10 @@ def norm_vector_field(field: list):
batch_results = twin_model.evaluate_batch(inputs_df=input_df, field_inputs={romname: {fieldname: inputfieldsnapshots}})
print(batch_results)
output_snapshots = twin_model.generate_snapshot_batch(batch_results, romname)

###############################################################################
# Plot results
# ~~~~~~~~~~~~
# Plot the results.

plot_result_comparison(sim_results)
57 changes: 22 additions & 35 deletions src/ansys/pytwin/evaluate/tbrom.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,11 @@ def generate_points(self, on_disk: bool, output_file_path: str, named_selection:
entire domain is considered.
"""
pointpath = os.path.join(self._tbrom_path, TbRom.OUT_F_KEY, TbRom.TBROM_POINTS)
vec = np.array(TbRom._read_binary(pointpath))
vec = TbRom._read_binary(pointpath)
if named_selection is not None:
pointsids = self.named_selection_indexes(named_selection)
listids = []
for i in pointsids:
for k in range(0, 3):
listids.append(i * 3 + k)
listids = np.concatenate((3 * pointsids, 3 * pointsids + 1, 3 * pointsids + 2))
listids = np.sort(listids)
vec = vec[listids]
if on_disk:
TbRom._write_binary(output_file_path, vec)
Expand Down Expand Up @@ -120,10 +118,12 @@ def generate_snapshot(self, on_disk: bool, output_file_path: str, named_selectio
vec = vec + mc[i] * mnp
if named_selection is not None:
pointsids = self.named_selection_indexes(named_selection)
listids = []
for i in pointsids:
for k in range(0, self.field_output_dim):
listids.append(i * self.field_output_dim + k)
listids = pointsids
if self.field_output_dim > 1:
listids = np.concatenate((self.field_output_dim * pointsids, self.field_output_dim * pointsids + 1))
for k in range(2, self.field_output_dim):
listids = np.concatenate((listids, self.field_output_dim * pointsids + k))
listids = np.sort(listids)
vec = vec[listids]
if on_disk:
TbRom._write_binary(output_file_path, vec)
Expand All @@ -144,8 +144,7 @@ def _reduce_field_input(self, name: str, snapshot_filepath: str):
is parameterized with multiple input fields.
"""
mc = []
vec = TbRom._read_binary(snapshot_filepath)
vecnp = np.array(vec)
vecnp = TbRom._read_binary(snapshot_filepath)
if name is None or self.field_input_count == 1:
basis = list(self._infbasis.values())[0]
else:
Expand Down Expand Up @@ -178,31 +177,19 @@ def _read_basis(filepath):
var = struct.unpack("cccccccccccccccc", f.read(16))[0]
nb_val = struct.unpack("Q", f.read(8))[0]
nb_mc = struct.unpack("Q", f.read(8))[0]
basis = []
for i in range(nb_mc):
vec = []
for j in range(nb_val):
vec.append(struct.unpack("d", f.read(8))[0])
basis.append(vec)
return basis
return np.fromfile(f, dtype=np.double, offset=0).reshape(-1, nb_val)

@staticmethod
def _read_binary(filepath):
with open(filepath, "rb") as f:
nbdof = struct.unpack("Q", f.read(8))[0]
vec = []
for i in range(nbdof):
vec.append(struct.unpack("d", f.read(8))[0])
return vec
return np.fromfile(filepath, dtype=np.double, offset=8).reshape(-1, 1)

@staticmethod
def _write_binary(filepath, vec):
if os.path.exists(filepath):
os.remove(filepath)
with open(filepath, "xb") as f:
f.write(struct.pack("Q", len(vec)))
for i in vec:
f.write(struct.pack("d", i))
vec.tofile(f)
return True

@staticmethod
Expand All @@ -229,15 +216,15 @@ def _read_settings(filepath):

# Create list of name selections indexes
for name, idsList in namedselection.items():
finallist = []
for i in range(0, len(idsList) - 1):
if int(idsList[i]) == -1:
for j in range(int(idsList[i - 1]) + 1, int(idsList[i + 1])):
finallist.append(j)
else:
finallist.append(int(idsList[i]))
finallist.append(int(idsList[len(idsList) - 1]))
tbromns.update({name: finallist})
idsListNp = np.array(idsList)
ind = np.where(idsListNp == -1)
i = 0
for elem in np.nditer(ind):
subarray = np.arange(idsListNp[elem - 1 - i] + 1, idsListNp[elem + 1 - i])
idsListNp = np.delete(idsListNp, elem - i)
idsListNp = np.concatenate((idsListNp, subarray))
i = i + 1
tbromns.update({name: idsListNp})

return [tbromns, dimensionality, outputname, unit]

Expand Down

0 comments on commit bfe9283

Please sign in to comment.