-
Notifications
You must be signed in to change notification settings - Fork 69
/
striplog.py
2741 lines (2311 loc) · 93.1 KB
/
striplog.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
A striplog is a sequence of intervals.
:copyright: 2019 Agile Geoscience
:license: Apache 2.0
"""
import re
from io import StringIO
import csv
import operator
import warnings
from collections import defaultdict
from collections import OrderedDict
from functools import reduce
from copy import deepcopy
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import requests
import json
from .interval import Interval, IntervalError
from .component import Component
from .legend import Legend
from .canstrat import parse_canstrat
from .markov import Markov_chain
from .lexicon import Lexicon
from . import utils
from . import templates
class StriplogError(Exception):
"""
Generic error class.
"""
pass
class Striplog:
"""
A Striplog is a sequence of intervals.
We will build them from LAS files or CSVs.
Args:
list_of_Intervals (list): A list of Interval objects.
source (str): A source for the data. Default None.
order (str): 'auto', 'depth', 'elevation', or 'none'. Please refer to
the documentation for details. Best idea is to let the default
work. Default: 'auto'.
"""
def __init__(self, list_of_Intervals, source=None, order='auto'):
list_of_Intervals = deepcopy(list_of_Intervals)
if not list_of_Intervals:
m = "Cannot create an empty Striplog."
raise StriplogError(m)
if order.lower()[0] == 'a': # Auto
# If bases == tops, then this is a bunch of 'points'.
if all([iv.base.z == iv.top.z for iv in list_of_Intervals]):
order = 'none'
self.order = 'none'
# We will tolerate zero-thickness intervals mixed in.
elif all([iv.base.z >= iv.top.z for iv in list_of_Intervals]):
order = 'depth'
self.order = 'depth'
elif all([iv.base.z <= iv.top.z for iv in list_of_Intervals]):
order = 'elevation'
self.order = 'elevation'
else:
m = "Could not determine order from tops and bases."
raise StriplogError(m)
if order.lower()[0] == 'n':
self.order = 'none'
# Sanity check
fail = any([iv.base.z != iv.top.z for iv in list_of_Intervals])
if fail:
m = "'None' order specified but tops != bases."
raise StriplogError(m)
# Order force
list_of_Intervals.sort(key=operator.attrgetter('top'))
elif order.lower()[0] == 'd':
self.order = 'depth'
# Sanity check
fail = any([iv.base.z < iv.top.z for iv in list_of_Intervals])
if fail:
m = "Depth order specified but base above top."
raise StriplogError(m)
# Order force
list_of_Intervals.sort(key=operator.attrgetter('top'))
else:
self.order = 'elevation'
fail = any([iv.base.z > iv.top.z for iv in list_of_Intervals])
if fail:
m = "Elevation order specified but base above top."
raise StriplogError(m)
# Order force
r = True
list_of_Intervals.sort(key=operator.attrgetter('top'), reverse=r)
self.source = source
self.__list = list_of_Intervals
self.__index = 0 # Set up iterable.
def __repr__(self):
length = len(self.__list)
details = "start={}, stop={}".format(self.start.z, self.stop.z)
return "Striplog({0} Intervals, {1})".format(length, details)
def __str__(self):
s = [str(i) for i in self.__list]
return '\n'.join(s)
def __getitem__(self, key):
if type(key) is slice:
i = key.indices(len(self.__list))
result = [self.__list[n] for n in range(*i)]
if result:
return Striplog(result)
else:
return None
elif type(key) is list:
result = []
for j in key:
result.append(self.__list[j])
if result:
return Striplog(result)
else:
return None
else:
return self.__list[key]
def __delitem__(self, key):
if (type(key) is list) or (type(key) is tuple):
# Have to compute what the indices *will* be as
# the initial ones are deleted.
indices = [x-i for i, x in enumerate(key)]
for k in indices:
del self.__list[k]
else:
del self.__list[key]
return
def __len__(self):
return len(self.__list)
def __setitem__(self, key, value):
if not key:
return
try:
for i, j in enumerate(key):
self.__list[j] = value[i]
except TypeError:
self.__list[key] = value
except IndexError:
raise StriplogError("There must be one Interval for each index.")
def __iter__(self):
return iter(self.__list)
def __next__(self):
"""
Supports iterable.
"""
try:
result = self.__list[self.__index]
except IndexError:
self.__index = 0
raise StopIteration
self.__index += 1
return result
def next(self):
"""
For Python 2 compatibility.
"""
return self.__next__()
def __contains__(self, item):
for r in self.__list:
if item in r.components:
return True
return False
def __reversed__(self):
return Striplog(self.__list[::-1])
def __add__(self, other):
if isinstance(other, self.__class__):
result = self.__list + other.__list
return Striplog(result)
elif isinstance(other, Interval):
result = self.__list + [other]
return Striplog(result)
else:
raise StriplogError("You can only add striplogs or intervals.")
def insert(self, index, item):
if isinstance(item, self.__class__):
for i, iv in enumerate(item):
self.__list.insert(index+i, iv)
elif isinstance(item, Interval):
self.__list.insert(index, item)
return
else:
raise StriplogError("You can only insert striplogs or intervals.")
def append(self, item):
"""
Implements list-like `append()` method.
"""
if isinstance(item, Interval):
self.__list.append(item)
return
else:
m = "You can only append an Interval to a Striplog."
raise StriplogError(m)
def extend(self, item):
"""
Implements list-like `extend()` method.
"""
if isinstance(item, self.__class__):
self.__list += item
return
else:
m = "You can only extend a Striplog with another Striplog."
raise StriplogError(m)
def pop(self, index):
"""
Implements list-like `pop()` method.
"""
self.__list.pop(index)
@property
def start(self):
"""
Property. The closest Position to the datum.
Returns:
Position.
"""
if self.order == 'depth':
# Too naive if intervals can overlap:
# return self[0].top
return min(i.top for i in self)
else:
return min(i.base for i in self)
@property
def stop(self):
"""
Property. The furthest Position from the datum.
Returns:
Position.
"""
if self.order == 'depth':
return max(i.base for i in self)
else:
return max(i.top for i in self)
def __sort(self):
"""
Private method. Sorts into 'natural' order: top-down for depth-ordered
striplogs; bottom-up for elevation-ordered.
Sorts in place.
Returns:
None.
"""
self.__list.sort(key=operator.attrgetter('top'))
return
def __strict(self):
"""
Private method. Checks if striplog is monotonically increasing in
depth.
Returns:
Bool.
"""
def conc(a, b):
return a + b
# Check boundaries, b
b = np.array(reduce(conc, [[i.top.z, i.base.z] for i in self]))
return all(np.diff(b) >= 0)
@property
def cum(self):
"""
Property. Gives the cumulative thickness of all filled intervals.
It would be nice to use sum() for this (by defining __radd__),
but I quite like the ability to add striplogs and get a striplog
and I don't think we can have both, it's too confusing.
Not calling it sum, because that's a keyword.
Returns:
Float. The cumulative thickness.
"""
total = 0.0
for i in self:
total += i.thickness
return total
@property
def mean(self):
"""
Property. Returns the mean thickness of all filled intervals.
Returns:
Float. The mean average of interval thickness.
"""
return self.cum / len(self)
@property
def components(self):
"""
Property. Returns the list of compenents in the striplog.
Returns:
List. A list of the unique components.
"""
return [i[0] for i in self.unique if i[0]]
@property
def unique(self):
"""
Property. Summarize a Striplog with some statistics.
Returns:
List. A list of (Component, total thickness thickness) tuples.
"""
all_rx = set([iv.primary for iv in self])
table = {r: 0 for r in all_rx}
for iv in self:
table[iv.primary] += iv.thickness
return sorted(table.items(), key=operator.itemgetter(1), reverse=True)
@property
def top(self):
"""
Property.
"""
# For backwards compatibility.
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "Striplog.top is deprecated; please use Striplog.unique"
warnings.warn(w, DeprecationWarning, stacklevel=2)
return self.unique
@classmethod
def __intervals_from_tops(self,
tops,
values,
basis,
components,
field=None,
ignore_nan=True):
"""
Private method. Take a sequence of tops in an arbitrary dimension,
and provide a list of intervals from which a striplog can be made.
This is only intended to be used by ``from_image()``.
Args:
tops (iterable). A list of floats.
values (iterable). A list of values to look up.
basis (iterable). A list of components.
components (iterable). A list of Components.
Returns:
List. A list of Intervals.
"""
# Scale tops to actual depths.
length = float(basis.size)
start, stop = basis[0], basis[-1]
tops = [start + (p/(length-1)) * (stop-start) for p in tops]
bases = tops[1:] + [stop]
list_of_Intervals = []
for i, t in enumerate(tops):
v, c, d = values[i], [], {}
if ignore_nan and np.isnan(v):
continue
if (field is not None):
d = {field: v}
if components is not None:
try:
c = [deepcopy(components[int(v)])]
except IndexError:
c = []
if c and (c[0] is None):
c = []
interval = Interval(t, bases[i], data=d, components=c)
list_of_Intervals.append(interval)
return list_of_Intervals
@staticmethod
def _clean_longitudinal_data(data, null=None):
"""
Private function. Make sure we have what we need to make a striplog.
"""
# Rename 'depth' or 'MD'
if ('top' not in data.keys()):
data['top'] = data.pop('depth', data.pop('MD', None))
# Sort everything
idx = list(data.keys()).index('top')
values = sorted(zip(*data.values()), key=lambda x: x[idx])
data = {k: list(v) for k, v in zip(data.keys(), zip(*values))}
if data['top'] is None:
raise StriplogError('Could not get tops.')
# Get rid of null-like values if specified.
if null is not None:
for k, v in data.items():
data[k] = [i if i != null else None for i in v]
return data
@classmethod
def from_petrel(cls, filename,
stop=None,
points=False,
null=None,
function=None,
include=None,
exclude=None,
remap=None,
ignore=None):
"""
Makes a striplog from a Petrel text file.
Returns:
striplog.
"""
result = utils.read_petrel(filename,
function=function,
remap=remap,
)
data = cls._clean_longitudinal_data(result,
null=null
)
list_of_Intervals = cls._build_list_of_Intervals(data,
stop=stop,
points=points,
include=include,
exclude=exclude,
ignore=ignore
)
if list_of_Intervals:
return cls(list_of_Intervals)
return None
@classmethod
def _build_list_of_Intervals(cls,
data_dict,
stop=None,
points=False,
include=None,
exclude=None,
ignore=None,
lexicon=None):
"""
Private function. Takes a data dictionary and constructs a list
of Intervals from it.
Args:
data_dict (dict)
stop (float): Where to end the last interval.
points (bool)
include (dict)
exclude (dict)
ignore (list)
lexicon (Lexicon)
Returns:
list.
"""
if not lexicon:
lexicon = Lexicon.default()
with warnings.catch_warnings():
warnings.simplefilter("module")
w = 'No lexicon provided, using the default.'
warnings.warn(w)
include = include or {}
exclude = exclude or {}
ignore = ignore or []
# Reassemble as list of dicts
all_data = []
for data in zip(*data_dict.values()):
all_data.append({k: v for k, v in zip(data_dict.keys(), data)})
# Sort
all_data = sorted(all_data, key=lambda x: x['top'])
# Filter down:
wanted_data = []
for dictionary in all_data:
keep = True
delete = []
for k, v in dictionary.items():
incl = include.get(k, utils.null_default(True))
excl = exclude.get(k, utils.null_default(False))
if k in ignore:
delete.append(k)
if not incl(v):
keep = False
if excl(v):
keep = False
if delete:
for key in delete:
_ = dictionary.pop(key, None)
if keep:
wanted_data.append(dictionary)
# Fill in
if not points:
for i, iv in enumerate(wanted_data):
if iv.get('base', None) is None:
try: # To set from next interval
iv['base'] = wanted_data[i+1]['top']
except (IndexError, KeyError):
# It's the last interval
if stop is not None:
thick = stop - iv['top']
else:
thick = 1
iv['base'] = iv['top'] + thick
# Build the list of intervals to pass to __init__()
list_of_Intervals = []
for iv in wanted_data:
top = iv.pop('top')
base = iv.pop('base', None)
descr = iv.pop('description', '')
if iv:
c, d = {}, {}
for k, v in iv.items():
match1 = (k[:9].lower() == 'component')
match2 = (k[:5].lower() == 'comp ')
if match1 or match2:
k = re.sub(r'comp(?:onent)? ', '', k, flags=re.I)
c[k] = v # It's a component
else:
if v is not None:
d[k] = v # It's data
comp = [Component(c)] if c else None
if comp:
this = Interval(**{'top': top,
'base': base,
'description': descr,
'data': d,
'components': comp})
elif not comp:
this = Interval(**{'top': top,
'base': base,
'data': d,
'description': descr,
'lexicon': lexicon})
else:
this = Interval(**{'top': top,
'base': base,
'description': descr,
'lexicon': lexicon})
list_of_Intervals.append(this)
return list_of_Intervals
@classmethod
def from_csv(cls, filename=None,
text=None,
dlm=',',
lexicon=None,
points=False,
include=None,
exclude=None,
remap=None,
function=None,
null=None,
ignore=None,
source=None,
stop=None,
fieldnames=None):
"""
Load from a CSV file or text.
Args
filename (str): The filename, or use `text`.
text (str): CSV data as a string, or use `filename`.
dlm (str): The delimiter, default ','.
lexicon (Lexicon): The lexicon to use, optional. Only needed if \
parsing descriptions (e.g. cuttings).
points (bool): Whether to make a point dataset (as opposed to \
ordinary intervals with top and base. Default is False.
include: Default is None.
exclude: Default is None.
remap: Default is None.
function: Default is None.
null: Default is None.
ignore: Default is None.
source: Default is None.
stop: Default is None.
fieldnames: Default is None.
Returns
Striplog. A new instance.
"""
if (filename is None) and (text is None):
raise StriplogError("You must provide a filename or CSV text.")
if (filename is not None):
if source is None:
source = filename
with open(filename, 'r') as f:
text = f.read()
source = source or 'CSV'
# Deal with multiple spaces in space delimited file.
if dlm == ' ':
text = re.sub(r'[ \t]+', ' ', text)
if fieldnames is not None:
text = dlm.join(fieldnames) + '\n' + text
try:
f = StringIO(text) # Python 3
except TypeError:
f = StringIO(unicode(text)) # Python 2
reader = csv.DictReader(f, delimiter=dlm)
# Reorganize the data to make fixing it easier.
reorg = {k.strip().lower(): []
for k in reader.fieldnames
if k is not None}
t = f.tell()
for key in reorg:
f.seek(t)
for r in reader:
s = {k.strip().lower(): v.strip() for k, v in r.items()}
try:
reorg[key].append(float(s[key]))
except ValueError:
reorg[key].append(s[key])
f.close()
remap = remap or {}
for k, v in remap.items():
reorg[v] = reorg.pop(k)
data = cls._clean_longitudinal_data(reorg, null=null)
list_of_Intervals = cls._build_list_of_Intervals(data,
points=points,
lexicon=lexicon,
include=include,
exclude=exclude,
ignore=ignore,
stop=stop)
return cls(list_of_Intervals, source=source)
@classmethod
def from_dict(cls, dictionary):
"""
Take a dictionary of the form name:depth and return a striplog of
complete intervals.
"""
d_sorted = sorted(dictionary.items(), key=lambda i: i[1])
names = [i[0] for i in d_sorted]
tops_ = [i[1] for i in d_sorted]
bases_ = tops_[1:] + [tops_[-1]+1]
comps_ = [Component({'formation': name}) for name in names]
list_of_Intervals = []
for top, base, comp in zip(tops_, bases_, comps_):
iv = Interval(top=top, base=base, components=[comp])
list_of_Intervals.append(iv)
return cls(list_of_Intervals)
@classmethod
def from_descriptions(cls, text,
lexicon=None,
source='CSV',
dlm=',',
points=False,
abbreviations=False,
complete=False,
order='depth',
columns=None,
):
"""
Convert a CSV string into a striplog. Expects 2 or 3 fields:
top, description
OR
top, base, description
Args:
text (str): The input text, given by ``well.other``.
lexicon (Lexicon): A lexicon, required to extract components.
source (str): A source. Default: 'CSV'.
dlm (str): The delimiter, given by ``well.dlm``. Default: ','
points (bool): Whether to treat as points or as intervals.
abbreviations (bool): Whether to expand abbreviations in the
description. Default: False.
complete (bool): Whether to make 'blank' intervals, or just leave
gaps. Default: False.
order (str): The order, 'depth' or 'elevation'. Default: 'depth'.
columns (tuple or list): The names of the columns.
Returns:
Striplog: A ``striplog`` object.
Example:
# TOP BOT LITH
312.34, 459.61, Sandstone
459.71, 589.61, Limestone
589.71, 827.50, Green shale
827.60, 1010.84, Fine sandstone
"""
text = re.sub(r'(\n+|\r\n|\r)', '\n', text.strip())
as_strings = []
try:
f = StringIO(text) # Python 3
except TypeError:
f = StringIO(unicode(text)) # Python 2
reader = csv.reader(f, delimiter=dlm, skipinitialspace=True)
for row in reader:
as_strings.append(row)
f.close()
if not columns:
if order[0].lower() == 'e':
columns = ('base', 'top', 'description')
else:
columns = ('top', 'base', 'description')
result = {k: [] for k in columns}
# Set the indices for the fields.
tix = columns.index('top')
bix = columns.index('base')
dix = columns.index('description')
for i, row in enumerate(as_strings):
# THIS ONLY WORKS FOR MISSING TOPS!
if len(row) == 2:
row = [row[0], None, row[1]]
# TOP
this_top = float(row[tix])
# THIS ONLY WORKS FOR MISSING TOPS!
# BASE
# Base is null: use next top if this isn't the end.
if row[1] is None:
if i < len(as_strings)-1:
this_base = float(as_strings[i+1][0]) # Next top.
else:
this_base = this_top + 1 # Default to 1 m thick at end.
else:
this_base = float(row[bix])
# DESCRIPTION
this_descr = row[dix].strip()
# Deal with making intervals or points...
if not points:
# Insert intervals where needed.
if complete and (i > 0) and (this_top != result['base'][-1]):
result['top'].append(result['base'][-1])
result['base'].append(this_top)
result['description'].append('')
else:
this_base = None # Gets set to Top in striplog creation
# ASSIGN
result['top'].append(this_top)
result['base'].append(this_base)
result['description'].append(this_descr)
# Build the list.
list_of_Intervals = []
for i, t in enumerate(result['top']):
b = result['base'][i]
d = result['description'][i]
interval = Interval(t, b, description=d,
lexicon=lexicon,
abbreviations=abbreviations)
list_of_Intervals.append(interval)
return cls(list_of_Intervals, source=source)
@classmethod
def from_image(cls, filename, start, stop, legend,
source="Image",
col_offset=0.1,
row_offset=2,
tolerance=0,
background=None):
"""
Read an image and generate Striplog.
Args:
filename (str): An image file, preferably high-res PNG.
start (float or int): The depth at the top of the image.
stop (float or int): The depth at the bottom of the image.
legend (Legend): A legend to look up the components in.
source (str): A source for the data. Default: 'Image'.
col_offset (Number): The proportion of the way across the image
from which to extract the pixel column. Default: 0.1 (ie 10%).
row_offset (int): The number of pixels to skip at the top of
each change in colour. Default: 2.
tolerance (float): The Euclidean distance between hex colours,
which has a maximum (black to white) of 441.67 in base 10.
Default: 0.
background (array): A background colour (as hex) to ignore.
Returns:
Striplog: The ``striplog`` object.
"""
if background is None:
bg = "#xxxxxx"
else:
bg = background
rgb = utils.loglike_from_image(filename, col_offset)
loglike = np.array([utils.rgb_to_hex(t) for t in rgb if utils.rgb_to_hex(t) != bg])
# Get the pixels and colour values at 'tops' (i.e. changes).
tops, hexes = utils.tops_from_loglike(loglike, offset=row_offset)
# If there are consecutive tops, we assume it's because there is a
# single-pixel row that we don't want. So take the second one only.
# We used to do this reduction in ``utils.tops_from_loglike()`` but
# it was preventing us from making intervals only one sample thick.
nonconsecutive = np.append(np.diff(tops), 2)
tops = tops[nonconsecutive > 1]
hexes = hexes[nonconsecutive > 1]
# Get the set of unique colours.
hexes_reduced = list(set(hexes))
# Get the components corresponding to the colours.
components = [legend.get_component(h, tolerance=tolerance)
for h in hexes_reduced]
# Turn them into integers.
values = [hexes_reduced.index(i) for i in hexes]
basis = np.linspace(start, stop, loglike.size)
list_of_Intervals = cls.__intervals_from_tops(tops,
values,
basis,
components)
list_of_Intervals = [iv for iv in list_of_Intervals
if isinstance(iv.primary, Component)]
return cls(list_of_Intervals, source="Image")
@classmethod
def from_img(cls, *args, **kwargs):
"""
For backwards compatibility.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "from_img() is deprecated; please use from_image()"
warnings.warn(w)
return cls.from_image(*args, **kwargs)
@classmethod
def _from_array(cls, a,
lexicon=None,
source="",
points=False,
abbreviations=False):
"""
DEPRECATING.
Turn an array-like into a Striplog. It should have the following
format (where ``base`` is optional):
[(top, base, description),
(top, base, description),
...
]
Args:
a (array-like): A list of lists or of tuples, or an array.
lexicon (Lexicon): A language dictionary to extract structured
objects from the descriptions.
source (str): The source of the data. Default: ''.
points (bool): Whether to treat as point data. Default: False.
Returns:
Striplog: The ``striplog`` object.
"""
with warnings.catch_warnings():
warnings.simplefilter("always")
w = "from_array() is deprecated."
warnings.warn(w, DeprecationWarning, stacklevel=2)
csv_text = ''
for interval in a:
interval = [str(i) for i in interval]
if (len(interval) < 2) or (len(interval) > 3):
raise StriplogError('Elements must have 2 or 3 items')
descr = interval[-1].strip('" ')
interval[-1] = '"' + descr + '"'
csv_text += ', '.join(interval) + '\n'
return cls.from_descriptions(csv_text,
lexicon,
source=source,
points=points,
abbreviations=abbreviations)
@classmethod
def from_log(cls, log,
cutoff=None,
components=None,
legend=None,
legend_field=None,
field=None,
right=False,
basis=None,
source='Log'):
"""
Turn a 1D array into a striplog, given a cutoff.
Args:
log (array-like): A 1D array or a list of integers.
cutoff (number or array-like): The log value(s) at which to bin
the log. Optional.
components (array-like): A list of components. Use this or
``legend``.
legend (``Legend``): A legend object. Use this or ``components``.
legend_field ('str'): If you're not trying to match against
components, then you can match the log values to this field in
the Decors.
field (str): The field in the Interval's ``data`` to store the log
values as.
right (bool): Which side of the cutoff to send things that are
equal to, i.e. right on, the cutoff.
basis (array-like): A depth basis for the log, so striplog knows
where to put the boundaries.
source (str): The source of the data. Default 'Log'.
Returns:
Striplog: The ``striplog`` object.
"""
# Try to deal with the log potentially being a welly.Curve, pd.Series,
# or pd.DataFrame. Squeeze down to 1D in case it's a column vector.
try:
log_arr = np.squeeze(log.values)
except AttributeError:
log_arr = np.squeeze(np.asanyarray(log))
if (components is None) and (legend is None) and (field is None):
m = 'You must provide a list of components and legend, or a field.'
raise StriplogError(m)