def test_legend(): legend = Legend.from_csv(csv_text) assert legend[0].colour == '#f7e9a6' assert legend.max_width == 5 assert legend.__str__() != '' assert legend.__repr__() != '' rock = Component(r) assert legend.get_colour(rock) == '#eeeeee' rock3 = Component(r3) assert legend.get_colour(rock3) == '#ffdbba' assert legend.get_width(rock3) == 3.0 c = legend.get_component('#f7e9a6') assert c.lithology == 'sandstone' colours = [d.colour for d in legend] assert len(colours) == 8 l = Legend.random([rock, rock3]) assert l != legend assert getattr(l[-1], 'colour') != '' assert l.to_csv() != '' summed = legend + l assert len(summed) == 10
def test_legend(): """Test all the basics. """ legend = Legend.from_csv(csv_text) assert legend[0].colour == '#f7e9a6' assert legend.max_width == 5 assert legend.__str__() != '' assert legend.__repr__() != '' assert len(legend[[3, 4]]) == 2 assert len(legend[3:5]) == 2 rock = Component(r) assert legend.get_colour(rock) == '#eeeeee' assert rock not in legend d = Decor({'colour': 'red', 'component': rock}) length = len(legend) legend[3] = d assert len(legend) == length assert legend[3].component == rock assert d in legend rock3 = Component(r3) assert legend.get_colour(rock3) == '#ffdbba' assert legend.get_width(rock3) == 3.0 c = legend.get_component('#f7e9a6') assert c.lithology == 'sandstone' c2 = legend.get_component('#f7e9a7', tolerance=30) assert c2.lithology == 'sandstone' colours = [d.colour for d in legend] assert len(colours) == 8 assert Legend.random(rock3)[0].colour != '' l = Legend.random([rock, rock3]) assert len(l) == 2 assert getattr(l[-1], 'colour') != '' assert l.to_csv() != '' assert l.max_width == 0 l = Legend.random([rock, rock3], width=True, colour='#abcdef') assert getattr(l[0], 'colour') == '#abcdef' # Test sums. summed = legend + l assert len(summed) == 10 summed_again = legend + d assert len(summed_again) == 9 summed_again_again = d + legend assert len(summed_again_again) == 9 # Test equality. assert not d == legend
def test_duplicate_warning(recwarn): """Test warning triggers if duplicate component in CSV. """ Legend.from_csv(csv_duplicate) w = recwarn.pop() assert issubclass(w.category, UserWarning) assert 'duplicate' in str(w.message) assert w.lineno
def test_legend_builtins(): """Test the builtins. """ assert len(Legend.builtin('nsdoe')) == 18 assert len(Legend.builtin('nagmdm__6_2')) == 206 # And builtin timescale. assert len(Legend.builtin_timescale('isc')) == 240
def test_duplicate_warning(recwarn): """Test warning triggers if duplicate component in CSV. """ Legend.from_csv(text=csv_duplicate) w = recwarn.pop() assert issubclass(w.category, UserWarning) assert 'duplicate' in str(w.message) assert w.lineno
def test_legend(): """Test all the basics. """ legend = Legend.from_csv(text=csv_text) assert legend[0].colour == '#f7e9a6' assert legend.max_width == 5 assert legend.__str__() != '' assert legend.__repr__() != '' assert len(legend[[3, 4]]) == 2 assert len(legend[3:5]) == 2 rock = Component(r) assert legend.get_colour(rock) == '#eeeeee' assert rock not in legend d = Decor({'colour': 'red', 'component': rock}) length = len(legend) legend[3] = d assert len(legend) == length assert legend[3].component == rock assert d in legend rock3 = Component(r3) assert legend.get_colour(rock3) == '#ffdbba' assert legend.get_width(rock3) == 3.0 c = legend.get_component('#f7e9a6') assert c.lithology == 'sandstone' c2 = legend.get_component('#f7e9a7', tolerance=30) assert c2.lithology == 'sandstone' colours = [d.colour for d in legend] assert len(colours) == 8 assert Legend.random(rock3)[0].colour != '' l = Legend.random([rock, rock3]) assert len(l) == 2 assert getattr(l[-1], 'colour') != '' assert l.to_csv() != '' assert l.max_width == 0 l = Legend.random([rock, rock3], width=True, colour='#abcdef') assert getattr(l[0], 'colour') == '#abcdef' # Test sums. summed = legend + l assert len(summed) == 10 summed_again = legend + d assert len(summed_again) == 9 summed_again_again = d + legend assert len(summed_again_again) == 9 # Test equality. assert not d == legend
def test_error(): """Test errors are raised. """ rock = Component(r) # No component with pytest.raises(LegendError): Decor({'colour': 'red'}) # No decoration with pytest.raises(LegendError): Decor({'component': rock}) # Bad colour with pytest.raises(LegendError): Decor({'colour': 'blurple', 'component': rock}) # Adding incompatible things legend = Legend.from_csv(csv_text) with pytest.raises(LegendError): legend + rock # Tolerance not allowed. with pytest.raises(LegendError): legend.get_component('#f7e9a7', tolerance=-1)
def test_from_image(): legend = Legend.builtin("NSDOE") imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_img(imgfile, 200, 300, legend=legend) assert len(striplog) == 26 assert striplog[-1].primary.summary() == "Volcanic" assert np.floor(striplog.find("sandstone").cum) == 15 assert striplog.depth(260).primary.lithology == "siltstone" assert striplog.to_las3() is not "" assert striplog.to_log()[5] == 2.0 assert striplog.cum == 100.0 assert striplog.thickest().primary.lithology == "anhydrite" assert striplog.thickest(n=7)[1].primary.lithology == "sandstone" assert striplog.thinnest().primary.lithology == "dolomite" assert striplog.thinnest(n=7)[1].primary.lithology == "siltstone" indices = [2, 7, 20] del striplog[indices] assert len(striplog.find_gaps()) == len(indices) striplog.prune(limit=1.0) assert len(striplog) == 14 striplog.anneal() assert not striplog.find_gaps() # Should be None rock = striplog.find("sandstone")[1].components[0] assert rock in striplog
def test_striplog_intersect(): """Test intersection. This example is from the tutorial. """ chrono = Striplog([ Interval(**{ 'top': 0, 'base': 60, 'components': [Component({'age': 'Holocene'})] }), Interval( **{ 'top': 60, 'base': 75, 'components': [Component({'age': 'Palaeogene'})] }), Interval( **{ 'top': 75, 'base': 100, 'components': [Component({'age': 'Cretaceous'})] }), ]) legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" strip = Striplog.from_image(imgfile, 14.3, 135.9, legend=legend) sands = strip.find('sandstone') cretaceous = chrono.find('Palaeogene') cret_sand = sands.intersect(cretaceous) assert len(cret_sand) == 3 assert cret_sand.stop.z == 75
def test_from_image(): legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_img(imgfile, 200, 300, legend=legend) assert len(striplog) == 26 assert striplog[-1].primary.summary() == 'Volcanic' assert np.floor(striplog.find('sandstone').cum) == 15 assert striplog.depth(260).primary.lithology == 'siltstone' assert striplog.to_las3() is not '' assert striplog.to_log()[5] == 2.0 assert striplog.cum == 100.0 assert striplog.thickest().primary.lithology == 'anhydrite' assert striplog.thickest(n=7)[1].primary.lithology == 'sandstone' assert striplog.thinnest().primary.lithology == 'dolomite' assert striplog.thinnest(n=7)[1].primary.lithology == 'siltstone' indices = [2, 7, 20] del striplog[indices] assert len(striplog.find_gaps()) == len(indices) striplog.prune(limit=1.0) assert len(striplog) == 14 striplog.anneal() assert not striplog.find_gaps() # Should be None rock = striplog.find('sandstone')[1].components[0] assert rock in striplog
def test_tolerance_warning(recwarn): """Test warning triggers if tolerance too low. """ legend = Legend.from_csv(text=csv_text) legend.get_component('#f7e9a7', tolerance=0) w = recwarn.pop() assert issubclass(w.category, UserWarning) assert 'tolerance of 0' in str(w.message) assert w.lineno
def test_warning(recwarn): """Test warning triggers if tolerance too low. """ legend = Legend.from_csv(csv_text) legend.get_component('#f7e9a7', tolerance=0) w = recwarn.pop() assert issubclass(w.category, UserWarning) assert 'tolerance of 0' in str(w.message) assert w.lineno
def test_bar(): """Test bar plot. """ fig, ax = plt.subplots() lexicon = Lexicon.default() striplog = Striplog.from_las3(las3, lexicon=lexicon) legend = Legend.builtin('nagmdm__6_2') ax = striplog.bar(sort=True, legend=legend, ax=ax, align='center') return fig
def __init__(self, intervals=None, components=None, name='', legend=None, x_collar=0., y_collar=0.): """ build a Borehole3D object from Striplog.Intervals list Parameters ----------- intervals : list list of Striplog.Interval object (default = None) components : (default = None) name : str legend : Striplog Legend object (default = None) x_collar : float X coordinate of the borehole (default = 0) y_collar : float Y coordinate of the borehole (default = 0) """ self.name = name if legend is None or not isinstance(legend, Legend): self.legend = Legend.default() else: self.legend = legend self.x_collar = x_collar self.y_collar = y_collar self.omf_legend, self.omf_cmap = striplog_legend_to_omf_legend( self.legend) if intervals is None: lexicon = Lexicon.default() with open(ROOT_DIR + '/data/test.las', 'r') as las3: default_intv = Striplog.from_las3(las3.read(), lexicon) intervals = list(default_intv) print("Pay attention that default intervals are actually used !\n") self.intervals = intervals self.geometry = [] # instantiation with supers properties Striplog.__init__(self, list_of_Intervals=self.intervals) # self.uid=uuid #get a unique for identification of borehole in the project self.build_geometry()
def test_legend(): """Test all the basics. """ legend = Legend.from_csv(csv_text) assert legend[0].colour == '#f7e9a6' assert legend.max_width == 5 assert legend.__str__() != '' assert legend.__repr__() != '' assert len(legend[[3, 4]]) == 2 assert len(legend[3:5]) == 2 rock = Component(r) assert legend.get_colour(rock) == '#eeeeee' assert rock not in legend d = Decor({'colour': 'red', 'component': rock}) length = len(legend) legend[3] = d assert len(legend) == length assert legend[3].component == rock assert d in legend rock3 = Component(r3) assert legend.get_colour(rock3) == '#ffdbba' assert legend.get_width(rock3) == 3.0 c = legend.get_component('#f7e9a6') assert c.lithology == 'sandstone' c2 = legend.get_component('#f7e9a7', tolerance=30) assert c2.lithology == 'sandstone' colours = [d.colour for d in legend] assert len(colours) == 8 l = Legend.random([rock, rock3]) assert l != legend assert getattr(l[-1], 'colour') != '' assert l.to_csv() != '' summed = legend + l assert len(summed) == 10
def test_striplog_plot(): """ Tests mpl image of striplog. """ legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_img(imgfile, 14.3, 135.9, legend=legend) fig = striplog.thickest(n=5).plot(legend=legend, return_fig=True) return fig
def test_striplog_plot(): """ Tests mpl image of striplog """ legend = Legend.default() imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_img(imgfile, 14.3, 135.9, legend=legend) fig = striplog.thickest(n=5).plot(legend=legend) return fig
def test_striplog_plot(): """ Tests mpl image of striplog """ legend = Legend.builtin("NSDOE") imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_img(imgfile, 14.3, 135.9, legend=legend) fig = striplog.thickest(n=5).plot(legend=legend, return_fig=True) return fig
def test_from_image(): """Test the generation of a striplog from an image. """ legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_image(imgfile, 200, 300, legend=legend) assert len(striplog) == 26 assert striplog[-1].primary.summary() == 'Volcanic' assert np.floor(striplog.find('sandstone').cum) == 15 assert striplog.read_at(260).primary.lithology == 'siltstone' assert striplog.to_las3() != '' assert striplog.cum == 100.0 assert striplog.thickest().primary.lithology == 'anhydrite' assert striplog.thickest(n=7)[1].primary.lithology == 'sandstone' assert striplog.thinnest().primary.lithology == 'dolomite' assert striplog.thinnest(n=7)[1].primary.lithology == 'siltstone' # To and from log. log, basis, table = striplog.to_log(step=0.1524, return_meta=True) assert log[5] == 2.0 strip = Striplog.from_log(log, basis=basis, components=table) assert len(strip) == len(striplog) strip2 = Striplog.from_log(log, basis=basis, cutoff=3, legend=legend) assert len(strip2) == 18 # Extract log onto striplog. striplog.extract(log, basis=basis, name="Log", function=np.mean) assert striplog[0].data['Log'] == 2.0 # Indexing. indices = [2, 7, 20] del striplog[indices] assert len(striplog.find_gaps()) == len(indices) # Prune and anneal. striplog = striplog.prune(limit=1.0, keep_ends=True) assert len(striplog) == 14 striplog = striplog.anneal() assert not striplog.find_gaps() # Should be None striplog = striplog.merge_neighbours() assert len(striplog) == 11 rock = striplog.find('sandstone')[1].components[0] assert rock in striplog # Anneal up or down s = striplog[[1, 3]] assert s.anneal(mode='up')[1].top.z == s[0].base.z assert s.anneal(mode='down')[0].base.z == s[1].top.z
def test_error(): """Test errors are raised. """ rock = Component(r) # Adding incompatible things legend = Legend.from_csv(csv_text) with pytest.raises(LegendError): _ = legend + rock assert _ # Tolerance not allowed. with pytest.raises(LegendError): legend.get_component('#f7e9a7', tolerance=-1)
def test_striplog_ladder_plot(): """ Tests mpl image of striplog with the ladder option. """ legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_image(imgfile, 14.3, 135.9, legend=legend) fig = striplog.thickest(n=5).plot(legend=legend, ladder=True, return_fig=True) return fig
def test_error(): """Test errors are raised. """ rock = Component(r) # Adding incompatible things legend = Legend.from_csv(text=csv_text) with pytest.raises(LegendError): _ = legend + rock assert _ # Tolerance not allowed. with pytest.raises(LegendError): legend.get_component('#f7e9a7', tolerance=-1)
def test_well(): fname = 'tutorial/P-129_out.LAS' well = Well(fname) assert well.well.DATE.data == '10-Oct-2007' assert well.data['GR'][0] == 46.69865036 legend = Legend.default() f = 'tutorial/P-129_280_1935.png' name, start, stop = f.strip('.png').split('_') striplog = Striplog.from_img(f, float(start), float(stop), legend=legend, tolerance=35) well.add_striplog(striplog, "striplog") assert well.striplog.striplog.source == 'Image' assert well.striplog.striplog.start == 280.0 assert len(well.striplogs_to_las3()) == 14841
def test_striplog_colour_plot(): """ Tests mpl image of striplog with the ladder option. """ legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_image(imgfile, 14.3, 135.9, legend=legend) for iv in striplog: iv.data['porosity'] = iv.top.z / 100 fig = striplog.plot(colour='porosity', aspect=3, return_fig=True) return fig
def test_from_image(): """Test the generation of a striplog from an image. """ legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" striplog = Striplog.from_image(imgfile, 200, 300, legend=legend) assert len(striplog) == 26 assert striplog[-1].primary.summary() == 'Volcanic' assert np.floor(striplog.find('sandstone').cum) == 15 assert striplog.depth(260).primary.lithology == 'siltstone' assert striplog.to_las3() is not '' assert striplog.cum == 100.0 assert striplog.thickest().primary.lithology == 'anhydrite' assert striplog.thickest(n=7)[1].primary.lithology == 'sandstone' assert striplog.thinnest().primary.lithology == 'dolomite' assert striplog.thinnest(n=7)[1].primary.lithology == 'siltstone' # To and from log. log, basis, table = striplog.to_log(step=0.1524, return_meta=True) assert log[5] == 2.0 strip = Striplog.from_log(log, basis=basis, components=table) assert len(strip) == len(striplog) strip2 = Striplog.from_log(log, basis=basis, cutoff=3, legend=legend) assert len(strip2) == 18 # Extract log onto striplog. striplog.extract(log, basis=basis, name="Log", function=np.mean) assert striplog[0].data['Log'] == 2.0 # Indexing. indices = [2, 7, 20] del striplog[indices] assert len(striplog.find_gaps()) == len(indices) # Prune and anneal. striplog.prune(limit=1.0) assert len(striplog) == 14 striplog.anneal() assert not striplog.find_gaps() # Should be None rock = striplog.find('sandstone')[1].components[0] assert rock in striplog
def test_striplog_intersect(): """Test intersection. This example is from the tutorial. """ chrono = Striplog([Interval(**{'top': 0, 'base': 60, 'components': [Component({'age': 'Holocene'})] }), Interval(**{'top': 60, 'base': 75, 'components': [Component({'age': 'Palaeogene'})] }), Interval(**{'top': 75, 'base': 100, 'components': [Component({'age': 'Cretaceous'})] }), ]) legend = Legend.builtin('NSDOE') imgfile = "tutorial/M-MG-70_14.3_135.9.png" strip = Striplog.from_image(imgfile, 14.3, 135.9, legend=legend) sands = strip.find('sandstone') cretaceous = chrono.find('Palaeogene') cret_sand = sands.intersect(cretaceous) assert len(cret_sand) == 3 assert cret_sand.stop.z == 75
def plot(self, legend=None, fig_width=1.5, aspect=10, width_field=None, depth_field=None, wentworth='fine', exxon_style=False, yticks_right=False, set_ylim=True, xlim=None, ax=None, **kwargs): """ Plot as a ``Striplog`` of ``Bed``s. Parameters ---------- legend: striplog.Legend, optional If beds have primary component with 'lithology' field, will use ``defaults.litholegend``, otherwise random. fig_width: int, optional Width of figure, if creating one. aspect: int, optional Aspect ratio of figure, if creating one. width_field: str or int The ``Bed.data``` field or ``Bed.values`` column used to define polyon widths. depth_field : The ``Bed.data`` field or ``Bed.values`` column defining depths of ``width_field`` samples wentworth: one of {'fine', 'coarse'} Which Wentworth scale to use for xlabels/ticks. exxon_style: bool, optional Set to true to invert the x-axis (so GS increases to the left). yticks_right: bool, optional If True, will move yticks/labels to right side. Defualt=False. set_ylim: bool, optional Whether to set the y-limits of the ax to [self.start, self.stop]. Default=True. **kwargs : optional ylabelsize, yticksize, xlabelsize, xlabelrotation """ if legend is None: # If beds have lithology, use litholegend if hasattr(self[0].primary, 'lithology'): legend = defaults.litholegend # Fall back to random legend if not else: legend = Legend.random(self.components) # Set up an ax if necessary if ax is None: return_ax = False fig = plt.figure(figsize=(fig_width, aspect * fig_width)) ax = fig.add_axes([0.35, 0.05, 0.6, 0.95]) else: return_ax = True if set_ylim: ax.set_ylim([self.start.z, self.stop.z]) #print('Set_ylim: ', [self.start.z, self.stop.z]) # Determine xlimits if xlim is not None: min_width, max_width = xlim assert min_width < max_width, f'Is {xlim} a valid `xlim`?' elif width_field: # Set from the data if possible min_width = floor(self.min_field(width_field) - 1) max_width = ceil(self.max_field(width_field) + 1) else: # Fall back to component decors if not min_width = min(d.width for d in legend) - 1 max_width = legend.max_width + 1 ax.set_xlim([min_width, max_width]) set_wentworth_ticks(ax, min_width, max_width, wentworth=wentworth) # Plot the individual Beds as patches for bed in self: ax.add_patch( bed.as_patch(legend, width_field, depth_field, min_width, max_width, **kwargs)) # Finalize axis settings ybase, ytop = ax.get_ylim() if self.order is 'depth' and ytop > ybase: ax.invert_yaxis() if yticks_right: ax.yaxis.set_label_position('right') ax.yaxis.tick_right() if exxon_style: ax.invert_xaxis() # Tick params settable with kwargs ax.tick_params('y', which='major', labelsize=kwargs.get('ylabelsize', 16), size=kwargs.get('yticksize', 16)) ax.tick_params('x', which='minor', labelsize=kwargs.get('xlabelsize', 12), labelrotation=kwargs.get('xlabelrotation', 60)) if return_ax: return ax
__author__ = 'kiruba' import numpy as np import matplotlib.pyplot as plt import pandas as pd import itertools from striplog import striplog, Legend, Lexicon legend = Legend.default() lexicon = Lexicon.default() csv_string = """ 200.000, 230.329, Anhydrite 230.329, 233.269, Grey vf-f sandstone 233.269, 234.700, Anhydrite 234.700, 236.596, Dolomite 236.596, 237.911, Red siltstone 237.911, 238.723, Anhydrite 238.723, 239.807, Grey vf-f sandstone 239.807, 240.774, Red siltstone 240.774, 241.122, Dolomite 241.122, 241.702, Grey siltstone 241.702, 243.095, Dolomite 243.095, 246.654, Grey vf-f sandstone 246.654, 247.234, Dolomite 247.234, 255.435, Grey vf-f sandstone 255.435, 258.723, Grey siltstone 258.723, 259.729, Dolomite 259.729, 260.967, Grey siltstone 260.967, 261.354, Dolomite 261.354, 267.041, Grey siltstone
gravel_decor = Decor({ 'component': Component({'lithology': 'gravel'}), 'colour': '#ff9408', # 'xkcd:tangerine' 'hatch': 'o', 'width': 4 }) missing_decor = Decor({ 'component': Component({'lithology': 'missing'}), 'colour': '#ffffff', # 'xkcd:white' 'hatch': 'x', 'width': -1 }) litholegend = Legend([mud_decor, sand_decor, gravel_decor, missing_decor]) ###++++++++++++++++++++### ### Default csv fields ### ###++++++++++++++++++++### DEFAULT_FIELDS = {'top': 'tops', 'base': 'bases'} def gs2litho(gs, units='psi'): """ Map grainsize value `gs` to `striplog.Component`. If `gs` is None or np.nan, maps to 'missing' Component. If `units` is 'mm' or 'phi', will convert to 'psi' first.
# %% # welly plot with gempy colors # Create Decor list dec_list = [] for e, i in enumerate(striplog_dict['alpha']): dec_list.append( Decor({ '_colour': geo_model.surfaces.df.loc[e, 'color'], 'width': None, 'component': i.primary, 'hatch': None })) # Create legend legend = Legend(dec_list) legend # %% # Plot striplogs: f, a = plt.subplots(ncols=4, sharey=True) for e, log in enumerate(striplog_dict.items()): log[1].plot(ax=a[e], legend=legend) f.tight_layout() plt.show() # %% # Modifying the coordinates to make more sense geo_model.surface_points.df[['X', 'Y' ]] = geo_model.surface_points.df[['X', 'Y']] * 10
print('\n LAS PATH:', path, '\n') lasfiles = glob(path + '*.LAS') for fname in lasfiles: print(' '*5, fname) print('\n') # Get striplog files path2 = 'data/Poseidon_data/tops/' print('\n STRIP PATH:', path2, '\n') stripfiles = glob(path2 + '*.csv') for fname in stripfiles: print(' '*5, fname) print('\n') tops_legend = Legend.from_csv(filename='data/Poseidon_data/tops_legend.csv') p = Project.from_las('data/Poseidon_data/las/*.LAS') well_uwi = [w.uwi for w in p] ##gets the well uwi data for use in the well-selector tool # Add striplogs to Project # Striplog must have the same name as LAS file. # e.g. Torosa-1.LAS and Torosa-1.csv for w in p: name = Path(w.fname).name.split('.')[0] new_path = f'data/Poseidon_data/tops/{name}.csv' print(name, new_path) strip = Striplog.from_csv(f'data/Poseidon_data/tops/{name}.csv') w.data['tops'] = strip
return 'data:image/png;base64,{}'.format(encoded_image.decode()) app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) # Create server variable with Flask server object for use with gunicorn server = app.server # Get las files path = 'data/Poseidon_data/las/' # direct link to specific data lasfiles = glob(path + '*.LAS') # Get striplog files path2 = 'data/Poseidon_data/tops/' # direct link to specific data stripfiles = glob(path2 + '*.csv') legend = Legend.from_csv(filename='data/Poseidon_data/tops_legend.csv' ) # direct link to specific data p = Project.from_las( 'data/Poseidon_data/las/*.LAS') # direct link to specific data well_uwi = [w.uwi for w in p ] ##gets the well uwi data for use in the well-selector tool # Add striplogs to Project # Striplog must have the same name as LAS file. # e.g. Torosa-1.LAS and Torosa-1.csv for w in p: name = Path(w.fname).stem strip = Striplog.from_csv( f'data/Poseidon_data/tops/{name}.csv') # direct link to specific data w.data['tops'] = strip
def plot_feature_well(tc, gs): """ Plotting function for the feature well. Args: tc (TransectContainer): The container for the main plot. log (axis): A matplotlib axis. gs (GridSpec): A matplotlib gridspec. """ fname = tc.settings['curve_display'] logs = tc.log.get(tc.feature_well) if not logs: # There was no data for this well, so there won't be a feature plot. Notice.fail("There's no well data for feature well " + tc.feature_well) return gs Z = logs.data['DEPT'] curves = ['GR', 'DT', 'DPHI_SAN', 'NPHI_SAN', 'DTS', 'RT_HRLT', 'RHOB', 'DRHO'] window = tc.settings.get('curve_smooth_window') or 51 ntracks = 5 lw = 1.0 smooth = True naxes = 0 ncurv_per_track = np.zeros(ntracks) if getattr(tc.log, 'striplog', None): ncurv_per_track[0] = 1 for curve in curves: naxes += 1 params = get_curve_params(curve, fname) ncurv_per_track[params['track']] += 1 axss = plt.subplot(gs[2:, -5]) axs0 = [axss, axss.twiny()] axs1 = [plt.subplot(gs[2:, -4])] axs2 = [plt.subplot(gs[2:, -3])] axs3 = [plt.subplot(gs[2:, -2])] axs4 = [plt.subplot(gs[2:, -1])] axs = [axs0, axs1, axs2, axs3, axs4] if getattr(tc.log, 'striplog', None): legend = Legend.default() try: logs.striplog[tc.log.striplog].plot_axis(axs0[0], legend=legend) except KeyError: # In fact, this striplog doesn't exist. Notice.fail("There is no such striplog" + tc.log.striplog) # And move on... axs0[0].set_ylim([Z[-1], 0]) label_shift = np.zeros(len(axs)) for curve in curves: try: values = logs.data[curve] except ValueError: Notice.warning("Curve not present: "+curve) values = np.empty_like(Z) values[:] = np.nan params = get_curve_params(curve, fname) i = params['track'] j = 0 label_shift[i] += 1 linOrlog = params['logarithmic'] sxticks = np.array(params['xticks']) xticks = np.array(sxticks, dtype=float) whichticks = 'major' if linOrlog == 'log': midline = np.log(np.mean(xticks)) xpos = midline whichticks = 'minor' else: midline = np.mean(xticks) xpos = midline if smooth: values = utils.rolling_median(values, window) if curve == 'GR': j = 1 # second axis in first track label_shift[i] = 1 if params['fill_left_cond']: # do the fill for the lithology track axs[i][j].fill_betweenx(Z, params['xleft'], values, facecolor=params['fill_left'], alpha=1.0, zorder=11) if (curve == 'DPHI_SAN') and params['fill_left_cond']: # do the fill for the neutron porosity track try: nphi = utils.rolling_median(logs.data['NPHI_SAN'], window) except ValueError: Notice.warning("No NPHI in this well") nphi = np.empty_like(Z) nphi[:] = np.nan axs[i][j].fill_betweenx(Z, nphi, values, where=nphi >= values, facecolor=params['fill_left'], alpha=1.0, zorder=11) axs[i][j].fill_betweenx(Z, nphi, values, where=nphi <= values, facecolor='#8C1717', alpha=0.5, zorder=12) if curve == 'DRHO': blk_drho = 3.2 values += blk_drho # this is a hack to get DRHO on RHOB scale axs[i][j].fill_betweenx(Z, blk_drho, values, where=nphi <= values, facecolor='#CCCCCC', alpha=0.5, zorder=12) # fill right if params['fill_right_cond']: axs[i][j].fill_betweenx(Z, values, params['xright'], facecolor=params['fill_right'], alpha=1.0, zorder=12) # plot curve axs[i][j].plot(values, Z, color=params['hexcolor'], lw=lw, zorder=13) # set scale of curve axs[i][j].set_xlim([params['xleft'], params['xright']]) # ------------------------------------------------- # # curve labels # ------------------------------------------------- # trans = transforms.blended_transform_factory(axs[i][j].transData, axs[i][j].transData) magic = -Z[-1] / 12. axs[i][j].text(xpos, magic - (magic/4)*(label_shift[i]-1), curve, horizontalalignment='center', verticalalignment='bottom', fontsize=12, color=params['hexcolor'], transform=trans) # curve units units = '${}$'.format(params['units']) if label_shift[i] <= 1: axs[i][j].text(xpos, magic*0.5, units, horizontalalignment='center', verticalalignment='top', fontsize=12, color='k', transform=trans) # ------------------------------------------------- # # scales and tickmarks # ------------------------------------------------- # axs[i][j].set_xscale(linOrlog) axs[i][j].set_ylim([Z[-1], 0]) axs[i][j].axes.xaxis.set_ticks(xticks) axs[i][j].axes.xaxis.set_ticklabels(sxticks, fontsize=8) for label in axs[i][j].axes.xaxis.get_ticklabels(): label.set_rotation(90) axs[i][j].tick_params(axis='x', direction='out') axs[i][j].xaxis.tick_top() axs[i][j].xaxis.set_label_position('top') axs[i][j].xaxis.grid(True, which=whichticks, linewidth=0.25, linestyle='-', color='0.75', zorder=100) axs[i][j].yaxis.grid(True, which=whichticks, linewidth=0.25, linestyle='-', color='0.75', zorder=100) axs[i][j].yaxis.set_ticks(np.arange(0, max(Z), 100)) if i != 0: axs[i][j].set_yticklabels("") # ------------------------------------------------- # # End of curve loop # ------------------------------------------------- # # Add Depth label axs[0][0].text(0, 1.05, 'MD\n$m$', fontsize='10', horizontalalignment='center', verticalalignment='center', transform=axs[0][0].transAxes) axs[0][0].axes.yaxis.get_ticklabels() axs[0][0].axes.xaxis.set_ticklabels('') for label in axs[0][0].axes.yaxis.get_ticklabels(): label.set_rotation(90) label.set_fontsize(10) for label in axs[1][0].axes.xaxis.get_ticklabels(): label.set_rotation(90) label.set_fontsize(10) # Add Tops try: if os.path.exists(tc.tops_file): tops = utils.get_tops(tc.tops_file) topx = get_curve_params('DT', fname) topmidpt = np.amax((topx)['xright']) # plot tops for i in range(ntracks): for mkr, depth in tops.iteritems(): # draw horizontal bars at the top position axs[i][-1].axhline(y=depth, xmin=0.01, xmax=.99, color='b', lw=2, alpha=0.5, zorder=100) # draw text box at the right edge of the last track axs[-1][-1].text(x=topmidpt, y=depth, s=mkr, alpha=0.5, color='k', fontsize='8', horizontalalignment='center', verticalalignment='center', zorder=10000, bbox=dict(facecolor='white', edgecolor='k', alpha=0.25, lw=0.25), weight='light') except AttributeError: Notice.warning("No tops for this well") except TypeError: # We didn't get a tops file so move along. print "No tops for this well" return gs
def test_error(): legend = Legend.from_csv(csv_text) rock = Component(r) with pytest.raises(LegendError): legend + rock
def plot_feature_well(tc, gs): """ Plotting function for the feature well. Args: tc (TransectContainer): The container for the main plot. log (axis): A matplotlib axis. gs (GridSpec): A matplotlib gridspec. """ fname = tc.settings['curve_display'] logs = tc.log.get(tc.feature_well) if not logs: # There was no data for this well, so there won't be a feature plot. Notice.fail("There's no well data for feature well " + tc.feature_well) return gs Z = logs.data['DEPT'] curves = [ 'GR', 'DT', 'DPHI_SAN', 'NPHI_SAN', 'DTS', 'RT_HRLT', 'RHOB', 'DRHO' ] window = tc.settings.get('curve_smooth_window') or 51 ntracks = 5 lw = 1.0 smooth = True naxes = 0 ncurv_per_track = np.zeros(ntracks) if getattr(tc.log, 'striplog', None): ncurv_per_track[0] = 1 for curve in curves: naxes += 1 params = get_curve_params(curve, fname) ncurv_per_track[params['track']] += 1 axss = plt.subplot(gs[2:, -5]) axs0 = [axss, axss.twiny()] axs1 = [plt.subplot(gs[2:, -4])] axs2 = [plt.subplot(gs[2:, -3])] axs3 = [plt.subplot(gs[2:, -2])] axs4 = [plt.subplot(gs[2:, -1])] axs = [axs0, axs1, axs2, axs3, axs4] if getattr(tc.log, 'striplog', None): legend = Legend.default() try: logs.striplog[tc.log.striplog].plot_axis(axs0[0], legend=legend) except KeyError: # In fact, this striplog doesn't exist. Notice.fail("There is no such striplog" + tc.log.striplog) # And move on... axs0[0].set_ylim([Z[-1], 0]) label_shift = np.zeros(len(axs)) for curve in curves: try: values = logs.data[curve] except ValueError: Notice.warning("Curve not present: " + curve) values = np.empty_like(Z) values[:] = np.nan params = get_curve_params(curve, fname) i = params['track'] j = 0 label_shift[i] += 1 linOrlog = params['logarithmic'] sxticks = np.array(params['xticks']) xticks = np.array(sxticks, dtype=float) whichticks = 'major' if linOrlog == 'log': midline = np.log(np.mean(xticks)) xpos = midline whichticks = 'minor' else: midline = np.mean(xticks) xpos = midline if smooth: values = utils.rolling_median(values, window) if curve == 'GR': j = 1 # second axis in first track label_shift[i] = 1 if params['fill_left_cond']: # do the fill for the lithology track axs[i][j].fill_betweenx(Z, params['xleft'], values, facecolor=params['fill_left'], alpha=1.0, zorder=11) if (curve == 'DPHI_SAN') and params['fill_left_cond']: # do the fill for the neutron porosity track try: nphi = utils.rolling_median(logs.data['NPHI_SAN'], window) except ValueError: Notice.warning("No NPHI in this well") nphi = np.empty_like(Z) nphi[:] = np.nan axs[i][j].fill_betweenx(Z, nphi, values, where=nphi >= values, facecolor=params['fill_left'], alpha=1.0, zorder=11) axs[i][j].fill_betweenx(Z, nphi, values, where=nphi <= values, facecolor='#8C1717', alpha=0.5, zorder=12) if curve == 'DRHO': blk_drho = 3.2 values += blk_drho # this is a hack to get DRHO on RHOB scale axs[i][j].fill_betweenx(Z, blk_drho, values, where=nphi <= values, facecolor='#CCCCCC', alpha=0.5, zorder=12) # fill right if params['fill_right_cond']: axs[i][j].fill_betweenx(Z, values, params['xright'], facecolor=params['fill_right'], alpha=1.0, zorder=12) # plot curve axs[i][j].plot(values, Z, color=params['hexcolor'], lw=lw, zorder=13) # set scale of curve axs[i][j].set_xlim([params['xleft'], params['xright']]) # ------------------------------------------------- # # curve labels # ------------------------------------------------- # trans = transforms.blended_transform_factory(axs[i][j].transData, axs[i][j].transData) magic = -Z[-1] / 12. axs[i][j].text(xpos, magic - (magic / 4) * (label_shift[i] - 1), curve, horizontalalignment='center', verticalalignment='bottom', fontsize=12, color=params['hexcolor'], transform=trans) # curve units units = '${}$'.format(params['units']) if label_shift[i] <= 1: axs[i][j].text(xpos, magic * 0.5, units, horizontalalignment='center', verticalalignment='top', fontsize=12, color='k', transform=trans) # ------------------------------------------------- # # scales and tickmarks # ------------------------------------------------- # axs[i][j].set_xscale(linOrlog) axs[i][j].set_ylim([Z[-1], 0]) axs[i][j].axes.xaxis.set_ticks(xticks) axs[i][j].axes.xaxis.set_ticklabels(sxticks, fontsize=8) for label in axs[i][j].axes.xaxis.get_ticklabels(): label.set_rotation(90) axs[i][j].tick_params(axis='x', direction='out') axs[i][j].xaxis.tick_top() axs[i][j].xaxis.set_label_position('top') axs[i][j].xaxis.grid(True, which=whichticks, linewidth=0.25, linestyle='-', color='0.75', zorder=100) axs[i][j].yaxis.grid(True, which=whichticks, linewidth=0.25, linestyle='-', color='0.75', zorder=100) axs[i][j].yaxis.set_ticks(np.arange(0, max(Z), 100)) if i != 0: axs[i][j].set_yticklabels("") # ------------------------------------------------- # # End of curve loop # ------------------------------------------------- # # Add Depth label axs[0][0].text(0, 1.05, 'MD\n$m$', fontsize='10', horizontalalignment='center', verticalalignment='center', transform=axs[0][0].transAxes) axs[0][0].axes.yaxis.get_ticklabels() axs[0][0].axes.xaxis.set_ticklabels('') for label in axs[0][0].axes.yaxis.get_ticklabels(): label.set_rotation(90) label.set_fontsize(10) for label in axs[1][0].axes.xaxis.get_ticklabels(): label.set_rotation(90) label.set_fontsize(10) # Add Tops try: if os.path.exists(tc.tops_file): tops = utils.get_tops(tc.tops_file) topx = get_curve_params('DT', fname) topmidpt = np.amax((topx)['xright']) # plot tops for i in range(ntracks): for mkr, depth in tops.iteritems(): # draw horizontal bars at the top position axs[i][-1].axhline(y=depth, xmin=0.01, xmax=.99, color='b', lw=2, alpha=0.5, zorder=100) # draw text box at the right edge of the last track axs[-1][-1].text(x=topmidpt, y=depth, s=mkr, alpha=0.5, color='k', fontsize='8', horizontalalignment='center', verticalalignment='center', zorder=10000, bbox=dict(facecolor='white', edgecolor='k', alpha=0.25, lw=0.25), weight='light') except AttributeError: Notice.warning("No tops for this well") except TypeError: # We didn't get a tops file so move along. print "No tops for this well" return gs
__author__ = 'kiruba' import numpy as np import matplotlib.pyplot as plt import pandas as pd import itertools from striplog import striplog, Legend, Lexicon legend = Legend.default() lexicon = Lexicon.default() csv_string = """ 200.000, 230.329, Anhydrite 230.329, 233.269, Grey vf-f sandstone 233.269, 234.700, Anhydrite 234.700, 236.596, Dolomite 236.596, 237.911, Red siltstone 237.911, 238.723, Anhydrite 238.723, 239.807, Grey vf-f sandstone 239.807, 240.774, Red siltstone 240.774, 241.122, Dolomite 241.122, 241.702, Grey siltstone 241.702, 243.095, Dolomite 243.095, 246.654, Grey vf-f sandstone 246.654, 247.234, Dolomite 247.234, 255.435, Grey vf-f sandstone 255.435, 258.723, Grey siltstone 258.723, 259.729, Dolomite 259.729, 260.967, Grey siltstone 260.967, 261.354, Dolomite 261.354, 267.041, Grey siltstone 267.041, 267.350, Dolomite 267.350, 274.004, Grey siltstone