Commit c44d5441 authored by Le Roux Erwan's avatar Le Roux Erwan
Browse files

[REFACTORING] refactor spatial_coordinates to coordinates. add experiment folder.

parent f846e3f6
No related merge requests found
Showing with 213 additions and 38 deletions
+213 -38
from extreme_estimator.estimator.max_stable_estimator import MaxStableEstimator
from extreme_estimator.extreme_models.max_stable_model.abstract_max_stable_model import AbstractMaxStableModel
from extreme_estimator.extreme_models.max_stable_model.max_stable_models import Smith
from experiment.robustness_plot.display_item import DisplayItem
from experiment.robustness_plot.multiple_plot import MultiplePlot
from experiment.robustness_plot.single_plot import SinglePlot
from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractCoordinates
from spatio_temporal_dataset.coordinates.spatial_coordinates.generated_coordinates import CircleCoordinatesRadius1
from spatio_temporal_dataset.dataset.simulation_dataset import MaxStableDataset
class MaxStableDisplayItem(DisplayItem):
def display_name_from_value(self, value: AbstractMaxStableModel):
return value.cov_mod
class CoordinateDisplayItem(DisplayItem):
def display_name_from_value(self, value: AbstractCoordinates):
return str(value).split('.')[-1].split("'")[0]
class MaxStableProcessPlot(object):
MaxStableModelItem = MaxStableDisplayItem('max_stable_model', Smith)
CoordinateClassItem = CoordinateDisplayItem('coordinate_class', CircleCoordinatesRadius1)
NbStationItem = DisplayItem('Number of stations', 50)
NbObservationItem = DisplayItem('nb_obs', 60)
def msp_spatial_ordinates(self, **kwargs_single_point) -> dict:
# Get the argument from kwargs
max_stable_model = self.MaxStableModelItem.value_from_kwargs(
**kwargs_single_point) # type: AbstractMaxStableModel
coordinate_class = self.CoordinateClassItem.value_from_kwargs(**kwargs_single_point)
nb_station = self.NbStationItem.value_from_kwargs(**kwargs_single_point)
nb_obs = self.NbObservationItem.value_from_kwargs(**kwargs_single_point)
# Run the estimation
spatial_coordinates = coordinate_class.from_nb_points(nb_points=nb_station)
dataset = MaxStableDataset.from_sampling(nb_obs=nb_obs, max_stable_model=max_stable_model,
coordinates=spatial_coordinates)
estimator = MaxStableEstimator(dataset, max_stable_model)
estimator.fit()
return estimator.scalars(max_stable_model.params_sample)
class SingleMaxStableProcessPlot(SinglePlot, MaxStableProcessPlot):
def compute_value_from_kwargs_single_point(self, **kwargs_single_point):
return self.msp_spatial_ordinates(**kwargs_single_point)
class MultipleMaxStableProcessPlot(MultiplePlot, MaxStableProcessPlot):
def compute_value_from_kwargs_single_point(self, **kwargs_single_point):
return self.msp_spatial_ordinates(**kwargs_single_point)
\ No newline at end of file
from extreme_estimator.extreme_models.max_stable_model.abstract_max_stable_model import AbstractMaxStableModel
from extreme_estimator.extreme_models.max_stable_model.max_stable_models import Smith, BrownResnick
from extreme_estimator.estimator.abstract_estimator import AbstractEstimator from extreme_estimator.estimator.abstract_estimator import AbstractEstimator
from extreme_estimator.estimator.max_stable_estimator import MaxStableEstimator from extreme_estimator.extreme_models.max_stable_model.max_stable_models import Smith, BrownResnick
from extreme_estimator.robustness_plot.multiple_plot import MultiplePlot from experiment.robustness_plot.estimation_robustness.max_stable_process_plot import MultipleMaxStableProcessPlot, MaxStableProcessPlot
from extreme_estimator.robustness_plot.single_plot import SinglePlot from experiment.robustness_plot.single_plot import SinglePlot
from spatio_temporal_dataset.dataset.simulation_dataset import MaxStableDataset
from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractSpatialCoordinates
from spatio_temporal_dataset.coordinates.spatial_coordinates.alps_station_2D_coordinates import \ from spatio_temporal_dataset.coordinates.spatial_coordinates.alps_station_2D_coordinates import \
AlpsStation2DCoordinatesBetweenZeroAndOne, AlpsStationCoordinatesBetweenZeroAndTwo AlpsStation2DCoordinatesBetweenZeroAndOne, AlpsStationCoordinatesBetweenZeroAndTwo
from spatio_temporal_dataset.coordinates.spatial_coordinates.generated_coordinates import CircleCoordinatesRadius1, \ from spatio_temporal_dataset.coordinates.spatial_coordinates.generated_coordinates import CircleCoordinatesRadius1, \
CircleCoordinatesRadius2 CircleCoordinatesRadius2
from extreme_estimator.robustness_plot.display_item import DisplayItem
class MaxStableDisplayItem(DisplayItem):
def display_name_from_value(self, value: AbstractMaxStableModel):
return value.cov_mod
class SpatialCoordinateDisplayItem(DisplayItem):
def display_name_from_value(self, value: AbstractSpatialCoordinates):
return str(value).split('.')[-1].split("'")[0]
class MspSpatial(object):
MaxStableModelItem = MaxStableDisplayItem('max_stable_model', Smith)
SpatialCoordinateClassItem = SpatialCoordinateDisplayItem('spatial_coordinate_class', CircleCoordinatesRadius1)
NbStationItem = DisplayItem('Number of stations', 50)
NbObservationItem = DisplayItem('nb_obs', 60)
def msp_spatial_ordinates(self, **kwargs_single_point) -> dict:
# Get the argument from kwargs
max_stable_model = self.MaxStableModelItem.value_from_kwargs(
**kwargs_single_point) # type: AbstractMaxStableModel
spatial_coordinate_class = self.SpatialCoordinateClassItem.value_from_kwargs(**kwargs_single_point)
nb_station = self.NbStationItem.value_from_kwargs(**kwargs_single_point)
nb_obs = self.NbObservationItem.value_from_kwargs(**kwargs_single_point)
# Run the estimation
spatial_coordinates = spatial_coordinate_class.from_nb_points(nb_points=nb_station)
dataset = MaxStableDataset.from_sampling(nb_obs=nb_obs, max_stable_model=max_stable_model,
spatial_coordinates=spatial_coordinates)
estimator = MaxStableEstimator(dataset, max_stable_model)
estimator.fit()
return estimator.scalars(max_stable_model.params_sample)
class SingleMspSpatial(SinglePlot, MspSpatial):
def compute_value_from_kwargs_single_point(self, **kwargs_single_point):
return self.msp_spatial_ordinates(**kwargs_single_point)
class MultipleMspSpatial(MultiplePlot, MspSpatial):
def compute_value_from_kwargs_single_point(self, **kwargs_single_point):
return self.msp_spatial_ordinates(**kwargs_single_point)
# def single_spatial_robustness_alps(): # def single_spatial_robustness_alps():
...@@ -75,18 +24,18 @@ class MultipleMspSpatial(MultiplePlot, MspSpatial): ...@@ -75,18 +24,18 @@ class MultipleMspSpatial(MultiplePlot, MspSpatial):
def multiple_spatial_robustness_alps(): def multiple_spatial_robustness_alps():
nb_observation = 60 nb_observation = 20
nb_sample = 10 nb_sample = 1
plot_name = 'fast_result' plot_name = 'fast_result'
nb_stations = list(range(43, 87, 15)) nb_stations = list(range(43, 87, 15))
# nb_stations = [10, 20, 30] # nb_stations = [10, 20, 30]
spatial_robustness = MultipleMspSpatial( spatial_robustness = MultipleMaxStableProcessPlot(
grid_column_item=MspSpatial.SpatialCoordinateClassItem, grid_column_item=MaxStableProcessPlot.CoordinateClassItem,
plot_row_item=MspSpatial.NbStationItem, plot_row_item=MaxStableProcessPlot.NbStationItem,
plot_label_item=MspSpatial.MaxStableModelItem, plot_label_item=MaxStableProcessPlot.MaxStableModelItem,
nb_samples=nb_sample, nb_samples=nb_sample,
main_title="Max stable analysis with {} years of observations".format(nb_observation), main_title="Max stable analysis with {} years of temporal_observations".format(nb_observation),
plot_png_filename=plot_name plot_png_filename=plot_name
) )
# Load all the models # Load all the models
...@@ -97,13 +46,13 @@ def multiple_spatial_robustness_alps(): ...@@ -97,13 +46,13 @@ def multiple_spatial_robustness_alps():
# Put only the parameter that will vary # Put only the parameter that will vary
spatial_robustness.robustness_grid_plot(**{ spatial_robustness.robustness_grid_plot(**{
SinglePlot.OrdinateItem.name: [AbstractEstimator.MAE_ERROR, AbstractEstimator.DURATION], SinglePlot.OrdinateItem.name: [AbstractEstimator.MAE_ERROR, AbstractEstimator.DURATION],
MspSpatial.NbStationItem.name: nb_stations, MaxStableProcessPlot.NbStationItem.name: nb_stations,
MspSpatial.NbObservationItem.name: nb_observation, MaxStableProcessPlot.NbObservationItem.name: nb_observation,
MspSpatial.MaxStableModelItem.name: msp_models, MaxStableProcessPlot.MaxStableModelItem.name: msp_models,
MspSpatial.SpatialCoordinateClassItem.name: [CircleCoordinatesRadius1, MaxStableProcessPlot.CoordinateClassItem.name: [CircleCoordinatesRadius1,
CircleCoordinatesRadius2, CircleCoordinatesRadius2,
AlpsStation2DCoordinatesBetweenZeroAndOne, AlpsStation2DCoordinatesBetweenZeroAndOne,
AlpsStationCoordinatesBetweenZeroAndTwo][:], AlpsStationCoordinatesBetweenZeroAndTwo][:],
}) })
......
from extreme_estimator.estimator.abstract_estimator import AbstractEstimator
from extreme_estimator.extreme_models.max_stable_model.max_stable_models import Smith, BrownResnick
from experiment.robustness_plot.estimation_robustness.max_stable_process_plot import MultipleMaxStableProcessPlot, MaxStableProcessPlot
from experiment.robustness_plot.single_plot import SinglePlot
from spatio_temporal_dataset.coordinates.spatial_coordinates.alps_station_2D_coordinates import \
AlpsStation2DCoordinatesBetweenZeroAndOne, AlpsStationCoordinatesBetweenZeroAndTwo
from spatio_temporal_dataset.coordinates.spatial_coordinates.generated_coordinates import CircleCoordinatesRadius1, \
CircleCoordinatesRadius2
# def single_spatial_robustness_alps():
# spatial_robustness = SingleMspSpatial(grid_row_item=SingleMspSpatial.NbObservationItem,
# grid_column_item=SingleMspSpatial.SpatialCoordinateClassItem,
# plot_row_item=SingleMspSpatial.NbStationItem,
# plot_label_item=SingleMspSpatial.MaxStableModelItem)
# # Put only the parameter that will vary
# spatial_robustness.robustness_grid_plot(**{
# SingleMspSpatial.NbStationItem.name: list(range(43, 87, 15)),
# SingleMspSpatial.NbObservationItem.name: [10],
# SingleMspSpatial.MaxStableModelItem.name: [Smith(), BrownResnick()][:],
# SingleMspSpatial.SpatialCoordinateClassItem.name: [CircleCoordinatesRadius1,
# AlpsStationCoordinatesBetweenZeroAndOne][:],
# })
def multiple_unidimensional_robustness():
nb_observation = 20
nb_sample = 1
plot_name = 'fast_result'
nb_stations = list(range(43, 87, 15))
# nb_stations = [10, 20, 30]
spatial_robustness = MultipleMaxStableProcessPlot(
grid_column_item=MaxStableProcessPlot.CoordinateClassItem,
plot_row_item=MaxStableProcessPlot.NbStationItem,
plot_label_item=MaxStableProcessPlot.MaxStableModelItem,
nb_samples=nb_sample,
main_title="Max stable analysis with {} years of temporal_observations".format(nb_observation),
plot_png_filename=plot_name
)
# Load all the models
msp_models = [Smith(), BrownResnick()]
# for covariance_function in CovarianceFunction:
# msp_models.extend([ExtremalT(covariance_function=covariance_function)])
# Put only the parameter that will vary
spatial_robustness.robustness_grid_plot(**{
SinglePlot.OrdinateItem.name: [AbstractEstimator.MAE_ERROR, AbstractEstimator.DURATION],
MaxStableProcessPlot.NbStationItem.name: nb_stations,
MaxStableProcessPlot.NbObservationItem.name: nb_observation,
MaxStableProcessPlot.MaxStableModelItem.name: msp_models,
MaxStableProcessPlot.CoordinateClassItem.name: [CircleCoordinatesRadius1,
CircleCoordinatesRadius2,
AlpsStation2DCoordinatesBetweenZeroAndOne,
AlpsStationCoordinatesBetweenZeroAndTwo][:],
})
if __name__ == '__main__':
# single_spatial_robustness_alps()
multiple_unidimensional_robustness()
from extreme_estimator.robustness_plot.single_plot import SinglePlot from experiment.robustness_plot.single_plot import SinglePlot
class MultiplePlot(SinglePlot): class MultiplePlot(SinglePlot):
......
import os import os
import os.path as op import os.path as op
import random
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
from itertools import product from itertools import product
from extreme_estimator.estimator.abstract_estimator import AbstractEstimator from extreme_estimator.estimator.abstract_estimator import AbstractEstimator
from extreme_estimator.robustness_plot.display_item import DisplayItem from experiment.robustness_plot.display_item import DisplayItem
from utils import get_full_path from utils import get_full_path
plt.style.use('seaborn-white') plt.style.use('seaborn-white')
......
...@@ -12,7 +12,7 @@ class AbstractEstimator(object): ...@@ -12,7 +12,7 @@ class AbstractEstimator(object):
# - The optimization method for each part of the process # - The optimization method for each part of the process
def __init__(self, dataset: AbstractDataset): def __init__(self, dataset: AbstractDataset):
self.dataset = dataset self.dataset = dataset # type: AbstractDataset
self.additional_information = dict() self.additional_information = dict()
def fit(self): def fit(self):
......
...@@ -25,7 +25,7 @@ class SmoothMarginalsThenUnitaryMsp(AbstractFullEstimator): ...@@ -25,7 +25,7 @@ class SmoothMarginalsThenUnitaryMsp(AbstractFullEstimator):
self.margin_estimator.fit() self.margin_estimator.fit()
# Compute the maxima_frech # Compute the maxima_frech
maxima_frech = AbstractMarginModel.gev2frech(maxima_gev=self.dataset.maxima_gev, maxima_frech = AbstractMarginModel.gev2frech(maxima_gev=self.dataset.maxima_gev,
coordinates=self.dataset.coordinates, coordinates=self.dataset.coordinates_values,
margin_function=self.margin_estimator.margin_function_fitted) margin_function=self.margin_estimator.margin_function_fitted)
# Update maxima frech field through the dataset object # Update maxima frech field through the dataset object
self.dataset.maxima_frech = maxima_frech self.dataset.maxima_frech = maxima_frech
......
...@@ -33,4 +33,4 @@ class SmoothMarginEstimator(AbstractMarginEstimator): ...@@ -33,4 +33,4 @@ class SmoothMarginEstimator(AbstractMarginEstimator):
def _fit(self): def _fit(self):
self._margin_function_fitted = self.margin_model.fitmargin_from_maxima_gev(maxima_gev=self.dataset.maxima_gev, self._margin_function_fitted = self.margin_model.fitmargin_from_maxima_gev(maxima_gev=self.dataset.maxima_gev,
coordinates=self.dataset.coordinates) coordinates=self.dataset.coordinates_values)
...@@ -19,8 +19,7 @@ class MaxStableEstimator(AbstractMaxStableEstimator): ...@@ -19,8 +19,7 @@ class MaxStableEstimator(AbstractMaxStableEstimator):
assert self.dataset.maxima_frech is not None assert self.dataset.maxima_frech is not None
self.max_stable_params_fitted = self.max_stable_model.fitmaxstab( self.max_stable_params_fitted = self.max_stable_model.fitmaxstab(
maxima_frech=self.dataset.maxima_frech, maxima_frech=self.dataset.maxima_frech,
df_coordinates=self.dataset.spatial_coordinates.df_coordinates) df_coordinates=self.dataset.coordinates.df_coordinates)
# coord=self.dataset.coordinates)
def _error(self, true_max_stable_params: dict): def _error(self, true_max_stable_params: dict):
absolute_errors = {param_name: np.abs(param_true_value - self.max_stable_params_fitted[param_name]) absolute_errors = {param_name: np.abs(param_true_value - self.max_stable_params_fitted[param_name])
......
...@@ -3,23 +3,23 @@ import numpy as np ...@@ -3,23 +3,23 @@ import numpy as np
from extreme_estimator.extreme_models.abstract_model import AbstractModel from extreme_estimator.extreme_models.abstract_model import AbstractModel
from extreme_estimator.extreme_models.margin_model.margin_function.abstract_margin_function import AbstractMarginFunction from extreme_estimator.extreme_models.margin_model.margin_function.abstract_margin_function import AbstractMarginFunction
from extreme_estimator.gev_params import GevParams from extreme_estimator.gev_params import GevParams
from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractSpatialCoordinates from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractCoordinates
class AbstractMarginModel(AbstractModel): class AbstractMarginModel(AbstractModel):
def __init__(self, spatial_coordinates: AbstractSpatialCoordinates, params_start_fit=None, params_sample=None): def __init__(self, coordinates: AbstractCoordinates, params_start_fit=None, params_sample=None):
super().__init__(params_start_fit, params_sample) super().__init__(params_start_fit, params_sample)
self.spatial_coordinates = spatial_coordinates self.coordinates = coordinates
self.margin_function_sample = None # type: AbstractMarginFunction self.margin_function_sample = None # type: AbstractMarginFunction
self.margin_function_start_fit = None # type: AbstractMarginFunction self.margin_function_start_fit = None # type: AbstractMarginFunction
self.load_margin_functions() self.load_margin_functions()
def load_margin_functions(self, margin_function_class: type = None): def load_margin_functions(self, margin_function_class: type = None):
assert margin_function_class is not None assert margin_function_class is not None
self.margin_function_sample = margin_function_class(spatial_coordinates=self.spatial_coordinates, self.margin_function_sample = margin_function_class(coordinates=self.coordinates,
default_params=GevParams.from_dict(self.params_sample)) default_params=GevParams.from_dict(self.params_sample))
self.margin_function_start_fit = margin_function_class(spatial_coordinates=self.spatial_coordinates, self.margin_function_start_fit = margin_function_class(coordinates=self.coordinates,
default_params=GevParams.from_dict( default_params=GevParams.from_dict(
self.params_start_fit)) self.params_start_fit))
......
...@@ -3,14 +3,14 @@ import matplotlib.pyplot as plt ...@@ -3,14 +3,14 @@ import matplotlib.pyplot as plt
import numpy as np import numpy as np
from extreme_estimator.gev_params import GevParams from extreme_estimator.gev_params import GevParams
from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractSpatialCoordinates from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractCoordinates
class AbstractMarginFunction(object): class AbstractMarginFunction(object):
""" Class of function mapping points from a space S (could be 1D, 2D,...) to R^3 (the 3 parameters of the GEV)""" """ Class of function mapping points from a space S (could be 1D, 2D,...) to R^3 (the 3 parameters of the GEV)"""
def __init__(self, spatial_coordinates: AbstractSpatialCoordinates, default_params: GevParams): def __init__(self, coordinates: AbstractCoordinates, default_params: GevParams):
self.spatial_coordinates = spatial_coordinates self.coordinates = coordinates
self.default_params = default_params.to_dict() self.default_params = default_params.to_dict()
def get_gev_params(self, coordinate: np.ndarray) -> GevParams: def get_gev_params(self, coordinate: np.ndarray) -> GevParams:
...@@ -20,8 +20,8 @@ class AbstractMarginFunction(object): ...@@ -20,8 +20,8 @@ class AbstractMarginFunction(object):
# Visualization function # Visualization function
def visualize_2D(self, gev_param_name=GevParams.GEV_LOC, ax=None, show=False): def visualize_2D(self, gev_param_name=GevParams.GEV_LOC, ax=None, show=False):
x = self.spatial_coordinates.x_coordinates x = self.coordinates.x_coordinates
y = self.spatial_coordinates.y_coordinates y = self.coordinates.y_coordinates
grid = self.get_grid_2D(x, y) grid = self.get_grid_2D(x, y)
gev_param_idx = GevParams.GEV_PARAM_NAMES.index(gev_param_name) gev_param_idx = GevParams.GEV_PARAM_NAMES.index(gev_param_name)
if ax is None: if ax is None:
......
...@@ -7,15 +7,15 @@ from extreme_estimator.extreme_models.margin_model.margin_function.param_functio ...@@ -7,15 +7,15 @@ from extreme_estimator.extreme_models.margin_model.margin_function.param_functio
from extreme_estimator.gev_params import GevParams from extreme_estimator.gev_params import GevParams
from extreme_estimator.extreme_models.margin_model.margin_function.abstract_margin_function import \ from extreme_estimator.extreme_models.margin_model.margin_function.abstract_margin_function import \
AbstractMarginFunction AbstractMarginFunction
from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractSpatialCoordinates from spatio_temporal_dataset.coordinates.abstract_coordinates import AbstractCoordinates
class IndependentMarginFunction(AbstractMarginFunction): class IndependentMarginFunction(AbstractMarginFunction):
"""Margin Function where each parameter of the GEV are modeled independently""" """Margin Function where each parameter of the GEV are modeled independently"""
def __init__(self, spatial_coordinates: AbstractSpatialCoordinates, default_params: GevParams): def __init__(self, coordinates: AbstractCoordinates, default_params: GevParams):
"""Attribute 'gev_param_name_to_param_function' maps each GEV parameter to its corresponding function""" """Attribute 'gev_param_name_to_param_function' maps each GEV parameter to its corresponding function"""
super().__init__(spatial_coordinates, default_params) super().__init__(coordinates, default_params)
self.gev_param_name_to_param_function = None # type: Dict[str, ParamFunction] self.gev_param_name_to_param_function = None # type: Dict[str, ParamFunction]
def get_gev_params(self, coordinate: np.ndarray) -> GevParams: def get_gev_params(self, coordinate: np.ndarray) -> GevParams:
...@@ -34,7 +34,7 @@ class LinearMarginFunction(IndependentMarginFunction): ...@@ -34,7 +34,7 @@ class LinearMarginFunction(IndependentMarginFunction):
On the extremal point along all the dimension, the GEV parameters will equal the default_param value On the extremal point along all the dimension, the GEV parameters will equal the default_param value
Then, it will augment linearly along a single linear axis""" Then, it will augment linearly along a single linear axis"""
def __init__(self, spatial_coordinates: AbstractSpatialCoordinates, def __init__(self, coordinates: AbstractCoordinates,
default_params: GevParams, default_params: GevParams,
gev_param_name_to_linear_axes: Dict[str, List[int]], gev_param_name_to_linear_axes: Dict[str, List[int]],
gev_param_name_and_axis_to_start_fit: Dict[Tuple[str, int], float] = None): gev_param_name_and_axis_to_start_fit: Dict[Tuple[str, int], float] = None):
...@@ -42,13 +42,13 @@ class LinearMarginFunction(IndependentMarginFunction): ...@@ -42,13 +42,13 @@ class LinearMarginFunction(IndependentMarginFunction):
-Attribute 'gev_param_name_to_linear_axis' maps each GEV parameter to its corresponding function -Attribute 'gev_param_name_to_linear_axis' maps each GEV parameter to its corresponding function
-Attribute 'gev_param_name_and_axis_to_start_fit' maps each tuple (GEV parameter, axis) to its start value for -Attribute 'gev_param_name_and_axis_to_start_fit' maps each tuple (GEV parameter, axis) to its start value for
fitting (by default equal to 1). Also start value for the intercept is equal to 0 by default.""" fitting (by default equal to 1). Also start value for the intercept is equal to 0 by default."""
super().__init__(spatial_coordinates, default_params) super().__init__(coordinates, default_params)
self.gev_param_name_and_axis_to_start_fit = gev_param_name_and_axis_to_start_fit self.gev_param_name_and_axis_to_start_fit = gev_param_name_and_axis_to_start_fit
self.gev_param_name_to_linear_axes = gev_param_name_to_linear_axes self.gev_param_name_to_linear_axes = gev_param_name_to_linear_axes
# Check the axes are well-defined with respect to the coordinates # Check the axes are well-defined with respect to the coordinates
for axes in self.gev_param_name_to_linear_axes.values(): for axes in self.gev_param_name_to_linear_axes.values():
assert all([axis < np.ndim(spatial_coordinates.coordinates) for axis in axes]) assert all([axis < np.ndim(coordinates.coordinates_values) for axis in axes])
# Build gev_parameter_to_param_function dictionary # Build gev_parameter_to_param_function dictionary
self.gev_param_name_to_param_function = {} # type: Dict[str, ParamFunction] self.gev_param_name_to_param_function = {} # type: Dict[str, ParamFunction]
...@@ -60,7 +60,7 @@ class LinearMarginFunction(IndependentMarginFunction): ...@@ -60,7 +60,7 @@ class LinearMarginFunction(IndependentMarginFunction):
# Otherwise, we fit a LinearParamFunction # Otherwise, we fit a LinearParamFunction
else: else:
param_function = LinearParamFunction(linear_axes=self.gev_param_name_to_linear_axes[gev_param_name], param_function = LinearParamFunction(linear_axes=self.gev_param_name_to_linear_axes[gev_param_name],
coordinates=self.spatial_coordinates.coordinates, coordinates=self.coordinates.coordinates_values,
start=self.default_params[gev_param_name]) start=self.default_params[gev_param_name])
# Some check on the Linear param function # Some check on the Linear param function
if gev_param_name == GevParams.GEV_SCALE: if gev_param_name == GevParams.GEV_SCALE:
...@@ -79,7 +79,7 @@ class LinearMarginFunction(IndependentMarginFunction): ...@@ -79,7 +79,7 @@ class LinearMarginFunction(IndependentMarginFunction):
:return: :return:
""" """
fit_marge_form_dict = {} fit_marge_form_dict = {}
axis_to_name = {i: name for i, name in enumerate(AbstractSpatialCoordinates.COORDINATE_NAMES)} axis_to_name = {i: name for i, name in enumerate(AbstractCoordinates.COORDINATE_NAMES)}
for gev_param_name in GevParams.GEV_PARAM_NAMES: for gev_param_name in GevParams.GEV_PARAM_NAMES:
axes = self.gev_param_name_to_linear_axes.get(gev_param_name, None) axes = self.gev_param_name_to_linear_axes.get(gev_param_name, None)
formula_str = '1' if axes is None else '+'.join([axis_to_name[axis] for axis in axes]) formula_str = '1' if axes is None else '+'.join([axis_to_name[axis] for axis in axes])
......
...@@ -13,10 +13,10 @@ class LinearMarginModel(AbstractMarginModel): ...@@ -13,10 +13,10 @@ class LinearMarginModel(AbstractMarginModel):
def load_margin_functions(self, gev_param_name_to_linear_axis=None): def load_margin_functions(self, gev_param_name_to_linear_axis=None):
self.default_params_sample = GevParams(1.0, 1.0, 1.0).to_dict() self.default_params_sample = GevParams(1.0, 1.0, 1.0).to_dict()
self.default_params_start_fit = GevParams(1.0, 1.0, 1.0).to_dict() self.default_params_start_fit = GevParams(1.0, 1.0, 1.0).to_dict()
self.margin_function_sample = LinearMarginFunction(spatial_coordinates=self.spatial_coordinates, self.margin_function_sample = LinearMarginFunction(coordinates=self.coordinates,
default_params=GevParams.from_dict(self.params_sample), default_params=GevParams.from_dict(self.params_sample),
gev_param_name_to_linear_axes=gev_param_name_to_linear_axis) gev_param_name_to_linear_axes=gev_param_name_to_linear_axis)
self.margin_function_start_fit = LinearMarginFunction(spatial_coordinates=self.spatial_coordinates, self.margin_function_start_fit = LinearMarginFunction(coordinates=self.coordinates,
default_params=GevParams.from_dict(self.params_start_fit), default_params=GevParams.from_dict(self.params_start_fit),
gev_param_name_to_linear_axes=gev_param_name_to_linear_axis) gev_param_name_to_linear_axes=gev_param_name_to_linear_axis)
......
...@@ -7,7 +7,7 @@ import matplotlib.pyplot as plt ...@@ -7,7 +7,7 @@ import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import Axes3D
class AbstractSpatialCoordinates(object): class AbstractCoordinates(object):
# Columns # Columns
COORDINATE_X = 'coord_x' COORDINATE_X = 'coord_x'
COORDINATE_Y = 'coord_y' COORDINATE_Y = 'coord_y'
...@@ -58,7 +58,7 @@ class AbstractSpatialCoordinates(object): ...@@ -58,7 +58,7 @@ class AbstractSpatialCoordinates(object):
@classmethod @classmethod
def from_nb_points(cls, nb_points: int, **kwargs): def from_nb_points(cls, nb_points: int, **kwargs):
# Call the default class method from csv # Call the default class method from csv
coordinates = cls.from_csv() # type: AbstractSpatialCoordinates coordinates = cls.from_csv() # type: AbstractCoordinates
# Sample randomly nb_points coordinates # Sample randomly nb_points coordinates
nb_coordinates = len(coordinates) nb_coordinates = len(coordinates)
if nb_points > nb_coordinates: if nb_points > nb_coordinates:
...@@ -72,12 +72,12 @@ class AbstractSpatialCoordinates(object): ...@@ -72,12 +72,12 @@ class AbstractSpatialCoordinates(object):
ind = self.s_split == split_str ind = self.s_split == split_str
return self.df_coordinates.loc[ind] return self.df_coordinates.loc[ind]
def coordinates_values(self, df_coordinates: pd.DataFrame) -> np.ndarray: def _coordinates_values(self, df_coordinates: pd.DataFrame) -> np.ndarray:
return df_coordinates.loc[:, self.coordinates_columns(df_coordinates)].values return df_coordinates.loc[:, self.coordinates_columns(df_coordinates)].values
@property @property
def coordinates(self) -> np.ndarray: def coordinates_values(self) -> np.ndarray:
return self.coordinates_values(df_coordinates=self.df_coordinates) return self._coordinates_values(df_coordinates=self.df_coordinates)
@property @property
def x_coordinates(self) -> np.ndarray: def x_coordinates(self) -> np.ndarray:
...@@ -89,11 +89,11 @@ class AbstractSpatialCoordinates(object): ...@@ -89,11 +89,11 @@ class AbstractSpatialCoordinates(object):
@property @property
def coordinates_train(self) -> np.ndarray: def coordinates_train(self) -> np.ndarray:
return self.coordinates_values(df_coordinates=self.df_coordinates_split(self.TRAIN_SPLIT_STR)) return self._coordinates_values(df_coordinates=self.df_coordinates_split(self.TRAIN_SPLIT_STR))
@property @property
def coordinates_test(self) -> np.ndarray: def coordinates_test(self) -> np.ndarray:
return self.coordinates_values(df_coordinates=self.df_coordinates_split(self.TEST_SPLIT_STR)) return self._coordinates_values(df_coordinates=self.df_coordinates_split(self.TEST_SPLIT_STR))
@property @property
def index(self): def index(self):
...@@ -103,20 +103,20 @@ class AbstractSpatialCoordinates(object): ...@@ -103,20 +103,20 @@ class AbstractSpatialCoordinates(object):
def visualization_1D(self): def visualization_1D(self):
assert len(self.coordinates_columns(self.df_coordinates)) >= 1 assert len(self.coordinates_columns(self.df_coordinates)) >= 1
x = self.coordinates[:] x = self.coordinates_values[:]
y = np.zeros(len(x)) y = np.zeros(len(x))
plt.scatter(x, y) plt.scatter(x, y)
plt.show() plt.show()
def visualization_2D(self): def visualization_2D(self):
assert len(self.coordinates_columns(self.df_coordinates)) >= 2 assert len(self.coordinates_columns(self.df_coordinates)) >= 2
x, y = self.coordinates[:, 0], self.coordinates[:, 1] x, y = self.coordinates_values[:, 0], self.coordinates_values[:, 1]
plt.scatter(x, y) plt.scatter(x, y)
plt.show() plt.show()
def visualization_3D(self): def visualization_3D(self):
assert len(self.coordinates_columns(self.df_coordinates)) == 3 assert len(self.coordinates_columns(self.df_coordinates)) == 3
x, y, z = self.coordinates[:, 0], self.coordinates[:, 1], self.coordinates[:, 2] x, y, z = self.coordinates_values[:, 0], self.coordinates_values[:, 1], self.coordinates_values[:, 2]
fig = plt.figure() fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # type: Axes3D ax = fig.add_subplot(111, projection='3d') # type: Axes3D
ax.scatter(x, y, z, marker='^') ax.scatter(x, y, z, marker='^')
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment