Skip to content

Commit

Permalink
style: lint with black
Browse files Browse the repository at this point in the history
  • Loading branch information
kieran-mackle committed Dec 17, 2023
1 parent 4d5d250 commit b4871bd
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 72 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ __pycache__/
.coverage
docs/build/
testing*
build/

# Miscellaneous
*.stl
Expand Down
35 changes: 13 additions & 22 deletions hypervehicle/components/component.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import meshio
import numpy as np
from stl import mesh
import multiprocess as mp
import meshio
from copy import deepcopy
from typing import Callable, Union
from abc import abstractmethod
from typing import Callable, Union
from hypervehicle.geometry import Vector3
from gdtk.geom.sgrid import StructuredGrid
from hypervehicle.geometry import (
Expand All @@ -13,10 +13,7 @@
MirroredPatch,
OffsetPatchFunction,
)
from hypervehicle.utilities import (
parametricSurfce2stl,
parametricSurfce2vtk
)
from hypervehicle.utilities import parametricSurfce2stl, parametricSurfce2vtk


class AbstractComponent:
Expand Down Expand Up @@ -89,10 +86,7 @@ def analyse(self):
def AssignTags2Celle(patch, length):
# Creates a tag vector for a given patch

tags_definition = {'FreeStream': 1,
'Inlet': 2,
'Outlet': 3,
'Nozzle': 4}
tags_definition = {"FreeStream": 1, "Inlet": 2, "Outlet": 3, "Nozzle": 4}

tags = np.ones(length) * tags_definition[patch.tag]
return tags
Expand All @@ -105,7 +99,7 @@ def __init__(
stl_resolution: int = 2,
verbosity: int = 1,
name: str = None,
output_file_type: str = 'stl'
output_file_type: str = "stl",
) -> None:
# Set verbosity
self.verbosity = verbosity
Expand Down Expand Up @@ -192,8 +186,7 @@ def mesh(self):
self.surface()

# Combine all surface data
surface_data = np.concatenate(
[s[1].data for s in self.surfaces.items()])
surface_data = np.concatenate([s[1].data for s in self.surfaces.items()])

# Create STL mesh
self._mesh = mesh.Mesh(surface_data)
Expand All @@ -206,13 +199,14 @@ def mesh(self, value):

def rotate(self, angle: float = 0, axis: str = "y"):
for key, patch in self.patches.items():
self.patches[key] = RotatedPatch(
patch, np.deg2rad(angle), axis=axis)
self.patches[key] = RotatedPatch(patch, np.deg2rad(angle), axis=axis)

def translate(self, offset: Union[Callable, Vector3]):
if isinstance(offset, Vector3):
# Translate vector into lambda function
def offset_function(x, y, z): return offset
def offset_function(x, y, z):
return offset

else:
offset_function = offset

Expand All @@ -231,8 +225,7 @@ def reflect(self, axis: str = None):
# Create mirrored patches
mirrored_patches = {}
for key, patch in self.patches.items():
mirrored_patches[f"{key}_mirrored"] = MirroredPatch(
patch, axis=axis)
mirrored_patches[f"{key}_mirrored"] = MirroredPatch(patch, axis=axis)

if self._append_reflection:
# Append mirrored patches to original patches
Expand Down Expand Up @@ -292,9 +285,7 @@ def wrapper(key: str, patch):
for result in pool.starmap(wrapper, self.patches.items()):
self.surfaces[result[0]] = result[1]


def cell(self, resolution: int = None):

stl_resolution = self.stl_resolution if resolution is None else resolution

# Check for patches
Expand Down Expand Up @@ -375,8 +366,8 @@ def to_vtk(self, outfile: str = None):
tags = np.concatenate([tags, sss[1][2]])

# Generate mesh in VTK format
cell_ids = [('triangle', cell_ids)]
cell_data = {'tag': [tags]}
cell_ids = [("triangle", cell_ids)]
cell_data = {"tag": [tags]}
vtk_mesh = meshio.Mesh(vertices, cell_ids, cell_data=cell_data)

# Write VTK to file
Expand Down
10 changes: 4 additions & 6 deletions hypervehicle/components/swept.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def __init__(
stl_resolution: int = 2,
verbosity: int = 1,
name: str = None,
tags: dict = None
tags: dict = None,
) -> None:
"""Create a swept component.
Expand All @@ -31,7 +31,6 @@ def __init__(
self.patches_tags = tags
super().__init__(stl_resolution=stl_resolution, verbosity=verbosity, name=name)


def generate_patches(self):
p = SweptPatch(
cross_sections=self.cross_sections,
Expand All @@ -43,7 +42,6 @@ def generate_patches(self):
self.patches["swept_patch_end_1"] = self.cross_sections[-1]

# Assign tags
self.patches["swept_patch"].tag = self.patches_tags['swept_tag']
self.patches["swept_patch_end_0"].tag = self.patches_tags['end_0_tag']
self.patches["swept_patch_end_1"].tag = self.patches_tags['end_1_tag']

self.patches["swept_patch"].tag = self.patches_tags["swept_tag"]
self.patches["swept_patch_end_0"].tag = self.patches_tags["end_0_tag"]
self.patches["swept_patch_end_1"].tag = self.patches_tags["end_1_tag"]
48 changes: 19 additions & 29 deletions hypervehicle/utilities.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import re
import os
import sys
import glob
Expand All @@ -8,7 +7,6 @@
from tqdm import tqdm
import xml.etree.ElementTree as ET
from typing import Dict, List, Optional
from pysagas.geometry import Cell, Vector


def create_cells(
Expand All @@ -20,7 +18,7 @@ def create_cells(
flip_faces=False,
):
"""
Generates a list of vertices and a corrosponding list of index triplets, each pinting the vertices of a single cell
Generates a list of vertices and a corrosponding list of index triplets, each pinting the vertices of a single cell
Parameters
----------
Expand Down Expand Up @@ -72,8 +70,7 @@ def gen_points(lb, ub, steps, spacing=1.0):
pos = parametric_surface(r, s)

