Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlos Lubbers committed Aug 3, 2023
1 parent c4f0aa1 commit 4908b93
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 51 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from geolib.geometry.one import Point
from geolib.models.dstability import DStabilityModel
from pathlib import Path
import pandas as pd

import matplotlib.pyplot as plt
import pandas as pd

from geolib.geometry.one import Point
from geolib.models.dstability import DStabilityModel
from geolib.models.dstability.analysis import (
DStabilityBishopAnalysisMethod,
DStabilityCircle,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
from geolib.models.dstability import DStabilityModel
from pathlib import Path
import pandas as pd

import matplotlib.pyplot as plt
import pandas as pd

from geolib.models.dstability import DStabilityModel
from geolib.models.dstability.internal import PersistableHeadLine, Waternet


def find_phreatic_line(waternet: Waternet) -> PersistableHeadLine:
'''
"""
Find the phreatic line in a given waternet.
:param waternet: Waternet to search in
:return: Phreatic line
'''
"""
for headline in waternet.HeadLines:
if headline.Id == waternet.PhreaticLineId:
return headline
raise ValueError("No phreatic line found")


def calculate_fragility_curve(input_file, z_start, z_end, z_step) -> pd.DataFrame:
'''
"""
Calculate the fragility curve for a given input file and a range of water levels.
This method will raise the first point of the water level by the given step size.
Expand All @@ -30,7 +31,7 @@ def calculate_fragility_curve(input_file, z_start, z_end, z_step) -> pd.DataFram
:param z_end: End of the water level range
:param z_step: Step size of the water level range
:return: Dataframe with the water level and the corresponding reliability index
'''
"""

# Prepare dataframe
df = pd.DataFrame(columns=["Waterlevel", "Beta", "Filename"])
Expand Down Expand Up @@ -62,7 +63,9 @@ def calculate_fragility_curve(input_file, z_start, z_end, z_step) -> pd.DataFram
headline_points[0].Z = new_z

# Serialize and execute
output_file = output_folder / (input_file_path.stem + "_" + str(new_z) + input_file_path.suffix)
output_file = output_folder / (
input_file_path.stem + "_" + str(new_z) + input_file_path.suffix
)
dm.serialize(Path(output_file))
dm.execute()

Expand Down Expand Up @@ -102,4 +105,4 @@ def calculate_fragility_curve(input_file, z_start, z_end, z_step) -> pd.DataFram
plt.title("Fragility curve")
plt.grid()
plt.savefig(output_folder / "fragility_curve.png")
plt.show()
plt.show()
61 changes: 37 additions & 24 deletions geolib/models/dstability/dstability_model.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,38 @@
import abc
import re
from enum import Enum
from pathlib import Path
from typing import BinaryIO, List, Optional, Set, Type, Union

from shapely.ops import polygonize
from shapely.geometry import LineString, Point, Polygon
from shapely.validation import make_valid

import matplotlib.pyplot as plt

from pydantic import DirectoryPath, FilePath
from shapely.geometry import LineString, Point, Polygon
from shapely.ops import polygonize
from shapely.validation import make_valid

from geolib.geometry import Point
from geolib.models import BaseModel
from geolib.soils import Soil

from ...utils import camel_to_snake, snake_to_camel
from .analysis import DStabilityAnalysisMethod
from .dstability_parserprovider import DStabilityParserProvider
from .internal import (
AnalysisType,
BishopSlipCircleResult,
CalculationSettings,
CalculationType,
DStabilityResult,
DStabilityStructure,
PersistableLayer,
PersistablePoint,
PersistableSoil,
PersistableStateCorrelation,
Scenario,
SoilCollection,
SoilCorrelation,
SoilLayerCollection,
SoilVisualisation,
SpencerSlipPlaneResult,
UpliftVanSlipCircleResult,
Waternet,
PersistableLayer,
SoilLayerCollection,
SoilVisualisation
)
from .loads import Consolidation, DStabilityLoad
from .reinforcements import DStabilityReinforcement
Expand Down Expand Up @@ -555,15 +550,21 @@ def add_layer_and_connect_points(

# Check if the new layer intersects with any of the existing layers
for layer in current_layers:
if layer != new_layer and self.dstability_points_to_shapely_polygon(layer.Points).exterior.intersects(
self.dstability_points_to_shapely_polygon(new_layer.Points).exterior):

if layer != new_layer and self.dstability_points_to_shapely_polygon(
layer.Points
).exterior.intersects(
self.dstability_points_to_shapely_polygon(new_layer.Points).exterior
):
# If it does, connect the layers
linestring1, linestring2 = self.connect_layers(layer, new_layer)

# Update the points of the layers
current_layers[current_layers.index(layer)].Points = self.to_dstability_points(linestring1)
current_layers[current_layers.index(new_layer)].Points = self.to_dstability_points(linestring2)
current_layers[
current_layers.index(layer)
].Points = self.to_dstability_points(linestring1)
current_layers[
current_layers.index(new_layer)
].Points = self.to_dstability_points(linestring2)

def to_shapely_linestring(self, points: List[PersistablePoint]) -> LineString:
converted_points = [(p.X, p.Z) for p in points]
Expand Down Expand Up @@ -1049,28 +1050,40 @@ def get_calculation_index(self, calculation_index: Optional[int]):
return calculation_index

@staticmethod
def get_soil_id_from_layer_id(layers: SoilLayerCollection, layer_id: str) -> Union[str, None]:
def get_soil_id_from_layer_id(
layers: SoilLayerCollection, layer_id: str
) -> Union[str, None]:
for layer in layers.SoilLayers:
if layer.LayerId == layer_id:
return layer.SoilId
return None

@staticmethod
def get_color_from_soil_id(soil_visualizations: SoilVisualisation, soil_id: str) -> str:
def get_color_from_soil_id(
soil_visualizations: SoilVisualisation, soil_id: str
) -> str:
for soil_visualization in soil_visualizations.SoilVisualizations:
if soil_visualization.SoilId == soil_id:
return soil_visualization.Color
return "#000000"

def _get_color_of_layer(self, layers_collection: SoilLayerCollection , layer: PersistableLayer) -> str:
def _get_color_of_layer(
self, layers_collection: SoilLayerCollection, layer: PersistableLayer
) -> str:
layer_id = layer.Id
# use the layer id to get the soil type id
soil_type_id = DStabilityModel.get_soil_id_from_layer_id(layers_collection, layer_id)
soil_type_id = DStabilityModel.get_soil_id_from_layer_id(
layers_collection, layer_id
)
# get the color of the soil type
color = DStabilityModel.get_color_from_soil_id(self.input.soilvisualizations, soil_type_id)
color = DStabilityModel.get_color_from_soil_id(
self.input.soilvisualizations, soil_type_id
)
return color.replace("#80", "#")

def plot(self, scenario_index: Optional[int] = None, stage_index: Optional[int] = None):
def plot(
self, scenario_index: Optional[int] = None, stage_index: Optional[int] = None
):
geometry = self._get_geometry(scenario_index, stage_index)
layers_collection = self._get_soil_layers(scenario_index, stage_index)
fig, ax = plt.subplots()
Expand All @@ -1083,5 +1096,5 @@ def plot(self, scenario_index: Optional[int] = None, stage_index: Optional[int]
color = self._get_color_of_layer(layers_collection, layer)
# create a polygon
ax.fill(x, y, color=color)
plt.axis('off')
return fig, ax
plt.axis("off")
return fig, ax
4 changes: 3 additions & 1 deletion geolib/models/dstability/internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,9 @@ class Loads(DStabilitySubStructure):

def add_load(
self, load: "DStabilityLoad", consolidations: List["Consolidation"]
) -> Union[PersistableUniformLoad, PersistableLineLoad, PersistableLayerLoad, PersistableTree]:
) -> Union[
PersistableUniformLoad, PersistableLineLoad, PersistableLayerLoad, PersistableTree
]:
internal_datastructure = load.to_internal_datastructure()

# Add consolidations if the load supports it
Expand Down
4 changes: 3 additions & 1 deletion geolib/models/dstability/loads.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ class TreeLoad(DStabilityLoad):
def to_internal_datastructure(self) -> PersistableTree:
return PersistableTree(
Label=self.label,
Location=PersistablePoint(X=self.tree_top_location.x, Z=self.tree_top_location.z),
Location=PersistablePoint(
X=self.tree_top_location.x, Z=self.tree_top_location.z
),
Force=self.wind_force,
RootZoneWidth=self.width_of_root_zone,
Spread=self.angle_of_distribution,
Expand Down
21 changes: 15 additions & 6 deletions tests/models/dstability/test_dstability_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,15 @@ def test_layer_with_incorrectly_ordered_points_are_fixed(self):
PersistablePoint(X=40, Z=-20),
PersistablePoint(X=30, Z=-20),
PersistablePoint(X=20, Z=-20),
PersistablePoint(X=-50,Z=-20),
PersistablePoint(X=-50,Z=-10),
PersistablePoint(X=20,Z=-10),
PersistablePoint(X=-50, Z=-20),
PersistablePoint(X=-50, Z=-10),
PersistablePoint(X=20, Z=-10),
]

assert dstability_model.datastructure.geometries[0].Layers[0].Points == expected_layer
assert (
dstability_model.datastructure.geometries[0].Layers[0].Points
== expected_layer
)

@pytest.mark.unittest
def test_layer_with_missing_points_on_edge_are_fixed(self):
Expand Down Expand Up @@ -150,7 +153,10 @@ def test_layer_with_missing_points_on_edge_are_fixed(self):
PersistablePoint(X=50, Z=-10),
]

assert dstability_model.datastructure.geometries[0].Layers[0].Points == expected_layer
assert (
dstability_model.datastructure.geometries[0].Layers[0].Points
== expected_layer
)

@pytest.mark.unittest
def test_multiple_layers_with_missing_points_on_edge_are_fixed(self):
Expand Down Expand Up @@ -193,4 +199,7 @@ def test_multiple_layers_with_missing_points_on_edge_are_fixed(self):
PersistablePoint(X=100, Z=10),
]

assert dstability_model.datastructure.geometries[0].Layers[0].Points == expected_layer
assert (
dstability_model.datastructure.geometries[0].Layers[0].Points
== expected_layer
)
12 changes: 4 additions & 8 deletions tests/models/dstability/test_dstability_model.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import os
import pathlib
import shutil
from io import BytesIO
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np

import pytest
from teamcity import is_running_under_teamcity

from geolib.geometry.one import Point
from geolib.models import BaseModel, BaseModelStructure
from geolib.models import BaseModel
from geolib.models.dstability import DStabilityModel
from geolib.models.dstability.analysis import (
DStabilityBishopAnalysisMethod,
Expand All @@ -31,15 +27,15 @@
PersistableStochasticParameter,
ShearStrengthModelTypePhreaticLevelInternal,
)
from geolib.models.dstability.loads import Consolidation, LineLoad, TreeLoad, UniformLoad
from geolib.models.dstability.loads import LineLoad, TreeLoad, UniformLoad
from geolib.models.dstability.reinforcements import ForbiddenLine, Geotextile, Nail
from geolib.models.dstability.states import (
DStabilityStateLinePoint,
DStabilityStatePoint,
DStabilityStress,
)
from geolib.soils import ShearStrengthModelTypePhreaticLevel, Soil, SuTablePoint
from tests.utils import TestUtils, only_teamcity
from tests.utils import TestUtils


class TestDStabilityModel:
Expand Down Expand Up @@ -528,7 +524,7 @@ def test_generate_model_from_scratch(self):
angle_of_distribution=30.0,
)
)

path = outputdir / "test_tree.stix"
dm.serialize(path)

Expand Down
1 change: 1 addition & 0 deletions tests/models/dstability/test_loads.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ def _get_line_load() -> LineLoad:
angle_of_distribution=45,
)


@pytest.fixture
def _get_tree_load() -> TreeLoad:
return TreeLoad(
Expand Down

0 comments on commit 4908b93

Please sign in to comment.