Está en la página 1de 62

Universidad de Chile

Facultad de Ciencias Físicas y Matemáticas


Departamento de Ingeniería Civil
CI7901-1 - Trabajo de Tesis Doctoral II

ANÁLISIS DINÁMICO EN PLAXIS2D


(INPUT-OUTPUT)
USANDO PYTHON
Caso de Estudio: Probabilidad de Observar Estados de Daños en Eventos Sísmicos en una
Presa de Relaves Construida por el Método de Aguas Abajo en Chile

Autor: Bastián Garrido

Fecha de realización: 12 de febrero de 2024


Santiago, Chile
i

Resumen
El presente documento contiene un set de rutinas implementadas en los lenguajes de progra-
mación Python y MATLAB que permiten generar modelos numéricos en el software PLAXIS 2D
para análisis dinámicos, obtener resultados específicos y posteriormente procesar los resultados.

Algunas limitaciones de PLAXIS 2D son:

El máximo número de muestras para análisis dinámicos es 10000

Es engorroso obtener registros de parámetros en el tiempo para diferentes puntos de monito-


reo.

El máximo numero de muestras es limitante al analizar registros sísmicos de eventos en la sub-


ducción de Chile, con duraciones sobre los 100 segundos, para una tasa de muestro de 200 muestras
por segundo requiere realizar análisis dinámicos secuenciales.

Manipular grandes volúmenes de información de forma manual puede conllevar errores, por lo
que automatización de la obtención de resultado en estos casos es necesaria.

El marco de trabajo de este documento a sido utilizado exitosamente en diferentes geoestruc-


turas como depositos de relaves y cuencas.

Versión 3

Se modifica la lectura de parámetros de los modelos constitutivos desde el código principal a


archivos de texto para evitar modificar el código principal.

Se incluyen modelos constitutivos desde User-defined, en particular se incluye el modelo PM4SAND


(agradecimientos a Nicolás Villanueva MSc(c) ).

Se incluye input sísmico en 2 direcciones respetando propagación de ondas de corte y compre-


sionales (agradecimientos a José Bustos PhD(c) ).

Versión 4 (en trabajo)

Se modifica la lectura de las coordenadas de los polígonos desde el código principal a archivos
de texto para evitar modificar el código principal.

Pendientes

Definir criterio para recortar registros.

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Índice de Contenidos ii

Índice de Contenidos

1. Generación del Modelo Numérico 1


1.1. Introducción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2. Geometría . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3. Materiales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4. Modelo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5. Malla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6. Fases Iniciales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7. Definición del Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8. Selección de puntos de monitoreo . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9. Registros Sísmicos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.9.1. Consideración importante . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.10. Fases Dinámicas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2. Output 19
2.1. Introducción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2. Obtención de Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3. Obtención de puntos de monitoreo . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3. Post-Procesamiento 24
3.1. MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Índice de Figuras
1. Acceder a rutinas de Python desde PLAXIS 2D . . . . . . . . . . . . . . . . . . . . . . 1
2. Creación servidor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
3. Geometría . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4. Creación del modelo - Asignación de materiales a los polígonos . . . . . . . . . . . . . 7
5. Malla de elementos finitos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
6. Archivos anidados Ejemplo 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7. Comparación desplazamientos en PLAXIS 2D (izquierda) y DEEPSOIL (derecha) para
el mismo registro de aceleraciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
8. Fases secuenciales y en paralelo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
9. Acceder a rutinas de Python desde PLAXIS 2D - Output . . . . . . . . . . . . . . . . 19
10. Step guardados en fase dinámica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
11. Archivos anidados en el ejemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
12. Resultado rutina animacion.m en un instante de tiempo . . . . . . . . . . . . . . . . 27

Índice de Códigos
1. Ejemplo creación objetos g_i.polygon() . . . . . . . . . . . . . . . . . . . . . . . . . 3
2. Ejemplo creación objetos g_i.neginterface() g_i.linedispl() . . . . . . . . . . . . 3
3. Ejemplo parametros del suelo soil_params . . . . . . . . . . . . . . . . . . . . . . . 5

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Índice de Códigos iii

4. Ejemplo vincular objetos g_i.polygon() y g_i.soilmat() . . . . . . . . . . . . . . . 7


5. Ejemplo creación de la malla y fases de carga iniciales . . . . . . . . . . . . . . . . . . 8
6. Ejemplo calculo de fases de carga iniciales - estáticas . . . . . . . . . . . . . . . . . . 10
7. Definición de input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
8. Ejemplo creación objetos g_o.addcurvepoint() . . . . . . . . . . . . . . . . . . . . 12
9. Ejemplo 1 formato registros_seleccionados.txt . . . . . . . . . . . . . . . . . . . . . . 13
10. Ejemplo 2 formato registros_seleccionados.txt . . . . . . . . . . . . . . . . . . . . . . 13
11. Ejemplo formato registro sísmico. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
12. Ejemplo creación objetos g_i.displmultiplier() . . . . . . . . . . . . . . . . . . . . . 14
13. Ejemplo creación de fases dinámicas . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
14. Ejemplo creación objetos g_o.getresults() . . . . . . . . . . . . . . . . . . . . . . . 21
15. Ejemplo creación objetos g_o.getresultspath() . . . . . . . . . . . . . . . . . . . . . 22
16. Ejemplo creación objetos g_o.getresults() . . . . . . . . . . . . . . . . . . . . . . . 23
17. curvedata.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
18. readframe.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
19. readEDP.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
20. animaciones.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 1

1. Generación del Modelo Numérico

1.1. Introducción
La presente sección contiene las rutinas escritas en Python para generar el modelo numérico en
el software PLAXIS 2D.

Para acceder a las rutinas es posible hacerlo a través del software PLAXIS 2D, en la barra de
herramientas Expert menu > Run Python script > Open... (Figura 1).

Figura 1: Acceder a rutinas de Python desde PLAXIS 2D

Para vincular PLAXIS 2D con Python se crea un servidor interno (Figura 2), aparece de forma
automática un mensaje y basta en dar click en Star server. En caso de que el puerto (port) no
este disponible es posible modificar el número por defecto (10000).

Figura 2: Creación servidor

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 2

1.2. Geometría
En PLAXIS 2D la geometría puede ser definida por medio de objetos g_i.borehole() (colum-
nas estatigraficas de suelo) o g_i.polygon() (poligonos).

En el caso de presas de relaves se opto por definir 3 polígonos representativos de las estructuras
principales: muro, fundación y relaves Figura 3.

Figura 3: Geometría

La definición del polígono se hace a través de sus vértices, estos se pueden asignar entregando
directamente un vector/tupla con todas las coordenadas. En el Código 1 se muestra un ejemplo
de una sección de deposito de relave utilizando como variables algunas medidas representativas:
Alturas del muro y de la fundación, pendientes aguas abajo y arriba, ancho del coronamiento y
revancha. El ancho de la fundación es función de la altura del muro y satisface que las distancias
entre el pie del talud aguas abajo y el borde de la fundación sin relaves, y el borde del coronamiento
aguas abajo y el borde de la fundación con relaves, es 10 veces la distancia horizontal entre el pie
del talud aguas abajo y el borde del coronamiento aguas abajo.

Usando las coordenadas de los polígonos representativos se define el lugar geométrico donde
se asignaran las condiciones de borde (g_i.neginterface()) y desde donde se propaga el registro
sísmico (g_i.linedispl()). En el Código 2 se muestra que el registro se propaga en ondas de
compresionales desde la base de la fundación (−L − 1), en la dirección Y y fijo en la dirección X y
escalado por 1. En ondas de corte desde la base de la fundación (−L), en la dirección X y libre en
la dirección Y y escalado por 1. Posteriormente cuando se creen las fases dinámicas se asignara un
valor especifico a los desplazamientos en Y (compresionales) y X (corte).

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 3

Código 1: Ejemplo creación objetos g_i.polygon()


1 def make_geometry(H, L, slope1, e_crest, rev, slope2):
2 # crea fundación, muro de partida y relaves respectivos
3
4 # Inputs:
5
6 # H : Altura del muro
7 # L : Altura de la fundación
8 # slope1 : Pendiente aguas abajo
9 # e_crest : Ancho del coronamiento
10 # rev : Revancha
11 # slope2 : Pendiente aguas arriba
12

13 # borde/origen del modelo


14 x_left = 0
15
16 # distancia del borde/origen al pie del talud - función de la distancia horizontal del talud W
,→ =H*slope1
17 x_toe = x_left + 10*H*slope1
18
19 x_crest = x_toe + H*slope1
20 x_right = x_crest + 10*H*slope1
21 w_crest = x_crest + e_crest
22 x_relave = w_crest + rev*slope2
23 x_muro = w_crest + H*slope2
24

25 # make polygons, start bottom left, counter clockwise


26

27 borehole_g = g_i.borehole(0)
28 borehole_g.Head = -L # NIVEL FREATICO
29 toppolygon1, topsoil1 = g_i.polygon([x_toe, 0],[x_muro, 0],[w_crest, H],[x_crest, H])
30 toppolygon2, topsoil2 = g_i.polygon([x_muro, 0],[x_right, 0],[ x_right, H-rev ],[ x_relave, H-rev
,→ ])
31 bottompolygon, bottomsoil = g_i.polygon([x_left, -L],[x_right, -L ],[ x_right, 0],[ x_left , 0])

Código 2: Ejemplo creación objetos g_i.neginterface() g_i.linedispl()

1
2 line_g = g_i.line ((0, -L), (0, 0)) [-1]
3 interfaces_g = g_i.neginterface(line_g)
4

5 line_g = g_i.line((x_right, H-rev), (x_right, -L)) [-1]


6 interfaces_g = g_i.neginterface(line_g)
7
8 line_g = g_i.line ((0, -L-1), (0, -L)) [-1]
9 interfaces_g = g_i.neginterface(line_g)
10

11 line_g = g_i.line((x_right, -L), (x_right, -L-1)) [-1]


12 interfaces_g = g_i.neginterface(line_g)
13
14 line_s = g_i.line((x_right, -L), (0, -L)) [-1]

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 4

