Skip to content

Commit

Permalink
Rename GenerateFluctuationField to FluctuationFieldGenerator and typing
Browse files Browse the repository at this point in the history
  • Loading branch information
mdmeeker committed Jan 15, 2025
1 parent 2f03693 commit 4cb3489
Show file tree
Hide file tree
Showing 18 changed files with 465 additions and 415 deletions.
47 changes: 16 additions & 31 deletions .github/new_windgen.py → .github/new_windgen.py_OLD
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
from pathlib import Path

# from plotly.graph_objs import *

import numpy as np
import torch

from drdmannturb.fluctuation_generation import (
plot_velocity_components, # utility function for plotting each velocity component in the field, not used in this example
)
from drdmannturb.fluctuation_generation import (
GenerateFluctuationField,
plot_velocity_magnitude,
FluctuationFieldGenerator,
)

path = Path().resolve()
Expand All @@ -30,7 +25,7 @@
reference_height = 180.0
roughness_height = 0.75

grid_dimensions = np.array([300.0, 864.0, 576.0]) #* 1/20#* 1/10
grid_dimensions = np.array([300.0, 864.0, 576.0]) # * 1/20#* 1/10
grid_levels = np.array([6, 6, 8])

seed = None # 9000
Expand All @@ -47,8 +42,7 @@
)



gen_drd = GenerateFluctuationField(
gen_drd = FluctuationFieldGenerator(
friction_velocity,
reference_height,
grid_dimensions,
Expand All @@ -59,49 +53,40 @@
)


for nBlocks in range(1, 15+1):
# gen_drd = GenerateFluctuationField(
# friction_velocity,
# reference_height,
# grid_dimensions,
# grid_levels,
# model=Type_Model,
# path_to_parameters=path_to_parameters,
# seed=seed,
# )
def log_law(z, z_0, u_ast):
return u_ast * np.log(z / z_0 + 1.0) / 0.41

fluctuation_field_drd = gen_drd.generate(1)

for nBlocks in range(1, 15 + 1):
fluctuation_field_drd = gen_drd.generate(1, zref, uref, z0, windprofiletype)

sd = np.sqrt(np.mean(fluctuation_field_drd**2))
fluctuation_field_drd = fluctuation_field_drd / sd
fluctuation_field_drd = fluctuation_field_drd / sd
fluctuation_field_drd *= 4.26

log_law = lambda z, z_0, u_ast: u_ast * np.log(z/z_0+1.0)/0.41
z = np.linspace(0.0,grid_dimensions[2], 2**(grid_levels[2])+1)
z = np.linspace(0.0, grid_dimensions[2], 2 ** (grid_levels[2]) + 1)

mean_profile_z = log_law(z, roughness_height, friction_velocity)

mean_profile = np.zeros_like(fluctuation_field_drd)
mean_profile[...,0] = np.tile(mean_profile_z.T, (mean_profile.shape[0], mean_profile.shape[1], 1))
mean_profile[..., 0] = np.tile(mean_profile_z.T, (mean_profile.shape[0], mean_profile.shape[1], 1))

# wind_field = mean_profile
fluctuation_field_drd += mean_profile

fluctuation_field_drd *= 40/63
fluctuation_field_drd *= 40 / 63

wind_field_vtk = tuple([np.copy(fluctuation_field_drd[...,i], order='C') for i in range(3)])
wind_field_vtk = tuple([np.copy(fluctuation_field_drd[..., i], order="C") for i in range(3)])

cellData = {'grid': np.zeros_like(fluctuation_field_drd[...,0]), 'wind': wind_field_vtk}
cellData = {"grid": np.zeros_like(fluctuation_field_drd[..., 0]), "wind": wind_field_vtk}
# .hl import imageToVTK

from pyevtk.hl import imageToVTK

FileName = f"dat/block_{nBlocks}"

imageToVTK(FileName, cellData = cellData, spacing=spacing)

imageToVTK(FileName, cellData=cellData, spacing=spacing)

print(f"generated blocks for {nBlocks}")


print("saved")
print("saved")
32 changes: 16 additions & 16 deletions docs/source/uml_fluct_gen.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
UML Diagram for Fluctuation Field Generation
============================================

Here is an UML diagram representing the interoperability between several internal classes of the package that comprise the fluctuation generator :py:class:`GenerateFluctuationField`. Please refer to specific class documentations for details. The following diagram is interactive -- try zooming and panning to resize for your convenience.
Here is an UML diagram representing the interoperability between several internal classes of the package that comprise the fluctuation generator :py:class:`FluctuationFieldGenerator`. Please refer to specific class documentations for details. The following diagram is interactive -- try zooming and panning to resize for your convenience.

These interactive UML diagrams have an issue with rendering the correct arrow types in dark mode, please consider switching to light mode.

.. mermaid::
.. mermaid::
:zoom:

classDiagram
direction LR
GenerateFluctuationField ..> VectorGaussianRandomField
FluctuationFieldGenerator ..> VectorGaussianRandomField
GaussianRandomField ..> Covariance

VectorGaussianRandomField --|> GaussianRandomField
Expand All @@ -24,16 +24,16 @@ These interactive UML diagrams have an issue with rendering the correct arrow ty
NNCovariance --|> Covariance
end
GenerateFluctuationField : +np.ndarray total_fluctuation
GenerateFluctuationField : +Callable log_law
GenerateFluctuationField : +int seed
GenerateFluctuationField : +Covariance Covariance
GenerateFluctuationField : +VectorGaussianRandomField RF
FluctuationFieldGenerator : +np.ndarray total_fluctuation
FluctuationFieldGenerator : +Callable log_law
FluctuationFieldGenerator : +int seed
FluctuationFieldGenerator : +Covariance Covariance
FluctuationFieldGenerator : +VectorGaussianRandomField RF

GenerateFluctuationField: -_generate_block()
GenerateFluctuationField: +generate()
GenerateFluctuationField: +normalize()
GenerateFluctuationField: +save_to_vtk()
FluctuationFieldGenerator: -_generate_block()
FluctuationFieldGenerator: +generate()
FluctuationFieldGenerator: +normalize()
FluctuationFieldGenerator: +save_to_vtk()
class VectorGaussianRandomField{
+int vdim
+tuple DomainSlice
Expand All @@ -53,21 +53,21 @@ These interactive UML diagrams have an issue with rendering the correct arrow ty
+reseed()
}
class VonKarmanCovariance{
+float length_scale
+float length_scale
+float E0
+precompute_Spectrum()
}
class MannCovariance{
+float length_scale
+float length_scale
+float E0
+float Gamma
+precompute_Spectrum()
}
class NNCovariance{
+float length_scale
+float length_scale
+float E0
+float Gamma
+float h_ref
+OnePointSpectra ops
+precompute_Spectrum()
}
}
14 changes: 7 additions & 7 deletions docs/source/windgeneration.rst
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
.. py:currentmodule:: drdmannturb
Fluctuation Field Generation
Fluctuation Field Generation
============================

