-
Notifications
You must be signed in to change notification settings - Fork 2
/
plotDisplacements.py
executable file
·256 lines (195 loc) · 7.42 KB
/
plotDisplacements.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env python3
'''
** RISeR Incremental Slip Rate Calculator **
Plot displacements on a single figure
Rob Zinke 2019-2021
'''
### IMPORT MODULES ---
import argparse
try:
import yaml
except:
print('Please install pyyaml'); exit()
import numpy as np
import matplotlib.pyplot as plt
from resultSaving import confirmOutputDir
### PARSER ---
Description = '''Plot displacements on a single figure. This script is meant for display purposes only and
will not affect the slip rate calculations.
This script accepts a list of displacements, encoded with the sample type, sample label, and path to file,
separated by colons. I.e.,
DatumType:[SampleName]:[FilePath]
For example:
Offset 1: {"file": "Offset1.txt", "dtype": "displacement"}
shows that the sample is a Displacement datum, labelled Offset1, and the path to file Offset1.txt is
provided. The displacement sample type can be color coded by type or user specification:
* Displacement
* Generic
Generic displacement PDFs can also be specified by the user with the --generic-color and --generic-alpha
options.
Other plot elements are also available, including line separators for ease of visualization:
* Line
* Dashed Line
* Bold Line
The line elements do not require file specification. For example:
Strat Boundary: {\"dtype\": \"bold line\"}
'''
Examples = '''EXAMPLES
# Plot displacements from displacement list
plotDisplacements.py DspList.yaml -y 'displacements (m)' -t 'Measurement Examples' -r 80 -o DspPlotExample --generic-color b
'''
def createParser():
parser = argparse.ArgumentParser(description=Description,
formatter_class=argparse.RawTextHelpFormatter, epilog=Examples)
parser.add_argument(dest='dspList', type=str,
help='YAML document with list of displacement files. See above for example.')
parser.add_argument('-r','--label-rotation', dest='labelRotation', default=0, type=float,
help='Label rotation')
parser.add_argument('-t','--title', dest='title', default=None, type=str,
help='Base for graph title.')
parser.add_argument('-x','--xlabel', dest='xlabel', default='Displacement', type=str,
help='X-axis label')
parser.add_argument('-o','--outName', dest='outName', default=None, type=str,
help='Base for graph title')
parser.add_argument('--pdf-scale', dest='pdfScale', default=1.0, type=float,
help='Vertical scale for PDFs')
parser.add_argument('--generic-color', dest='genericColor', default='k',
help='Color for generic plot')
parser.add_argument('--generic-alpha', dest='genericAlpha', type=float, default=1.0,
help='Opacity for generic plot')
return parser
def cmdParser(inpt_args=None):
parser = createParser()
return parser.parse_args(inpt_args)
### PLOT DISPLACEMENTS ---
class dspPlot:
'''
Plot provided displacements on a single figure
'''
def __init__(self, dspList):
'''
Establish figure and plot data. See examples for "dspsList".
'''
# Initialize figure
self.__setupFig__()
# Read and parse data
self.__loadData__(dspList)
def __setupFig__(self):
'''
Setup initial figure.
'''
self.fig, self.ax = plt.subplots(figsize=(10, 10))
def __loadData__(self, dspList):
'''
Open list of displacement files, gather inputs as "data".
'''
# Read data from file
with open(dspList, 'r') as dspFile:
# Parse data within file
self.dspData = yaml.load(dspFile, Loader=yaml.FullLoader)
self.dataNames = list(self.dspData.keys())[::-1]
def plotData(self, pdfScale=1.0, genericColor='k', genericAlpha=1.0):
'''
Work line by line to plot data based on datum type.
'''
# Initialize colors
self.__initColors__(genericColor, genericAlpha)
# Plot data one by one
k = 0 # start counter
for key in self.dataNames:
datum = self.dspData[key]
properties = list(datum.keys())
properties = [property.lower() for property in properties]
# Determine datum type
if not 'dtype' in properties:
# Default data type = age
dtype = 'generic'
else:
dtype = datum['dtype'].lower().replace(' ', '')
## Plot line breaks
# Plot simple line
if dtype == 'line':
self.ax.axhline(k, color=(0.7,0.75,0.8))
# Plot dashed line
elif dtype == 'dashedline':
self.ax.axhline(k, color=(0.7,0.75,0.8), linestyle='--')
# Plot thicker line
elif dtype == 'boldline':
self.ax.axhline(k, color=(0.3,0.35,0.35))
## Assume displacement PDF
else:
# Load and format displacement datum
xDsp, pxDsp = self.__formatDsp__(datum['file'], pdfScale)
# Shift
pxDsp += k
# Plot data
if 'color' not in properties:
color = self.colors[dtype]
else:
color = datum['color']
if 'alpha' not in properties:
alpha = self.alphas[dtype]
else:
alpha = datum['alpha']
self.ax.fill(xDsp, pxDsp, color=color, alpha=alpha)
k += 1 # update counter
def __formatDsp__(self, dspFile, pdfScale):
'''
Load and format displacement data.
'''
# Load data from file
dspData = np.loadtxt(dspFile)
xDsp = dspData[:,0]
pxDsp = dspData[:,1]
# Zero-pad
xDsp = np.pad(xDsp, (1,1), 'edge')
pxDsp = np.pad(pxDsp, (1,1), 'constant')
# Scale probability to 1.0 * scale factor
pxDsp = pdfScale*pxDsp/pxDsp.max()
return xDsp, pxDsp
def __initColors__(self, genericColor, genericAlpha):
'''
Color lookup table.
'''
self.colors = {}
self.alphas = {}
# Non-specific displacement
self.colors['displacement'] = (0,0,0)
self.alphas['displacement'] = 1.0
# Generic PDF
self.colors['generic'] = genericColor
self.alphas['generic'] = genericAlpha
def finalizeFig(self, title=None, xlabel='Displacement', labelRotation=0, outName=None):
'''
Finalize figure.
'''
# X-labels
ticks = np.arange(len(self.dspData))
self.ax.set_yticks(ticks)
self.ax.set_yticklabels(self.dataNames, rotation=labelRotation)
# Y-labels
self.ax.set_xlabel(xlabel)
# Title
if title: self.ax.set_title(title)
# Finalize
self.fig.tight_layout()
# Save to file
if outName:
savename = '{:s}.pdf'.format(outName)
self.fig.savefig(savename, type='pdf')
print('Saved to: {:s}'.format(savename))
### MAIN ---
if __name__ == '__main__':
# Gather arguments
inps = cmdParser()
# Confirm output directory exists
confirmOutputDir(inps.outName)
# Plot displacements
displacements = dspPlot(inps.dspList)
displacements.plotData(pdfScale = inps.pdfScale,
genericColor = inps.genericColor, genericAlpha = inps.genericAlpha)
displacements.finalizeFig(title = inps.title,
xlabel = inps.xlabel,
labelRotation = inps.labelRotation,
outName = inps.outName)
plt.show()