15 linedisplacement_s = g_i.linedispl (line_s , "Displacement_x", "Prescribed", "Displacement_y", "


,→ free", "ux_start", 1.0)
16 interfaces_s = g_i.neginterface(line_s)
17

18
19 line_p = g_i.line((x_right, -L-1), (0, -L-1)) [-1]
20 linedisplacement_p = g_i.linedispl(line_p, "Displacement_x", "fixed", "Displacement_y", "
,→ Prescribed", "uy_start", 1.0)
21 interfaces_s = g_i.neginterface(line_p)
22

23 return toppolygon1, toppolygon2, bottompolygon, toppolygonsc, bottompolygon2

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 5

1.3. Materiales
La asignación de los materiales a los polígonos se hace por medio del objeto g_i.soilmat(),
La definición de parámetros se hace completando el valor de cada llaves/clave del diccionario
(soil_params), es importante respetar la numeración del modelo de suelo y el nombre de las variables
(llaves). En el Código 3 se tienen 4 modelos de suelo:

1: Lineal Elástico

2: Mohr-Coulomb

4: HS small

100: User-defined (PM4SAND)

Es posible apreciar en el Código 3 que a medida que el modelo se complejiza, requiere completar
una mayor cantidad de parámetros.

Código 3: Ejemplo parametros del suelo soil_params


1 def make_soilmaterial( soilinfo ) :
2

3 if soilinfo [ "soilmodel"] == 1:
4 soil_params = [("MaterialName", soilinfo["name"]),
5 ("SoilModel", soilinfo [ "soilmodel" ]) ,
6 ("DrainageType", soilinfo [ "drainagetype"]) ,
7 ("gammaUnsat", soilinfo["gammaUnsat"]),
8 ("gammaSat", soilinfo["gammaSat"]),
9 ("Gref", soilinfo [ "E"]/(2*(1+soilinfo [ "nu"]))) ,
10 ("nu", soilinfo [ "nu"]) ,
11 (" cref " , soilinfo [ "cu"]) ,
12 ("RayleighAlpha", soilinfo [ "RayleighAlpha"]),
13 ("RayleighBeta", soilinfo [ "RayleighBeta"])]
14
15 if soilinfo [ "soilmodel"] == 2:
16 soil_params = [("MaterialName", soilinfo["name"]),
17 ("SoilModel", soilinfo [ "soilmodel" ]) ,
18 ("DrainageType", soilinfo [ "drainagetype"]) ,
19 ("gammaUnsat", soilinfo["gammaUnsat"]),
20 ("gammaSat", soilinfo["gammaSat"]),
21 ("Gref", soilinfo [ "E"]/(2*(1+soilinfo [ "nu"]))) ,
22 ("nu", soilinfo [ "nu"]) ,
23 (" cref " , soilinfo [ "cu"]) ,
24 ("cinc" , soilinfo [ "cinc" ]) ,
25 (" verticalRef " , soilinfo [ " verticalRef " ]) ,
26 ("RayleighAlpha", soilinfo [ "RayleighAlpha"]),
27 ("RayleighBeta", soilinfo [ "RayleighBeta"])]
28
29 if soilinfo [ "soilmodel"] == 4:
30 soil_params = [("MaterialName", soilinfo["name"]),
31 ("SoilModel", soilinfo [ "soilmodel" ]) ,
32 ("DrainageType", soilinfo [ "drainagetype"]) ,
33 ("gammaUnsat", soilinfo["gammaUnsat"]),

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 6

34 ("gammaSat", soilinfo["gammaSat"]),
35 ("E50ref", soilinfo [ "E50ref"]) ,
36 ("EoedRef", soilinfo [ "EoedRef"]),
37 ("EurRef", soilinfo [ "EurRef"]),
38 ("powerm", soilinfo [ "powerm"]),
39 ("G0ref", soilinfo [ "G0ref"]) ,
40 ("gamma07", soilinfo["gamma07"]),
41 ("K0nc", soilinfo [ "K0nc"]),
42 ("DefaultValuesAdvanced", soilinfo [ "DefaultValuesAdvanced"]),
43 ("nu", soilinfo [ "nu"]) ,
44 (" cref " , soilinfo [ "cu"]) ,
45 ("phi", soilinfo [ "phi" ]) ,
46 ("RayleighAlpha", soilinfo [ "RayleighAlpha"]),
47 ("RayleighBeta", soilinfo [ "RayleighBeta"])]
48

49 if soilinfo [ "soilmodel"] == 100:


50 soil_params = [("MaterialName", soilinfo["name"]),
51 ("SoilModel", soilinfo [ "soilmodel" ]) ,
52 ("UserDLLName", soilinfo["UserDLLName"]),
53 ("UserModel", soilinfo [ "UserModel"]),
54 ("DrainageType", soilinfo [ "drainagetype"]) ,
55 ("gammaUnsat", soilinfo["gammaUnsat"]),
56 ("gammaSat", soilinfo["gammaSat"]),
57 ("User1", soilinfo [ "User1"]) ,
58 ("User2", soilinfo [ "User2"]) ,
59 ("User3", soilinfo [ "User3"]) ,
60 ("User4", soilinfo [ "User4"]) ,
61 ("User5", soilinfo [ "User5"]) ,
62 ("User6", soilinfo [ "User6"]) ,
63 ("User7", soilinfo [ "User7"]) ,
64 ("User8", soilinfo [ "User8"]) ,
65 ("User9", soilinfo [ "User9"]) ,
66 ("User10", soilinfo [ "User10"]),
67 ("User11", soilinfo [ "User11"]),
68 ("User12", soilinfo [ "User12"]),
69 ("User13", soilinfo [ "User13"]),
70 (" cref " , soilinfo [ " cref " ]) ,
71 ("Gref", soilinfo [ "Gref"]) ,
72 ("DefaultValuesAdvanced", soilinfo [ "DefaultValuesAdvanced"])]
73

74 soil_material = g_i.soilmat(*soil_params)
75

76 return soil_material

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 7

1.4. Modelo
Definidos los polígonos representativos y los materiales es posible vincularlos para definir el
modelo numérico. En el Código 4 se muestra como vincularlos y en la Figura 4 es posible ver
visualmente en el software PLAXIS 2D esta asignación.

Código 4: Ejemplo vincular objetos g_i.polygon() y g_i.soilmat()


1 def make_model(H, L, slope1, e_crest, rev, slope2, toplayer1 , toplayer2 , bottomlayer):
2 # make geometry
3 top_pg1, top_pg2, bottom_pg = make_geometry(H, L, slope1, e_crest, rev, slope2)
4
5 # assign materials
6 bottommaterial = make_soilmaterial(bottomlayer)
7 bottom_pg.Soil.Material = bottommaterial
8
9 topmaterial1 = make_soilmaterial(toplayer1)
10 top_pg1.Soil.Material = topmaterial1
11

12 topmaterial2 = make_soilmaterial(toplayer2)
13 top_pg2.Soil.Material = topmaterial2
14
15 return topmaterial1, topmaterial2

Figura 4: Creación del modelo - Asignación de materiales a los polígonos

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 8

1.5. Malla
Las opciones disponibles para generar un malla/grilla de elementos finitos son definir un razón
máxima de área de acuerdo con el área total del polígono (g_i.mesh()) o especificar el área
máxima de la malla (g_i.meshd()). Adicionalmente es posible pre-definir un refinamiento de un
polígono (g_i.refine()). En el Código se muestra como ejemplo el refinamiento de los polígonos 1
y 4 9 veces y el tamaño máximo de los elementos de la malla base es 100, de esta forma se obtienen
elementos de aproximadamente 3 metros de lado en el coronamiento (Figura 5), lugar con menor
velocidad de onda de corte y por tanto menor resolución de acuerdo con la expresión:

f = Vs /λ (1)
Considerando elementos finitos triangulares de 15 nodos media longitud de onda (λ/2) queda
bien caracterizada entre los nodos extremos del mismo lado (la linea tiene 5 nodos, otros criterios
usan 8 a 10 nodos por la longitud de onda completa). De esta forma considerando los elementos de
3 metros se tiene:

f = Vs /6
Para valores de Vs = 100m/s se tiene una resolución en frecuencia de 16Hz.

El motivo de refinar es por que para valores muy pequeños el proceso de creación de malla con-
sume mucho tiempo computacional y en ocasiones no logra generar una malla tan fina.

Este proceso no se ha logrado resolver sin un numero arbitrario de refinamientos en los polígo-
nos.

Código 5: Ejemplo creación de la malla y fases de carga iniciales


1 def meshcalculate(s_i, g_i):
2 # mesh
3 g_i.gotomesh()
4

5 for i in range(1,9) :
6 g_i. refine (g_i.Polygon_4)
7 g_i. refine (g_i.Polygon_1)
8

9 g_i.meshd(100)
10

11 output_port = g_i.viewmesh()
12 s , g = new_server(’localhost’, port=output_port, password=s_i.connection._password)

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 9

Figura 5: Malla de elementos finitos

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 10

1.6. Fases Iniciales


Definida la malla es posible crear las fases iniciales (g_i.InitialPhase()) y (g_i.phase()),
y realizar los análisis preliminares donde se carga la gravedad y se consolida el modelo. Para la
secuencia de fases se debe definir la fase precedente, por ejemplo, la fase después de la fase inicial
se define phase1_s = g_i.phase(g_i.InitialPhase). Si deseo realizar fases secuenciales debo
ir actualizando la fase precedente a la ultima fase realizada, en el caso de fase en paralelo, todas
las fases empiezan desde la misma fase precedente (esto se vera posteriormente en la definición de
fases dinámicas).

Código 6: Ejemplo calculo de fases de carga iniciales - estáticas


1 # set up calculation
2 g_i.gotostages()
3
4 # initial phase
5
6 g_i. InitialPhase .DeformCalcType = "Gravity loading"
7 g_i. activate (g_i.Soil_4_1, g_i.InitialPhase)
8 g_i. activate (g_i.Soil_3_1, g_i.InitialPhase)
9 g_i. activate (g_i.Soil_2_1, g_i.InitialPhase)
10 g_i. activate (g_i.Soil_1_1, g_i.InitialPhase)
11
12 ## plastic phase
13 phase1_s = g_i.phase(g_i.InitialPhase)
14 phase1_s.DeformCalcType = "Plastic"
15 phase1_s. Identification = "Plastic"
16 phase1_s.TimeInterval = 30
17 phase1_s.Deform.UseDefaultIterationParams = False
18 phase1_s.Deform.UseUpdateMesh = True
19 phase1_s.Deform.ToleratedError = 0.01
20

21 # calculate
22 g_i. calculate ()
23

24 return s , g

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 11

1.7. Definición del Input


Para el caso de estudio se definen los parámetros geométricos representativos de una presa de
relaves y los parámetros de los materiales se definen en diccionarios contenidos en archivos de texto
como se presenta en el Código 7:

Código 7: Definición de input


1 slope1 = 2.2 # pendiente aguas abajo
2 slope2 = 2.2 # pendiente aguas arriba
3 H = 50 # Altura presa
4 L= 200 # Altura fundación
5 rev = 5 # revancha
6 e_crest= 15 # ancho coronamiento
7

8 # Materiales
9 with open(’HSS.txt’) as f :
10 data1 = f.read()
11 toplayer1 = json.loads(data1) # Muro HSS
12 with open(’PM4SAND.txt’) as f:
13 data2 = f.read()
14 toplayerPM4 = json.loads(data2) # Muro PM4SAND
15 with open(’MC.txt’) as f :
16 data3 = f.read()
17 toplayer2 = json.loads(data3) # Relaves Mohr-Coulomb
18 with open(’Elastico . txt ’ ) as f :
19 data4 = f.read()
20 bottomlayer = json.loads(data4) # Fundacion Lineal Elastico
21

22 make_model(H, L, slope1, e_crest, rev, slope2, toplayer1 , toplayer2 , bottomlayer)


23 s_o, g_o = meshcalculate(s_i, g_i)

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 12

1.8. Selección de puntos de monitoreo


Previo a la fase dinámica es importante tener en cuenta que el software guarda información de
salida (output) de dos formas, la opción por defecto es guardar todas las variables definidas en el
menú Deformations y Stresses para el instante de tiempo final. Si se desea tener esa información
para otros instantes de tiempo es necesario modificar la opción MaxStepsStored. Otra forma de
obtener informacion de salida del modelo es definir puntos de monitoreo que guardan la información
de un nodo o punto de integración de un elemento finito en todos los instantes de tiempo. En el
ejemplo las coordenadas de los nodos y puntos de integración se pre-definen en un archivo de
texto (coord.txt) y se crea para cada linea del archivo un punto de control de nodos y punto de
integración.

Código 8: Ejemplo creación objetos g_o.addcurvepoint()


1 g_i.gotostages()
2 g_i.selectmeshpoints()
3
4 # Los puntos de monitoreo quedan guardados de forma ordenada de acuerdo a como se definen en el
,→ objeto Nodes
5

6 coord = np.loadtxt(’coord.txt’ . replace( ’\n’, ’ ’ ))


7 for i in range(len(coord)):
8 g_o.addcurvepoint("node", *coord[i])
9 g_o.addcurvepoint("stresspoint", *coord[i ])

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 13

1.9. Registros Sísmicos


Se implemento un modulo versátil en cuanto a la selección de los registros a utilizar.

La rutina primero lee un archivo de texto que contiene los nombres de los registros seleccionados
(registros_seleccionados.txt). En el ejemplo 1 se leen los registros 1, 9 y 23. En el ejemplo 2 se leen
los registros Maule 2010 Mw8.8 en santiago centro e Illapel 2015 Mw8.4 en la estación V05.

Código 9: Ejemplo 1 formato registros_seleccionados.txt


1 registro_1. txt
2 registro_9. txt
3 registro_23.txt

Código 10: Ejemplo 2 formato registros_seleccionados.txt


1 20100227_8.8Mw_36.10S_73.08W_30KM_st07_SANTIAGO CENTRO_L.txt
2 20150916_8.4Mw_31.55S_71.86W_11KM_st1_VA05_HNE.txt

Los archivos de texto con los registros deben estar en la misma carpeta que el archivo antes
descrito.

Figura 6: Archivos anidados Ejemplo 1

Los registros deben estar en un formato por columnas, el primer elemento del encabezado con-
tiene el numero de muestras del registro, el segundo termino del encabezado muestra la tasa de
muestreo del registro. La primera columna después del encabezado corresponde al tiempo y la se-
gunda columna después del encabezado corresponde a desplazamiento, velocidad o aceleración en
el tiempo. El ejemplo corresponde a un registros de aceleración de 37616 muestras con una tasa
de muestreo de 0.005 segundos. Se eligió este formato porque es el mismo utilizado en el software
DEEPSOIL.

Código 11: Ejemplo formato registro sísmico.


1 37616 0.005
2 0.005 1.19124667708577E-10
3 0.01 1.19382061743194E-10
4 0.015 1.19639421017524E-10
5 ...

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 14

Dada la limitación de 10000 muestras se corta el registro en ventanas de 10000 muestras y cada
ventana se guarda en un objeto g_i.displmultiplier(), este objeto se asigna posteriormente al lu-
gar geométrico desde donde se propaga la onda sísmica. Para cada registro se guarda el numero de
ventanas para posteriormente en la creación de fases, crear análisis dinámicos en serie o secuenciales.

Posteriormente es posible crear fases en paralelo para cada set de análisis secuenciales de forma
de optimizar el usos de procesadores (se ha visto que los menores tiempos de calculo se obtienen al
asignar un procesador a un registro). En el ejemplo se leen los registros de aceleración y se escalan
por 9.8*3 (los registros se ingresan en unidades de m/s2 ).

Código 12: Ejemplo creación objetos g_i.displmultiplier()


1 import numpy as np
2 import math
3

4 def read_records(parent_dir=None, DataType=None, Scale=None):


5

6 # Regisros Sismicos
7 filename = []
8 with open(parent_dir) as f:
9 filename = f. readlines ()
10
11 cont_fases = 0
12
13 for fn in filename:
14 data = np.loadtxt(fn.replace( ’\n’, ’ ’ ))
15 cont_fases = cont_fases + int(data [0][0]) # largo del registro
16
17 max_step_plaxis = 10000 # Numero maximo de muestras de un registro temporal por fase
18
19 cont_fases = math.ceil(cont_fases/max_step_plaxis) # numero de fases
20 #print(cont_phases)
21

22 aux = 0
23 disp = [0]*cont_fases
24 lr = [0]*len(filename)
25 dt2 = [0]*len(filename)
26 MOD = [0]*len(filename)
27

28 for fn in filename:
29 data = np.loadtxt(fn.replace( ’\n’, ’ ’ ))
30 ifn = filename.index(fn)
31 lr [ ifn ] = int(data [0][0]) # largo del registro
32 dt2[ ifn ] = data [0][1] # dt del registro
33 mod = math.ceil(lr[ifn ]/max_step_plaxis) # numero de ventanas
34 MOD[ifn] = mod
35 for k2 in range(0, mod):
36 #for k2 in range(0, 1): PARA CORRER SOLO LA PRIMERA VENTANA
37 a = (*data[1],*data [2])
38

39 # borrar
40 #print(a)

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 15

41 #print(*data[0])
42 #print(*data[1])
43 #print(*data[2])
44 #
45
46 for j in range(3, min(max_step_plaxis+1,lr[ifn]-k2*max_step_plaxis)):
47 a = (*a,*data[j ])
48

49 disp[aux] = g_i. displmultiplier ()


50 disp[aux]. setproperties ("Signal" , "Table", "DataType", DataType)
51 disp[aux].Table.set(*a)
52 disp[aux].ScalingValue = Scale
53 disp[aux].transform ()
54 disp[aux].DriftCorrection . set(False)
55

56 aux = aux+1
57 data = data[9999:]
58
59 return disp, filename, lr , dt2, MOD
60
61 disp, filename, lr , dt2, MOD = read_records(parent_dir=’DB_REGISTROS.txt’, DataType="
,→ Displacements", Scale=9.8*3)

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 16

1.9.1. Consideración importante


Para evitar corrimientos globales en el análisis de los desplazamientos dentro de la presa, se
corrigen los registros sísmicos por linea base. Este procesamiento se ha realizado utilizando tanto
el software DEEPSOIL como MATLAB, sin embargo al verificar los desplazamientos del registro
corregido en PLAXIS 2D se observan de todas formas corrimientos (Figura 7):

Figura 7: Comparación desplazamientos en PLAXIS 2D (izquierda) y


DEEPSOIL (derecha) para el mismo registro de aceleraciones

Considerando lo anterior se recomienda ingresar el input sísmico en desplazamientos para evitar


los corrimientos generados por el software PLAXIS 2D, sin embargo al revisar posteriormente la
aceleración en superficie libre en ocasiones aparecen algunas inestabilidades numéricas puntuales
donde se dispara el valor de la aceleración.

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 17

1.10. Fases Dinámicas


En el ejemplo se ven 3 fases secuenciales dinámicas ([2-5],[6-9] y [10-13]) calculadas en paralelo
a partir de la fase predecesora Plastic [Phase_1]

Figura 8: Fases secuenciales y en paralelo

Código 13: Ejemplo creación de fases dinámicas


1 Phase_aux=g_i.Phases[-1]
2 aux3=0
3
4 for k in range(0, len(filename)) :
5 phase2_s = g_i.phase(Phase_aux)
6 phase2_s.DeformCalcType = phase2_s.DeformCalcType.dynamic
7 phase2_s.Deform.TimeIntervalSeconds = dt2[k]*min(max_step_plaxis,lr[k])
8 phase2_s.Deform.ResetDisplacementsToZero = False
9 phase2_s.Deform.UseDefaultIterationParams = False
10 phase2_s.Deform.MaxSteps = min(max_step_plaxis,lr[k])
11 phase2_s.Deform.TimeStepDetermType = "Manual"
12 phase2_s.Deform.SubSteps = 1
13 phase2_s.Deform.ToleratedError = 0.001
14 phase2_s.MaxStepsStored = math.ceil(min(max_step_plaxis,lr[k])/10) # Guarda el total de
,→ muestras, se puede dividir por algun entero para obtener un submuestreo
15 #phase2_s.MaxStepsStored = 1 # Usar 1 cuando se procesan los puntos de monitoreo, para
,→ animaciones usar un submuestreo
16 phase2_s.MaxCores = 16
17

18 g_i.LineDisplacements.activate(phase2_s)
19 g_i.DynLineDisplacement_1_1.activate(phase2_s)
20 g_i.DynLineDisplacement_1_1.Multiplierx.set(phase2_s, disp[aux3])
21

22
23 g_i.Dynamics.BoundaryYMin.set(phase2_s,"Compliant base")
24 g_i.Dynamics.BoundaryXMin.set(phase2_s,"Free-field")
25

26 for k2 in range(1, 1): #Analisis dinamico solamente de la primera ventana


27 #for k2 in range(1, MOD[k]):
28 aux3=aux3+1
29 phase2_s = g_i.Phases[-1]

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Generación del Modelo Numérico 18

30 phase3_s = g_i.phase(phase2_s)
31 phase3_s.DeformCalcType = phase3_s.DeformCalcType.dynamic
32 phase3_s.Deform.TimeIntervalSeconds = dt2[k]*min(max_step_plaxis,lr[k]-max_step_plaxis
,→ *k2)
33 phase3_s.Deform.ResetDisplacementsToZero = False
34 phase3_s.Deform.UseDefaultIterationParams = False
35 phase3_s.Deform.MaxSteps = min(max_step_plaxis,lr[k]-max_step_plaxis*k2)
36 phase3_s.Deform.TimeStepDetermType = "Manual"
37 phase3_s.Deform.SubSteps = 1
38 phase3_s.Deform.ToleratedError = 0.001
39 #phase3_s.MaxStepsStored = min(max_step_plaxis,lr[k]-max_step_plaxis*k2)
40 phase3_s.MaxStepsStored = 1
41 phase3_s.MaxCores = 16
42
43

44 g_i.LineDisplacements.activate(phase3_s)
45 g_i.DynLineDisplacement_1_1.activate(phase3_s)
46 g_i.DynLineDisplacement_1_1.Multiplierx.set(phase3_s, disp[aux3])
47

48 g_i.Dynamics.BoundaryYMin.set(phase3_s,"Compliant base")
49 g_i.Dynamics.BoundaryXMin.set(phase3_s,"Free-field")
50
51 #g_i.Dynamics.BoundaryYMin.set(phase3_s,"None")
52 #g_i.Dynamics.BoundaryXMin.set(phase2_s,"Viscous")
53 #g_i.Dynamics.BoundaryYMin.set(phase2_s,"Compliant base")
54
55 aux3=aux3+1
56
57 g_i. calculate ()

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Output 19

2. Output

2.1. Introducción
La presente sección contiene las rutinas escritas en Python para generar el modelo numérico en
el software PLAXIS 2D.

Para acceder a las rutinas es posible hacerlo a través del software PLAXIS 2D, en la barra de
herramientas Expert menu > Run Python script > Open...

Figura 9: Acceder a rutinas de Python desde PLAXIS 2D - Output

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Output 20

2.2. Obtención de Frames


Se denomina Frame a la información (tipo de resultado, ya sea Deformation o Stresses) de
todos los nodos (o puntos de integración) en una fase especifica y paso especifico, múltiples Frames
pueden generar un vídeo. Dependiendo de la configuración es posible obtener desde 1 frame hasta
la serie completa de tiempo, la limitación de lo ultimo es el volumen de datos generados. Cuando
se pide una muestra de la serie completa, no es posible obtener información de los pasos que no
se guardaron y es necesario saltarlos manualmente, en el ejemplo se recorre un arreglo desde 9 a
4000 con un paso de 10, esto se debe a que se guardo una sub-muestra del total con paso de 10
muestras (para conocer previamente cual es la etiqueta de cada step es posible utilizar el comando
print(g_o.Phases[-1].Steps.echo()), en el ejemplo el primer Step de la fase dinámica es el Step
llamado de forma automatica por PLAXIS "Step_41"guardado numero 9 en el total de Step, ver
Figura 10). Los resultados se guardan en un formato que posteriormente sea fácil de manipular,
en el ejemplo la ruta de un paso especifico es: Frame/Fase/Tipo de punto/Tipo de resultado/Paso
Especifico.

Figura 10: Step guardados en fase dinámica

2.3. Obtención de puntos de monitoreo


Para superar el problema del volumen de información es posible definir puntos de monitoreo y de
esta forma obtener las series de tiempo para un tipo de resultado de forma mas rápida. En el caso de
fases secuenciales se obtiene la serie de tiempo completa para cada fase y luego es necesario unirlas
en una unica serie. Para obtener la información completa de la fase en un tipo de punto se utiliza el
objeto g_o.getresultspath(). En el ejemplo la ruta de un punto de monitoreo es: EDP/Fase/Tipo
de resultado/Punto de Monitoreo, la rutina guarda la información de todos los puntos de monitoreo.

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Output 21

Código 14: Ejemplo creación objetos g_o.getresults()


1 def getframe(filename=None, phaseorder=None, p_type=None, resulttypes=None):
2 value_o = g_o.getresults(phaseorder, resulttypes , p_type, True)
3 with open(filename, "w") as file :
4 file . writelines ([ "{}\n".format(*nr)
5 for nr in zip(value_o)])
6

7 def saveframe(parent_dir=None, phaseorder=None, p_type=None, EDP=None):


8 # PRIMER PASO: CARPETA DONDE SE GUARDARAN LOS RESULTADOS
9 #parent_dir = ’C:\\Users\\Bastian Garrido\\Desktop\\Frame\\’
10

11 # SEGUNDO PASO: FASE


12 #phaseorder = g_o.Phases[-1]
13 phase_name = phaseorder.Name.value
14

15 # TERCER PASO: TIPO DE PUNTO StressPoints o Nodes


16 #p_type= "stresspoint"
17 #p_type= "node"
18

19 # CUARTO PASO: TIPO DE RESULTADO (VER CELDA INFERIOR CON TODOS LOS
,→ TIPOS DE RESULTADO)
20 #EDP = ’PlasticPointHistoryMohrCoulomb’
21 resulttypes = getattr(g_o.ResultTypes.Soil, EDP)
22

23 import os
24 newpath = os.path.join(parent_dir, ’{0}\ {1}\ {2}’.format(phase_name,p_type,EDP))
25 if not os.path. exists (newpath):
26 os.makedirs(newpath)
27
28 #print(g_o.Phases[-1].Steps.echo())
29 # 9/-4881. Step named "Step_41"
30 for i in range(9, 4000, 10):
31 #for i in range(3999, 4000, 10):
32 step = phaseorder.Steps[i]
33 #st = int(phaseorder.Steps [-1]. Name.value.replace("Step_", ""))
34 st = int(step.Name.value.replace("Step_", ""))
35 getframe(filename= os.path.join(newpath, ’{0}.txt’ .format(st)) ,
36 phaseorder = step, p_type = p_type, resulttypes = resulttypes)

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Output 22

Código 15: Ejemplo creación objetos g_o.getresultspath()


1 def gettable_time_vs_EDP(filename=None, phaseorder=None, node=None, resulttypes=None):
2 value_o = g_o.getcurveresultspath(node, phaseorder, phaseorder, resulttypes)
3 with open(filename, "w") as file :
4 file . writelines ([ "{}\n".format(*nr)
5 for nr in zip(value_o)])
6

7 def savetable_time_vs_EDP(parent_dir=None, phaseorder=None, p_type=None, EDP=None):


8 # PRIMER PASO: CARPETA DONDE SE GUARDARAN LOS RESULTADOS
9 #parent_dir = ’C:\\Users\\Bastian Garrido\\Desktop\\EDP\\’
10

11 # SEGUNDO PASO: FASE


12 #phaseorder = g_o.Phases[-1]
13 phase_name = phaseorder.Name.value
14

15 # TERCER PASO: TIPO DE PUNTO StressPoints o Nodes


16 #p_type= ’StressPoints’
17 #p_type= ’Nodes’
18 pointtype = getattr(g_o.CurvePoints, p_type)
19
20 if p_type == ’StressPoints’:
21 #pointtype = g_o.CurvePoints.StressPoints
22 pre = "CS_"
23 else :
24 #pointtype = g_o.CurvePoints.Nodes
25 pre = "CN_"
26
27 # CUARTO PASO: TIPO DE RESULTADO (VER CELDA INFERIOR CON TODOS LOS
,→ TIPOS DE RESULTADO)
28 #EDP = ’Gamxy’
29 resulttypes = getattr(g_o.ResultTypes.Soil, EDP)
30

31 import os
32 newpath = os.path.join(parent_dir, ’{0}\ {1}’.format(phase_name,EDP))
33 if not os.path. exists (newpath):
34 os.makedirs(newpath)
35
36 for node in pointtype:
37 print(node.Name.value)
38 st = node.Name.value.replace(pre, "")
39 gettable_time_vs_EDP(filename= os.path.join(newpath, ’{0}.txt’.format(st)),
40 phaseorder = phaseorder, node = node, resulttypes = resulttypes)

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Output 23

Para ejecutar los funciones antes descritas basta llamarlas de la siguiente forma:

Código 16: Ejemplo creación objetos g_o.getresults()


1 savetable_time_vs_EDP(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\EDP\\’,
,→ phaseorder=g_o.Phases[-i] , p_type=’StressPoints’, EDP=’Gamxy’)
2 savetable_time_vs_EDP(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\EDP\\’,
,→ phaseorder=g_o.Phases[-i] , p_type=’StressPoints’, EDP=’Sigxy’)
3
4 saveframe(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\Frame\\’, phaseorder=g_o.
,→ Phases[-i], p_type="node", EDP=’Uy’)
5 saveframe(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\Frame\\’, phaseorder=g_o.
,→ Phases[-i], p_type="node", EDP=’Ux’)

En el ejemplo, primero se muestra como obtener en los puntos de monitoreo (del tipo puntos
de integración) la deformación γxy y la tensión τxy . Además se muestra como obtener los despla-
zamientos Uy y Ux para todos los nodos del modelo en todos los pasos guardados y definidos en
saveframe.

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Post-Procesamiento 24

3. Post-Procesamiento

3.1. MATLAB
Se presentan las rutinas que permiten leer la información de las carpetas generadas en la sección
output.

La función curvedata.m lee toda la información en una carpeta. En el caso de Frame desde
Python se crea una carpeta con el nombre del tipo de resultado y dentro un archivo de texto para
cada step con su respectivo nombre, dentro del archivo se encuentra la informacion de cada tipo de
punto del modelo completo. En el caso de EDP desde Python se crea una carpeta con el nombre
del tipo de resultado y dentro un archivo de texto para cada punto de monitoreo con su respectivo
nombre, dentro del archivo se encuentra la información para todo el intervalo de tiempo.

Frame guarda una foto del modelo completo para un determinado instante de tiempo y tipo
de resultado. EDP guarda una serie de tiempo para un tipo de resultado en los puntos de monitoreo.

Para manipular los archivos generados tanto para Frame como EDP se crearon las rutinas read-
frame.m y readEDP.m que usan la rutina curvedata.m pero mantienen el formato usado en
Python para crear las carpetas.

Código 17: curvedata.m


1 function [Np,step]=curvedata(MainFolder)
2 % step es la etiqueta de Np
3 % en frame corresponde a paso de tiempo
4 % en tablas corresponde al punto de monitoreo
5
6 listing = dir(MainFolder);
7 listing = natsortfiles ( listing ) ;
8 Nstep = length(listing ) -2;
9 step = zeros(Nstep,1);
10 M=importdata([MainFolder ’/’ listing(2).name]);
11 [l_p,l_edp]=size(M);
12

13 Np=zeros(l_p,l_edp,Nstep);
14

15 for i = 1:Nstep
16 step( i ) = str2double( listing ( i+1).name(1:end-4));
17 Np (:,:, i )=importdata([MainFolder ’/’ listing( i+1).name]);
18 end
19
20 end

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Post-Procesamiento 25

Código 18: readframe.m


1 function [EDPg,step]=readframe(MainFolder_Frame,Phase,p_type,EDP)
2 % (EDP) global en un dominio definido
3
4 % Misma secuencia como se guardan en Python-Plaxis
5 % PRIMER PASO: CARPETA DONDE ESTAN LOS RESULTADOS
6 %MainFolder_Frame = ’./Frame’;
7 % SEGUNDO PASO: FASE
8 %Phase = ’Phase_2’;
9 % TERCER PASO: TIPO DE PUNTO StressPoints o Nodes
10 %p_type = ’stresspoint’; % or ’node’
11 % CUARTO PASO: TIPO DE RESULTADO
12 %EDP = ’Gamxy’;
13
14 path = [MainFolder_Frame ’/’ Phase ’/’ p_type];
15
16 % EDP global
17 [EDPg,step]=curvedata([path ’/’ EDP]);
18

19 end

Código 19: readEDP.m


1 function [EDPt,t,p_m]=readEDP(MainFolder_EDP,Phase,EDP,dt)
2 % Series de tiempo para cada punto de monitoreo (EDP)
3 % Misma secuencia como se guardan en Python-Plaxis
4

5 % PRIMER PASO: CARPETA DONDE ESTAN LOS RESULTADOS


6 %MainFolder_EDP = ’./EDP’;
7
8 % SEGUNDO PASO: FASE
9 %Phase = ’Phase_2’;
10
11 % TERCER PASO: TIPO DE PUNTO StressPoints o Nodes
12 % No influye en la lectura
13

14 % CUARTO PASO: TIPO DE RESULTADO


15 %EDP = ’Gamxy’;
16
17 path = [MainFolder_EDP ’/’ Phase];
18
19 % EDP en puntos de monitoreos
20 [EDP_t,p_m]=curvedata([path ’/’ EDP]);
21 l_p=length(EDP_t);
22 EDPt=reshape(EDP_t,l_p,[]);
23 t=0:dt:(l_p-1)*dt;
24
25 end

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Post-Procesamiento 26

En la rutina animaciones.m se utilizan las rutinas antes mencionadas para crear una animación
de las deformaciones totales producidas en una presa de relaves. Los archivos utilizados en el ejemplo
se encuentran anidados de la siguiente forma (Figura 11):

Figura 11: Archivos anidados en el ejemplo

Código 20: animaciones.m


1 path_Frame = ’./Animacion4/Gabor/Frame’;
2
3 % Coordenadas punto de integracion
4 [x1,~]=readframe(path_Frame,’Phase_2’,’stresspoint’,’X’);
5 [y1,~]=readframe(path_Frame,’Phase_2’,’stresspoint’,’Y’);
6
7 % Coordenadas nodos
8 [x2,~]=readframe(path_Frame,’Phase_2’,’node’,’X’);
9 [y2,~]=readframe(path_Frame,’Phase_2’,’node’,’Y’);
10
11 [Ux,step]=readframe(path_Frame,’Phase_2’,’node’,’Ux’);
12 Ux_ = reshape(Ux,[],length(step));
13 [Uy,step]=readframe(path_Frame,’Phase_2’,’node’,’Uy’);
14 Uy_ = reshape(Uy,[],length(step));
15 [Utot,step]=readframe(path_Frame,’Phase_2’,’node’,’Utot’);
16 Utot_ = reshape(Utot,[],length(step));
17

18 % Dominio parabolico (estetico)


19 % stresspoint
20 dominio1 = (0.8*(x1-1217).^2+5*y1.^2)<150^2;
21 % nodos
22 dominio2 = (0.8*(x2-1217).^2+5*y2.^2)<150^2;
23
24 %%
25 tic
26 axis tight manual
27 v = VideoWriter(’utot3_F1_V3_3.avi’);

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Post-Procesamiento 27

28 open(v);
29 set(gcf , ’ position ’ ,get (0, ’ScreenSize’)) ;
30
31 for k= 1:length(step)
32
33 %figure(’ visible ’,’ off ’)
34 scatter (x2(dominio2)+Ux_(dominio2,k)*1,...
35 y2(dominio2)+Ux_(dominio2,k)*1,...
36 30,Utot_(dominio2,k),’ filled ’ )
37 % Configuración del plot
38 axis equal
39 colormap(jet)
40 hcb=colorbar;
41 hcb.Label.String= ’U_{total} [m]’;
42 caxis ([0 0.2])
43 xlabel( ’Seccion Transversal [m]’, ’FontSize’ , 14)
44 ylabel( ’ Elevación [m]’, ’FontSize’ , 14)
45 title ([ ’ t= ’ num2str((step(k)-31)*0.001) ’ [ s ] ’ ], ’FontSize’ , 14)
46 set(gca, ’FontSize’ ,14, ’Color’ ,[0.8 0.8 0.8])
47 frame = getframe(gcf);
48 set(gca, ’nextplot’ , ’ replacechildren ’ ) ;
49 writeVideo(v,frame)
50

51 end
52 close (v);
53 toc

En la Figura 12 se puede observar el resultado de la rutina animacion.m para un instante de


tiempo.

Figura 12: Resultado rutina animacion.m en un instante de tiempo

CI7901-1 Trabajo de Tesis Doctoral II


ANÁLISIS DINÁMICO EN PLAXIS2D
(INPUT-OUTPUT)
USANDO PYTHON
Universidad de Chile
Facultad de Ciencias Físicas y Matemáticas
Departamento de Ingeniería Civil
CI7901-1 - Trabajo de Tesis Doctoral II

DYNAMIC ANALYSIS IN PLAXIS 2D


(INPUT-OUTPUT)
USING PYTHON
Case Study: Probability of Observing Damage States in Seismic Events in a Tailings Dam
Built by the Downstrem Method in Chile

Author: Bastián Garrido

Date of realization: 12 de febrero de 2024


Santiago, Chile
i

Resumen
This document contains a set of routines implemented in Python and MATLAB programming
languages that allow for the generate numerical models in PLAXIS 2D software for dynamic analy-
sis, obtaining specific results, and processing the results.

Some limitations of PLAXIS 2D are:

The maximum number of samples for dynamic analysis is 10000.

Obtaining parameter records over time for different monitoring points is cumbersome.

The maximum number of samples is limiting when analyzing seismic records of events in the
subduction zone of Chile, with duration over 100 seconds. For a sampling rate of 200 samples per
second, sequential dynamic analysis is required.

Manipulating large volumes of information manually can lead to errors, so automation of result
retrieval in these cases is necessary.

The framework of this document has been successfully used in different geo-structures such as
tailings deposits and basins.

Version 3

The reading of parameters of the constitutive models from the main code to text files is modifies
to avoid modifying the main code.

Constitutive models from User-defined are inclued, in particular the PM4SAND model (thanks
to Nicolás Villanueva MSc(c)).

Seismic inputs are included in two directions respecting shear and compresional wave propaga-
tion (thanks to José Bustos PhD(c)).

Version 4 (in progress)

The reading of polygon coordinates from the main code to text file is modified to avoid modifyng
the main code.

Pending tasks

Define criteria for trimming records.

Save the file upon completing a Phase calculation.

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Índice de Contenidos ii

Índice de Contenidos

1. Numerical Model Generation 1


1.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2. Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3. Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4. Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5. Mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6. Initial Phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7. Input definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8. Monitoring point selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9. Seismic Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.9.1. Important consideration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.10. Dynamic Phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2. Output 19
2.1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2. Obtaining Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3. Obtaining monitoring points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3. Post-Processing 24
3.1. MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Índice de Figuras
1. Accessing Python routines from PLAXIS 2D . . . . . . . . . . . . . . . . . . . . . . . 1
2. Server creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
3. Geometría . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4. Creating the model - Assigning materials to polygons . . . . . . . . . . . . . . . . . . . 7
5. Finite element mesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
6. Nested files Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7. Comparison of displacements in PLAXIS 2D (left) and DEEPSOIL (right) for the
same acceleration record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
8. Sequential and parallel phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
9. Accessing Python routines from PLAXIS 2D - Output . . . . . . . . . . . . . . . . . . 19
10. Step saved in dynamic phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
11. Nested files in the example (Code 20 ) . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
12. Results animation.m routine at a time instant . . . . . . . . . . . . . . . . . . . . . . 27

Índice de Códigos
1. Example objet g_i.polygon() creation . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2. Example objets g_i.neginterface() g_i.linedispl() creation . . . . . . . . . . . . . 3
3. Example soil parameters soil_params . . . . . . . . . . . . . . . . . . . . . . . . . . 5

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Índice de Códigos iii

4. Example linking objects g_i.polygon() and g_i.soilmat() . . . . . . . . . . . . . . 7


5. Example of mesh creation and initial loading phases . . . . . . . . . . . . . . . . . . . 8
6. Example of calculation of initial - static load stages . . . . . . . . . . . . . . . . . . . 10
7. Input definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
8. Example object g_o.addcurvepoint() creation . . . . . . . . . . . . . . . . . . . . . 12
9. Example 1 format registros_seleccionados.txt . . . . . . . . . . . . . . . . . . . . . . . 13
10. Example 2 format registros_seleccionados.txt . . . . . . . . . . . . . . . . . . . . . . . 13
11. Example of seismic record format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
12. Example object g_i.displmultiplier() creation . . . . . . . . . . . . . . . . . . . . . 14
13. Example dynamic phases creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
14. Example object g_o.getresults() creation . . . . . . . . . . . . . . . . . . . . . . . . 21
15. Example object g_o.getresultspath() creation . . . . . . . . . . . . . . . . . . . . . 22
16. Example g_o.getresults() and g_o.getresultspath() . . . . . . . . . . . . . . . . . 23
17. curvedata.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
18. readframe.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
19. readEDP.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
20. animation.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 1

1. Numerical Model Generation

1.1. Introduction
This section contains the routines written in Python to generate the numerical model in PLA-
XIS 2D software.

To access the routines it is possible to do it through the PLAXIS 2D software, in the toolbar
Expert menu > Run Python script > Open... (Figura 1).

Figura 1: Accessing Python routines from PLAXIS 2D

To link PLAXIS 2D with Python an internal server is created (Figura 2), a message appears
automatically and just click on Star server. In case the port is not available it is possible to change
the default number (10000).

Figura 2: Server creation

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 2

1.2. Geometry
In PLAXIS 2D the geometry can be defined by mens of objects g_i.borehole() (statigraphic
ground columns) or g_i.polygon() (polygons).

In the case of tailing storage facilities, we chose to define 3 polygons representative of the main
structures: dam, foundation and tailings Figure 3.

Figura 3: Geometría

The definition of the polygon is done through its vertices, these can be assigned by directly
providing a vector/tuple with all the coordinates. Code 1 shows an example of a tailing storage
facility cross section using as variables some representative measures: dam and foundation heights,
downstream and upstream slopes, crest width, and freeboard. The width of the foundation is a
function of the dam height and satisfies that the distances between the downstream slope toe and
the edge of the foundation without tailings, and the downstream crest edge and the edge of the
foundation with tailings, is 10 times the horizontal distance between the downstream slope toe and
the downstream crest edge.

Using the coordinates of the representative polygons, we define the geometrical place where
the boundary condition will be assigned (g_i.neginterface()) and from here the seismic record
propagates (g_i.linedispl()). In Code 2, it is shown that the record propagates in compressional
waves from the base of the foundation (−L − 1), in the Y direction, and fixed in the X direction
and scaled by 1. In shear waves from the base of the foundation (−L), in the X direction, and free
in the Y direction and scaled by 1. Later, when the dynamic phases are created, a specific value
will be assigned to the displacements in Y (compressional) and X (shear).

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 3

Código 1: Example objet g_i.polygon() creation


1 def make_geometry(H, L, slope1, e_crest, rev, slope2):
2 # crea fundación, muro de partida y relaves respectivos
3
4 # Inputs:
5
6 # H : Dam height
7 # L : Foundation height
8 # slope1 : Downstream slope
9 # e_crest : Crest width
10 # rev : Freeboard
11 # slope2 : Upstream slope
12

13 # Model edge/origin
14 x_left = 0
15
16 # distance from the edge/origin to the slope toe - function of the horizontal slope distance W
,→ =H*slope1
17

18 x_toe = x_left + 10*H*slope1


19

20 x_crest = x_toe + H*slope1


21 x_right = x_crest + 10*H*slope1
22 w_crest = x_crest + e_crest
23 x_relave = w_crest + rev*slope2
24 x_muro = w_crest + H*slope2
25
26 # make polygons, start bottom left, counter clockwise
27
28 borehole_g = g_i.borehole(0)
29 borehole_g.Head = -L # NIVEL FREATICO
30 toppolygon1, topsoil1 = g_i.polygon([x_toe, 0],[x_muro, 0],[w_crest, H],[x_crest, H])
31 toppolygon2, topsoil2 = g_i.polygon([x_muro, 0],[x_right, 0],[ x_right, H-rev ],[ x_relave, H-rev
,→ ])
32 bottompolygon, bottomsoil = g_i.polygon([x_left, -L],[x_right, -L ],[ x_right, 0],[ x_left , 0])

Código 2: Example objets g_i.neginterface() g_i.linedispl() creation


1
2 line_g = g_i.line ((0, -L), (0, 0)) [-1]
3 interfaces_g = g_i.neginterface(line_g)
4

5 line_g = g_i.line((x_right, H-rev), (x_right, -L)) [-1]


6 interfaces_g = g_i.neginterface(line_g)
7
8 line_g = g_i.line ((0, -L-1), (0, -L)) [-1]
9 interfaces_g = g_i.neginterface(line_g)
10

11 line_g = g_i.line((x_right, -L), (x_right, -L-1)) [-1]


12 interfaces_g = g_i.neginterface(line_g)
13
14 line_s = g_i.line((x_right, -L), (0, -L)) [-1]

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 4

15 linedisplacement_s = g_i.linedispl (line_s , "Displacement_x", "Prescribed", "Displacement_y", "


,→ free", "ux_start", 1.0)
16 interfaces_s = g_i.neginterface(line_s)
17

18
19 line_p = g_i.line((x_right, -L-1), (0, -L-1)) [-1]
20 linedisplacement_p = g_i.linedispl(line_p, "Displacement_x", "fixed", "Displacement_y", "
,→ Prescribed", "uy_start", 1.0)
21 interfaces_s = g_i.neginterface(line_p)
22

23 return toppolygon1, toppolygon2, bottompolygon, toppolygonsc, bottompolygon2

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 5

1.3. Materials
The assignment of materials to the polygons is done using the g_i.soilmat() object. Parameter
definitions are accomplished by assigning a value to each key in the (soil_params) dictionary. In
Code 3 there are 4 soil models:

1: Linear Elastic

2: Mohr-Coulomb

4: HS small

100: User-defined (PM4SAND)

It is possible to appreciate in Code 3 that as the model becomes more complex, it requires the
completion of a greater number of parameters.

Código 3: Example soil parameters soil_params


1 def make_soilmaterial( soilinfo ) :
2
3 if soilinfo [ "soilmodel"] == 1:
4 soil_params = [("MaterialName", soilinfo["name"]),
5 ("SoilModel", soilinfo [ "soilmodel" ]) ,
6 ("DrainageType", soilinfo [ "drainagetype"]) ,
7 ("gammaUnsat", soilinfo["gammaUnsat"]),
8 ("gammaSat", soilinfo["gammaSat"]),
9 ("Gref", soilinfo [ "E"]/(2*(1+soilinfo [ "nu"]))) ,
10 ("nu", soilinfo [ "nu"]) ,
11 (" cref " , soilinfo [ "cu"]) ,
12 ("RayleighAlpha", soilinfo [ "RayleighAlpha"]),
13 ("RayleighBeta", soilinfo [ "RayleighBeta"])]
14

15 if soilinfo [ "soilmodel"] == 2:
16 soil_params = [("MaterialName", soilinfo["name"]),
17 ("SoilModel", soilinfo [ "soilmodel" ]) ,
18 ("DrainageType", soilinfo [ "drainagetype"]) ,
19 ("gammaUnsat", soilinfo["gammaUnsat"]),
20 ("gammaSat", soilinfo["gammaSat"]),
21 ("Gref", soilinfo [ "E"]/(2*(1+soilinfo [ "nu"]))) ,
22 ("nu", soilinfo [ "nu"]) ,
23 (" cref " , soilinfo [ "cu"]) ,
24 ("cinc" , soilinfo [ "cinc" ]) ,
25 (" verticalRef " , soilinfo [ " verticalRef " ]) ,
26 ("RayleighAlpha", soilinfo [ "RayleighAlpha"]),
27 ("RayleighBeta", soilinfo [ "RayleighBeta"])]
28

29 if soilinfo [ "soilmodel"] == 4:
30 soil_params = [("MaterialName", soilinfo["name"]),
31 ("SoilModel", soilinfo [ "soilmodel" ]) ,
32 ("DrainageType", soilinfo [ "drainagetype"]) ,
33 ("gammaUnsat", soilinfo["gammaUnsat"]),
34 ("gammaSat", soilinfo["gammaSat"]),

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 6

35 ("E50ref", soilinfo [ "E50ref"]) ,


36 ("EoedRef", soilinfo [ "EoedRef"]),
37 ("EurRef", soilinfo [ "EurRef"]),
38 ("powerm", soilinfo [ "powerm"]),
39 ("G0ref", soilinfo [ "G0ref"]) ,
40 ("gamma07", soilinfo["gamma07"]),
41 ("K0nc", soilinfo [ "K0nc"]),
42 ("DefaultValuesAdvanced", soilinfo [ "DefaultValuesAdvanced"]),
43 ("nu", soilinfo [ "nu"]) ,
44 (" cref " , soilinfo [ "cu"]) ,
45 ("phi", soilinfo [ "phi" ]) ,
46 ("RayleighAlpha", soilinfo [ "RayleighAlpha"]),
47 ("RayleighBeta", soilinfo [ "RayleighBeta"])]
48
49 if soilinfo [ "soilmodel"] == 100:
50 soil_params = [("MaterialName", soilinfo["name"]),
51 ("SoilModel", soilinfo [ "soilmodel" ]) ,
52 ("UserDLLName", soilinfo["UserDLLName"]),
53 ("UserModel", soilinfo [ "UserModel"]),
54 ("DrainageType", soilinfo [ "drainagetype"]) ,
55 ("gammaUnsat", soilinfo["gammaUnsat"]),
56 ("gammaSat", soilinfo["gammaSat"]),
57 ("User1", soilinfo [ "User1"]) ,
58 ("User2", soilinfo [ "User2"]) ,
59 ("User3", soilinfo [ "User3"]) ,
60 ("User4", soilinfo [ "User4"]) ,
61 ("User5", soilinfo [ "User5"]) ,
62 ("User6", soilinfo [ "User6"]) ,
63 ("User7", soilinfo [ "User7"]) ,
64 ("User8", soilinfo [ "User8"]) ,
65 ("User9", soilinfo [ "User9"]) ,
66 ("User10", soilinfo [ "User10"]),
67 ("User11", soilinfo [ "User11"]),
68 ("User12", soilinfo [ "User12"]),
69 ("User13", soilinfo [ "User13"]),
70 (" cref " , soilinfo [ " cref " ]) ,
71 ("Gref", soilinfo [ "Gref"]) ,
72 ("DefaultValuesAdvanced", soilinfo [ "DefaultValuesAdvanced"])]
73

74 soil_material = g_i.soilmat(*soil_params)
75
76 return soil_material

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 7

1.4. Model
Once the representative polygons and materials have been defined, it is possible to link them to
define the numerical model. In Code 4 it is shown how to link them and in Figure 4 it is possible
to see visually in the PLAXIS 2D software this assignment.

Código 4: Example linking objects g_i.polygon() and g_i.soilmat()


1 def make_model(H, L, slope1, e_crest, rev, slope2, toplayer1 , toplayer2 , bottomlayer):
2 # make geometry
3 top_pg1, top_pg2, bottom_pg = make_geometry(H, L, slope1, e_crest, rev, slope2)
4
5 # assign materials
6 bottommaterial = make_soilmaterial(bottomlayer)
7 bottom_pg.Soil.Material = bottommaterial
8
9 topmaterial1 = make_soilmaterial(toplayer1)
10 top_pg1.Soil.Material = topmaterial1
11

12 topmaterial2 = make_soilmaterial(toplayer2)
13 top_pg2.Soil.Material = topmaterial2
14
15 return topmaterial1, topmaterial2

Figura 4: Creating the model - Assigning materials to polygons

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 8

1.5. Mesh
The options available to generate a finite element mesh/grid are to define a maximum area
ratio according to the total area of the polygon (g_i.mesh()) or to specify the maximum area
of the mesh (g_i.meshd()). Additionally it is possible to pre-define a refinement of a polygon
(g_i.refine()). The Code shows as an example the refinement of polygons 1 and 4, 9 times, and
the maximum size of the base mesh elements is 100, thus obtaining elements of approximately 3
meters side at the crest (Figure 5), a place with lower shear wave velocity and therefore lower
resolution according to the expression:

f = Vs /λ (1)
Considering triangular finite elements of 15 nodes half wavelength (λ/2) is well characterized
between nodes of the same side (the line has 5 nodes, other criteria use 8 to 10 nodes for the full
wavelength). Thus, considering the elements of 3 meters we have:

f = Vs /6
For values of Vs = 100m/s there is a frequency resolution of 16Hz.

The reason for refining is that for very small values the mesh creation process takes a lot of
computational time and sometimes fails to generate such a fine mesh.

This process has not been solved without an arbitrary number of refinements in the polygons

Código 5: Example of mesh creation and initial loading phases


1 def meshcalculate(s_i, g_i):
2 # mesh
3 g_i.gotomesh()
4

5 for i in range(1,9) :
6 g_i. refine (g_i.Polygon_4)
7 g_i. refine (g_i.Polygon_1)
8

9 g_i.meshd(100)
10

11 output_port = g_i.viewmesh()
12 s , g = new_server(’localhost’, port=output_port, password=s_i.connection._password)

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 9

Figura 5: Finite element mesh

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 10

1.6. Initial Phases


Once the mesh is defined, it is possible to create the initial phases (g_i.InitialPhase()) and
(g_i.phase()), and to perform the preliminary analysis where gravity is loaded and the model is
consolidated. For the sequence of phases, the preceding phase must be defined; for example, the
phase after the initial phase is defined as phase1_s = g_i.phase(g_i.InitialPhase). If I want
to perform sequential phases, I must update the preceding phase to the last phase performed. In
the case of parallel phases, all phases start from the same preceding phase (this will be seen later
in the definition of dynamic phases).

Código 6: Example of calculation of initial - static load stages


1 # set up calculation
2 g_i.gotostages()
3
4 # initial phase
5
6 g_i. InitialPhase .DeformCalcType = "Gravity loading"
7 g_i. activate (g_i.Soil_4_1, g_i.InitialPhase)
8 g_i. activate (g_i.Soil_3_1, g_i.InitialPhase)
9 g_i. activate (g_i.Soil_2_1, g_i.InitialPhase)
10 g_i. activate (g_i.Soil_1_1, g_i.InitialPhase)
11
12 ## plastic phase
13 phase1_s = g_i.phase(g_i.InitialPhase)
14 phase1_s.DeformCalcType = "Plastic"
15 phase1_s. Identification = "Plastic"
16 phase1_s.TimeInterval = 30
17 phase1_s.Deform.UseDefaultIterationParams = False
18 phase1_s.Deform.UseUpdateMesh = True
19 phase1_s.Deform.ToleratedError = 0.01
20

21 # calculate
22 g_i. calculate ()
23

24 return s , g

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 11

1.7. Input definition


For the case study, geometric parameters representative of a tailings dam are defined and ma-
terial parameters are defined in dictionaries contained in text files as presented in Code 7:

Código 7: Input definition


1 slope1 = 2.2 # Downstream slope
2 slope2 = 2.2 # Upstream slope
3 H = 50 # Dam height
4 L= 200 # Foundation height
5 rev = 5 # Freeboard
6 e_crest= 15 # Crest width
7

8 # Materials
9 with open(’HSS.txt’) as f :
10 data1 = f.read()
11 toplayer1 = json.loads(data1) # HSS Dam
12 with open(’PM4SAND.txt’) as f:
13 data2 = f.read()
14 toplayerPM4 = json.loads(data2) # PM4SAND Dam
15 with open(’MC.txt’) as f :
16 data3 = f.read()
17 toplayer2 = json.loads(data3) # Mohr-Coulomb Tailings
18 with open(’Elastico . txt ’ ) as f :
19 data4 = f.read()
20 bottomlayer = json.loads(data4) # Linear Elastic Foundation
21

22 make_model(H, L, slope1, e_crest, rev, slope2, toplayer1 , toplayer2 , bottomlayer)


23 s_o, g_o = meshcalculate(s_i, g_i)

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 12

1.8. Monitoring point selection


Prior to the dynamic phase, it is important to take into account that the software saves output
information in two ways. The default option is to save all the variables defined in the Deformations
and Stresses menu for the final time instant. If you want to have that information for the other
time instants, it is necessary to modify the MaxStepsStored option. Another way to obtain output
information from the model is to define monitoring points that store the information of a node or
integration points of a finite element in all time instants. In the example, the coordinates of the
nodes and integration points are predefined in a text file (coord.txt), and a node and integration
point monitoring point is created for each line of the file

Código 8: Example object g_o.addcurvepoint() creation


1 g_i.gotostages()
2 g_i.selectmeshpoints()
3
4 # Monitoring points are stored in an ordely fashion as defined in the object Nodes.
5
6 coord = np.loadtxt(’coord.txt’ . replace( ’\n’, ’ ’ ))
7 for i in range(len(coord)):
8 g_o.addcurvepoint("node", *coord[i])
9 g_o.addcurvepoint("stresspoint", *coord[i ])

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 13

1.9. Seismic Records


A versatile module was implemented in terms of the selection of the records to be used.

The routine first reads a text file containing the names of the selected records (registros_seleccionados.txt).
In example 1 (Code 9), records 1, 9 and 23 are read. In example 2 (Code 10), records Maule 2010
Mw 8.8 in Santiago Centro and Illapel 2015 Mw 8.4 in station V05 are read.

Código 9: Example 1 format registros_seleccionados.txt


1 registro_1. txt
2 registro_9. txt
3 registro_23.txt

Código 10: Example 2 format registros_seleccionados.txt


1 20100227_8.8Mw_36.10S_73.08W_30KM_st07_SANTIAGO CENTRO_L.txt
2 20150916_8.4Mw_31.55S_71.86W_11KM_st1_VA05_HNE.txt

The text files with the records must be in the same folder as the file described above, Figure 6.

Figura 6: Nested files Example 1

The records should be in a columnar format, the first element of the header has the number
of samples in the record, the second term of the header shows the sampling rate of the record.
The first column afeter the header corresponds to time and the seconrd column after the header
corresponds to displacement, velocity or acceleration over time. The example (Code 11)corresponds
to an acceleration record of 37616 samples with a sampling rate of 0.005 seconds, This format was
chosen because it is the same format used in the DEEPSOIL software

Código 11: Example of seismic record format


1 37616 0.005
2 0.005 1.19124667708577E-10
3 0.01 1.19382061743194E-10
4 0.015 1.19639421017524E-10
5 ...

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 14

Given the limitation of 10000 samples, the record is cut into windows of 10000 samples, and each
window is saved in an object g_i.displmultiplier(). This object is then assigned to the geometric
location from where the seismic wave propagates. For each record, the number of windows is saved
for later in the creation of phases, to create dynamic analysis in series.

Subsequently, it is possible to create parallel phases for each set of sequential analyses in order to
optimize the use of processors (it has been shown that the shortest computation times are obtained
by assigning a processor to a record). In the example (Code 12) the acceleration records are read
and scaled by 9.8*3 (the records are entered in units of m/s2 ).

Código 12: Example object g_i.displmultiplier() creation


1 import numpy as np
2 import math
3

4 def read_records(parent_dir=None, DataType=None, Scale=None):


5

6 # Seismic Records
7 filename = []
8 with open(parent_dir) as f:
9 filename = f. readlines ()
10
11 cont_fases = 0
12
13 for fn in filename:
14 data = np.loadtxt(fn.replace( ’\n’, ’ ’ ))
15 cont_fases = cont_fases + int(data [0][0]) # Record length
16
17 max_step_plaxis = 10000 # Maximum number of samples of a time record per phase
18
19 cont_fases = math.ceil(cont_fases/max_step_plaxis) # number of phases
20
21 aux = 0
22 disp = [0]*cont_fases
23 lr = [0]*len(filename)
24 dt2 = [0]*len(filename)
25 MOD = [0]*len(filename)
26
27 for fn in filename:
28 data = np.loadtxt(fn.replace( ’\n’, ’ ’ ))
29 ifn = filename.index(fn)
30 lr [ ifn ] = int(data [0][0]) # record length
31 dt2[ ifn ] = data [0][1] # time sample
32 mod = math.ceil(lr[ifn ]/max_step_plaxis) # number of windows
33 MOD[ifn] = mod
34 for k2 in range(0, mod):
35 a = (*data[1],*data [2])
36

37 for j in range(3, min(max_step_plaxis+1,lr[ifn]-k2*max_step_plaxis)):


38 a = (*a,*data[j ])
39
40 disp[aux] = g_i. displmultiplier ()

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 15

41 disp[aux]. setproperties ("Signal" , "Table", "DataType", DataType)


42 disp[aux].Table.set(*a)
43 disp[aux].ScalingValue = Scale
44 disp[aux].transform ()
45 disp[aux].DriftCorrection . set(False)
46

47 aux = aux+1
48 data = data[10000:]
49
50 return disp, filename, lr , dt2, MOD
51

52 disp, filename, lr , dt2, MOD = read_records(parent_dir=’DB_REGISTROS.txt’, DataType="


,→ Displacements", Scale=9.8*3)

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 16

1.9.1. Important consideration


To avoid global shifts in the analysis of the displacements inside the the dam, the seismic
records are corrected by baseline. This processing has been performed using both DEEPSOIL and
MATLAB software, however, when verifying the displacements of the corrected record in PLAXIS
2D, shifts are still observed (Figure 7):

Figura 7: Comparison of displacements in PLAXIS 2D (left) and DEEP-


SOIL (right) for the same acceleration record

Considering the above, it is recommended to enter the seismic input in displacements to avoid
the shifts generated by the PLAXIS 2D software. However, when subsequently reviewing the ac-
celeration at the free surface, sometimes some punctual numerical instabilities appear where the
acceleration value is triggered.

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 17

1.10. Dynamic Phases


The example (Figure 8,Code 16) shows 3 dynamic sequential phases ([2-5],[6-9] y [10-13]) cal-
culated in parallel from the predecessor phase Plastic [Phase_1]

Figura 8: Sequential and parallel phases

Código 13: Example dynamic phases creation


1 Phase_aux=g_i.Phases[-1]
2 aux3=0
3
4 for k in range(0, len(filename)) :
5 phase2_s = g_i.phase(Phase_aux)
6 phase2_s.DeformCalcType = phase2_s.DeformCalcType.dynamic
7 phase2_s.Deform.TimeIntervalSeconds = dt2[k]*min(max_step_plaxis,lr[k])
8 phase2_s.Deform.ResetDisplacementsToZero = False
9 phase2_s.Deform.UseDefaultIterationParams = False
10 phase2_s.Deform.MaxSteps = min(max_step_plaxis,lr[k])
11 phase2_s.Deform.TimeStepDetermType = "Manual"
12 phase2_s.Deform.SubSteps = 1
13 phase2_s.Deform.ToleratedError = 0.001
14 phase2_s.MaxStepsStored = math.ceil(min(max_step_plaxis,lr[k])/10)
15 phase2_s.MaxCores = 16
16
17 g_i.LineDisplacements.activate(phase2_s)
18 g_i.DynLineDisplacement_1_1.activate(phase2_s)
19 g_i.DynLineDisplacement_1_1.Multiplierx.set(phase2_s, disp[aux3])
20
21

22 g_i.Dynamics.BoundaryYMin.set(phase2_s,"Compliant base")
23 g_i.Dynamics.BoundaryXMin.set(phase2_s,"Free-field")
24
25 for k2 in range(1, 1):
26 aux3=aux3+1
27 phase2_s = g_i.Phases[-1]
28 phase3_s = g_i.phase(phase2_s)
29 phase3_s.DeformCalcType = phase3_s.DeformCalcType.dynamic
30 phase3_s.Deform.TimeIntervalSeconds = dt2[k]*min(max_step_plaxis,lr[k]-max_step_plaxis
,→ *k2)

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Numerical Model Generation 18

31 phase3_s.Deform.ResetDisplacementsToZero = False
32 phase3_s.Deform.UseDefaultIterationParams = False
33 phase3_s.Deform.MaxSteps = min(max_step_plaxis,lr[k]-max_step_plaxis*k2)
34 phase3_s.Deform.TimeStepDetermType = "Manual"
35 phase3_s.Deform.SubSteps = 1
36 phase3_s.Deform.ToleratedError = 0.001
37 phase3_s.MaxStepsStored = 1
38 phase3_s.MaxCores = 16
39
40 g_i.LineDisplacements.activate(phase3_s)
41 g_i.DynLineDisplacement_1_1.activate(phase3_s)
42 g_i.DynLineDisplacement_1_1.Multiplierx.set(phase3_s, disp[aux3])
43

44 g_i.Dynamics.BoundaryYMin.set(phase3_s,"Compliant base")
45 g_i.Dynamics.BoundaryXMin.set(phase3_s,"Free-field")
46
47 aux3=aux3+1
48
49 g_i. calculate ()

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Output 19

2. Output

2.1. Introduction
This section contains the routines written in Python to generate the numerical model in PLA-
XIS 2D software.

The routines can be accessed through the PLAXIS 2D software, in the toolbar Expert menu >
Run Python script > Open... (Figura 9).

Figura 9: Accessing Python routines from PLAXIS 2D - Output

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Output 20

2.2. Obtaining Frames


A frame is the information (type of result, either Deformation or Stresses) of all nodes (or
integration points) in a specific phase and specific step. Multiple frames can be used to generate a
video. Depending on the configuration, it is possible to obtain from 1 frame to the complete time
series. However, the limitation of the latter is the volume of data generated. When a sample of the
complete series is requested, it is not possible to obtain information for the steps that were not saved,
and it is necessary to skip them manually. In the example, an array is run from 9 to 4000 with a step
of 10. This is because a sub-sample of the total with a step of 10 samples was saved. To know the
label of each step beforehand, it is possible to use the command print(g_o.Phases[-1].Steps.echo()).
In the example, the first step of the dynamic phase is the step called automatically by PLAXIS
"Step_41", saved as number 9 in the total steps. (See Figure 10)). The results are saved in a format
that is easy to manipulate later. In the example, the path to a specific step is: Frame/Phase/Point
Type/Result Type/Specific Step.

Figura 10: Step saved in dynamic phase

2.3. Obtaining monitoring points


To overcome the problem of the volume of information, it is possible to define monitoring
points and thus obtain the time series for a type of result more quickly. In the case of sequential
phases, the complete time series is obtained for each phase, and then it is necessary to merge them
into a single time series. To obtain the complete phase information for a point type, the object
g_o.getresultspath() is used. In the example, the path of a monitoring point is: EDP/Phase/-
Result Type/Monitoring Point. The routine saves the information of all monitoring points.

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Output 21

Código 14: Example object g_o.getresults() creation


1 def getframe(filename=None, phaseorder=None, p_type=None, resulttypes=None):
2 value_o = g_o.getresults(phaseorder, resulttypes , p_type, True)
3 with open(filename, "w") as file :
4 file . writelines ([ "{}\n".format(*nr)
5 for nr in zip(value_o)])
6

7 def saveframe(parent_dir=None, phaseorder=None, p_type=None, EDP=None):


8 # FIRST STEP: FOLDER WHERE THE RESULTS WILL BE SAVED
9 #parent_dir = ’C:\\Users\\Bastian Garrido\\Desktop\\Frame\\’
10

11 # SECOND STEP: PHASE


12 #phaseorder = g_o.Phases[-1]
13 phase_name = phaseorder.Name.value
14

15 # THIRD STEP: POINT TYPE StressPoints or Nodes


16 #p_type= "stresspoint"
17 #p_type= "node"
18

19 # FOURTH STEP PASO: RESULT TYPE


20 resulttypes = getattr(g_o.ResultTypes.Soil, EDP)
21

22 import os
23 newpath = os.path.join(parent_dir, ’{0}\ {1}\ {2}’.format(phase_name,p_type,EDP))
24 if not os.path. exists (newpath):
25 os.makedirs(newpath)
26
27 #print(g_o.Phases[-1].Steps.echo())
28 # 9/-4881. Step named "Step_41"
29 for i in range(9, 4000, 10):
30 step = phaseorder.Steps[i]
31 st = int(step.Name.value.replace("Step_", ""))
32 getframe(filename= os.path.join(newpath, ’{0}.txt’ .format(st)) ,
33 phaseorder = step, p_type = p_type, resulttypes = resulttypes)

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Output 22

Código 15: Example object g_o.getresultspath() creation


1 def gettable_time_vs_EDP(filename=None, phaseorder=None, node=None, resulttypes=None):
2 value_o = g_o.getcurveresultspath(node, phaseorder, phaseorder, resulttypes)
3 with open(filename, "w") as file :
4 file . writelines ([ "{}\n".format(*nr)
5 for nr in zip(value_o)])
6

7 def savetable_time_vs_EDP(parent_dir=None, phaseorder=None, p_type=None, EDP=None):


8 # FIRST STEP: FOLDER WHERE THE RESULTS WILL BE SAVED
9 #parent_dir = ’C:\\Users\\Bastian Garrido\\Desktop\\EDP\\’
10

11 # SECOND STEP: PHASE


12 #phaseorder = g_o.Phases[-1]
13 phase_name = phaseorder.Name.value
14

15 # THIRD STEP: POINT TYPE StressPoints or Nodes


16 #p_type= ’StressPoints’
17 #p_type= ’Nodes’
18 pointtype = getattr(g_o.CurvePoints, p_type)
19
20 if p_type == ’StressPoints’:
21 #pointtype = g_o.CurvePoints.StressPoints
22 pre = "CS_"
23 else :
24 #pointtype = g_o.CurvePoints.Nodes
25 pre = "CN_"
26
27 # FOURTH STEP PASO: RESULT TYPE
28 resulttypes = getattr(g_o.ResultTypes.Soil, EDP)
29

30 import os
31 newpath = os.path.join(parent_dir, ’{0}\ {1}’.format(phase_name,EDP))
32 if not os.path. exists (newpath):
33 os.makedirs(newpath)
34
35 for node in pointtype:
36 print(node.Name.value)
37 st = node.Name.value.replace(pre, "")
38 gettable_time_vs_EDP(filename= os.path.join(newpath, ’{0}.txt’.format(st)),
39 phaseorder = phaseorder, node = node, resulttypes = resulttypes)

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Output 23

To execute the functions described above just call them as follows:

Código 16: Example g_o.getresults() and g_o.getresultspath()


1 savetable_time_vs_EDP(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\EDP\\’,
,→ phaseorder=g_o.Phases[-i] , p_type=’StressPoints’, EDP=’Gamxy’)
2 savetable_time_vs_EDP(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\EDP\\’,
,→ phaseorder=g_o.Phases[-i] , p_type=’StressPoints’, EDP=’Sigxy’)
3
4 saveframe(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\Frame\\’, phaseorder=g_o.
,→ Phases[-i], p_type="node", EDP=’Uy’)
5 saveframe(parent_dir=’C:\\Users\\Bastian Garrido\\Desktop\\Frame\\’, phaseorder=g_o.
,→ Phases[-i], p_type="node", EDP=’Ux’)

In the example, first it is shown how to obtain the shear strain γxy and the shear stress τxy
at the monitoring points (of the integration point type). Additionally, it is shown how to obtain
the displacements Uy and Ux for all the nodes of the model in all the steps saved and defined in
saveframe.

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Post-Processing 24

3. Post-Processing

3.1. MATLAB
The routines that allow reading the information of folders generated in the output section are
presented.

The curvedata.m function reads all the information in a folder. In the case of Frame from
Python, a folder is created with the name of the type of result, and inside, a text file is created for
each step with its respective name. Inside the file is the information of each type of point of the
complete model. In the case of EDP from Python, a folder is created with the name of the type of
result, and inside, a text file is created for each monitoring point with its respective name. Inside
the file is the information for the entire time interval.

Frame stores a snapshot of the entire model for a given time instant and result type. EDP
saves a time series for a result type at the monitoring points.

To manipulate the files generated for both Frame and EDP, readframe.m and readEDP.m
routines were created. These routines use the curvedata.m routine but maintain the format used
in Python to create the folders.

Código 17: curvedata.m


1 function [Np,step]=curvedata(MainFolder)
2 % step is the label of Np
3 % frame corresponds to time step
4 % tables corresponds to the monitoring point
5
6 listing = dir(MainFolder);
7 listing = natsortfiles ( listing ) ;
8 Nstep = length(listing ) -2;
9 step = zeros(Nstep,1);
10 M=importdata([MainFolder ’/’ listing(2).name]);
11 [l_p,l_edp]=size(M);
12

13 Np=zeros(l_p,l_edp,Nstep);
14

15 for i = 1:Nstep
16 step( i ) = str2double( listing ( i+1).name(1:end-4));
17 Np (:,:, i )=importdata([MainFolder ’/’ listing( i+1).name]);
18 end
19
20 end

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Post-Processing 25

Código 18: readframe.m


1 function [EDPg,step]=readframe(MainFolder_Frame,Phase,p_type,EDP)
2 % (EDP) overall in a defined domain
3
4 % Same sequence as saved in Python-Plaxis
5 % FIRST STEP: FOLDER WHERE THE RESULTS ARE
6 %MainFolder_Frame = ’./Frame’;
7 % SECOND STEP: PHASE
8 %Phase = ’Phase_2’;
9 % THIRD STEP: POINT TYPE StressPoints or Nodes
10 %p_type = ’stresspoint’; % or ’node’
11 % FOURTH STEP: RESULT TYPE
12 %EDP = ’Gamxy’;
13
14 path = [MainFolder_Frame ’/’ Phase ’/’ p_type];
15
16 % EDP global
17 [EDPg,step]=curvedata([path ’/’ EDP]);
18

19 end

Código 19: readEDP.m


1 function [EDPt,t,p_m]=readEDP(MainFolder_EDP,Phase,EDP,dt)
2 % Times series for each monitoring point (EDP)
3
4 % Same sequence as saved in Python-Plaxis
5 % FIRST STEP: FOLDER WHERE THE RESULTS ARE
6 %MainFolder_EDP = ’./EDP’;
7
8 % SECOND STEP: PHASE
9 %Phase = ’Phase_2’;
10
11 % THIRD STEP: POINT TYPE StressPoints or Nodes
12 % No influye en la lectura
13

14 % FOURTH STEP: RESULT TYPE


15 %EDP = ’Gamxy’;
16
17 path = [MainFolder_EDP ’/’ Phase];
18
19 % EDP at monitoring points
20 [EDP_t,p_m]=curvedata([path ’/’ EDP]);
21 l_p=length(EDP_t);
22 EDPt=reshape(EDP_t,l_p,[]);
23 t=0:dt:(l_p-1)*dt;
24
25 end

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Post-Processing 26

In the animation.m routine (Code 20), the above routines are used to create an animation
of the total deformation produced in a tailings dam. The files used in the example are nested as
follows (Figure 11):

Figura 11: Nested files in the example (Code 20 )

Código 20: animation.m


1 path_Frame = ’./Animacion4/Gabor/Frame’;
2
3 % Integration points coordinates
4 [x1,~]=readframe(path_Frame,’Phase_2’,’stresspoint’,’X’);
5 [y1,~]=readframe(path_Frame,’Phase_2’,’stresspoint’,’Y’);
6
7 % Nodes coordinates
8 [x2,~]=readframe(path_Frame,’Phase_2’,’node’,’X’);
9 [y2,~]=readframe(path_Frame,’Phase_2’,’node’,’Y’);
10
11 [Ux,step]=readframe(path_Frame,’Phase_2’,’node’,’Ux’);
12 Ux_ = reshape(Ux,[],length(step));
13 [Uy,step]=readframe(path_Frame,’Phase_2’,’node’,’Uy’);
14 Uy_ = reshape(Uy,[],length(step));
15 [Utot,step]=readframe(path_Frame,’Phase_2’,’node’,’Utot’);
16 Utot_ = reshape(Utot,[],length(step));
17

18 % Parabolic domain (esthetic)


19 % stresspoint
20 dominio1 = (0.8*(x1-1217).^2+5*y1.^2)<150^2;
21 % nodes
22 dominio2 = (0.8*(x2-1217).^2+5*y2.^2)<150^2;
23
24 %%
25 tic
26 axis tight manual
27 v = VideoWriter(’utot3_F1_V3_3.avi’);

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON
Post-Processing 27

28 open(v);
29 set(gcf , ’ position ’ ,get (0, ’ScreenSize’)) ;
30
31 for k= 1:length(step)
32
33 %figure(’ visible ’,’ off ’)
34 scatter (x2(dominio2)+Ux_(dominio2,k)*1,...
35 y2(dominio2)+Ux_(dominio2,k)*1,...
36 30,Utot_(dominio2,k),’ filled ’ )
37

38 axis equal
39 colormap(jet)
40 hcb=colorbar;
41 hcb.Label.String= ’U_{total} [m]’;
42 caxis ([0 0.2])
43 xlabel( ’Seccion Transversal [m]’, ’FontSize’ , 14)
44 ylabel( ’ Elevación [m]’, ’FontSize’ , 14)
45 title ([ ’ t= ’ num2str((step(k)-31)*0.001) ’ [ s ] ’ ], ’FontSize’ , 14)
46 set(gca, ’FontSize’ ,14, ’Color’ ,[0.8 0.8 0.8])
47 frame = getframe(gcf);
48 set(gca, ’nextplot’ , ’ replacechildren ’ ) ;
49 writeVideo(v,frame)
50

51 end
52 close (v);
53 toc

Figure 12 shows the result of the animation.m routine for an instant of time.

Figura 12: Results animation.m routine at a time instant

CI7901-1 Trabajo de Tesis Doctoral II


DYNAMIC ANALYSIS IN PLAXIS 2D
(INPUT-OUTPUT)
USING PYTHON

También podría gustarte