src.helper package
Submodules
src.helper.commons module
- author
Shahin (Amir Hossein) Rabbani
- contact
- copyright
See License
Note
dataclass
needs python 3.7, replace it with NamedTuple
with python 3.6.
- class src.helper.commons.BoundaryType(value)
Bases:
Enum
Boundary conditions.
Warning
Only
NEUMANN_EDGE
is fully implemented and tested.CONST_FRAME
means simple single padded values; mostly no action is required.- CONST_FRAME = 4
- DIRICHLET = 3
- NEUMANN_CENTER = 2
- NEUMANN_EDGE = 1
- class src.helper.commons.ColorMapModesVectorField(value)
Bases:
Enum
Options for plotting vector fields.
- Choices:
VECTOR_ANGLE
: color map based on the vector angleVECTOR_LENGTH
: color map based on the vector length
- VECTOR_ANGLE = 1
- VECTOR_LENGTH = 2
- class src.helper.commons.ConvolutionOrientation(value)
Bases:
Enum
By convolution orientation we mean the filter orientation when convolving the domain.
Note
FIBER
is the same as depth for 3D convolutions.CENTER
only does one multiplication on the central cell, no orientation.
- CENTER = 4
- FIBER = 3
- HORIZONTAL = 1
- UNKNOWN = 0
- VERTICAL = 2
- class src.helper.commons.DataFileFormat(value)
Bases:
Enum
IO file formats
- UNKNOWN = 0
- cpp = 5
- hlsli = 4
- npy = 1
- npz = 2
- txt = 3
- class src.helper.commons.DataMatrixMode(value)
Bases:
Enum
Making sample data matrices with different patterns.
- Choices:
CONST_VALUE
: constant value everywhereRANDOMIZE_INT
: random dataSPECIAL_PATTERN
: special scripted pattersLINEAR_RANGE_FULL
: \([1, 2, ..., n]\)LINEAR_RANGE_4BLOCK_SYMMETRIC_MIRRORED
: generates 4 sub-matrices that are mirrored of each other. Also, each block is symmetric along the diagonalRANDOMIZE_FLOAT_UNIFORM
: use uniform random data to generate the input matrixRANDOMIZE_FLOAT_GAUSSIAN
: use Gaussian random data to generate the input matrix
- CONST_VALUE = 1
- LINEAR_RANGE_4BLOCK_SYMMETRIC_MIRRORED = 5
- LINEAR_RANGE_FULL = 4
- RANDOMIZE_FLOAT_GAUSSIAN = 7
- RANDOMIZE_FLOAT_UNIFORM = 6
- RANDOMIZE_INT = 2
- SPECIAL_PATTERN = 3
- class src.helper.commons.DataMatrixPattern(value)
Bases:
Enum
Use this function to create options for scripting matrix data with special patterns.
Current (only) implementation:
CENTRAL_SQUARE
: Make a data matrix with a non-zero box at the center and zero everywhere else.- CENTRAL_SQUARE = 1
- class src.helper.commons.DataMatrixPatternParams(radius: float = 0.05)
Bases:
object
Special data pattern generation parameters.
- radius: float = 0.05
- class src.helper.commons.DecompMethod(value)
Bases:
Enum
Decomposition methods for 2D and 3D.
NONE
: no decomposition, forces a full kernel return. Anything butNONE
forces a return of a reduced kernel.- NONE = 1
- SVD_2D = 2
- SYM_CP_3D = 3
- TUCKER_3D = 4
- UNKNOWN = 0
- class src.helper.commons.ExportFormat(value)
Bases:
Enum
C++/HLSL friendly export options for the filters
- Choices:
SEPARATE_RANK_FILTERS
: float[ float, float, ..] separate arrays for each ranked filterGROUP_RANK_SEQUENTIAL
: float[ rank 1 floats.. // rank 2 floats.. // ..] packing 4 ranked filters sequentiallyGROUP_RANK_FLOAT4_HLSL
: float4[ float4(rank 1 .. 4), float4(rank 1 .. 4), ..] packing hlsl friendly
- GROUP_RANK_FLOAT4_HLSL = 3
- GROUP_RANK_SEQUENTIAL = 2
- SEPARATE_RANK_FILTERS = 1
- class src.helper.commons.NormOptions(value)
Bases:
Enum
Matrix norms.
- Choices:
MSE
: mean squared errorFROBENIUS
: frobeniusINF
: infinity
- FROBENIUS = 2
- INF = 3
- MSE = 1
- class src.helper.commons.OptionsBoundary(condition: BoundaryType = BoundaryType.CONST_FRAME, enforce: bool = False, val: float = 1.0, padding_size: int = 1, dynamic_padding: bool = True, left_wall: bool = True, right_wall: bool = True, up_wall: bool = True, down_wall: bool = True, front_wall: bool = True, back_wall: bool = True, obj_collide: bool = True, post_solve_enforcement: bool = True)
Bases:
object
Dataclass to pack options for boundary treatment.
Note
To see how to pack options, look at main demos, or see
generic_options()
.- Parameters
condition (BoundaryType) – (Default =
BoundaryType.CONST_FRAME
)enforce (bool) – (Default =
False
) with or without boundary conditionval (float) – (Default =
1.0
) constant boundary condition value to be enforcedpadding_size (int) – (Default =
1
) thickness of the boundarydynamic_padding (bool) – (Default =
True
) automatically add padding to compensate for convolution shrinkageleft_wall (bool) – (Default =
True
) active left wall boundaryright_wall (bool) – (Default =
True
) active right wall boundaryup_wall (bool) – (Default =
True
) active up wall boundarydown_wall (bool) – (Default =
True
) active down wall boundaryfront_wall (bool) – (Default =
True
) 3D: active front wall boundaryback_wall (bool) – (Default =
True
) 3D: active behind wall boundaryobj_collide (bool) – (Default =
True
) collide with the object in the domainpost_solve_enforcement (bool) – (Default =
True
) clean up boundary treatment; enforce boundary condition after Jacobi/Poisson solve
- back_wall: bool = True
- condition: BoundaryType = 4
- down_wall: bool = True
- dynamic_padding: bool = True
- enforce: bool = False
- front_wall: bool = True
- left_wall: bool = True
- obj_collide: bool = True
- padding_size: int = 1
- post_solve_enforcement: bool = True
- right_wall: bool = True
- up_wall: bool = True
- val: float = 1.0
- class src.helper.commons.OptionsDataMatrix(pattern_params: ~src.helper.commons.DataMatrixPatternParams = DataMatrixPatternParams(radius=0.05), shape: (<class 'int'>, <class 'int'>) = (41, 41), mode: ~src.helper.commons.DataMatrixMode = DataMatrixMode.RANDOMIZE_INT, force_symmetric_unit_range: bool = False, const_input: float = 1.0, rand_seed: int = 13, rand_range: (<class 'int'>, <class 'int'>) = (1, 10), special_pattern: ~src.helper.commons.DataMatrixPattern = DataMatrixPattern.CENTRAL_SQUARE)
Bases:
object
Packing options for data matrix generation
- Parameters
pattern_params (DataMatrixPatternParams) – special pattern parameters
shape (tuple) – (Default =
(41, 41)
) 2d input matrix size. Does not have to be square. For 3d use(int, int, int)
mode (DataMatrixMode) – (Default =
DataMatrixMode.RANDOMIZE_INT
)force_symmetric_unit_range (bool) – (Default =
False
) Data will be forced to be in \([-1, +1]\)const_input (float) – (Default =
1.0
) using a matrix with the same element values. If randomized, this will be ignoredrand_seed (int) – (Default =
13
)rand_range (tuple) – (Default =
(1, 10) `) - :math:`(int, int)
. integer in (low, high) to generate random matrix data. ‘high’ is excluded.special_pattern (DataMatrixPattern) – (Default =
DataMatrixPattern.CENTRAL_SQUARE
) special data patterns
- const_input: float = 1.0
- force_symmetric_unit_range: bool = False
- mode: DataMatrixMode = 2
- pattern_params: DataMatrixPatternParams = DataMatrixPatternParams(radius=0.05)
- rand_range: (<class 'int'>, <class 'int'>) = (1, 10)
- rand_seed: int = 13
- shape: (<class 'int'>, <class 'int'>) = (41, 41)
- special_pattern: DataMatrixPattern = 1
- class src.helper.commons.OptionsGeneral(solver: OptionsPoissonSolver, kernel: OptionsKernel, reduction: OptionsReduction, boundary: OptionsBoundary, input: OptionsDataMatrix)
Bases:
object
Packing all options into one super pack.
Note
To see how to pack options, look at main demos, or see
generic_options()
.- boundary: OptionsBoundary
- input: OptionsDataMatrix
- kernel: OptionsKernel
- reduction: OptionsReduction
- solver: OptionsPoissonSolver
- class src.helper.commons.OptionsKernel(kernel_type: PoissonKernelType, itr: int = 30, dx: float = 1.0, dt: float = 1.0, kappa: float = 1.0, alpha: float = 1.0, beta: float = 1.0, clear_memo: bool = True)
Bases:
object
Dataclass to pack options for the kernel generator.
Note
To see how to pack options, look at main demos, or see
generic_options()
.- Parameters
kernel_type (PoissonKernelType) – standard, unified
itr (int) – (Default =
30
) target Jacobi iteration, also Poisson filters orderdx (float) – cell size (Default =
1.0
)dt (float) – diffusivity rate per time step (different from simulation time step) (Default =
1.0
)kappa (float) – diffusivity (Default =
1.0
)alpha (float) – (Default =
1.0
). Seefunctions.generator.compute_alpha()
beta (float) – (Default =
1.0
). Seefunctions.generator.compute_beta()
clear_memo (bool) – better set to be
True
for recursion to avoid garbage cashing when using memoization (Default =True
)
- alpha: float = 1.0
- beta: float = 1.0
- clear_memo: bool = True
- dt: float = 1.0
- dx: float = 1.0
- itr: int = 30
- kappa: float = 1.0
- kernel_type: PoissonKernelType
- class src.helper.commons.OptionsPlots(show_values: bool = False, no_ticks: bool = False, frame_on: bool = True, limits_x_tight: bool = False, limits_y_tight: bool = False, aspect_ratio: float = 1.0, line_widths: float = 0.2, cmap: str = 'rocket_r', blend_cmaps: bool = False, cmap_secondary_blend: str = 'flag', fmt: str = '.2f', plt_show: bool = False, cbar: bool = True, cbar_border: bool = False, cbar_outline_color: str = 'black', cbar_label: Optional[str] = None, cbar_label_color: str = 'white', cbar_ticks: bool = True, cbar_tick_color: Optional[str] = None, cbar_only_min_max: bool = False, cbar_add_percentile: bool = False, cbar_orientation: str = 'horizontal', cbar_location: str = 'bottom', cbar_shrink: float = 1.0, cbar_scientific: bool = False, cbar_special: bool = False, show_contour: bool = False, contour_res: int = 50, contour_show_values: bool = False, contour_cmap: str = 'gist_heat', contour_cbar: bool = False, contour_cbar_orientation: str = 'vertical', contour_cbar_location: str = 'right', contour_cbar_border: bool = False, contour_cbar_no_ticks: bool = False, beautify: bool = False, projection: str = '2d', interpolate: bool = False, interp_1d: bool = False, interp_1d_res: int = 10, interp_2d_mode: Optional[str] = None, interp_3d: bool = False, alpha: float = 1.0, highlight_edgecolor: str = 'red', highlight_facecolor: str = 'pink', highlight_fill: bool = False, highlight_line_width: int = 2, axis_background_color: Optional[str] = None, canvas_background_color: Optional[str] = None)
Bases:
object
Plot options
- alpha: float = 1.0
- aspect_ratio: float = 1.0
- axis_background_color: str = None
- beautify: bool = False
- blend_cmaps: bool = False
- canvas_background_color: str = None
- cbar: bool = True
- cbar_add_percentile: bool = False
- cbar_border: bool = False
- cbar_label: str = None
- cbar_label_color: str = 'white'
- cbar_location: str = 'bottom'
- cbar_only_min_max: bool = False
- cbar_orientation: str = 'horizontal'
- cbar_outline_color: str = 'black'
- cbar_scientific: bool = False
- cbar_shrink: float = 1.0
- cbar_special: bool = False
- cbar_tick_color: str = None
- cbar_ticks: bool = True
- cmap: str = 'rocket_r'
- cmap_secondary_blend: str = 'flag'
- contour_cbar: bool = False
- contour_cbar_border: bool = False
- contour_cbar_location: str = 'right'
- contour_cbar_no_ticks: bool = False
- contour_cbar_orientation: str = 'vertical'
- contour_cmap: str = 'gist_heat'
- contour_res: int = 50
- contour_show_values: bool = False
- fmt: str = '.2f'
- frame_on: bool = True
- highlight_edgecolor: str = 'red'
- highlight_facecolor: str = 'pink'
- highlight_fill: bool = False
- highlight_line_width: int = 2
- interp_1d: bool = False
- interp_1d_res: int = 10
- interp_2d_mode: str = None
- interp_3d: bool = False
- interpolate: bool = False
- limits_x_tight: bool = False
- limits_y_tight: bool = False
- line_widths: float = 0.2
- no_ticks: bool = False
- plt_show: bool = False
- projection: str = '2d'
- show_contour: bool = False
- show_values: bool = False
- class src.helper.commons.OptionsPoissonSolver(dim: SolverDimension, solver_type: PoissonSolverType, zero_init: bool = True)
Bases:
object
Dataclass to pack options for the Poisson solver.
Note
To see how to pack options, look at main demos, or see
generic_options()
.- Parameters
dim (SolverDimension) – 2D or 3D
solver_type (PoissonSolverType) – inverse or forward Poisson
zero_init (bool) – (Default =
True
) if the initial guess in the Jacobi solver is set to zero. If not use \(b\) in \(Ax=b\). If zero initial guess, we produce a smaller kernel. If not using zero initial guess, we are warm starting the Jacobi solver with a nonzero matrix. This makes the kernel slightly larger \((+2)\). We can use zero initial guess for Poisson pressure only (inverse Poisson). Diffusion step (forward Poisson) has to warm start with a nonzero initial guess. Seefunctions.generator.i_want_to_warm_start()
.
- dim: SolverDimension
- solver_type: PoissonSolverType
- zero_init: bool = True
- class src.helper.commons.OptionsReduction(reduce: bool = False, use_separable_filters: bool = False, rank: int = 1, truncation_method: TruncationMode = TruncationMode.PERCENTAGE, truncation_value: float = 0.0, preserve_shape: bool = True, decomp_method: DecompMethod = DecompMethod.UNKNOWN, output_format: OutputFormat = OutputFormat.ABSORBED_FILTERS)
Bases:
object
Dataclass to pack options for reductions.
Note
To see how to pack options, look at main demos, or see
generic_options()
.- Parameters
reduce (bool) – (Default =
False
)use_separable_filters (bool) – (Default =
False
) use separable filters ifTrue
, else use the low rank kernel.rank (int) – (Default =
1
) desired reduction rank. will be ignored if not in the reduction mode. If in reduction, then ifrank==None
get the low rank kernel, ifrank >= 1
then get the separable filters. You can usedecompositions.get_max_rank_2d()
for the best approximationtruncation_method (TruncationMode) – (Default =
PERCENTAGE
)truncation_value (float) – (Default =
0.0
) depends on the truncation method: ifPERCENTAGE
, truncation factor in \([0, 1]\). IfFIXED_THRESHOLD
, cut any elements smaller than a fixed value, only working with symmetrical filters, and only cutting the outer parts of the filters. This value will be ignored if not in the reduction mode.preserve_shape (bool) – (Default =
True
) in case of adaptive truncation withTruncationMode.FIXED_THRESHOLD
we can either keep the shape of the filter and just zero out the truncated values (preserve_shape=True
) or trim the filters (preserve_shape=False
). Forcing to preserve shape makes less complicated convolutions for different ranks as all the filters will have the same size. Also, the data generator function that automatically computes data size and dynamic padding does not currently support varying size filters for each rank.decomp_method (DecompMethod) – (Default =
DecompMethod.UNKNOWN
)output_format (OutputFormat) – (Default =
OutputFormat.ABSORBED_FILTERS
) only used for 3D filters
- decomp_method: DecompMethod = 0
- output_format: OutputFormat = 1
- preserve_shape: bool = True
- rank: int = 1
- reduce: bool = False
- truncation_method: TruncationMode = 1
- truncation_value: float = 0.0
- use_separable_filters: bool = False
- class src.helper.commons.OptionsSubPlots(layout: (<class 'int'>, <class 'int'>) = (2, 2), titles: ~typing.List[~typing.List[str]] = <factory>, highlights: ~typing.List[~typing.List[~numpy.array]] = <factory>, cbar_percentiles: ~typing.List[~typing.List[float]] = <factory>, cmaps: ~typing.List[~typing.List[str]] = <factory>)
Bases:
object
Subplot options
- cbar_percentiles: List[List[float]]
- cmaps: List[List[str]]
- highlights: List[List[array]]
- layout: (<class 'int'>, <class 'int'>) = (2, 2)
- titles: List[List[str]]
- class src.helper.commons.OutputFormat(value)
Bases:
Enum
Choices to compute and pack filter values/components.
- Format choices:
ABSORBED_FILTERS
:Ready to use filters
The core weights are already absorbed into the factors. Safe to use the filters directly.
ALL_COMPONENTS
:Core weights of the decomposed kernel are not absorbed into the filters
Receive a break-down of components: kernel, cores, factors
USE CASE: we can experiment with either Tucker or CP for the decomposition method.
- ABSORBED_FILTERS = 1
- ALL_COMPONENTS = 2
- UNKNOWN = 0
- class src.helper.commons.PoissonKernelType(value)
Bases:
Enum
STANDARD
: (Safe Default) Takes care of \(\pm \alpha\) sign in the kernel. Supports warm starting for both inverse and forward Poisson equations.UNIFIED
: If using this, a negative sign must be absorbed in the input for inverse Poisson. Always uses \(+ \alpha\) sign in the kernel. Only supports warm starting in forward Poisson.- STANDARD = 1
- UNIFIED = 2
- UNKNOWN = 0
- class src.helper.commons.PoissonSolverType(value)
Bases:
Enum
INVERSE
: Solving \(Ax=b\) for \(x\) in matrix-vector setup, or in our matrix-matrix convolution setup, solve for \(X\) in \(L * X=B\) for the given input \(B\), where Laplacian \(L\) is implicitly approximated. Examples: pressure-projection, seamless cloning.FORWARD
: Solving for rhs \(b\) in \(Ax=b\) in matrix-vector setup, or in our matrix-matrix convolution setup, solve for \(B\) in \(L*X=B\) for the given input \(X\), where Laplacian \(L\) is implicitly approximated. Examples: density diffusion, heat equation, viscosity.- FORWARD = 2
- INVERSE = 1
- UNKNOWN = 0
- class src.helper.commons.SolverDimension(value)
Bases:
Enum
Dimension of the solver, either 2D or 3D
- D2 = 2
- D3 = 3
- UNKNOWN = 0
- class src.helper.commons.TruncationMode(value)
Bases:
Enum
Methods to truncate the filters.
Regardless of the method we are always cutting off both sides of the symmetrical filter equally.
[….outer part….cut | ……inner part…… | cut ….outer part….]
- Choices:
PERCENTAGE
: truncate \(\%\) of the filter; values in range \([0, 1]\)FIXED_THRESHOLD
: adaptive truncation : zero out or cut off any element whose absolute value is below a fixed threshold. Note that in this technique we only find and truncate the small values on the outer side of the symmetrical filter, i.e. we use the fixed threshold to find the first element that should be kept on either side of the filter. Then mark the left and right places to cut. We do not test the “inner” elements against the threshold, so after truncation is done, it is possible that the array has still elements below the cut-off threshold. Plot filters to see what this means.
- FIXED_THRESHOLD = 2
- PERCENTAGE = 1
- UNKNOWN = 0
- class src.helper.commons.Vector2DInt(v1, v2)
Bases:
object
- add(another)
- mul(another)
- set(v1, v2)
- set_from(another)
- set_v1(v1)
- set_v2(v2)
- v1()
- v2()
- value()
- class src.helper.commons.Vector2DIntData(v1: int = 0, v2: int = 0)
Bases:
object
- v1: int = 0
- v2: int = 0
- class src.helper.commons.Vector3DInt(v1, v2, v3)
Bases:
object
- add(another)
- mul(another)
- set(v1, v2, v3)
- set_from(another)
- set_v1(v1)
- set_v2(v2)
- set_v3(v3)
- v1()
- v2()
- v3()
- value()
- class src.helper.commons.Vector3DIntData(v1: int = 0, v2: int = 0, v3: int = 0)
Bases:
object
- v1: int = 0
- v2: int = 0
- v3: int = 0
- src.helper.commons.generic_options(dim=SolverDimension.D2, solver_type=PoissonSolverType.INVERSE, zero_init=True, kernel_type=PoissonKernelType.STANDARD, itr=60, rank=4, domain_size=(81, 81), rand_seed=50, dx=1.0, dt=1.0, kappa=1.0, alpha=1.0, beta=4.0, truncation_method=TruncationMode.PERCENTAGE, truncation_value=0.0, obj_collide=True, force_symmetric_unit_range=True)
Generating a set of generic and safe paramteres. Use this as an example of how to pack different options. Look at parameter types for explanations.
- Parameters
dim (SolverDimension) – See
SolverDimension()
solver_type (PoissonSolverType) – See
PoissonSolverType()
zero_init (bool) – See
OptionsPoissonSolver()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
itr (int) – target Jacobi iteration, also Poisson filter order. See
OptionsKernel()
rank (int) – See
OptionsReduction()
domain_size (tuple) – See
OptionsDataMatrix()
rand_seed – See
OptionsDataMatrix()
dx – See
OptionsKernel()
dt – See
OptionsKernel()
kappa – See
OptionsKernel()
alpha – See
OptionsKernel()
beta – See
OptionsKernel()
truncation_method – See
OptionsReduction()
truncation_value – See
OptionsReduction()
obj_collide – See
OptionsBoundary()
force_symmetric_unit_range – See
OptionsDataMatrix()
- Returns
- src.helper.commons.get_default_padding()
- Returns
Fixed padding size
- src.helper.commons.is_solver_2d(dim)
- src.helper.commons.is_solver_3d(dim)
- src.helper.commons.to_string_norm(norm)
src.helper.iohandler module
- author
Shahin (Amir Hossein) Rabbani
- contact
- copyright
See License
Technicals
Tip
A number of pre-generated 2D and 3D filters, and their corresponding decomposition components already exist in different file formats in this repo.
- Path to files:
filters (c++/hlsli/npy/npz):
data/preprocess/filters
csv:
data/preprocess/components
- Naming convention:
If “min_x_max_y” in the file name, it is a filter database with orders in the min and max range
if “single_” prefix in the file name, it is only a single order filter set
- Useful 3D filter samples:
already available in the project
For Poisson pressure:
A useful database to immediately get started with in simulation:
poisson_D3_INVERSE_STANDARD_dx_1.0_itr_min_1_max_100.hlsli
Useful pre-generated single 3D Poisson filters:
single_poisson_D3_INVERSE_STANDARD_dx_1.0_itr_60.hlsli
single_poisson_D3_INVERSE_STANDARD_dx_1.0_itr_100.hlsli
single_poisson_D3_INVERSE_STANDARD_dx_1.0_itr_200.hlsli
If you experience stability issues with the Poisson solution, try lowering \(dx\). Some examples are pre-generated for you with \(dx=0.9\) (note the
_dx_0.9
key in the file name):single_poisson_D3_INVERSE_STANDARD_dx_0.9_itr_60.hlsli
single_poisson_D3_INVERSE_STANDARD_dx_0.9_itr_100.hlsli
single_poisson_D3_INVERSE_STANDARD_dx_0.9_itr_200.hlsli
- Export Filters: Working With Database
Generating filters specially in 3D and for high orders can be very expensive. You can generate and export filters (HLSL friendly) once and load them when using them from the database (npz).
Check out
demo_generate_and_export_filters_database_2d()
ordemo_generate_and_export_filters_database_3d()
to see how it is done.If not already generated, you need to set
load_database_from_file=False
in order to force generate the database for the first time. Then you can useload_database_from_file=True
to load the filters.Use
only_single_itr
if you only want to export one filter. Set the desired target iteration inmax_itr
. There is safety code to save the database with “single_” in its name to avoid accidental overwriting the actual database.Use
com.ExportFormat.GROUP_RANK_FLOAT4_HLSL()
to makeR14
andR58
array groups (default). Better for the shader code; else each ranked filter will be stored in a single float array in HLSL.To export filters to simulation use:
- Poisson-Pressure (Inverse Poisson):
solver_type=PoissonSolverType.INVERSE
kernel_type=PoissonKernelType.UNIFIED
(and multiply the divergence by \(-1\)), orkernel_type=PoissonKernelType.STANDARD
(no need to adjust divergence)
- Diffusion (Forward Poisson):
solver_type=PoissonSolverType.FORWARD
kernel_type=PoissonKernelType.STANDARD
- Example diffusivity values that worked well in the simulation
\(\kappa = [5e-5, 5e-4, 1e-3, 5e-3, 1e-2, 2.5e-2, 5e-2, 1e-1, 2.5e-1, 5e-1, 1.]\)
- src.helper.iohandler.batch_generate_filters(opts, only_single_itr, single_itr_num, rank_filter_reorder_3d=True)
Generate a batch of Poisson filters for a range of target Jacobi iterations (filter orders). The function supports a single filter order generation as well.
- Parameters
opts (OptionsGeneral) –
only_single_itr (bool) – do not generate the whole batch, only a single filter corresponding to
single_itr_num
.single_itr_num (int) – target Jacobi iteration (filter order) for the single filter export. Make sure it is
=< max_itr
rank_filter_reorder_3d (bool) – only 3d; if
True
, change from default (filters, ranks) to (ranks, filters) to make it consistent with 2d
- Returns
list of filters corresponding to each target Jacobi iteration
- src.helper.iohandler.convert_database_to_str(filters_iterations, specs_info_str, only_single_itr, single_itr_num, max_itr, solver_type, pack_mode=ExportFormat.GROUP_RANK_FLOAT4_HLSL, min_itr=1)
Generate string format of the filters to be exported to C++ or HLSL firendly formats.
- Parameters
filters_iterations (List[int]) – list of target Jacobi iterations (filter orders)
specs_info_str (str) – specs header string
only_single_itr (bool) – do not generate the whole set of filters, only a single filter corresponding to
single_itr_num
.single_itr_num (int) – target Jacobi iteration (filter order) for the single filter export. Make sure it is
=< max_itr
max_itr (int) – max target Jacobi iteration (filter order)
solver_type (PoissonSolverType) – See
PoissonSolverType()
pack_mode (ExportFormat) – how to arrange the filter values
min_itr (int) – min target Jacobi iteration (filter order) (Default=
1
)
- Returns
database as formatted string
- src.helper.iohandler.demo_export_single_order_filters_2d(load_database_from_file=False)
Example showcasing exporting a single set of 2D Poisson filters to file for a desired target Jacobi iteration. Try loading it from a database (if available) because it is faster. Generate fresh filters by default instead of loading them.
- Parameters
load_database_from_file (bool) – if
False
, forces it to generate everything, else database with a proper key must be available. Seedatabase_max_itr_key
inprint_poisson_filters()
. (Default=False
).
- src.helper.iohandler.demo_export_single_order_filters_3d(load_database_from_file=True)
Example showcasing exporting a single set of 2D Poisson filters to file for a desired target Jacobi iteration. Try loading it from a database (if available) because it is faster. Generate fresh filters by default instead of loading them.
- Parameters
load_database_from_file (bool) – if
False
, forces it to generate everything, else database with a proper key must be available. Seedatabase_max_itr_key
inprint_poisson_filters()
. (Default=False
).
- src.helper.iohandler.demo_generate_and_export_filters_database_2d()
Example showcasing how to generate 2D filter database (or reload an existing database) and export them to file.
- src.helper.iohandler.demo_generate_and_export_filters_database_3d()
Example showcasing how to generate 3D filter database (or reload an existing database) and export them to file.
- src.helper.iohandler.demo_generate_and_export_single_order_filters_2d()
Example showcasing generating and exporting 2D Poisson filters.
- src.helper.iohandler.demo_generate_and_export_single_order_filters_3d()
Example showcasing generating and exporting 3D Poisson filters.
- src.helper.iohandler.demo_print_filters_2d()
Example showcasing generating and printing 2D Poisson filters.
- src.helper.iohandler.demo_print_filters_3d()
Example showcasing generating and printing 3D Poisson filters.
- src.helper.iohandler.export_components_csv(dim, solver_type, order, safe_rank, filters, modes, full_kernel)
Export full Poisson ernel, its modes and separable filters to
.csv
. Find them indata/preprocess/components
.- Parameters
dim (SolverDimension) – 2D or 3D
solver_type (PoissonSolverType) – See
PoissonSolverType()
order (int) – filter order (target Jacobi iteration)
safe_rank (int) – maximum acceptable rank
filters (ndarray) – filter values
modes (List[ndarray]) – list of modes with square matrix shape
full_kernel (ndarray) – full Poisson kernel matrix
- src.helper.iohandler.export_filters(max_itr, max_rank, dx, dt, dim, kappa, single_itr_num, solver_type, kernel_type, load_database_from_file, only_single_itr, print_content=True, export_pack_mode=ExportFormat.GROUP_RANK_FLOAT4_HLSL, export_file_format=DataFileFormat.hlsli)
Generate or load filters, and export them to the desired file format (C++, HLSL, etc.)
Note
Check out
data/preprocess/
to find exported files.- Parameters
max_itr (int) – max target Jacobi iteration (filter order)
max_rank (int) – maximum cumulative rank, i.e. maximum rank to be included. must be safe.
dx (float) – cell size
dt (float) – diffusion timestep. See
OptionsKernel()
dim (SolverDimension) – 2D or 3D.
kappa (float) – diffusivity. See
OptionsKernel()
single_itr_num (int) – target Jacobi iteration (filter order) for the single filter export. Make sure it is
=< max_itr
solver_type (PoissonSolverType) – See
PoissonSolverType()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
load_database_from_file (bool) – load database; it has to exist
only_single_itr (bool) – do not generate the whole set of filters, only a single filter corresponding to
single_itr_num
.print_content (bool) – also print in the terminal
export_pack_mode (ExportFormat) – how to arrange the filter values (Default=
GROUP_RANK_FLOAT4_HLSL
)export_file_format (DataFileFormat) – (Default=
hlsli
)
- src.helper.iohandler.format_scientific(x, dynamic_format=False)
- Parameters
x (float) – input value
dynamic_format (bool) – fixed or dynamic format
- Returns
string
- src.helper.iohandler.generate_dump_path_filter_database(max_itr, dx, kappa, dim, solver_type, kernel_type, only_single_itr, single_itr_num, file_format, min_itr=1)
Auto-generate path string.
- Parameters
max_itr (int) – max target Jacobi iteration (filter order)
dx (float) – cell size
kappa (float) – diffusivity (will be ignored if not
FORWARD
)dim (SolverDimension) – See
SolverDimension()
solver_type (PoissonSolverType) – See
PoissonSolverType()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
only_single_itr (bool) – if we are interested only in generating a single set of filters for a specific target Jacobi iteration/filter order.
single_itr_num (int) – target Jacobi iteration/filter order if
only_single_itr=True
file_format (DataFileFormat) –
min_itr (int) – min target Jacobi iteration (filter order) (Default=
1
)
- Returns
path string
- src.helper.iohandler.generate_or_load_filters(opts, max_itr, load_database_from_file, only_single_itr, single_itr_num)
Generate a Poisson filter database or load it from file. It can also be a single set of filter values only for one target iteration.
- Parameters
opts (OptionsGeneral) –
max_itr (int) – max target Jacobi iteration (filter order)
load_database_from_file (bool) – load database; it has to exist
only_single_itr (bool) – do not generate the whole set of filters, only a single filter corresponding to
single_itr_num
.single_itr_num (int) – target Jacobi iteration (filter order) for the single filter export. Make sure it is
=< max_itr
- Returns
list of filters for each target Jacobi iteration (filter order)
- src.helper.iohandler.generate_specs_info(opts, min_itr=1)
Generate a string of specification information of the kernel and solver properties.
- Parameters
opts (OptionsGeneral) –
min_itr (int) – only included when it is
>0
, in which case it means we are batch generating filters betweenmin_itr
andmax_itr
.
- Returns
spec string
- src.helper.iohandler.load_filter_database(max_itr, dx, kappa, dim, solver_type, kernel_type, min_itr=1)
Load filter values. If
min_itr==max_itr
take it as a signal to load only a single filter, else return filters for all target Jacobi iterations betweenmin_itr
andmax_itr
if the database exists.- Parameters
max_itr (int) – max target Jacobi iteration (filter order)
dx (float) – cell size
kappa (float) – diffusivity (will be ignored if not
FORWARD
)dim (SolverDimension) – See
SolverDimension()
solver_type (PoissonSolverType) – See
PoissonSolverType()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
min_itr (int) – min target Jacobi iteration (filter order) (Default=
1
)
- Returns
list of filters for each order if loading a database of filters, else a single set of filter values
- src.helper.iohandler.make_options_batch_filter_generation(max_itr, max_rank, dx, dt, kappa, solver_type, kernel_type, zero_init, dim)
Generate options for the batch task.
Note
To see how to pack options, look at main demos, or see
helper.commons.generic_options()
.- Parameters
max_itr (int) – used to generate a database key in case of loading filters from database, otherwise it is simply the target iteration we are interested in.
max_rank (int) – maximum cumulative rank, i.e. maximum rank to be included. must be safe.
dx (float) – See
OptionsKernel()
dt (float) – See
OptionsKernel()
kappa (float) – See
OptionsKernel()
solver_type (PoissonSolverType) – See
PoissonSolverType()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
zero_init (bool) – See
OptionsPoissonSolver()
dim (SolverDimension) – See
SolverDimension()
- Returns
packed options
- Return type
- src.helper.iohandler.print_components_3d(cores, factors, decomp_method)
Print filters and their core values, only for the reduced case (separable filters).
Warning
Filters must be in (rank, filters) order.
Warning
Assumption: filter is symmetrical along all 3 dimensions.
Warning
Decomposition method must be
SYM_CP_3D
. ForTUCKER_3D
use the same order but with an extra dimension.filter_1d = factors[0][rr, ::]
for Tucker,as opposed to
filter_1d = factors[rr, ::]
for SymCP.- Parameters
cores (ndarray) – core values from CP decomposition
factors (ndarray) – factor values from CP decomposition
decomp_method (DecompMethod) – decomposition method
- src.helper.iohandler.print_cpp_friendly(v, name, no_last_element_comma=True, print_content=True, same_line=False, additional_info=False)
Generate string for and print a vector whose format is c/c++ friendly (easy copy & paste).
- Parameters
v (ndarray) – vector values
name (str) – given name
no_last_element_comma (bool) – if we do not want to have comma added to the last element
print_content (bool) – print the generated content
same_line (bool) – printing values in the same line instead of new line
additional_info (bool) – print additional info if there is any
- Returns
content string
- src.helper.iohandler.print_filters(filters, same_line=True, additional_info=True)
Print filters for the reduced case (separable filters).
Warning
Filters must be in (rank, filters) order.
- Parameters
filters (ndarray) – (rank, 1darray filter values)
same_line (bool) – printing values in the same line instead of new line
additional_info (bool) – print additional info if there is any
- src.helper.iohandler.print_float4_group_array_hlsl_friendly(v1, v2, v3, v4)
Given a 4d array, pack the \(i_{th}\) element of all arrays in one
float4
tuple (hlsl friendly).Works with at least one not
None
array (v1
).0
will be inserted if any of vectors areNone
.Output format:
float4(v1_0, v2_0, v3_0, v4_0),
float4(v1_1, v2_1, v3_2, v4_3),
...
- Parameters
v1 (ndarray) – 1d array, must be not
None
v2 (ndarray) – 1d array, if
None
,0
will be inserted infloat4()
v3 (ndarray) – 1d array, if
None
,0
will be inserted infloat4()
v4 (ndarray) – 1d array, if
None
,0
will be inserted infloat4()
- Returns
content string
- src.helper.iohandler.print_poisson_components_3d(opts, rank_filter_reorder=True)
Print reduced components of the Poisson kernel. Decomposition method can be Tucker or CP.
- Parameters
opts (OptionsGeneral) –
rank_filter_reorder (bool) – if
True
, change from (filters, ranks) to (ranks, filters); consistent with 2d
- Returns
filters or factors, depending on whether the cores are absorbed or not. (rank, filter) shape.
- src.helper.iohandler.print_poisson_filters(dim, itr, max_rank, dx, dt, kappa, kernel_type, solver_type, load_database_from_file, database_max_itr_key, rank_filter_reorder=True)
Print Poisson filters for a desired target Jacobi iteration (filter order). Force generate the filters if they do not exist in the database in case of loading from file.
Output is already transposed by default to match (rank, filter) order: consistent with 2d. You can disable it by setting
rank_filter_order=False
.- Parameters
database_max_itr_key (int) – if loading from database, the database must already exist in
data/preprocess/filters/
withmax_itr
keyload_database_from_file (bool) – database file must already exist with a valid
database_max_itr_key
solver_type (PoissonSolverType) – See
PoissonSolverType()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
kappa (float) – diffusivity. See
OptionsKernel()
dt (float) – diffusion timestep. See
OptionsKernel()
dx (float) – cell size
max_rank (int) – maximum cumulative rank, i.e. maximum rank to be included. must be safe.
itr (int) – target Jacobi iteration (filter order)
dim (SolverDimension) – 2D or 3D. See
SolverDimension()
rank_filter_reorder (bool) – if
True
, change from (filters, ranks) to (ranks, filters); consistent with 2d
- src.helper.iohandler.save_filter_database(filters_iterations, max_itr, dx, kappa, dim, solver_type, kernel_type, min_itr=1)
Save filter values either as
npz
(many filters) ornpy
(single filter). Ifmin_itr==max_itr
take it as a signal to save only a single filter.Saved format: (iteration, rank, 1darray filter values).
- Parameters
filters_iterations (List[int]) – list of target Jacobi iterations (filter orders)
max_itr (int) – max target Jacobi iteration (filter order)
dx (float) – cell size
kappa (float) – diffusivity (will be ignored if not
FORWARD
)dim (SolverDimension) – See
SolverDimension()
solver_type (PoissonSolverType) – See
PoissonSolverType()
kernel_type (PoissonKernelType) – See
PoissonKernelType()
min_itr (int) – min target Jacobi iteration (filter order) (Default=
1
)
- Returns
path string where the file is saved
- src.helper.iohandler.str_float4_hlsl_friendly(x1, x2, x3, x4)
Pack 4 scalars in
float4()
.String format:
float4(x1, x2, x3, x4)
- Parameters
x1 (float) – scalar
x2 (float) – scalar
x3 (float) – scalar
x4 (float) – scalar
- Returns
string of
float4(x1, x2, x3, x4)
src.helper.visualizer module
- author
Shahin (Amir Hossein) Rabbani
- contact
- copyright
See License
- class src.helper.visualizer.FFormatter(fformat='%1.2f', offset=True, useMathText=True)
Bases:
ScalarFormatter
- src.helper.visualizer.add_collision_masks(interior_mask, contour_mask, opts_plots, opts_subplots, axes)
Add a mask to visualize a collider in a matrix domain for all subplot axes. Matrices are 2D numpy arrays.
- Parameters
interior_mask (ndarray) –
contour_mask (ndarray) –
opts_plots (OptionsPlots) –
opts_subplots (OptionsSubPlots) –
axes (Axes) – all subplot axes
- src.helper.visualizer.add_grid_subplots_gridspec(fig, grid_spec, annot=False)
Add axes to an already created figure layout using GridSpec.
- Parameters
fig (matplotlib.figure.Figure) –
grid_spec (matplotlib.GridSpec) – created GridSpec
annot (bool) – show axis info annotations
- Returns
axes
- src.helper.visualizer.add_grid_subplots_mosaic(fig, layout_str, subplot_kw=None, grid_spec_kw=None)
Add subplots to an already existing figure using mosaics.
Check out this example or this one to learn how to gain more control over mosaic subplots.
- Parameters
fig (matplotlib.figure.Figure) –
layout_str (List[List[str]]) –
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.subplot_kw – check out subplot_kw doc.
grid_spec_kw – check out grid_spec_kw doc.
- Returns
axes
- src.helper.visualizer.add_object_mask(interior_mask, contour_mask, opts_plots, show_interior_mask, fill_interior_mask, show_contour_mask, fill_contour_mask, ax, interior_facecolor='cornflowerblue', contour_facecolor='cornflowerblue', edge_color='azure', interior_linewidth=1, contour_linewidth=1)
Add a mask to visualize an object in a matrix domain. Matrices are 2D numpy arrays.
Here is a list of colors.
- Parameters
interior_mask (ndarray) –
contour_mask (ndarray) –
opts_plots (OptionsPlots) –
show_interior_mask (bool) –
fill_interior_mask (bool) –
show_contour_mask (bool) –
fill_contour_mask (bool) –
ax (Axes) –
interior_facecolor (str) –
contour_facecolor (str) –
edge_color (str) –
interior_linewidth (int) –
contour_linewidth (int) –
- src.helper.visualizer.add_subplot(M, title, sub_plots, opts_subplots, highlights=None, cbar_percentile_list=None, cmap=None)
Add an element to a list of subplots
- Parameters
M (ndarray) – input matrix
title (List[str]) –
sub_plots (List[ndarray]) – list of subplot matrices
opts_subplots (OptionsSubPlots) –
highlights (List[ndarray]) – in case of plotting a matrix, the index values of the highlighted cells. This will be ignored if
None
.cbar_percentile_list (List[float]) –
cmap (List[str]) –
- src.helper.visualizer.add_text(ax, coord_x, coord_y, text, fontsize=14, color='red', fontweight='bold', alpha=0.75, horizontal_alignment='center', vertical_alignment='center')
Add text in value coordinates.
- Parameters
ax (Axes) –
coord_x (float) –
coord_y (float) –
text (str) –
fontsize (int) –
color (str) –
fontweight (str) –
alpha (float) – transparency
horizontal_alignment (str) – Default=
"center"
vertical_alignment (str) – Default=
"center"
- src.helper.visualizer.adjust_axis_projection(fig, ax, grid_spec, projection)
Change the axis projection by removing and re-adding the axis.
- Parameters
fig (matplotlib.figure.Figure) –
ax (Axes) –
grid_spec (matplotlib.GridSpec) –
projection (str) –
'2d'
or'3d'
- Returns
axis
- src.helper.visualizer.beautify_axis(ax)
Beautify axis by hiding the axis, ticks, axis lines, and setting the panes to black.
- Parameters
ax (Axes) –
- src.helper.visualizer.clear_axis(axis)
- Parameters
axis (Axes) –
- Returns
- src.helper.visualizer.compute_layout(columns, num_elements)
Compute the layout rows and columns for a desired number of columns and the total number of elements.
- Parameters
columns (int) –
num_elements (int) – total number of elements
- Returns
(rows, columns)
- src.helper.visualizer.correct_color_bar_2d(M, interior_mask)
Due to the likely presence of a solid object inside the domain the color bar might be wrongly shifted. This is because the interior part of it is not updated during the solve and could remain zero or some other initial const value. To fix this, we find and set them to be the average of min and max of the domain, so they do not shift the color bar.
- Parameters
M (ndarray) – input 2d matrix
interior_mask (ndarray) – mask matrix
- Returns
adjusted matrix
- src.helper.visualizer.draw_line(ax, from_x, from_y, to_x, to_y, color='red', linewidth=2.5, linestyle='--')
Draw line in value coordinates.
- Parameters
ax (Axes) –
from_x (float) – starting x position
from_y (float) – starting y position
to_x (float) – ending x position
to_y (float) – ending y position
color (str) –
linewidth (int) –
linestyle (str) –
- src.helper.visualizer.draw_truncation_visuals(truncation_method, truncation_value, filter_1d, ax)
Add visuals to an existing filter plot displaying adaptive truncation (single filter)
- Parameters
truncation_method (TruncationMode) – for now only works with
FIXED_THRESHOLD
truncation_value (float) –
filter_1d (1darray) –
ax (Axes) –
- src.helper.visualizer.fmt_imshow(x: str)
- Parameters
x (str) –
- Returns
- src.helper.visualizer.grid_layout_example_1()
An example of making complex grids using manual widths and heights.
- src.helper.visualizer.grid_layout_example_2()
An example of creating a grid using mosaic. String based layout (easier control when combining axes).
Check out this example or this one to learn how to gain more control over mosaic subplots.
- src.helper.visualizer.highlght_cells(highlights, opts, ax, cell_offset_x=0, cell_offset_y=0)
Add rectangular patch to matrix cells.
- Parameters
highlights (ndarray) – row/column of the highlighted cells
opts (OptionsPlots) –
ax (Axes) –
cell_offset_x (int) –
cell_offset_y (int) –
- src.helper.visualizer.init_subplots(sub_plots, opts_subplots)
- Parameters
sub_plots (List[ndarray]) – list of subplot matrices
opts_subplots (OptionsSubPlots) –
- src.helper.visualizer.initialize_grid_layout_gridspec(fig_size, widths_ratios, heights_ratios, constrained_layout=True, canvas_background_color=None)
- Parameters
fig_size ((float, float)) – (width, height)
widths_ratios (List[float]) –
heights_ratios (List[float]) –
constrained_layout (bool) –
nice and tidy layout (can’t manually tweak it though).
Warning
this is not compatible with fine adjustments of GridSpec.
canvas_background_color (str) –
- Returns
figure, and the created grid spec
- src.helper.visualizer.make_grid_layout_gridspec(fig_size, widths_ratios, heights_ratios, constrained_layout=True, annot=False)
Create a detailed grid subplots with full control over the layout
- Parameters
fig_size ((float, float)) – (width, height)
widths_ratios (List[float]) –
heights_ratios (List[float]) –
constrained_layout (bool) –
nice and tidy layout (can’t manually tweak it though).
Warning
this is not compatible with fine adjustments of GridSpec.
annot – show axis info annotations
- Returns
fig, axes list in the shape of [nrows][ncols], and the created grid spec
- src.helper.visualizer.make_grid_layout_mosaic(layout_str, fig_size, constrained_layout=True, canvas_background_color=None, subplot_kw=None, grid_spec_kw=None)
Make a figure and its mosaic subplots. Check out this example or this one to learn how to gain more control over mosaic subplots.
- Parameters
layout_str (List[List[str]]) –
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.fig_size ((float, float)) – (width, height)
constrained_layout (bool) –
nice and tidy layout (can’t manually tweak it though).
Warning
this is not compatible with fine adjustments of GridSpec.
canvas_background_color (str) –
subplot_kw – See
add_grid_subplots_mosaic()
grid_spec_kw – See
add_grid_subplots_mosaic()
- Returns
fig: new figure
axs:
dict[label, Axes]
: A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.
- src.helper.visualizer.plot_1d_array(array, title, plt_show, no_ticks, color=None, interpolate=True, interp_res=10, symmetric_x_axis=True, ax=None, label=None, line_style=None, linewidth=1, swap_axes=False, frame_on=True, limits_x_tight=True, limits_y_tight=False)
- Parameters
array (1darray) –
title (str) –
plt_show (bool) – force plot if
True
, else delay the plot showno_ticks (bool) –
color (str) – if
None
plot style picks the best one. ‘firebrick’ is a nice choice.interpolate (bool) –
interp_res (int) –
1
no interpolation,1>
increased resolutionsymmetric_x_axis (bool) – if
True
add points equally to each side of the array centerax (Axes) –
label (str) – line label
line_style (str) –
linewidth (int) –
swap_axes (bool) –
frame_on (bool) – border control
limits_x_tight (bool) – no horizontal space in the axis
limits_y_tight (bool) – no vertical space in the axis
- Returns
axis
- Return type
Axes:
- src.helper.visualizer.plot_1d_array_grid(G, title, opts_general, opts_subplots)
Plot 1d arrays (usually filters) in a grid structure with automatic handling of its properties.
- Parameters
G (List[ndarray]) – list of 1d arrays
title (str) –
opts_general (OptionsPlots) –
opts_subplots (OptionsSubPlots) –
- Returns
- src.helper.visualizer.plot_filters(opts_plots, safe_rank, filters, specs_info)
Plot 1d Poisson filters.
- Parameters
opts_plots (OptionsPlots) –
safe_rank (int) – cumulative rank, i.e. maximum rank to be included; must be safe; “safe” means a rank that does not exceed the actual rank of the kernel
filters (1darray) –
specs_info (str) –
- src.helper.visualizer.plot_filters_3d_advanced(processed_filters, axes_1d, axes_2d, fig, visualize_truncation, truncation_method, truncation_value, filter_titles, swap_axes, opts_plots)
Plot beautified filters with truncation bars.
- Parameters
processed_filters (ndarray) –
axes_1d (Axes) – axes to draw 1d views
axes_2d (Axes) – axes to draw 2d views
fig (matplotlib.figure.Figure) –
visualize_truncation (bool) –
truncation_method (TruncationMode) – for now only works with
FIXED_THRESHOLD
truncation_value (float) –
filter_titles (str) –
swap_axes (bool) – swaps x-axis and y-axis (vertical or horizontal)
opts_plots (OptionsPlots) –
- Returns
- src.helper.visualizer.plot_matrix_2d_advanced(M, title, opts, ax_img=None, cbar_ax=None)
With color bar control. By default, auto-generate the figure, image and color bar axes (when all are
None
in the input).- Parameters
M (ndarray) – 2D input matrix
title (str) –
opts (OptionsPlots) –
ax_img (Axes) – image axis
cbar_ax (Axes) – color bar axis
- Returns
figure and image axis
- src.helper.visualizer.plot_matrix_2d_simple(M, title, opts, rotate_ticks=True, highlights=None, cmap=None, cbar_percentiles=None, ax=None)
- Parameters
M (ndarray) – 2D input matrix
title (str) –
opts (OptionsPlots) –
rotate_ticks (bool) – rotate ticks by 45 degrees
highlights (ndarray) – if not
None
, highlight the cells with non-zero values. Must be the same size as input matrixM
.cmap (str) – color map. Can be matplotlib.colors.Colormap too. If not
None
overwrite the cmap inopts
, else useopts.cmap
cbar_percentiles (list) – percentile list, e.g.
[95, 99]
ax (Axes) – input axis
- Returns
axis
- src.helper.visualizer.plot_matrix_3d(M, title, opts, cmap=None, ax=None, cbar_show=False, cbar_ax=None, fig=None)
By default, auto-generate the figure, image and color bar axes (when all are
None
in the input).- Parameters
M (ndarray) – 3D input array (tensor)
title (str) –
opts (OptionsPlots) –
cmap (str) – color map. Can be matplotlib.colors.Colormap too. If not
None
overwrite the cmap inopts
, else useopts.cmap
ax (Axes) –
cbar_show (bool) –
cbar_ax (Axes) –
fig (matplotlib.figure.Figure) –
- Returns
axis
- src.helper.visualizer.plot_matrix_grid(G, projection, opts_general, opts_subplots, title=None, cmaps=None, fig_size=None, clear_unused=True)
Plot 2d matrices in a grid structure with automatic handling of its properties.
- Parameters
G (List[ndarray]) – list of 2d matrices
title (str) –
projection (str) –
"2d"
or"3d"
opts_general (OptionsPlots) –
opts_subplots (OptionsSubPlots) –
cmaps – color map. Can be matplotlib.colors.Colormap too. If not
None
overwrite the cmap inopts
, else useopts.cmap
fig_size ((float, float)) – (width, height) in inches
clear_unused (bool) – clear unused subplots. Do not clean if the remaining subplots are used by an external function.
- Returns
axes
- src.helper.visualizer.plot_scalar_field(M, ax, fig, title, show_contour, interp_mode, cmap, blend_color, cmap_secondary_blend='flag', show_cbar=True, ax_cbar_image=None, cbar_location='right', cbar_orientation='vertical', show_contour_values=False, contour_res=100, cmap_contour='gist_heat', ax_cbar_contour=None, show_contour_cbar=True, contour_cbar_location='right', contour_cbar_orientation='vertical', bar_indicator_val=None, vrange_im=None, vrange_contour=None, contour_cbar_border=False, contour_cbar_no_ticks=True, ax_noticks=False, cbar_border=False, cbar_outline_color='black', cbar_label=None, cbar_label_color='white', cbar_ticks=True, cbar_tick_color=None)
Plot a scalar field with contours.
- Parameters
M (ndarray) – input matrix
ax (Axes) – image axis
fig (matplotlib.figure.Figure) –
title (str) –
show_contour (bool) –
interp_mode (str) –
[None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']
. Here is the full list with examples.cmap (str) – colormap
blend_color (bool) – blend between the image cmap and an additional one given in
cmap_secondary_blend
(usually to make a more detailed cmap)cmap_secondary_blend (str) – when blending, blend image cmap with this cmap
show_cbar (bool) –
ax_cbar_image (Axes) – image axis.
None
by default (if show cbar, this will automatically create one by dividing the image axis)cbar_location (str) –
'right', 'left', 'top', 'bottom'
cbar_orientation (str) –
'horizontal', 'vertical'
show_contour_values (bool) –
contour_res (int) – contour resolution
cmap_contour (str) – contour colormap
ax_cbar_contour – contour color bar axis.
None
by default (if show contour cbar, this will automatically create one by dividing the image axis)show_contour_cbar (bool) –
bar_indicator_val (float) – if not
None
, path indicator in the color bar. Bar indicator sits on the color bar. Must be normalized.vrange_im ((float, float)) – (min, max); used to force the image color bar to a min and max Can be left
None
and imshow will automatically compute itvrange_contour ((float, float)) – (min, max); used to force the contour color bar to a min and max
contour_cbar_location (str) –
'right', 'left', 'top', 'bottom'
contour_cbar_orientation – for now only
'vertical'
workscontour_cbar_border (bool) – remove contour cbar borders when
False
contour_cbar_no_ticks (bool) – remove contour cbar ticks
ax_noticks (bool) –
cbar_border (bool) –
cbar_outline_color (str) –
cbar_label (str) –
cbar_label_color (str) –
cbar_ticks (bool) –
cbar_tick_color (str) –
- Returns
image and contour handles
- src.helper.visualizer.plot_scalar_field_unpack_opts(M, ax_img, fig, opts, vrange_im, title='', ax_cbar_image=None, ax_cbar_contour=None, vrange_contour=None, bar_indicator_val=None)
Plot scalar field. This is a helper function to unpack options when calling the main plot function.
- Parameters
M (ndarray) – input matrix
ax_img (Axes) – image axis
fig (matplotlib.figure.Figure) –
opts (OptionsPlots) –
vrange_im ((float, float)) – (min, max); used to force the image color bar to a min and max
title (str) –
ax_cbar_image (Axes) – image color bar axis
ax_cbar_contour (Axes) – contour color bar axis
vrange_contour ((float, float)) – (min, max); used to force the contour color bar to a min and max
bar_indicator_val (float) – if not
None
, draw a little marker line on the color bar. Must be normalized.
- src.helper.visualizer.plot_vector_field_2d(Mx, My, title, plt_show=False, interp=False, flip_vertically=True, cmap=None, vector_variable_cmap=True, variable_cmap_mode=ColorMapModesVectorField.VECTOR_ANGLE, show_cbar=False, ax_no_ticks=False, down_sample_rate=None, alpha=1.0, background_tone=0.0, scale=None, ax=None)
- Parameters
Mx (ndarray) – x components of the input matrix
My (ndarray) – y components of the input matrix
title (str) –
plt_show (bool) – force plot if
True
, else delay the plot showinterp (bool) – interpolate values
flip_vertically (bool) – flip vectors
cmap (str) – color map. Can be matplotlib.colors.Colormap too. If not
None
overwrite the cmap inopts
, else useopts.cmap
vector_variable_cmap (bool) – apply custom dynamic vector color
variable_cmap_mode (ColorMapModesVectorField) – vector angle or vector length color map
show_cbar (bool) –
ax_no_ticks (bool) –
down_sample_rate (int) –
alpha (float) –
background_tone (float) – background color tone
scale (float) – scales the arrow. Smaller values make the arrows longer. Good value
1e4
. Default=None
(auto)ax (Axes) –
- Returns
- src.helper.visualizer.simple_animation_examples()
Contains two animations. The first one is a random walk plot. The second is an image animation.
Other examples are found here.
- src.helper.visualizer.super_impose_mask(M, opts, edge_color, line_width, ax, fill=False, face_color='pink', allow_mask_interpolation=True)
Superimpose a 2D mask onto a 2D domain matrix.
Warning
We override some variables in the
OptionsPlots
, which will persist after the lifespan of this method.- Parameters
M (ndarray) – input matrix
opts (OptionsPlots) –
edge_color (str) –
line_width (int) –
ax (Axes) –
fill (bool) –
face_color (str) –
allow_mask_interpolation (bool) –
- src.helper.visualizer.use_style(style_name)
Instant stylization of the plot (e.g. black background).
Here is the reference.
- Parameters
style_name (str) –
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']