signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@callback_register.register("<STR_LIT>")<EOL>@dice_result(higher_than=<NUM_LIT:3>)<EOL>def print_high_result(result):
print("<STR_LIT>" % result)<EOL>assert result > <NUM_LIT:3><EOL>
Function that prints all higher than 3 rolls.
f13339:m3
@callback_register.register("<STR_LIT>")<EOL>@dice_result(equal=<NUM_LIT:3>)<EOL>def print_three_message(result):
print("<STR_LIT>" % result)<EOL>assert result == <NUM_LIT:3><EOL>
Function that prints all results equal to 3.
f13339:m4
@callback_register.register("<STR_LIT>")<EOL>@dice_result(equal=<NUM_LIT:2>)<EOL>def print_two_message(result):
print("<STR_LIT>" % result)<EOL>assert result == <NUM_LIT:2><EOL>
Function that prints all results equal to 2.
f13339:m5
@callback_register.register("<STR_LIT>")<EOL>@dice_result(equal=<NUM_LIT:1>)<EOL>def print_one_message(result):
print("<STR_LIT>" % result)<EOL>assert result == <NUM_LIT:1><EOL>
Function that prints all results equal to 1.
f13339:m6
@classmethod<EOL><INDENT>def setup_class(cls):<DEDENT>
class Register(SequenceModel):<EOL><INDENT>id = AttributeField(ID())<EOL>name = CharField()<EOL>addressOffset = IntegerField()<EOL>size = ModelField(Size)<EOL>class Meta:<EOL><INDENT>sequence = [<EOL>SequenceElement('<STR_LIT:name>', min_occurs=<NUM_LIT:1>),<EOL>SequenceElement('<STR_LIT>', min_occurs=<NUM_LIT:1>),<EOL...
setup any state specific to the execution of the given class (which usually contains tests).
f13340:c0:m0
@classmethod<EOL><INDENT>def setup_class(cls):<DEDENT>
class Register(Model):<EOL><INDENT>id = AttributeField(ID())<EOL>name = CharField()<EOL>addressOffset = IntegerField()<EOL>size = ModelField(Size)<EOL><DEDENT>register_dict = {<EOL>'<STR_LIT:name>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:0>',<EOL>'<STR_LIT:size>': {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR...
setup any state specific to the execution of the given class (which usually contains tests).
f13340:c1:m0
def parse_time(timestring):
timestring = str(timestring).strip()<EOL>for regex, pattern in TIME_FORMATS:<EOL><INDENT>if regex.match(timestring):<EOL><INDENT>found = regex.search(timestring).groupdict()<EOL>dt = datetime.utcnow().strptime(found['<STR_LIT:time>'], pattern)<EOL>dt = datetime.combine(date.today(), dt.time())<EOL>if '<STR_LIT>' in fou...
Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object.
f13346:m1
def parse(representation):
representation = str(representation).upper().strip()<EOL>return parse_date(representation)<EOL>
Attempts to parse an ISO8601 formatted ``representation`` string, which could be of any valid ISO8601 format (date, time, duration, interval). Return value is specific to ``representation``.
f13349:m0
def get_source(self, key, name_spaces=None, default_prefix='<STR_LIT>'):
source = self.source or key<EOL>prefix = default_prefix<EOL>if name_spaces and self.name_space and self.name_space in name_spaces:<EOL><INDENT>prefix = '<STR_LIT>'.join([name_spaces[self.name_space], '<STR_LIT::>'])<EOL><DEDENT>return '<STR_LIT>'.join([prefix, source])<EOL>
Generates the dictionary key for the serialized representation based on the instance variable source and a provided key. :param str key: name of the field in model :returns: self.source or key
f13351:c1:m3
def validate(self, raw_data, **kwargs):
return raw_data<EOL>
The validate method validates raw_data against the field . :param raw_data: raw data for field :type raw_data: str or other valid formats :returns: validated_data :raises ValidationException: if self.required and raw_data is None
f13351:c1:m4
def validate(self, raw_data, **kwargs):
try:<EOL><INDENT>converted_data = int(raw_data)<EOL>return super(IntegerField, self).validate(converted_data)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValidationException(self.messages['<STR_LIT>'], repr(raw_data))<EOL><DEDENT>
Convert the raw_data to an integer.
f13351:c12:m1
def validate(self, raw_data, **kwargs):
try:<EOL><INDENT>converted_data = float(raw_data)<EOL>super(FloatField, self).validate(converted_data, **kwargs)<EOL>return raw_data<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValidationException(self.messages['<STR_LIT>'], repr(raw_data))<EOL><DEDENT>
Convert the raw_data to a float.
f13351:c16:m1
def validate(self, raw_data, **kwargs):
super(BooleanField, self).validate(raw_data, **kwargs)<EOL>if isinstance(raw_data, string_types):<EOL><INDENT>valid_data = raw_data.strip().lower() == '<STR_LIT:true>'<EOL><DEDENT>elif isinstance(raw_data, bool):<EOL><INDENT>valid_data = raw_data<EOL><DEDENT>else:<EOL><INDENT>valid_data = raw_data > <NUM_LIT:0><EOL><DE...
The string ``'True'`` (case insensitive) will be converted to ``True``, as will any positive integers.
f13351:c18:m0
def validate(self, raw_data, **kwargs):
super(DateTimeField, self).validate(raw_data, **kwargs)<EOL>try:<EOL><INDENT>if isinstance(raw_data, datetime.datetime):<EOL><INDENT>self.converted = raw_data<EOL><DEDENT>elif self.serial_format is None:<EOL><INDENT>self.converted = parse(raw_data)<EOL><DEDENT>else:<EOL><INDENT>self.converted = datetime.datetime.strpti...
The raw_data is returned unchanged.
f13351:c20:m1
def deserialize(self, raw_data, **kwargs):
super(DateTimeField, self).deserialize(raw_data, **kwargs)<EOL>return self.converted<EOL>
A :class:`datetime.datetime` object is returned.
f13351:c20:m2
@classmethod<EOL><INDENT>def from_dict(cls, raw_data, **kwargs):<DEDENT>
instance = cls()<EOL>instance.populate(raw_data, **kwargs)<EOL>instance.validate(**kwargs)<EOL>return instance<EOL>
This factory for :class:`Model` creates a Model from a dict object.
f13355:c4:m5
def tt2nav(toctree, klass=None, appendix=None, divider=False):
tt = toctree<EOL>divider = '<STR_LIT>' if divider else '<STR_LIT>'<EOL>if appendix:<EOL><INDENT>tt = re.sub(r'<STR_LIT>', r'<STR_LIT>'.format(appendix), tt)<EOL><DEDENT>tt = re.sub(r'<STR_LIT>', r'<STR_LIT>', tt)<EOL>if klass:<EOL><INDENT>tt = re.sub(r'<STR_LIT>', r'<STR_LIT>'.format(klass), tt)<EOL>
Injects ``has-dropdown`` and ``dropdown`` classes to HTML generated by the :func:`toctree` function. :param str toctree: HTML generated by the :func:`toctree` function.
f13359:m0
def patch_connection(filename='<STR_LIT>'):
if no_redis:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>RliteConnection.set_file(filename)<EOL>global orig_classes<EOL>if orig_classes:<EOL><INDENT>return<EOL><DEDENT>orig_classes = (redis.connection.Connection,<EOL>redis.connection.ConnectionPool)<EOL>_set_classes(RliteConnection, RliteConnectionPool)<EOL>
``filename``: rlite filename to store db in, or memory Patch the redis-py Connection and the static from_url() of Redis and StrictRedis to use RliteConnection
f13362:m0
@contextmanager<EOL>def patch(filename='<STR_LIT>'):
patch_connection(filename)<EOL>yield<EOL>unpatch_connection()<EOL>
Context manager version of patch_connection/unpatch_connection
f13362:m2
def open(filename, mode = '<STR_LIT:r>', iline = <NUM_LIT>,<EOL>xline = <NUM_LIT>,<EOL>strict = True,<EOL>ignore_geometry = False,<EOL>endian = '<STR_LIT>' ):
if '<STR_LIT:w>' in mode:<EOL><INDENT>problem = '<STR_LIT>'<EOL>solution = '<STR_LIT>'<EOL>raise ValueError('<STR_LIT:U+002CU+0020>'.join((problem, solution)))<EOL><DEDENT>endians = {<EOL>'<STR_LIT>': <NUM_LIT>, <EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>}<EOL>if endian...
Open a seismic unix file. Behaves identically to open(), except it expects the seismic unix format, not SEG-Y. Parameters ---------- filename : str Path to file to open mode : {'r', 'r+'} File access mode, read-only ('r', default) or read-write ('r+') iline : int or segyi...
f13371:m0
def create(filename, spec):
from . import _segyio<EOL>if not structured(spec):<EOL><INDENT>tracecount = spec.tracecount<EOL><DEDENT>else:<EOL><INDENT>tracecount = len(spec.ilines) * len(spec.xlines) * len(spec.offsets)<EOL><DEDENT>ext_headers = spec.ext_headers if hasattr(spec, '<STR_LIT>') else <NUM_LIT:0><EOL>samples = numpy.asarray(spec.sample...
Create a new segy file. Create a new segy file with the geometry and properties given by `spec`. This enables creating SEGY files from your data. The created file supports all segyio modes, but has an emphasis on writing. The spec must be complete, otherwise an exception will be raised. A default, empt...
f13373:m2
def flush(self):
self.xfd.flush()<EOL>
Flush the file Write the library buffers to disk, like C's ``fflush``. This method is mostly useful for testing. It is not necessary to call this method unless you want to observe your changes on-disk while the file is still open. The file will automatically be flushed for you ...
f13375:c0:m5
def close(self):
self.xfd.close()<EOL>
Close the file This method is mostly useful for testing. It is not necessary to call this method if you're using the `with` statement, which will close the file for you. Calling methods on a previously-closed file will raise `IOError`. Notes ----- .. versionad...
f13375:c0:m6
def mmap(self):
return self.xfd.mmap()<EOL>
Memory map the file Memory map the file. This is an advanced feature for speed and optimization; however, it is no silver bullet. If your file is smaller than the memory available on your system this will likely result in faster reads and writes, especially for line modes. However, if t...
f13375:c0:m7
@property<EOL><INDENT>def dtype(self):<DEDENT>
return self._dtype<EOL>
The data type object of the traces. This is the format most accurate and efficient to exchange with the underlying file, and the data type you will find the data traces. Returns ------- dtype : numpy.dtype Notes ----- .. versionadded:: 1.6
f13375:c0:m8
@property<EOL><INDENT>def sorting(self):<DEDENT>
return self._sorting<EOL>
Inline or crossline sorting, or Falsey (None or 0) if unstructured. Returns ------- sorting : int
f13375:c0:m9
@property<EOL><INDENT>def tracecount(self):<DEDENT>
return self._tracecount<EOL>
Number of traces in this file Equivalent to ``len(f.trace)`` Returns ------- count : int Number of traces in this file
f13375:c0:m10
@property<EOL><INDENT>def samples(self):<DEDENT>
return self._samples<EOL>
Return the array of samples with appropriate intervals. Returns ------- samples : numpy.ndarray of int Notes ----- It holds that ``len(f.samples) == len(f.trace[0])``
f13375:c0:m11
@property<EOL><INDENT>def offsets(self):<DEDENT>
return self._offsets<EOL>
Return the array of offset names. For post-stack data, this array has a length of 1 Returns ------- offsets : numpy.ndarray of int
f13375:c0:m12
@property<EOL><INDENT>def ext_headers(self):<DEDENT>
return self._ext_headers<EOL>
Extra text headers The number of extra text headers, given by the ``ExtendedHeaders`` field in the binary header. Returns ------- headers : int Number of extra text headers
f13375:c0:m13
@property<EOL><INDENT>def unstructured(self):<DEDENT>
return self.ilines is None<EOL>
If the file is unstructured, sophisticated addressing modes that require the file to represent a proper cube won't work, and only raw data reading and writing is supported. Returns ------- unstructured : bool ``True`` if this file is unstructured, ``False`` if not
f13375:c0:m14
@property<EOL><INDENT>def header(self):<DEDENT>
return self._header<EOL>
Interact with segy in header mode Returns ------- header : Header Notes ----- .. versionadded:: 1.1
f13375:c0:m15
@header.setter<EOL><INDENT>def header(self, val):<DEDENT>
self.header[:] = val<EOL>
headers macro assignment A convenient way for operating on all headers of a file is to use the default full-file range. It will write headers 0, 1, ..., n, but uses the iteration specified by the right-hand side (i.e. can skip headers etc). If the right-hand-side headers are e...
f13375:c0:m16
def attributes(self, field):
return Attributes(field, self.xfd, self.tracecount)<EOL>
File-wide attribute (header word) reading Lazily gather a single header word for every trace in the file. The array can be sliced, supports index lookup, and numpy-style list-of-indices. Parameters ---------- field : int or segyio.TraceField field ...
f13375:c0:m17
@property<EOL><INDENT>def trace(self):<DEDENT>
return self._trace<EOL>
Interact with segy in trace mode. Returns ------- trace : Trace Notes ----- .. versionadded:: 1.1
f13375:c0:m18
@trace.setter<EOL><INDENT>def trace(self, val):<DEDENT>
self.trace[:] = val<EOL>
traces macro assignment Convenient way for setting traces from 0, 1, ... n, based on the iterable set of traces on the right-hand-side. If the right-hand-side traces are exhausted before all the destination file traces the writing will stop, i.e. not all all traces in the desti...
f13375:c0:m19
@property<EOL><INDENT>def ilines(self):<DEDENT>
return self._ilines<EOL>
Inline labels The inline labels in this file, if structured, else None Returns ------- inlines : array_like of int or None
f13375:c0:m20
@property<EOL><INDENT>def iline(self):<DEDENT>
if self.unstructured:<EOL><INDENT>raise ValueError(self._unstructured_errmsg)<EOL><DEDENT>if self._iline is not None:<EOL><INDENT>return self._iline<EOL><DEDENT>self._iline = Line(self,<EOL>self.ilines,<EOL>self._iline_length,<EOL>self._iline_stride,<EOL>self.offsets,<EOL>'<STR_LIT>',<EOL>)<EOL>return self._iline<EOL>
Interact with segy in inline mode Returns ------- iline : Line or None Raises ------ ValueError If the file is unstructured Notes ----- .. versionadded:: 1.1
f13375:c0:m21
@iline.setter<EOL><INDENT>def iline(self, value):<DEDENT>
self.iline[:] = value<EOL>
inlines macro assignment Convenient way for setting inlines, from left-to-right as the inline numbers are specified in the file.ilines property, from an iterable set on the right-hand-side. If the right-hand-side inlines are exhausted before all the destination file inlines the...
f13375:c0:m22
@property<EOL><INDENT>def xlines(self):<DEDENT>
return self._xlines<EOL>
Crossline labels The crosslane labels in this file, if structured, else None Returns ------- crosslines : array_like of int or None
f13375:c0:m23
@property<EOL><INDENT>def xline(self):<DEDENT>
if self.unstructured:<EOL><INDENT>raise ValueError(self._unstructured_errmsg)<EOL><DEDENT>if self._xline is not None:<EOL><INDENT>return self._xline<EOL><DEDENT>self._xline = Line(self,<EOL>self.xlines,<EOL>self._xline_length,<EOL>self._xline_stride,<EOL>self.offsets,<EOL>'<STR_LIT>',<EOL>)<EOL>return self._xline<EOL>
Interact with segy in crossline mode Returns ------- xline : Line or None Raises ------ ValueError If the file is unstructured Notes ----- .. versionadded:: 1.1
f13375:c0:m24
@xline.setter<EOL><INDENT>def xline(self, value):<DEDENT>
self.xline[:] = value<EOL>
crosslines macro assignment Convenient way for setting crosslines, from left-to-right as the inline numbers are specified in the file.ilines property, from an iterable set on the right-hand-side. If the right-hand-side inlines are exhausted before all the destination file inlin...
f13375:c0:m25
@property<EOL><INDENT>def fast(self):<DEDENT>
if self.sorting == TraceSortingFormat.INLINE_SORTING:<EOL><INDENT>return self.iline<EOL><DEDENT>elif self.sorting == TraceSortingFormat.CROSSLINE_SORTING:<EOL><INDENT>return self.xline<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>
Access the 'fast' dimension This mode yields iline or xline mode, depending on which one is laid out `faster`, i.e. the line with linear disk layout. Use this mode if the inline/crossline distinction isn't as interesting as traversing in a fast manner (typically when you want to apply a...
f13375:c0:m26
@property<EOL><INDENT>def slow(self):<DEDENT>
if self.sorting == TraceSortingFormat.INLINE_SORTING:<EOL><INDENT>return self.xline<EOL><DEDENT>elif self.sorting == TraceSortingFormat.CROSSLINE_SORTING:<EOL><INDENT>return self.iline<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>
Access the 'slow' dimension This mode yields iline or xline mode, depending on which one is laid out `slower`, i.e. the line with strided disk layout. Use this mode if the inline/crossline distinction isn't as interesting as traversing in the slower direction. Returns -...
f13375:c0:m27
@property<EOL><INDENT>def depth_slice(self):<DEDENT>
if self.depth is not None:<EOL><INDENT>return self.depth<EOL><DEDENT>from .depth import Depth<EOL>self.depth = Depth(self)<EOL>return self.depth<EOL>
Interact with segy in depth slice mode (fixed z-coordinate) Returns ------- depth : Depth Notes ----- .. versionadded:: 1.1 .. versionchanged:: 1.7.1 enabled for unstructured files
f13375:c0:m28
@depth_slice.setter<EOL><INDENT>def depth_slice(self, value):<DEDENT>
self.depth_slice[:] = value<EOL>
depth macro assignment Convenient way for setting depth slices, from left-to-right as the depth slices numbers are specified in the file.depth_slice property, from an iterable set on the right-hand-side. If the right-hand-side depth slices are exhausted before all the destination ...
f13375:c0:m29
@property<EOL><INDENT>def gather(self):<DEDENT>
if self.unstructured:<EOL><INDENT>raise ValueError(self._unstructured_errmsg)<EOL><DEDENT>if self._gather is not None:<EOL><INDENT>return self._gather<EOL><DEDENT>self._gather = Gather(self.trace, self.iline, self.xline, self.offsets)<EOL>return self._gather<EOL>
Interact with segy in gather mode Returns ------- gather : Gather
f13375:c0:m30
@property<EOL><INDENT>def text(self):<DEDENT>
return Text(self.xfd, self._ext_headers + <NUM_LIT:1>)<EOL>
Interact with segy in text mode This mode gives access to reading and writing functionality for textual headers. The primary data type is the python string. Reading textual headers is done with ``[]``, and writing is done via assignment. No additional structure is built around ...
f13375:c0:m31
@property<EOL><INDENT>def bin(self):<DEDENT>
return Field.binary(self)<EOL>
Interact with segy in binary mode This mode gives access to reading and writing functionality for the binary header. Please note that using numeric binary offsets uses the offset numbers from the specification, i.e. the first field of the binary header starts at 3201, not 1. If you're using the enumerations this is ha...
f13375:c0:m32
@bin.setter<EOL><INDENT>def bin(self, value):<DEDENT>
self.bin.update(value)<EOL>
Update binary header Update a value or replace the binary header Parameters ---------- value : dict_like dict_like, keys of int or segyio.BinField or segyio.su
f13375:c0:m33
@property<EOL><INDENT>def readonly(self):<DEDENT>
return '<STR_LIT:+>' not in self._mode<EOL>
File is read-only Returns ------- readonly : bool True if this file is read-only Notes ----- .. versionadded:: 1.6
f13375:c0:m35
def interpret(self, ilines, xlines, offsets=None, sorting=TraceSortingFormat.INLINE_SORTING):
valid_sortings = {<EOL><NUM_LIT:1> : TraceSortingFormat.CROSSLINE_SORTING,<EOL><NUM_LIT:2> : TraceSortingFormat.INLINE_SORTING,<EOL>'<STR_LIT>' : TraceSortingFormat.INLINE_SORTING,<EOL>'<STR_LIT>' : TraceSortingFormat.INLINE_SORTING,<EOL>'<STR_LIT>' : TraceSortingFormat.CROSSLINE_SORTI...
(Re-)interpret structure on top of a file (Re-)interpret the structure of the file given the new sorting, ilines, xlines and offset indices. Note that file itself is not changed in any way, it is only segyio's interpretation of the file that changes. It's a way of telling segyio that a ...
f13375:c0:m36
def __getitem__(self, i):
try:<EOL><INDENT>i = self.wrapindex(i)<EOL>buf = np.empty(self.shape, dtype=self.dtype)<EOL>return self.filehandle.getdepth(i, buf.size, self.offsets, buf)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise...
depth[i] ith depth, a horizontal cross-section of the file, starting at 0. depth[i] returns a numpy.ndarray, and changes to this array will *not* be reflected on disk. When i is a slice, a generator of numpy.ndarray is returned. The depth slices are returned as a fast-by-slow ...
f13377:c0:m1
def __setitem__(self, depth, val):
if isinstance(depth, slice):<EOL><INDENT>for i, x in zip(range(*depth.indices(len(self))), val):<EOL><INDENT>self[i] = x<EOL><DEDENT>return<EOL><DEDENT>val = castarray(val, dtype = self.dtype)<EOL>self.filehandle.putdepth(depth, val.size, self.offsets, val)<EOL>
depth[i] = val Write the ith depth, a horizontal cross-section, of the file, starting at 0. It accepts any array_like, but `val` must be at least as big as the underlying data slice. If `val` is longer than the underlying trace, `val` is essentially truncated. Parameters ...
f13377:c0:m2
def open(filename, mode="<STR_LIT:r>", iline = <NUM_LIT>,<EOL>xline = <NUM_LIT>,<EOL>strict = True,<EOL>ignore_geometry = False,<EOL>endian = '<STR_LIT>'):
if '<STR_LIT:w>' in mode:<EOL><INDENT>problem = '<STR_LIT>'<EOL>solution = '<STR_LIT>'<EOL>raise ValueError('<STR_LIT:U+002CU+0020>'.join((problem, solution)))<EOL><DEDENT>endians = {<EOL>'<STR_LIT>': <NUM_LIT>, <EOL>'<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>}<EOL>if endian...
Open a segy file. Opens a segy file and tries to figure out its sorting, inline numbers, crossline numbers, and offsets, and enables reading and writing to this file in a simple manner. For reading, the access mode `r` is preferred. All write operations will raise an exception. For writing, the mo...
f13378:m1
def __getitem__(self, index):
if len(index) < <NUM_LIT:3>:<EOL><INDENT>index = (index[<NUM_LIT:0>], index[<NUM_LIT:1>], None)<EOL><DEDENT>il, xl, off = index<EOL>if off is None and len(self.offsets) == <NUM_LIT:1>:<EOL><INDENT>off = self.offsets[<NUM_LIT:0>]<EOL><DEDENT>off = off or slice(None)<EOL>def isslice(x): return isinstance(x, slice)<EOL>if...
gather[i, x, o], gather[:,:,:] Get the gather or range of gathers, defined as offsets intersection between an in- and a crossline. Also works on post-stack files (with only 1 offset), although it is less useful in those cases. If offsets are omitted, the default is all offsets. ...
f13381:c0:m1
def __len__(self):
return self.length<EOL>
x.__len__() <==> len(x)
f13382:c0:m1
def __iter__(self):
<EOL>return self[:]<EOL>
x.__iter__() <==> iter(x)
f13382:c0:m2
def __getitem__(self, i):
try:<EOL><INDENT>i = self.wrapindex(i)<EOL>buf = np.zeros(self.shape, dtype = self.dtype)<EOL>return self.filehandle.gettr(buf, i, <NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>msg = '<STR_LIT>'<EOL>rais...
trace[i] ith trace of the file, starting at 0. trace[i] returns a numpy array, and changes to this array will *not* be reflected on disk. When i is a slice, a generator of numpy arrays is returned. Parameters ---------- i : int or slice Returns -------...
f13382:c1:m1
def __setitem__(self, i, val):
if isinstance(i, slice):<EOL><INDENT>for j, x in zip(range(*i.indices(len(self))), val):<EOL><INDENT>self[j] = x<EOL><DEDENT>return<EOL><DEDENT>xs = castarray(val, self.dtype)<EOL>self.filehandle.puttr(self.wrapindex(i), xs)<EOL>
trace[i] = val Write the ith trace of the file, starting at 0. It accepts any array_like, but val must be at least as big as the underlying data trace. If val is longer than the underlying trace, it is essentially truncated. For the best performance, val should be a nu...
f13382:c1:m2
@property<EOL><INDENT>def raw(self):<DEDENT>
return RawTrace(self.filehandle,<EOL>self.dtype,<EOL>len(self),<EOL>self.shape,<EOL>self.readonly,<EOL>)<EOL>
An eager version of Trace Returns ------- raw : RawTrace
f13382:c1:m4
@property<EOL><INDENT>@contextlib.contextmanager<EOL>def ref(self):<DEDENT>
x = RefTrace(self.filehandle,<EOL>self.dtype,<EOL>len(self),<EOL>self.shape,<EOL>self.readonly,<EOL>)<EOL>yield x<EOL>x.flush()<EOL>
A write-back version of Trace Returns ------- ref : RefTrace `ref` is returned in a context manager, and must be in a ``with`` statement Notes ----- .. versionadded:: 1.6 Examples -------- >>> with trace.ref as ref: ... ref[10] += 1.617
f13382:c1:m5
def __getitem__(self, i):
try:<EOL><INDENT>i = self.wrapindex(i)<EOL>buf = np.zeros(self.shape, dtype = self.dtype)<EOL>return self.filehandle.gettr(buf, i, <NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>msg = '<STR_LIT>'<EOL>rais...
trace[i] Eagerly read the ith trace of the file, starting at 0. trace[i] returns a numpy array, and changes to this array will *not* be reflected on disk. When i is a slice, this returns a 2-dimensional numpy.ndarray . Parameters ---------- i : int or slice ...
f13382:c2:m1
def flush(self):
garbage = []<EOL>for i, (x, signature) in self.refs.items():<EOL><INDENT>if sys.getrefcount(x) == <NUM_LIT:3>:<EOL><INDENT>garbage.append(i)<EOL><DEDENT>if fingerprint(x) == signature: continue<EOL>self.filehandle.puttr(i, x)<EOL>signature = fingerprint(x)<EOL><DEDENT>for i in garbage:<EOL><INDENT>del self.refs[i]<EOL>...
Commit cached writes to the file handle. Does not flush libc buffers or notifies the kernel, so these changes may not immediately be visible to other processes. Updates the fingerprints whena writes happen, so successive ``flush()`` invocations are no-ops. It is not necessary to call this method in user code. Notes ...
f13382:c3:m1
def __getitem__(self, i):
try:<EOL><INDENT>i = self.wrapindex(i)<EOL>if i in self.refs:<EOL><INDENT>return self.refs[i][<NUM_LIT:0>]<EOL><DEDENT>x = self.fetch(i)<EOL>self.refs[i] = (x, fingerprint(x))<EOL>return x<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><I...
trace[i] Read the ith trace of the file, starting at 0. trace[i] returns a numpy array, but unlike Trace, changes to this array *will* be reflected on disk. The modifications must happen to the actual array (views are ok), so in-place operations work, but assignments will not:: ...
f13382:c3:m3
def __getitem__(self, i):
try:<EOL><INDENT>i = self.wrapindex(i)<EOL>return Field.trace(traceno = i, segy = self.segy)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise TypeError(msg.format(type(i).__name__))<EOL><DEDENT>def gen():...
header[i] ith header of the file, starting at 0. Parameters ---------- i : int or slice Returns ------- field : Field dict_like header Notes ----- .. versionadded:: 1.1 Behaves like [] for lists. Examples ...
f13382:c4:m1
def __setitem__(self, i, val):
x = self[i]<EOL>try:<EOL><INDENT>x.update(val)<EOL><DEDENT>except AttributeError:<EOL><INDENT>if isinstance(val, Field) or isinstance(val, dict):<EOL><INDENT>val = itertools.repeat(val)<EOL><DEDENT>for h, v in zip(x, val):<EOL><INDENT>h.update(v)<EOL><DEDENT><DEDENT>
header[i] = val Write the ith header of the file, starting at 0. Unlike data traces (which return numpy.ndarrays), changes to returned headers being iterated over *will* be reflected on disk. Parameters ---------- i : int or slice val : Field or array_like of ...
f13382:c4:m2
@property<EOL><INDENT>def iline(self):<DEDENT>
return HeaderLine(self, self.segy.iline, '<STR_LIT>')<EOL>
Headers, accessed by inline Returns ------- line : HeaderLine
f13382:c4:m3
@iline.setter<EOL><INDENT>def iline(self, value):<DEDENT>
for i, src in zip(self.segy.ilines, value):<EOL><INDENT>self.iline[i] = src<EOL><DEDENT>
Write iterables to lines Examples: Supports writing to *all* crosslines via assignment, regardless of data source and format. Will respect the sample size and structure of the file being assigned to, so if the argument traces are longer than that of the file bein...
f13382:c4:m4
@property<EOL><INDENT>def xline(self):<DEDENT>
return HeaderLine(self, self.segy.xline, '<STR_LIT>')<EOL>
Headers, accessed by crossline Returns ------- line : HeaderLine
f13382:c4:m5
@xline.setter<EOL><INDENT>def xline(self, value):<DEDENT>
for i, src in zip(self.segy.xlines, value):<EOL><INDENT>self.xline[i] = src<EOL><DEDENT>
Write iterables to lines Examples: Supports writing to *all* crosslines via assignment, regardless of data source and format. Will respect the sample size and structure of the file being assigned to, so if the argument traces are longer than that of the file bein...
f13382:c4:m6
def __getitem__(self, i):
try:<EOL><INDENT>xs = np.asarray(i, dtype = self.dtype)<EOL>xs = xs.astype(dtype = self.dtype, order = '<STR_LIT:C>', copy = False)<EOL>attrs = np.empty(len(xs), dtype = self.dtype)<EOL>return self.filehandle.field_foreach(attrs, xs, self.field)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>i = slice(i, i ...
attributes[:] Parameters ---------- i : int or slice or array_like Returns ------- attributes : array_like of dtype Examples -------- Read all unique sweep frequency end: >>> end = segyio.TraceField.SweepFrequencyEnd >>> sfe = n...
f13382:c5:m2
def __getitem__(self, i):
try:<EOL><INDENT>i = self.wrapindex(i)<EOL>return self.filehandle.gettext(i)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise TypeError(msg.format(type(i).__name__))<EOL><DEDENT>def gen():<EOL><INDENT>for...
text[i] Read the text header at i. 0 is the mandatory, main Examples -------- Print the textual header: >>> print(f.text[0]) Print the first extended textual header: >>> print(f.text[1]) Print a textual header line-by-line: >>> # using zip, ...
f13382:c6:m1
def __setitem__(self, i, val):
if isinstance(val, Text):<EOL><INDENT>self[i] = val[<NUM_LIT:0>]<EOL>return<EOL><DEDENT>try:<EOL><INDENT>i = self.wrapindex(i)<EOL>self.filehandle.puttext(i, val)<EOL><DEDENT>except TypeError:<EOL><INDENT>try:<EOL><INDENT>indices = i.indices(len(self))<EOL><DEDENT>except AttributeError:<EOL><INDENT>msg = '<STR_LIT>'<EO...
text[i] = val Write the ith text header of the file, starting at 0. If val is instance of Text or iterable of Text, value is set to be the first element of every Text Parameters ---------- i : int or slice val : str, Text or iterable if i is slice Examp...
f13382:c6:m2
def dt(f, fallback_dt=<NUM_LIT>):
return f.xfd.getdt(fallback_dt)<EOL>
Delta-time Infer a ``dt``, the sample rate, from the file. If none is found, use the fallback. Parameters ---------- f : segyio.SegyFile fallback_dt : float delta-time to fall back to, in microseconds Returns ------- dt : float Notes ----- .. versionadded:: ...
f13383:m0
def sample_indexes(segyfile, t0=<NUM_LIT:0.0>, dt_override=None):
if dt_override is None:<EOL><INDENT>dt_override = dt(segyfile)<EOL><DEDENT>return [t0 + t * dt_override for t in range(len(segyfile.samples))]<EOL>
Creates a list of values representing the samples in a trace at depth or time. The list starts at *t0* and is incremented with am*dt* for the number of samples. If a *dt_override* is not provided it will try to find a *dt* in the file. Parameters ---------- segyfile : segyio.SegyFile t0 : float initial sample, o...
f13383:m1
def create_text_header(lines):
rows = []<EOL>for line_no in range(<NUM_LIT:1>, <NUM_LIT>):<EOL><INDENT>line = "<STR_LIT>"<EOL>if line_no in lines:<EOL><INDENT>line = lines[line_no]<EOL><DEDENT>row = "<STR_LIT>".format(line_no, line)<EOL>rows.append(row)<EOL><DEDENT>rows = '<STR_LIT>'.join(rows)<EOL>return rows<EOL>
Format textual header Create a "correct" SEG-Y textual header. Every line will be prefixed with C## and there are 40 lines. The input must be a dictionary with the line number[1-40] as a key. The value for each key should be up to 76 character long string. Parameters ---------- lines : d...
f13383:m2
def wrap(s, width=<NUM_LIT>):
return '<STR_LIT:\n>'.join(textwrap.wrap(str(s), width=width))<EOL>
Formats the text input with newlines given the user specified width for each line. Parameters ---------- s : str width : int Returns ------- text : str Notes ----- .. versionadded:: 1.1
f13383:m3
def native(data,<EOL>format = segyio.SegySampleFormat.IBM_FLOAT_4_BYTE,<EOL>copy = True):
data = data.view( dtype = np.single )<EOL>if copy:<EOL><INDENT>data = np.copy( data )<EOL><DEDENT>format = int(segyio.SegySampleFormat(format))<EOL>return segyio._segyio.native(data, format)<EOL>
Convert numpy array to native float Converts a numpy array from raw segy trace data to native floats. Works for numpy ndarrays. Parameters ---------- data : numpy.ndarray format : int or segyio.SegySampleFormat copy : bool If True, convert on a copy, and leave the input array unmodifi...
f13383:m4
def collect(itr):
return np.stack([np.copy(x) for x in itr])<EOL>
Collect traces or lines into one ndarray Eagerly copy a series of traces, lines or depths into one numpy ndarray. If collecting traces or fast-direction over a post-stacked file, reshaping the resulting array is equivalent to calling ``segyio.tools.cube``. Parameters ---------- itr : iterable...
f13383:m5
def cube(f):
if not isinstance(f, segyio.SegyFile):<EOL><INDENT>with segyio.open(f) as fl:<EOL><INDENT>return cube(fl)<EOL><DEDENT><DEDENT>ilsort = f.sorting == segyio.TraceSortingFormat.INLINE_SORTING<EOL>fast = f.ilines if ilsort else f.xlines<EOL>slow = f.xlines if ilsort else f.ilines<EOL>fast, slow, offs = len(fast), len(slow)...
Read a full cube from a file Takes an open segy file (created with segyio.open) or a file name. If the file is a prestack file, the cube returned has the dimensions ``(fast, slow, offset, sample)``. If it is post-stack (only the one offset), the dimensions are normalised to ``(fast, slow, sample)`` ...
f13383:m6
def rotation(f, line = '<STR_LIT>'):
if f.unstructured:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>lines = { '<STR_LIT>': f.fast,<EOL>'<STR_LIT>': f.slow,<EOL>'<STR_LIT>': f.iline,<EOL>'<STR_LIT>': f.xline,<EOL>}<EOL>if line not in lines:<EOL><INDENT>error = "<STR_LIT>".format(line)<EOL>solution = "<STR_LIT>".format('<STR_LIT:U+0020>'.join(line...
Find rotation of the survey Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)`` The clock-wise rotation is defined as the angle in radians between line given by the first and last trace of the first line and the axis that gives increasing CDP-Y, in the direction that gives incre...
f13383:m7
def metadata(f):
if not isinstance(f, segyio.SegyFile):<EOL><INDENT>with segyio.open(f) as fl:<EOL><INDENT>return metadata(fl)<EOL><DEDENT><DEDENT>spec = segyio.spec()<EOL>spec.iline = f._il<EOL>spec.xline = f._xl<EOL>spec.samples = f.samples<EOL>spec.format = f.format<EOL>spec.ilines = f.ilines<EOL>spec.xlines = f.xlines<EOL>spec.offs...
Get survey structural properties and metadata Create a description object that, when passed to ``segyio.create()``, would create a new file with the same structure, dimensions, and metadata as ``f``. Takes an open segy file (created with segyio.open) or a file name. Parameters ---------- ...
f13383:m8
def resample(f, rate = None, delay = None, micro = False,<EOL>trace = True,<EOL>binary = True):
if rate is not None:<EOL><INDENT>if not micro: rate *= <NUM_LIT:1000><EOL>if binary: f.bin[segyio.su.hdt] = rate<EOL>if trace: f.header = { segyio.su.dt: rate}<EOL><DEDENT>if delay is not None:<EOL><INDENT>f.header = { segyio.su.delrt: delay }<EOL><DEDENT>t0 = delay if delay is not None else f.samples[<NUM_LIT:0>]<EOL>...
Resample a file Resample all data traces, and update the file handle to reflect the new sample rate. No actual samples (data traces) are modified, only the header fields and interpretation. By default, the rate and the delay are in millseconds - if you need higher resolution, passing micro=True in...
f13383:m9
def from_array(filename, data, iline=<NUM_LIT>,<EOL>xline=<NUM_LIT>,<EOL>format=SegySampleFormat.IBM_FLOAT_4_BYTE,<EOL>dt=<NUM_LIT>,<EOL>delrt=<NUM_LIT:0>):
dt = int(dt)<EOL>delrt = int(delrt)<EOL>data = np.asarray(data)<EOL>dimensions = len(data.shape)<EOL>if dimensions not in range(<NUM_LIT:2>, <NUM_LIT:5>):<EOL><INDENT>problem = "<STR_LIT>".format(dimensions)<EOL>raise ValueError(problem)<EOL><DEDENT>spec = segyio.spec()<EOL>spec.iline = iline<EOL>spec.xline = xline...
Create a new SEGY file from an n-dimentional array. Create a structured SEGY file with defaulted headers from a 2-, 3- or 4-dimensional array. ilines, xlines, offsets and samples are inferred from the size of the array. Please refer to the documentation for functions from_array2D, from_array3D and from_...
f13383:m10
def from_array2D(filename, data, iline=<NUM_LIT>,<EOL>xline=<NUM_LIT>,<EOL>format=SegySampleFormat.IBM_FLOAT_4_BYTE,<EOL>dt=<NUM_LIT>,<EOL>delrt=<NUM_LIT:0>):
data = np.asarray(data)<EOL>dimensions = len(data.shape)<EOL>if dimensions != <NUM_LIT:2>:<EOL><INDENT>problem = "<STR_LIT>".format(dimensions)<EOL>raise ValueError(problem)<EOL><DEDENT>from_array(filename, data, iline=iline, xline=xline, format=format,<EOL>dt=dt,<EOL>delrt=delrt)<EOL>
Create a new SEGY file from a 2D array Create an structured SEGY file with defaulted headers from a 2-dimensional array. The file is inline-sorted and structured as a slice, i.e. it has one iline and the xlinecount equals the tracecount. The tracecount and samplecount are inferred from the size of the a...
f13383:m11
def from_array3D(filename, data, iline=<NUM_LIT>,<EOL>xline=<NUM_LIT>,<EOL>format=SegySampleFormat.IBM_FLOAT_4_BYTE,<EOL>dt=<NUM_LIT>,<EOL>delrt=<NUM_LIT:0>):
data = np.asarray(data)<EOL>dimensions = len(data.shape)<EOL>if dimensions != <NUM_LIT:3>:<EOL><INDENT>problem = "<STR_LIT>".format(dimensions)<EOL>raise ValueError(problem)<EOL><DEDENT>from_array(filename, data, iline=iline, xline=xline, format=format,<EOL>dt=dt,<EOL>delrt=delrt)<EOL>
Create a new SEGY file from a 3D array Create an structured SEGY file with defaulted headers from a 3-dimensional array. The file is inline-sorted. ilines, xlines and samples are inferred from the array. Structure-defining fields in the binary header and in the traceheaders are set accordingly. Such fie...
f13383:m12
def from_array4D(filename, data, iline=<NUM_LIT>,<EOL>xline=<NUM_LIT>,<EOL>format=SegySampleFormat.IBM_FLOAT_4_BYTE,<EOL>dt=<NUM_LIT>,<EOL>delrt=<NUM_LIT:0>):
data = np.asarray(data)<EOL>dimensions = len(data.shape)<EOL>if dimensions != <NUM_LIT:4>:<EOL><INDENT>problem = "<STR_LIT>".format(dimensions)<EOL>raise ValueError(problem)<EOL><DEDENT>from_array(filename, data, iline=iline, xline=xline, format=format,<EOL>dt=dt,<EOL>delrt=delrt)<EOL>
Create a new SEGY file from a 4D array Create an structured SEGY file with defaulted headers from a 4-dimensional array. The file is inline-sorted. ilines, xlines, offsets and samples are inferred from the array. Structure-defining fields in the binary header and in the traceheaders are set accordingly....
f13383:m13
def fetch(self, buf = None, traceno = None):
if buf is None:<EOL><INDENT>buf = self.buf<EOL><DEDENT>if traceno is None:<EOL><INDENT>traceno = self.traceno<EOL><DEDENT>try:<EOL><INDENT>if self.kind == TraceField:<EOL><INDENT>if traceno is None: return buf<EOL>return self.filehandle.getth(traceno, buf)<EOL><DEDENT>else:<EOL><INDENT>return self.filehandle.getbin()<E...
Fetch the header from disk This object will read header when it is constructed, which means it might be out-of-date if the file is updated through some other handle. This method is largely meant for internal use - if you need to reload disk contents, use ``reload``. Fetch does ...
f13385:c0:m1
def reload(self):
self.buf = self.fetch(buf = self.buf)<EOL>return self<EOL>
This object will read header when it is constructed, which means it might be out-of-date if the file is updated through some other handle. It's rarely required to call this method, and it's a symptom of fragile code. However, if you have multiple handles to the same header, it might be necessary. Consider the followin...
f13385:c0:m2
def flush(self):
if self.kind == TraceField:<EOL><INDENT>self.filehandle.putth(self.traceno, self.buf)<EOL><DEDENT>elif self.kind == BinField:<EOL><INDENT>self.filehandle.putbin(self.buf)<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise RuntimeError(msg.format(self.kind))<EOL><DEDENT>
Commit backing storage to disk This method is largely internal, and it is not necessary to call this from user code. It should not be explicitly invoked and may be removed in future versions.
f13385:c0:m3
def __getitem__(self, key):
try: return self.getfield(self.buf, int(key))<EOL>except TypeError: pass<EOL>return {self.kind(k): self.getfield(self.buf, int(k)) for k in key}<EOL>
d[key] Read the associated value of `key`. `key` can be any iterable, to retrieve multiple keys at once. In this case, a mapping of key -> value is returned. Parameters ---------- key : int, or iterable of int Returns ------- value : int or dic...
f13385:c0:m4
def __setitem__(self, key, val):
self.putfield(self.buf, key, val)<EOL>self.flush()<EOL>return val<EOL>
d[key] = val Set d[key] to val. Setting keys commits changes to disk, although the changes may not be visible until the kernel schedules the write. Unlike d[key], this method does not support assigning multiple values at once. To set multiple values at once, use the `update` method. ...
f13385:c0:m5
def __delitem__(self, key):
self[key] = <NUM_LIT:0><EOL>
del d[key] 'Delete' the key by setting value to zero. Equivalent to ``d[key] = 0``. Notes ----- .. versionadded:: 1.6
f13385:c0:m6
def keys(self):
return list(self._keys)<EOL>
D.keys() -> a set-like object providing a view on D's keys
f13385:c0:m7
def __len__(self):
return len(self._keys)<EOL>
x.__len__() <==> len(x)
f13385:c0:m8
def __iter__(self):
return iter(self._keys)<EOL>
x.__iter__() <==> iter(x)
f13385:c0:m9
def __eq__(self, other):
if not isinstance(other, collections.Mapping):<EOL><INDENT>return NotImplemented<EOL><DEDENT>if len(self) != len(other):<EOL><INDENT>return False<EOL><DEDENT>def intkeys(d):<EOL><INDENT>return { int(k): v for k, v in d.items() }<EOL><DEDENT>return intkeys(self) == intkeys(other)<EOL>
x.__eq__(y) <==> x == y
f13385:c0:m10
def update(self, *args, **kwargs):
if len(args) > <NUM_LIT:1>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise TypeError(msg.format(len(args)))<EOL><DEDENT>buf = bytearray(self.buf)<EOL>if len(args) == <NUM_LIT:1>:<EOL><INDENT>other = args[<NUM_LIT:0>]<EOL>if isinstance(other, collections.Mapping):<EOL><INDENT>for key in other:<EOL><INDENT>self.putfield(buf, in...
d.update([E, ]**F) -> None. Update D from mapping/iterable E and F. Overwrite the values in `d` with the keys from `E` and `F`. If any key in `value` is invalid in `d`, ``KeyError`` is raised. This method is atomic - either all values in `value` are set in `d`, or none are. ``update``...
f13385:c0:m11
def __getitem__(self, index):
offset = self.default_offset<EOL>try: index, offset = index<EOL>except TypeError: pass<EOL>try:<EOL><INDENT>head = self.heads[index] + self.offsets[offset]<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return self.filehandle.getline(head,<EOL>self.length,<EOL>self.stride,<EOL>len(self.off...
line[i] or line[i, o] The line `i`, or the line `i` at a specific offset `o`. ``line[i]`` returns a numpy array, and changes to this array will *not* be reflected on disk. The `i` and `o` are *keys*, and should correspond to the line- and offset labels in your file, and in the ...
f13387:c0:m2