# Assign vertex
vertices[j * (ni + 1) + i] = np.array([pos.x,
y_mult * pos.y, pos.z])
vertices[j * (ni + 1) + i] = np.array([pos.x, y_mult * pos.y, pos.z])

# Create vertices for centre point of each quad cell
try:
Expand Down Expand Up @@ -162,8 +159,9 @@ def parametricSurfce2stl(
The numpy-stl mesh.
"""

vertices, cell_ids = create_cells(parametric_surface, triangles_per_edge,
si, sj, mirror_y, flip_faces)
vertices, cell_ids = create_cells(
parametric_surface, triangles_per_edge, si, sj, mirror_y, flip_faces
)

# Create the STL mesh object
stl_mesh = mesh.Mesh(np.zeros(cell_ids.shape[0], dtype=mesh.Mesh.dtype))
Expand All @@ -186,7 +184,7 @@ def parametricSurfce2vtk(
):
"""
Function to convert parametric_surface generated using the Eilmer Geometry
Package into a vtk cell format.
Package into a vtk cell format.
Parameters
----------
Expand All @@ -206,8 +204,9 @@ def parametricSurfce2vtk(
cells
"""
# Generate the mesh vertices and cell index list
vertices, cell_ids = create_cells(parametric_surface, triangles_per_edge,
si, sj, mirror_y, flip_faces)
vertices, cell_ids = create_cells(
parametric_surface, triangles_per_edge, si, sj, mirror_y, flip_faces
)

# Create the vtk cells format and add patch_tag to each cell
# cells = []
Expand All @@ -221,7 +220,7 @@ def parametricSurfce2vtk(
# y=vertices[cell_id[2]][1], z=vertices[cell_id[2]][2]),
# face_ids=cell_id
# ))
# cells.attributes[-1] = {'cell_tag': 1}
# cells.attributes[-1] = {'cell_tag': 1}

return (vertices, cell_ids)

Expand Down Expand Up @@ -274,8 +273,7 @@ def assess_inertial_properties(vehicle, component_densities: Dict[str, float]):
total_volume = 0

for name, component in vehicle._named_components.items():
inertia_handle = getattr(
component.mesh, "get_mass_properties_with_density")
inertia_handle = getattr(component.mesh, "get_mass_properties_with_density")

volume, vmass, cog, inertia = inertia_handle(component_densities[name])

Expand Down Expand Up @@ -417,8 +415,7 @@ def dvdp(
dp = adjusted_parameters[parameter] - value

# Create Vehicle instance with perturbed parameter
constructor_instance = self.vehicle_constructor(
**adjusted_parameters)
constructor_instance = self.vehicle_constructor(**adjusted_parameters)
parameter_instance = constructor_instance.create_instance()
parameter_instance.verbosity = 0

Expand Down Expand Up @@ -455,8 +452,7 @@ def dvdp(
# Return output
self.parameter_sensitivities = sensitivities
self.scalar_sensitivities = analysis_sens
self.component_sensitivities = self._combine(
nominal_instance, sensitivities)
self.component_sensitivities = self._combine(nominal_instance, sensitivities)

return sensitivities

Expand Down Expand Up @@ -493,8 +489,7 @@ def to_csv(self, outdir: Optional[str] = None):
os.mkdir(properties_dir)

vm = {
p: {k: self.scalar_sensitivities[p][k]
for k in ["volume", "mass"]}
p: {k: self.scalar_sensitivities[p][k] for k in ["volume", "mass"]}
for p in self.scalar_sensitivities
}
pd.DataFrame(vm).to_csv(
Expand All @@ -503,13 +498,11 @@ def to_csv(self, outdir: Optional[str] = None):

for param in self.scalar_sensitivities:
self.scalar_sensitivities[param]["cog"].tofile(
os.path.join(properties_dir,
f"{param}_cog_sensitivity.txt"),
os.path.join(properties_dir, f"{param}_cog_sensitivity.txt"),
sep=", ",
)
self.scalar_sensitivities[param]["moi"].tofile(
os.path.join(properties_dir,
f"{param}_moi_sensitivity.txt"),
os.path.join(properties_dir, f"{param}_moi_sensitivity.txt"),
sep=", ",
)

Expand Down Expand Up @@ -549,10 +542,8 @@ def _compare_meshes(mesh1, mesh2, dp, parameter_name: str) -> pd.DataFrame:
all_data[:, 3:6] = flat_diff # Location deltas

# Create DataFrame
df = pd.DataFrame(data=all_data, columns=[
"x", "y", "z", "dx", "dy", "dz"])
df["magnitude"] = np.sqrt(
np.square(df[["dx", "dy", "dz"]]).sum(axis=1))
df = pd.DataFrame(data=all_data, columns=["x", "y", "z", "dx", "dy", "dz"])
df["magnitude"] = np.sqrt(np.square(df[["dx", "dy", "dz"]]).sum(axis=1))

# Sensitivity calculations
sensitivities = df[["dx", "dy", "dz"]] / dp
Expand Down Expand Up @@ -654,8 +645,7 @@ def append_sensitivities_to_tri(
points_data_list = [el.split() for el in points_data.splitlines()]
points_data_list = [[float(j) for j in i] for i in points_data_list]

points_df = pd.DataFrame(points_data_list, columns=[
"x", "y", "z"]).dropna()
points_df = pd.DataFrame(points_data_list, columns=["x", "y", "z"]).dropna()

# Ensure previous components sensitivity file is not included
try:
Expand Down
28 changes: 13 additions & 15 deletions hypervehicle/vehicle.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ def configure(self, name: str = None, verbosity: int = 1):

self.verbosity = verbosity


def add_component(
self,
component: Component,
Expand Down Expand Up @@ -128,8 +127,7 @@ def add_component(
self.components.append(component)

# Add component count
component_count = self._component_counts.get(
component.componenttype, 0) + 1
component_count = self._component_counts.get(component.componenttype, 0) + 1
self._component_counts[component.componenttype] = component_count
self._enumerated_components[
f"{component.componenttype}_{component_count}"
Expand All @@ -147,8 +145,7 @@ def add_component(
print(f"Added new {component.componenttype} component.")

else:
raise Exception(
f"Unrecognised component type: {component.componenttype}")
raise Exception(f"Unrecognised component type: {component.componenttype}")

def generate(self):
"""Generate all components of the vehicle."""
Expand All @@ -160,8 +157,7 @@ def generate(self):

for component in self.components:
if self.verbosity > 1:
print(
f" Generating patches for {component.componenttype} component.")
print(f" Generating patches for {component.componenttype} component.")

# Generate component patches
component.generate_patches()
Expand Down Expand Up @@ -250,7 +246,7 @@ def transform(self, transformations: List[Tuple[str, Any]]) -> None:
component.surfaces = None
component.mesh = None

def to_file(self, prefix: str = None, file_type: str = 'stl') -> None:
def to_file(self, prefix: str = None, file_type: str = "stl") -> None:
"""Writes the vehicle components to output file. If analysis results are
present, they will also be written to file, either as CSV, or using
the Numpy tofile method.
Expand All @@ -266,12 +262,12 @@ def to_file(self, prefix: str = None, file_type: str = 'stl') -> None:
The default is None.
file_type: str
Defines the output file format to be written to. Can be stl or
Defines the output file format to be written to. Can be stl or
vtk. Default file_type is 'stl'
"""
file_type = file_type.lower()
if file_type not in ['stl', 'vtk']:
raise ('Invalid output file type. STL or VTK supported')
if file_type not in ["stl", "vtk"]:
raise ("Invalid output file type. STL or VTK supported")

if self.verbosity > 0:
s = "Writing vehicle components to"
Expand All @@ -298,7 +294,7 @@ def to_file(self, prefix: str = None, file_type: str = 'stl') -> None:
if self.verbosity > 0:
print(f" Writing: {file_name} ", end="\r")

if file_type == 'stl':
if file_type == "stl":
component.to_stl(file_name)
else:
component.to_vtk(file_name)
Expand Down Expand Up @@ -333,7 +329,9 @@ def to_file(self, prefix: str = None, file_type: str = 'stl') -> None:

if self.verbosity > 0:
print(
f"\rAll components written to {file_type.upper()} file format.", end="\n")
f"\rAll components written to {file_type.upper()} file format.",
end="\n",
)

def to_stl(self, prefix: str = None) -> None:
"""Writes the vehicle components to STL. If analysis results are
Expand All @@ -350,7 +348,7 @@ def to_stl(self, prefix: str = None) -> None:
The default is None.
"""

self.to_file(prefix, file_type='stl')
self.to_file(prefix, file_type="stl")

def to_vtk(self, prefix: str = None) -> None:
"""Writes the vehicle components to VTK. If analysis results are
Expand All @@ -367,7 +365,7 @@ def to_vtk(self, prefix: str = None) -> None:
The default is None.
"""

self.to_file(prefix, file_type='vtk')
self.to_file(prefix, file_type="vtk")

def analyse(self, densities: dict) -> Tuple:
"""Evaluates the mesh properties of the vehicle instance.
Expand Down

0 comments on commit b4871bd

Please sign in to comment.