Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F65674550
nearest_neighbor.py
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Wed, Jun 5, 11:14
Size
7 KB
Mime Type
text/x-python
Expires
Fri, Jun 7, 11:14 (2 d)
Engine
blob
Format
Raw Data
Handle
18110545
Attached To
R6746 RationalROMPy
nearest_neighbor.py
View Options
# Copyright (C) 2018 by the RROMPy authors
#
# This file is part of RROMPy.
#
# RROMPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RROMPy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with RROMPy. If not, see <http://www.gnu.org/licenses/>.
#
import
numpy
as
np
from
collections.abc
import
Iterable
from
copy
import
deepcopy
as
copy
from
.generic_standard_approximant
import
GenericStandardApproximant
from
rrompy.utilities.base
import
verbosityManager
as
vbMng
from
rrompy.utilities.poly_fitting.nearest_neighbor
import
(
NearestNeighborInterpolator
as
NNI
)
from
rrompy.utilities.exception_manager
import
RROMPyAssert
__all__
=
[
'NearestNeighbor'
]
class
NearestNeighbor
(
GenericStandardApproximant
):
"""
ROM nearest neighbor approximant computation for parametric problems.
Args:
HFEngine: HF problem solver.
mu0(optional): Default parameter. Defaults to 0.
approxParameters(optional): Dictionary containing values for main
parameters of approximant. Recognized keys are:
- 'POD': kind of snapshots orthogonalization; allowed values
include 0, 1/2, and 1; defaults to 1, i.e. POD;
- 'scaleFactorDer': scaling factors for derivative computation;
defaults to 'AUTO';
- 'S': total number of samples current approximant relies upon;
- 'sampler': sample point generator;
- 'nNeighbors': number of nearest neighbors; defaults to 1;
- 'radialDirectionalWeights': directional weights for computation
of parameter distance; defaults to 1.
Defaults to empty dict.
approx_state(optional): Whether to approximate state. Defaults and must
be True.
verbosity(optional): Verbosity level. Defaults to 10.
Attributes:
HFEngine: HF problem solver.
mu0: Default parameter.
mus: Array of snapshot parameters.
approxParameters: Dictionary containing values for main parameters of
approximant. Recognized keys are in parameterList.
parameterListSoft: Recognized keys of soft approximant parameters:
- 'POD': kind of snapshots orthogonalization;
- 'scaleFactorDer': scaling factors for derivative computation;
- 'nNeighbors': number of nearest neighbors;
- 'radialDirectionalWeights': directional weights for computation
of parameter distance.
parameterListCritical: Recognized keys of critical approximant
parameters:
- 'S': total number of samples current approximant relies upon;
- 'sampler': sample point generator.
approx_state: Whether to approximate state.
verbosity: Verbosity level.
POD: Kind of snapshots orthogonalization.
scaleFactorDer: Scaling factors for derivative computation.
S: Number of solution snapshots over which current approximant is
based upon.
sampler: Sample point generator.
nNeighbors: Number of nearest neighbors.
radialDirectionalWeights: Directional weights for computation of
parameter distance.
muBounds: list of bounds for parameter values.
samplingEngine: Sampling engine.
uHF: High fidelity solution(s) with parameter(s) lastSolvedHF as
sampleList.
lastSolvedHF: Parameter(s) corresponding to last computed high fidelity
solution(s) as parameterList.
uApproxReduced: Reduced approximate solution(s) with parameter(s)
lastSolvedApprox as sampleList.
lastSolvedApproxReduced: Parameter(s) corresponding to last computed
reduced approximate solution(s) as parameterList.
uApprox: Approximate solution(s) with parameter(s) lastSolvedApprox as
sampleList.
lastSolvedApprox: Parameter(s) corresponding to last computed
approximate solution(s) as parameterList.
"""
def
__init__
(
self
,
*
args
,
**
kwargs
):
self
.
_preInit
()
self
.
_addParametersToList
([
"nNeighbors"
,
"radialDirectionalWeights"
],
[
1
,
1.
])
super
()
.
__init__
(
*
args
,
**
kwargs
)
self
.
_postInit
()
@property
def
tModelType
(
self
):
from
.trained_model.trained_model_nearest_neighbor
import
(
TrainedModelNearestNeighbor
)
return
TrainedModelNearestNeighbor
@property
def
nNeighbors
(
self
):
"""Value of nNeighbors."""
return
self
.
_nNeighbors
@nNeighbors.setter
def
nNeighbors
(
self
,
nNeighbors
):
self
.
_nNeighbors
=
max
(
1
,
nNeighbors
)
self
.
_approxParameters
[
"nNeighbors"
]
=
self
.
nNeighbors
@property
def
radialDirectionalWeights
(
self
):
"""Value of radialDirectionalWeights."""
return
self
.
_radialDirectionalWeights
@radialDirectionalWeights.setter
def
radialDirectionalWeights
(
self
,
radialDirectionalWeights
):
if
isinstance
(
radialDirectionalWeights
,
Iterable
):
radialDirectionalWeights
=
list
(
radialDirectionalWeights
)
else
:
radialDirectionalWeights
=
[
radialDirectionalWeights
]
self
.
_radialDirectionalWeights
=
radialDirectionalWeights
self
.
_approxParameters
[
"radialDirectionalWeights"
]
=
(
self
.
radialDirectionalWeights
)
def
setupApprox
(
self
)
->
int
:
"""Compute RB projection matrix."""
if
self
.
checkComputedApprox
():
return
-
1
RROMPyAssert
(
self
.
_mode
,
message
=
"Cannot setup approximant."
)
vbMng
(
self
,
"INIT"
,
"Setting up {}."
.
format
(
self
.
name
()),
5
)
self
.
computeSnapshots
()
setData
=
self
.
trainedModel
is
None
self
.
_setupTrainedModel
(
self
.
samplingEngine
.
projectionMatrix
)
if
setData
:
self
.
trainedModel
.
data
.
NN
=
NNI
()
if
self
.
POD
==
1
:
R
=
self
.
samplingEngine
.
Rscale
if
isinstance
(
R
,
(
np
.
ndarray
,)):
vals
,
supp
=
list
(
R
.
T
),
[
0
]
*
R
.
shape
[
1
]
else
:
vals
,
supp
=
[],
[]
for
j
in
range
(
R
.
shape
[
1
]):
idx
=
R
.
indices
[
R
.
indptr
[
j
]
:
R
.
indptr
[
j
+
1
]]
if
len
(
idx
)
==
0
:
supp
+=
[
0
]
val
=
np
.
empty
(
0
,
dtype
=
R
.
dtype
)
else
:
supp
+=
[
idx
[
0
]]
idx
=
idx
-
idx
[
0
]
val
=
np
.
zeros
(
idx
[
-
1
]
+
1
,
dtype
=
R
.
dtype
)
val
[
idx
]
=
R
.
data
[
R
.
indptr
[
j
]
:
R
.
indptr
[
j
+
1
]]
vals
+=
[
val
]
else
:
if
self
.
POD
==
0
:
vals
=
[
np
.
ones
(
1
)]
*
len
(
self
.
mus
)
else
:
vals
=
list
(
self
.
samplingEngine
.
Rscale
.
reshape
(
-
1
,
1
))
supp
=
list
(
range
(
len
(
self
.
mus
)))
self
.
trainedModel
.
data
.
NN
.
setupByInterpolation
(
self
.
mus
,
np
.
arange
(
len
(
self
.
mus
)),
self
.
nNeighbors
,
self
.
radialDirectionalWeights
)
self
.
trainedModel
.
data
.
vals
,
self
.
trainedModel
.
data
.
supp
=
vals
,
supp
self
.
trainedModel
.
data
.
approxParameters
=
copy
(
self
.
approxParameters
)
vbMng
(
self
,
"DEL"
,
"Done setting up approximant."
,
5
)
return
0
Event Timeline
Log In to Comment