DRDMannTurb provides generic methods for generating fluctuation fields from specified spectra models. Please refer to :doc:`the UML diagram <./uml_fluct_gen>` to see the class hierarchy.
DRDMannTurb provides generic methods for generating fluctuation fields from specified spectra models. Please refer to :doc:`the UML diagram <./uml_fluct_gen>` to see the class hierarchy.

.. autoclass:: drdmannturb.GenerateFluctuationField
:members:
.. autoclass:: drdmannturb.FluctuationFieldGenerator
:members:

Plotting Utilities
Plotting Utilities
==================

.. currentmodule:: drdmannturb.fluctuation_generation.wind_plot

.. autofunction:: plot_velocity_magnitude

.. autofunction:: plot_velocity_components
.. autofunction:: plot_velocity_components

.. autofunction:: format_wind_field
.. autofunction:: format_wind_field

.. autofunction:: create_grid
62 changes: 61 additions & 1 deletion drdmannturb/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
"""
DRDMannTurb (short for Deep Rapid Distortion theory Mann Turbulence model) is a data-driven
framework for syntetic turbulence generation in Python. The code is based on the original work
of Jacob Mann in 1994 and 1998 as well as in the deep-learning enhancement developed by Keith
et al. in 2021.
"""

from .common import (
CPU_Unpickler,
Mann_linear_exponential_approx,
Expand All @@ -8,8 +15,8 @@
from .enums import DataType, EddyLifetimeType, PowerSpectraType
from .fluctuation_generation import (
Covariance,
FluctuationFieldGenerator,
GaussianRandomField,
GenerateFluctuationField,
MannCovariance,
NNCovariance,
Sampling_DCT,
Expand Down Expand Up @@ -41,3 +48,56 @@
OnePointSpectraDataGenerator,
PowerSpectraRDT,
)

__all__ = [
# Common
"CPU_Unpickler",
"Mann_linear_exponential_approx",
"MannEddyLifetime",
"VKEnergySpectrum",
"plot_loss_logs",
# Enums
"DataType",
"EddyLifetimeType",
"PowerSpectraType",
# Fluctuation Generation
"Covariance",
"FluctuationFieldGenerator",
"GaussianRandomField",
"MannCovariance",
"NNCovariance",
"Sampling_DCT",
"Sampling_DST",
"Sampling_FFT",
"Sampling_FFTW",
"Sampling_method_base",
"Sampling_method_freq",
"Sampling_VF_FFTW",
"VectorGaussianRandomField",
"VonKarmanCovariance",
"create_grid",
"format_wind_field",
"plot_velocity_components",
"plot_velocity_magnitude",
# Interpolation
"extract_x_spectra",
"interp_spectra",
"interpolate",
# NN Modules
"CustomMLP",
"CustomNet",
"Rational",
"SimpleNN",
"TauNet",
# Parameters
"LossParameters",
"NNParameters",
"PhysicalParameters",
"ProblemParameters",
# Spectra Fitting
"CalibrationProblem",
"LossAggregator",
"OnePointSpectra",
"OnePointSpectraDataGenerator",
"PowerSpectraRDT",
]
4 changes: 2 additions & 2 deletions drdmannturb/fluctuation_generation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"MannCovariance",
"GaussianRandomField",
"VectorGaussianRandomField",
"GenerateFluctuationField",
"FluctuationFieldGenerator",
"NNCovariance",
"Sampling_method_base",
"Sampling_method_freq",
Expand All @@ -20,7 +20,7 @@
]

from .covariance_kernels import Covariance, MannCovariance, VonKarmanCovariance
from .fluctuation_field_generator import GenerateFluctuationField
from .fluctuation_field_generator import FluctuationFieldGenerator
from .gaussian_random_fields import GaussianRandomField, VectorGaussianRandomField
from .nn_covariance import NNCovariance
from .sampling_methods import (
Expand Down
26 changes: 16 additions & 10 deletions drdmannturb/fluctuation_generation/fluctuation_field_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from math import ceil
from os import PathLike
from pathlib import Path
from typing import Optional, Union
from typing import Callable, Optional, Union

import numpy as np
import torch
Expand All @@ -19,7 +19,7 @@
from .nn_covariance import NNCovariance


class GenerateFluctuationField:
class FluctuationFieldGenerator:
r"""
.. _generate-fluctuation-field-reference:
Class for generating a fluctuation field either from a Mann model or a pre-fit DRD model that generates
Expand Down Expand Up @@ -82,7 +82,7 @@ def __init__(
energy_spectrum_scale: Optional[float] = None,
lowfreq_params: Optional[LowFreqParameters] = None,
path_to_parameters: Optional[Union[str, PathLike]] = None,
seed: int = None,
seed: Optional[int] = None,
blend_num=10,
):
r"""
Expand Down Expand Up @@ -154,9 +154,10 @@ def __init__(
L *= reference_height
Gamma = T

else: # VK or Mann model
if any(p is None for p in [length_scale, time_scale, energy_spectrum_scale]):
raise ValueError("VK/Mann models require length, time and energy spectrum scales")
else: # VK or Mann model case
assert length_scale is not None, "VK/Mann models require length scale" # for type checker
assert time_scale is not None, "VK/Mann models require time scale"
assert energy_spectrum_scale is not None, "VK/Mann models require energy spectrum scale"

E0 = energy_spectrum_scale * friction_velocity**2 * reference_height ** (-2 / 3)
L = length_scale
Expand Down Expand Up @@ -235,11 +236,14 @@ def make_slice(start=None, end=None):
self.noise = None
self.total_fluctuation = np.zeros(wind_shape)

self.log_law = lambda z, z0, zref, uref: uref * np.log(z / z0 + 1.0) / np.log(zref / z0)
self.power_law = lambda z, zref, Uref, a: Uref * (z / zref) ** a
CovarianceType = Union[
type[VonKarmanCovariance],
type[MannCovariance],
Callable[..., NNCovariance],
]

### Random field object
covariance_map = {
covariance_map: dict[str, CovarianceType] = { # type: ignore
"VK": VonKarmanCovariance,
"Mann": MannCovariance,
"DRD": lambda **kwargs: NNCovariance(**kwargs, ops=pb.OPS, h_ref=reference_height),
Expand Down Expand Up @@ -366,10 +370,12 @@ def _normalize_block(
if windprofiletype == "LOG":
mean_profile_z = self.log_law(z_space, z0, zref, uref)
else:
assert plexp is not None, "Power law exponent (plexp) is required when using power law mean profile."
mean_profile_z = self.power_law(z_space, zref, uref, plexp)

mean_profile = np.zeros_like(curr_block)
mean_profile[..., 0] = np.tile(mean_profile_z.T, (mean_profile.shape[0], mean_profile.shape[1], 1))
# NOTE: (Leaving for now) this *was* mean_profile_z.T, but that's a float? so there's no transpose.
mean_profile[..., 0] = np.tile(mean_profile_z, (mean_profile.shape[0], mean_profile.shape[1], 1))

return curr_block + mean_profile

Expand Down
Loading

0 comments on commit 4cb3489

Please sign in to comment.