bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
|
def longest_path(self, s=None, t=None, weighted=False, algorithm="MILP", solver=None, verbose=0): r""" Returns a longest path of ``self``.
| 473,300
|
sage: def maple_leaf(t):
|
sage: def maple_leaf(t):
| 473,301
|
sage: def maple_leaf(t):
|
sage: def maple_leaf(t):
| 473,302
|
sage: def maple_leaf(t):
|
sage: def maple_leaf(t):
| 473,303
|
sage: def maple_leaf(t):
|
sage: def maple_leaf(t):
| 473,304
|
sage: def maple_leaf(t):
|
sage: def maple_leaf(t):
| 473,305
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points.
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=None): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points.
| 473,306
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points.
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points.
| 473,307
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points.
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points.
| 473,308
|
def is_S_integral(self,S): r""" Return True if this fractional ideal is integral with respect to the list of primes ``S``.
|
def is_S_integral(self,S): r""" Return True if this fractional ideal is integral with respect to the list of primes ``S``.
| 473,309
|
def bin_to_ascii(B): r""" Return the ASCII representation of the binary string ``B``. INPUT: - ``B`` -- a non-empty binary string or a non-empty list of bits. The number of bits in ``B`` must be a multiple of 8. OUTPUT: - The ASCII string corresponding to ``B``. ALGORITHM: Consider a block of bits `B = b_0 b_1 \cdots b_{n-1}` where each sub-block `b_i` is a binary string of length 8. Then the total number of bits is a multiple of 8 and is given by `8n`. Let `c_i` be the integer representation of `b_i`. We can consider `c_i` as the integer representation of an ASCII character. Then the ASCII representation `A` of `B` is `A = a_0 a_1 \cdots a_{n-1}`. EXAMPLES: Convert some ASCII strings to their binary representations and recover the ASCII strings from the binary representations:: sage: from sage.crypto.util import ascii_to_bin sage: from sage.crypto.util import bin_to_ascii sage: A = "Abc" sage: B = ascii_to_bin(A); B 010000010110001001100011 sage: bin_to_ascii(B) 'Abc' sage: bin_to_ascii(B) == A True :: sage: A = "123 \" #" sage: B = ascii_to_bin(A); B 00110001001100100011001100100000001000100010000000100011 sage: bin_to_ascii(B) '123 " #' sage: bin_to_ascii(B) == A True This function also accepts strings and lists of bits:: sage: from sage.crypto.util import bin_to_ascii sage: bin_to_ascii("010000010110001001100011") 'Abc' sage: bin_to_ascii([0, 1, 0, 0, 0, 0, 0, 1]) 'A' TESTS: The number of bits in ``B`` must be non-empty and a multiple of 8:: sage: from sage.crypto.util import bin_to_ascii sage: bin_to_ascii("") Traceback (most recent call last): ... ValueError: B must be a non-empty binary string. sage: bin_to_ascii([]) Traceback (most recent call last): ... ValueError: B must be a non-empty binary string. sage: bin_to_ascii(" ") Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. sage: bin_to_ascii("101") Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. sage: bin_to_ascii([1, 0, 1]) Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. """ # sanity checks n = len(B) if n == 0: raise ValueError("B must be a non-empty binary string.") if mod(n, 8) != 0: raise ValueError("The number of bits in B must be a multiple of 8.") # perform conversion to ASCII string b = map(lambda x: int(str(x)), list(B)) A = [] # the number of 8-bit blocks k = n / 8 for i in xrange(k): # Convert from 8-bit string to ASCII integer. Then convert the # ASCII integer to the corresponding ASCII character. A.append(chr(ascii_integer(b[8*i : 8*(i+1)]))) return "".join(A)
|
def bin_to_ascii(B): r""" Return the ASCII representation of the binary string ``B``. INPUT: - ``B`` -- a non-empty binary string or a non-empty list of bits. The number of bits in ``B`` must be a multiple of 8. OUTPUT: - The ASCII string corresponding to ``B``. ALGORITHM: Consider a block of bits `B = b_0 b_1 \cdots b_{n-1}` where each sub-block `b_i` is a binary string of length 8. Then the total number of bits is a multiple of 8 and is given by `8n`. Let `c_i` be the integer representation of `b_i`. We can consider `c_i` as the integer representation of an ASCII character. Then the ASCII representation `A` of `B` is `A = a_0 a_1 \cdots a_{n-1}`. EXAMPLES: Convert some ASCII strings to their binary representations and recover the ASCII strings from the binary representations:: sage: from sage.crypto.util import ascii_to_bin sage: from sage.crypto.util import bin_to_ascii sage: A = "Abc" sage: B = ascii_to_bin(A); B 010000010110001001100011 sage: bin_to_ascii(B) 'Abc' sage: bin_to_ascii(B) == A True :: sage: A = "123 \" #" sage: B = ascii_to_bin(A); B 00110001001100100011001100100000001000100010000000100011 sage: bin_to_ascii(B) '123 " #' sage: bin_to_ascii(B) == A True This function also accepts strings and lists of bits:: sage: from sage.crypto.util import bin_to_ascii sage: bin_to_ascii("010000010110001001100011") 'Abc' sage: bin_to_ascii([0, 1, 0, 0, 0, 0, 0, 1]) 'A' TESTS: The number of bits in ``B`` must be non-empty and a multiple of 8:: sage: from sage.crypto.util import bin_to_ascii sage: bin_to_ascii("") Traceback (most recent call last): ... ValueError: B must be a non-empty binary string. sage: bin_to_ascii([]) Traceback (most recent call last): ... ValueError: B must be a non-empty binary string. sage: bin_to_ascii(" ") Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. sage: bin_to_ascii("101") Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. sage: bin_to_ascii([1, 0, 1]) Traceback (most recent call last): ... ValueError: The number of bits in B must be a multiple of 8. """ # sanity checks n = len(B) if n == 0: raise ValueError("B must be a non-empty binary string.") if mod(n, 8) != 0: raise ValueError("The number of bits in B must be a multiple of 8.") # perform conversion to ASCII string b = map(lambda x: int(str(x)), list(B)) A = [] # the number of 8-bit blocks k = n / 8 for i in xrange(k): # Convert from 8-bit string to ASCII integer. Then convert the # ASCII integer to the corresponding ASCII character. A.append(chr(ascii_integer(b[8*i: 8*(i+1)]))) return "".join(A)
| 473,310
|
sage: def my_carmichael(n):
|
sage: def my_carmichael(n):
| 473,311
|
sage: def my_carmichael(n):
|
sage: def my_carmichael(n):
| 473,312
|
sage: def my_carmichael(n):
|
sage: def my_carmichael(n):
| 473,313
|
sage: def my_carmichael(n):
|
sage: def my_carmichael(n):
| 473,314
|
sage: def my_carmichael(n):
|
sage: def my_carmichael(n):
| 473,315
|
def least_significant_bits(n, k): r""" Return the ``k`` least significant bits of ``n``. INPUT: - ``n`` -- an integer. - ``k`` -- a positive integer. OUTPUT: - The ``k`` least significant bits of the integer ``n``. If ``k=1``, then return the parity bit of the integer ``n``. Let `b` be the binary representation of ``n``, where `m` is the length of the binary string `b`. If `k \geq m`, then return the binary representation of ``n``. EXAMPLES: Obtain the parity bits of some integers:: sage: from sage.crypto.util import least_significant_bits sage: least_significant_bits(0, 1) [0] sage: least_significant_bits(2, 1) [0] sage: least_significant_bits(3, 1) [1] sage: least_significant_bits(-2, 1) [0] sage: least_significant_bits(-3, 1) [1] Obtain the 4 least significant bits of some integers:: sage: least_significant_bits(101, 4) [0, 1, 0, 1] sage: least_significant_bits(-101, 4) [0, 1, 0, 1] sage: least_significant_bits(124, 4) [1, 1, 0, 0] sage: least_significant_bits(-124, 4) [1, 1, 0, 0] The binary representation of 123:: sage: n = 123; b = n.binary(); b '1111011' sage: least_significant_bits(n, len(b)) [1, 1, 1, 1, 0, 1, 1] """ return map(lambda x: int(x), list(n.binary()[-k:]))
|
def least_significant_bits(n, k): r""" Return the ``k`` least significant bits of ``n``. INPUT: - ``n`` -- an integer. - ``k`` -- a positive integer. OUTPUT: - The ``k`` least significant bits of the integer ``n``. If ``k=1``, then return the parity bit of the integer ``n``. Let `b` be the binary representation of ``n``, where `m` is the length of the binary string `b`. If `k \geq m`, then return the binary representation of ``n``. EXAMPLES: Obtain the parity bits of some integers:: sage: from sage.crypto.util import least_significant_bits sage: least_significant_bits(0, 1) [0] sage: least_significant_bits(2, 1) [0] sage: least_significant_bits(3, 1) [1] sage: least_significant_bits(-2, 1) [0] sage: least_significant_bits(-3, 1) [1] Obtain the 4 least significant bits of some integers:: sage: least_significant_bits(101, 4) [0, 1, 0, 1] sage: least_significant_bits(-101, 4) [0, 1, 0, 1] sage: least_significant_bits(124, 4) [1, 1, 0, 0] sage: least_significant_bits(-124, 4) [1, 1, 0, 0] The binary representation of 123:: sage: n = 123; b = n.binary(); b '1111011' sage: least_significant_bits(n, len(b)) [1, 1, 1, 1, 0, 1, 1] """ return map(int, list(n.binary()[-k:]))
| 473,316
|
def height(self): r""" Returns the height of self.
|
def height(self): r""" Returns the height of self.
| 473,317
|
def width(self): r""" Returns the width of self.
|
def width(self): r""" Returns the width of self.
| 473,318
|
def tikz_trajectory(self): r""" Returns the trajectory of self as a tikz str.
|
def tikz_trajectory(self): r""" Returns the trajectory of self as a tikz str.
| 473,319
|
def tikz_trajectory(self): r""" Returns the trajectory of self as a tikz str.
|
def tikz_trajectory(self): r""" Returns the trajectory of self as a tikz str.
| 473,320
|
def __contains__(self, x): """ Returns True if x is contained in self.
|
def __contains__(self, x): """ Returns True if x is contained in self.
| 473,321
|
def strip_answer(self, s): """ Returns the string s with Matlab's answer prompt removed.
|
def strip_answer(self, s): r""" Returns the string s with Matlab's answer prompt removed.
| 473,322
|
def map(self, f, name=None): """ Returns the image `\{f(x) x in self\}` of this combinatorial class by `f`, as a combinatorial class.
|
def map(self, f, name=None): r""" Returns the image `\{f(x) | x \in \text{self}\}` of this combinatorial class by `f`, as a combinatorial class.
| 473,323
|
'def identity_matrix'
|
'def identity_matrix'
| 473,324
|
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
|
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise.
| 473,325
|
def __init__(self, point, r, angle, options): """ Initializes base class Disk.
|
def __init__(self, point, r, angle, options): """ Initializes base class Disk.
| 473,326
|
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
|
def get_minmax_data(self): """ Returns a dictionary with the bounding box data.
| 473,327
|
def _allowed_options(self): """ Return the allowed options for the Disk class.
|
def _allowed_options(self): """ Return the allowed options for the Disk class.
| 473,328
|
def _repr_(self): """ String representation of Disk primitive.
|
def _repr_(self): """ String representation of Disk primitive.
| 473,329
|
def plot3d(self, z=0, **kwds): """ Plots a 2D disk (actually a 52-gon) in 3D, with default height zero.
|
def plot3d(self, z=0, **kwds): """ Plots a 2D disk (actually a 52-gon) in 3D, with default height zero.
| 473,330
|
def diamond_bracket_operator(self, d): r""" Return the diamond bracket d operator on this modular symbols space.
|
def diamond_bracket_operator(self, d): r""" Return the diamond bracket d operator on this modular symbols space.
| 473,331
|
def example(self): """ Returns an example of finite permutation group, as per :meth:`Category.example`.
|
def example(self): """ Returns an example of finite permutation group, as per :meth:`Category.example`.
| 473,332
|
def __new__(cls, *args, **kwds): r""" TEST: sage: from sage.combinat.words.word_generators import ChristoffelWord_Lower sage: w = ChristoffelWord_Lower(1,0); w doctest:1: DeprecationWarning: ChristoffelWord_Lower is deprecated, use LowerChristoffelWord instead word: 1 """ from sage.misc.misc import deprecation deprecation("ChristoffelWord_Lower is deprecated, use LowerChristoffelWord instead") return LowerChristoffelWord.__new__(cls, *args, **kwds)
|
def __new__(cls, *args, **kwds): r""" TEST: sage: from sage.combinat.words.word_generators import ChristoffelWord_Lower sage: w = ChristoffelWord_Lower(1,0); w doctest:1: DeprecationWarning: ChristoffelWord_Lower is deprecated, use LowerChristoffelWord instead word: 1 """ from sage.misc.misc import deprecation deprecation("ChristoffelWord_Lower is deprecated, use LowerChristoffelWord instead") return LowerChristoffelWord.__new__(cls, *args, **kwds)
| 473,333
|
def _sage_doc_(self): """ EXAMPLES::
|
def _sage_doc_(self): """ EXAMPLES::
| 473,334
|
def add_base_flags(module): incdirs = filter(os.path.exists, [os.path.join(p, 'include') for p in basedir[sys.platform] ]) libdirs = filter(os.path.exists, [os.path.join(p, 'lib') for p in basedir[sys.platform] ]+ [os.path.join(p, 'lib64') for p in basedir[sys.platform] ] ) module.include_dirs.extend(incdirs) module.include_dirs.append('.') module.include_dirs.append(sage_inc) module.library_dirs.extend(libdirs) module.library_dirs.extend([sage_lib])
|
def add_base_flags(module): incdirs = filter(os.path.exists, [os.path.join(p, 'include') for p in basedir[sys.platform] ]) libdirs = filter(os.path.exists, [os.path.join(p, 'lib') for p in basedir[sys.platform] ]+ [os.path.join(p, 'lib64') for p in basedir[sys.platform] ] ) module.include_dirs.extend(incdirs) module.include_dirs.append('.') module.library_dirs.extend(libdirs) module.library_dirs.extend([sage_lib])
| 473,335
|
def add_base_flags(module): incdirs = filter(os.path.exists, [os.path.join(p, 'include') for p in basedir[sys.platform] ]) libdirs = filter(os.path.exists, [os.path.join(p, 'lib') for p in basedir[sys.platform] ]+ [os.path.join(p, 'lib64') for p in basedir[sys.platform] ] ) module.include_dirs.extend(incdirs) module.include_dirs.append('.') module.include_dirs.append(sage_inc) module.library_dirs.extend(libdirs) module.library_dirs.extend([sage_lib])
|
def add_base_flags(module): incdirs = filter(os.path.exists, [os.path.join(p, 'include') for p in basedir[sys.platform] ]) libdirs = filter(os.path.exists, [os.path.join(p, 'lib') for p in basedir[sys.platform] ]+ [os.path.join(p, 'lib64') for p in basedir[sys.platform] ] ) module.include_dirs.extend(incdirs) module.include_dirs.append('.') module.include_dirs.append(sage_inc) module.library_dirs.extend(libdirs)
| 473,336
|
def check_for_numpy(): try: import numpy except ImportError: print_status("numpy", "no") print_message("You must install numpy 1.1 or later to build matplotlib.") return False nn = numpy.__version__.split('.') if not (int(nn[0]) >= 1 and int(nn[1]) >= 1): print_message( 'numpy 1.1 or later is required; you have %s' % numpy.__version__) return False module = Extension('test', []) add_numpy_flags(module) add_base_flags(module) print_status("numpy", numpy.__version__) if not find_include_file(module.include_dirs, os.path.join("numpy", "arrayobject.h")): print_message("Could not find the headers for numpy. You may need to install the development package.") return False return True
|
def check_for_numpy(): try: import numpy except ImportError: print_status("numpy", "no") print_message("You must install numpy 1.1 or later to build matplotlib.") return False nn = numpy.__version__.split('.') if not (int(nn[0]) >= 1 and int(nn[1]) >= 1): if not int(nn[0]) >= 1: print_message( 'numpy 1.1 or later is required; you have %s' % numpy.__version__) return False module = Extension('test', []) add_numpy_flags(module) add_base_flags(module) print_status("numpy", numpy.__version__) if not find_include_file(module.include_dirs, os.path.join("numpy", "arrayobject.h")): print_message("Could not find the headers for numpy. You may need to install the development package.") return False return True
| 473,337
|
def query_tcltk(): """Tries to open a Tk window in order to query the Tk object about its library paths. This should never be called more than once by the same process, as Tk intricacies may cause the Python interpreter to hang. The function also has a workaround if no X server is running (useful for autobuild systems).""" global TCL_TK_CACHE # Use cached values if they exist, which ensures this function only executes once if TCL_TK_CACHE is not None: return TCL_TK_CACHE # By this point, we already know that Tkinter imports correctly import Tkinter tcl_lib_dir = '' tk_lib_dir = '' # First try to open a Tk window (requires a running X server) try: tk = Tkinter.Tk() except Tkinter.TclError: # Next, start Tcl interpreter without opening a Tk window (no need for X server) # This feature is available in python version 2.4 and up try: tcl = Tkinter.Tcl() except AttributeError: # Python version not high enough pass except Tkinter.TclError: # Something went wrong while opening Tcl pass else: tcl_lib_dir = str(tcl.getvar('tcl_library')) # Guess Tk location based on Tcl location tk_lib_dir = tcl_lib_dir.replace('Tcl', 'Tk').replace('tcl', 'tk') else: # Obtain Tcl and Tk locations from Tk widget tk.withdraw() tcl_lib_dir = str(tk.getvar('tcl_library')) tk_lib_dir = str(tk.getvar('tk_library')) tk.destroy() # Save directories and version string to cache TCL_TK_CACHE = tcl_lib_dir, tk_lib_dir, str(Tkinter.TkVersion)[:3] return TCL_TK_CACHE
|
def query_tcltk(): """Tries to open a Tk window in order to query the Tk object about its library paths. This should never be called more than once by the same process, as Tk intricacies may cause the Python interpreter to hang. The function also has a workaround if no X server is running (useful for autobuild systems).""" global TCL_TK_CACHE # Use cached values if they exist, which ensures this function only executes once if TCL_TK_CACHE is not None: return TCL_TK_CACHE # By this point, we already know that Tkinter imports correctly import Tkinter tcl_lib_dir = '' tk_lib_dir = '' # First try to open a Tk window (requires a running X server) try: tk = Tkinter.Tk() except Tkinter.TclError: # Next, start Tcl interpreter without opening a Tk window (no need for X server) # This feature is available in python version 2.4 and up try: tcl = Tkinter.Tcl() except AttributeError: # Python version not high enough pass except Tkinter.TclError: # Something went wrong while opening Tcl pass else: tcl_lib_dir = str(tcl.getvar('tcl_library')) # Guess Tk location based on Tcl location (head, tail) = os.path.split(tcl_lib_dir) tail = tail.replace('Tcl', 'Tk').replace('tcl', 'tk') tk_lib_dir = os.path.join(head, tail) if not os.path.exists(tk_lib_dir): tk_lib_dir = tcl_lib_dir.replace('Tcl', 'Tk').replace('tcl', 'tk') else: # Obtain Tcl and Tk locations from Tk widget tk.withdraw() tcl_lib_dir = str(tk.getvar('tcl_library')) tk_lib_dir = str(tk.getvar('tk_library')) tk.destroy() # Save directories and version string to cache TCL_TK_CACHE = tcl_lib_dir, tk_lib_dir, str(Tkinter.TkVersion)[:3] return TCL_TK_CACHE
| 473,338
|
def build_ft2font(ext_modules, packages): global BUILT_FT2FONT if BUILT_FT2FONT: return # only build it if you you haven't already deps = ['src/ft2font.cpp', 'src/mplutils.cpp'] deps.extend(glob.glob('CXX/*.cxx')) deps.extend(glob.glob('CXX/*.c')) module = Extension('matplotlib.ft2font', deps, define_macros=[('PY_ARRAYAUNIQUE_SYMBOL', 'MPL_ARRAY_API')]) add_ft2font_flags(module) ext_modules.append(module) BUILT_FT2FONT = True
|
def build_ft2font(ext_modules, packages): global BUILT_FT2FONT if BUILT_FT2FONT: return # only build it if you you haven't already deps = ['src/ft2font.cpp', 'src/mplutils.cpp'] deps.extend(glob.glob('CXX/*.cxx')) deps.extend(glob.glob('CXX/*.c')) module = Extension('matplotlib.ft2font', deps, define_macros=[('PY_ARRAY_UNIQUE_SYMBOL', 'MPL_ARRAY_API')]) add_ft2font_flags(module) ext_modules.append(module) BUILT_FT2FONT = True
| 473,339
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
|
def _read_in_file_command(self, filename): """ Load and *execute* the content of ``filename`` in Macaulay2. :param filename: the name of the file to be loaded and executed. :type filename: string :returns: Macaulay2 command loading and executing commands in ``filename``, that is, ``'load "filename"'``. :rtype: string TESTS:: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
| 473,340
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("sage_test = 7;") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
| 473,341
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional sage: macaulay2.eval("sage_test") 7 sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
| 473,342
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
|
def _read_in_file_command(self, filename): """ EXAMPLES: sage: from sage.misc.misc import tmp_filename sage: filename = tmp_filename() sage: f = open(filename, "w") sage: f.write("Hello") sage: f.close() sage: command = macaulay2._read_in_file_command(filename) sage: macaulay2.eval(command) #optional Hello sage: import os sage: os.unlink(filename) """ return 'get "%s"'%filename
| 473,343
|
def metaclass(name, bases): """ Creates a new class in this metaclass INPUT:: - name: a string - bases: a tuple of classes EXAMPLES:: sage: from sage.misc.test_class_pickling import metaclass, bar sage: c = metaclass("foo2", (object, bar,)) constructing class sage: c <class 'sage.misc.test_class_pickling.foo2'> sage: type(c) <class 'sage.misc.test_class_pickling.Metaclass'> sage: c.__bases__ (<type 'object'>, <class sage.misc.test_class_pickling.bar at ...>) """ print "constructing class" result = Metaclass(name, bases, dict()) result.reduce_args = (name, bases) return result
|
def metaclass(name, bases): """ Creates a new class in this metaclass INPUT:: - name: a string - bases: a tuple of classes EXAMPLES:: sage: from sage.misc.test_class_pickling import metaclass, bar sage: c = metaclass("foo2", (object, bar,)) constructing class sage: c <class 'sage.misc.test_class_pickling.foo2'> sage: type(c) <class 'sage.misc.test_class_pickling.Metaclass'> sage: c.__bases__ (<type 'object'>, <class sage.misc.test_class_pickling.bar at ...>) """ print "constructing class" result = Metaclass(name, bases, dict()) result.reduce_args = (name, bases) return result
| 473,344
|
def metaclass(name, bases): """ Creates a new class in this metaclass INPUT:: - name: a string - bases: a tuple of classes EXAMPLES:: sage: from sage.misc.test_class_pickling import metaclass, bar sage: c = metaclass("foo2", (object, bar,)) constructing class sage: c <class 'sage.misc.test_class_pickling.foo2'> sage: type(c) <class 'sage.misc.test_class_pickling.Metaclass'> sage: c.__bases__ (<type 'object'>, <class sage.misc.test_class_pickling.bar at ...>) """ print "constructing class" result = Metaclass(name, bases, dict()) result.reduce_args = (name, bases) return result
|
def metaclass(name, bases): Creates a new class in this metaclass INPUT:: - name: a string - bases: a tuple of classes EXAMPLES:: sage: from sage.misc.test_class_pickling import metaclass, bar sage: c = metaclass("foo2", (object, bar,)) constructing class sage: c <class 'sage.misc.test_class_pickling.foo2'> sage: type(c) <class 'sage.misc.test_class_pickling.Metaclass'> sage: c.__bases__ (<type 'object'>, <class sage.misc.test_class_pickling.bar at ...>) print "constructing class" result = Metaclass(name, bases, dict()) result.reduce_args = (name, bases) return result
| 473,345
|
def srange(start, end=None, step=1, universe=None, check=True, include_endpoint=False, endpoint_tolerance=1e-5): r""" Return list of numbers ``a, a+step, ..., a+k*step``, where ``a+k*step < b`` and ``a+(k+1)*step >= b`` over exact rings, and makes a best attempt for inexact rings (see note below). This provides one way to iterate over Sage integers as opposed to Python int's. It also allows you to specify step sizes for such an iteration. Note, however, that what is returned is a full list of Integers and not an iterator. It is potentially much slower than the Python range function, depending on the application. The function xsrange() provides an iterator with similar functionality which would usually be more efficient than using srange(). INPUT: - ``a`` - number - ``b`` - number (default: None) - ``step`` - number (default: 1) - ``universe`` - Parent or type where all the elements should live (default: deduce from inputs) - ``check`` - make sure a, b, and step all lie in the same universe - ``include_endpoint`` - whether or not to include the endpoint (default: False) - ``endpoint_tolerance`` - used to determine whether or not the endpoint is hit for inexact rings (default 1e-5) OUTPUT: - list If b is None, then b is set equal to a and a is set equal to the 0 in the parent of b. Unlike range, a and b can be any type of numbers, and the resulting list involves numbers of that type. .. note:: The list elements are computed via repeated addition rather than multiplication, which may produce slightly different results with inexact rings. For example:: sage: sum([1.1] * 10) == 1.1 * 10 False Also, the question of whether the endpoint is hit exactly for a given ``a + k*step`` is fuzzy for an inexact ring. If ``a + k*step = b`` for some k within ``endpoint_tolerance`` of being integral, it is considered an exact hit, thus avoiding spurious values falling just below the endpoint. .. note:: This function is called ``srange`` to distinguish it from the built-in Python ``range`` command. The s at the beginning of the name stands for "Sage". .. seealso: :func:`xsrange` -- iterator version EXAMPLES:: sage: v = srange(5); v [0, 1, 2, 3, 4] sage: type(v[2]) <type 'sage.rings.integer.Integer'> sage: srange(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9] sage: srange(10, 1, -1) [10, 9, 8, 7, 6, 5, 4, 3, 2] sage: srange(10,1,-1, include_endpoint=True) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] sage: srange(1, 10, universe=RDF) [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] sage: srange(1, 10, 1/2) [1, 3/2, 2, 5/2, 3, 7/2, 4, 9/2, 5, 11/2, 6, 13/2, 7, 15/2, 8, 17/2, 9, 19/2] sage: srange(1, 5, 0.5) [1.00000000000000, 1.50000000000000, 2.00000000000000, 2.50000000000000, 3.00000000000000, 3.50000000000000, 4.00000000000000, 4.50000000000000] sage: srange(0, 1, 0.4) [0.000000000000000, 0.400000000000000, 0.800000000000000] sage: srange(1.0, 5.0, include_endpoint=True) [1.00000000000000, 2.00000000000000, 3.00000000000000, 4.00000000000000, 5.00000000000000] sage: srange(1.0, 1.1) [1.00000000000000] sage: srange(1.0, 1.0) [] sage: V = VectorSpace(QQ, 2) sage: srange(V([0,0]), V([5,5]), step=V([2,2])) [(0, 0), (2, 2), (4, 4)] Including the endpoint:: sage: srange(0, 10, step=2, include_endpoint=True) [0, 2, 4, 6, 8, 10] sage: srange(0, 10, step=3, include_endpoint=True) [0, 3, 6, 9] Try some inexact rings:: sage: srange(0.5, 1.1, 0.1, universe=RDF, include_endpoint=False) [0.5, 0.6, 0.7, 0.8, 0.9, 1.0] sage: srange(0.5, 1, 0.1, universe=RDF, include_endpoint=False) [0.5, 0.6, 0.7, 0.8, 0.9] sage: srange(0.5, 0.9, 0.1, universe=RDF, include_endpoint=False) [0.5, 0.6, 0.7, 0.8] sage: srange(0, 1.1, 0.1, universe=RDF, include_endpoint=True) [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1] sage: srange(0, 0.2, 0.1, universe=RDF, include_endpoint=True) [0.0, 0.1, 0.2] sage: srange(0, 0.3, 0.1, universe=RDF, include_endpoint=True) [0.0, 0.1, 0.2, 0.3] """ from sage.structure.sequence import Sequence from sage.rings.all import ZZ if end is None: end = start start = 0 if check: if universe is None: universe = Sequence([start, end, step]).universe() start, end, step = universe(start), universe(end), universe(step) if universe in [int, long, ZZ]: if include_endpoint and (end-start) % step == 0: end += step if universe is ZZ: return ZZ.range(start, end, step) else: # universe is int or universe is long: return range(start, end, step) count = (end-start)/step if not isinstance(universe, type) and universe.is_exact(): icount = int(math.ceil(float(count))) if icount != count: include_endpoint = False else: icount = int(math.ceil(float(count) - endpoint_tolerance)) if abs(float(count) - icount) > endpoint_tolerance: include_endpoint = False L = [] for k in xrange(icount): L.append(start) start += step if include_endpoint: L.append(end) return L
|
def srange(start, end=None, step=1, universe=None, check=True, include_endpoint=False, endpoint_tolerance=1e-5): r""" Return list of numbers ``a, a+step, ..., a+k*step``, where ``a+k*step < b`` and ``a+(k+1)*step >= b`` over exact rings, and makes a best attempt for inexact rings (see note below). This provides one way to iterate over Sage integers as opposed to Python int's. It also allows you to specify step sizes for such an iteration. Note, however, that what is returned is a full list of Integers and not an iterator. It is potentially much slower than the Python range function, depending on the application. The function xsrange() provides an iterator with similar functionality which would usually be more efficient than using srange(). INPUT: - ``a`` - number - ``b`` - number (default: None) - ``step`` - number (default: 1) - ``universe`` - Parent or type where all the elements should live (default: deduce from inputs) - ``check`` - make sure a, b, and step all lie in the same universe - ``include_endpoint`` - whether or not to include the endpoint (default: False) - ``endpoint_tolerance`` - used to determine whether or not the endpoint is hit for inexact rings (default 1e-5) OUTPUT: - list If b is None, then b is set equal to a and a is set equal to the 0 in the parent of b. Unlike range, a and b can be any type of numbers, and the resulting list involves numbers of that type. .. note:: The list elements are computed via repeated addition rather than multiplication, which may produce slightly different results with inexact rings. For example:: sage: sum([1.1] * 10) == 1.1 * 10 False Also, the question of whether the endpoint is hit exactly for a given ``a + k*step`` is fuzzy for an inexact ring. If ``a + k*step = b`` for some k within ``endpoint_tolerance`` of being integral, it is considered an exact hit, thus avoiding spurious values falling just below the endpoint. .. note:: This function is called ``srange`` to distinguish it from the built-in Python ``range`` command. The s at the beginning of the name stands for "Sage". .. seealso: :func:`xsrange` -- iterator version EXAMPLES:: sage: v = srange(5); v [0, 1, 2, 3, 4] sage: type(v[2]) <type 'sage.rings.integer.Integer'> sage: srange(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9] sage: srange(10, 1, -1) [10, 9, 8, 7, 6, 5, 4, 3, 2] sage: srange(10,1,-1, include_endpoint=True) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] sage: srange(1, 10, universe=RDF) [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] sage: srange(1, 10, 1/2) [1, 3/2, 2, 5/2, 3, 7/2, 4, 9/2, 5, 11/2, 6, 13/2, 7, 15/2, 8, 17/2, 9, 19/2] sage: srange(1, 5, 0.5) [1.00000000000000, 1.50000000000000, 2.00000000000000, 2.50000000000000, 3.00000000000000, 3.50000000000000, 4.00000000000000, 4.50000000000000] sage: srange(0, 1, 0.4) [0.000000000000000, 0.400000000000000, 0.800000000000000] sage: srange(1.0, 5.0, include_endpoint=True) [1.00000000000000, 2.00000000000000, 3.00000000000000, 4.00000000000000, 5.00000000000000] sage: srange(1.0, 1.1) [1.00000000000000] sage: srange(1.0, 1.0) [] sage: V = VectorSpace(QQ, 2) sage: srange(V([0,0]), V([5,5]), step=V([2,2])) [(0, 0), (2, 2), (4, 4)] Including the endpoint:: sage: srange(0, 10, step=2, include_endpoint=True) [0, 2, 4, 6, 8, 10] sage: srange(0, 10, step=3, include_endpoint=True) [0, 3, 6, 9] Try some inexact rings:: sage: srange(0.5, 1.1, 0.1, universe=RDF, include_endpoint=False) [0.5, 0.6, 0.7, 0.8, 0.9, 1.0] sage: srange(0.5, 1, 0.1, universe=RDF, include_endpoint=False) [0.5, 0.6, 0.7, 0.8, 0.9] sage: srange(0.5, 0.9, 0.1, universe=RDF, include_endpoint=False) [0.5, 0.6, 0.7, 0.8] sage: srange(0, 1.1, 0.1, universe=RDF, include_endpoint=True) [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1] sage: srange(0, 0.2, 0.1, universe=RDF, include_endpoint=True) [0.0, 0.1, 0.2] sage: srange(0, 0.3, 0.1, universe=RDF, include_endpoint=True) [0.0, 0.1, 0.2, 0.3] """ from sage.structure.sequence import Sequence from sage.rings.all import ZZ if end is None: end = start start = 0 if check: if universe is None: universe = Sequence([start, end, step]).universe() start, end, step = universe(start), universe(end), universe(step) if universe in [int, long, ZZ]: if include_endpoint and (end-start) % step == 0: end += step if universe is ZZ: return ZZ.range(start, end, step) else: # universe is int or universe is long: return range(start, end, step) count = (end-start)/step if not isinstance(universe, type) and universe.is_exact(): icount = int(math.ceil(float(count))) if icount != count: include_endpoint = False else: icount = int(math.ceil(float(count) - endpoint_tolerance)) if abs(float(count) - icount) > endpoint_tolerance: include_endpoint = False L = [] for k in xrange(icount): L.append(start) start += step if include_endpoint: L.append(end) return L
| 473,346
|
def generic_xsrange(): cur = start for k in xrange(icount): yield cur cur += step if include_endpoint: yield end
|
def generic_xsrange(): cur = start for k in xrange(icount): yield cur cur += step if include_endpoint: yield end
| 473,347
|
def _newVolume(self,data,copyFrom=None,rescale=True): """Takes a numpy array and makes a geoprobe volume. This volume can then be written to disk using the write() method."""
|
def _newVolume(self,data,copyFrom=None,rescale=True): """Takes a numpy array and makes a geoprobe volume. This volume can then be written to disk using the write() method."""
| 473,348
|
def write(self, filename): """Writes a geoprobe volume to disk using memmapped arrays""" # Write header values self._infile = BinaryFile(filename, 'w') for varname, info in _headerDef.iteritems(): value = getattr(self, varname, info['default']) self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value)
|
def write(self, filename): """Writes a geoprobe volume to disk.""" # Write header values self._infile = BinaryFile(filename, 'w') for varname, info in _headerDef.iteritems(): value = getattr(self, varname, info['default']) self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value)
| 473,349
|
def write(self, filename): """Writes a geoprobe volume to disk using memmapped arrays""" # Write header values self._infile = BinaryFile(filename, 'w') for varname, info in _headerDef.iteritems(): value = getattr(self, varname, info['default']) self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value)
|
def write(self, filename): """Writes a geoprobe volume to disk using memmapped arrays""" # Write header values outfile = BinaryFile(filename, 'w') for varname, info in _headerDef.iteritems(): value = getattr(self, varname, info['default']) self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value)
| 473,350
|
def write(self, filename): """Writes a geoprobe volume to disk using memmapped arrays""" # Write header values self._infile = BinaryFile(filename, 'w') for varname, info in _headerDef.iteritems(): value = getattr(self, varname, info['default']) self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value)
|
def write(self, filename): """Writes a geoprobe volume to disk using memmapped arrays""" # Write header values self._infile = BinaryFile(filename, 'w') for varname, info in _headerDef.iteritems(): value = getattr(self, varname, info['default']) self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value)
| 473,351
|
def _setData(self, newData): newData = np.asarray(newData).astype(np.uint8) try: self._nx, self._ny, self._nz = newData.shape except ValueError, AttributeError: raise TypeError('Data must be a 3D numpy array') # We don't update dv and d0 here. This is to avoid overwriting the "real" # dv and d0 when you're manipulating the data in some way. When making a # new volume object from an existing numpy array (in _newVolume), dv and d0 are set self._data = newData
|
def _setData(self, newData): newData = np.asarray(newData, dtype=np.uint8) try: self._nx, self._ny, self._nz = newData.shape except ValueError, AttributeError: raise TypeError('Data must be a 3D numpy array') # We don't update dv and d0 here. This is to avoid overwriting the "real" # dv and d0 when you're manipulating the data in some way. When making a # new volume object from an existing numpy array (in _newVolume), dv and d0 are set self._data = newData
| 473,352
|
def _readHorizon(self,filename): self._file = HorizonFile(filename, 'r')
|
def _readHorizon(self,filename): self._file = HorizonFile(filename, 'r')
| 473,353
|
def read(self): """ Reads in the entire horizon file and returns a numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon. """ # Note: The total number of points in the file is not directly stored # on disk. Therefore, we must read through the entire file, store # each section's points in a list, and then create a contigious array # from them. Using numpy.append is much simpler, but quite slow.
|
def read_all(self): """ Reads in the entire horizon file and returns a numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon. """ # Note: The total number of points in the file is not directly stored # on disk. Therefore, we must read through the entire file, store # each section's points in a list, and then create a contigious array # from them. Using numpy.append is much simpler, but quite slow.
| 473,354
|
def _newVolume(self,data,copyFrom=None,rescale=True): """Takes a numpy array and makes a geoprobe volume. This volume can then be written to disk using the write() method."""
|
def _newVolume(self,data,copyFrom=None,rescale=True): """Takes a numpy array and makes a geoprobe volume. This volume can then be written to disk using the write() method."""
| 473,355
|
def __init__(self, input): """Takes either a filename or a numpy array"""
|
def __init__(self, input): """Takes either a filename or a numpy array"""
| 473,356
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = self._ensure_correct_dtype(args[0]) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = self._ensure_correct_dtype(args[0]) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
| 473,357
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" grid = np.ones((self.y.ptp() + 1, self.x.ptp() +1 ), dtype=np.float32) grid *= self.nodata I = np.array(self.x - self.xmin, dtype=np.int) J = np.array(self.y - self.ymin, dtype=np.int) for k in xrange(I.size): i, j, d = I[k], J[k], self.z[k] grid[j,i] = d return grid
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" x, y, z = self.x, self.y, self.z grid = np.ones((y.ptp() + 1, x.ptp() +1 ), dtype=np.float32) grid *= self.nodata I = np.array(self.x - self.xmin, dtype=np.int) J = np.array(self.y - self.ymin, dtype=np.int) for k in xrange(I.size): i, j, d = I[k], J[k], self.z[k] grid[j,i] = d return grid
| 473,358
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" grid = np.ones((self.y.ptp() + 1, self.x.ptp() +1 ), dtype=np.float32) grid *= self.nodata I = np.array(self.x - self.xmin, dtype=np.int) J = np.array(self.y - self.ymin, dtype=np.int) for k in xrange(I.size): i, j, d = I[k], J[k], self.z[k] grid[j,i] = d return grid
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" grid = np.ones((self.y.ptp() + 1, self.x.ptp() +1 ), dtype=np.float32) grid *= self.nodata I = np.array(x - x.min(), dtype=np.int) J = np.array(y - y.min(), dtype=np.int) for k in xrange(I.size): i, j, d = I[k], J[k], self.z[k] grid[j,i] = d return grid
| 473,359
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" grid = np.ones((self.y.ptp() + 1, self.x.ptp() +1 ), dtype=np.float32) grid *= self.nodata I = np.array(self.x - self.xmin, dtype=np.int) J = np.array(self.y - self.ymin, dtype=np.int) for k in xrange(I.size): i, j, d = I[k], J[k], self.z[k] grid[j,i] = d return grid
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" grid = np.ones((self.y.ptp() + 1, self.x.ptp() +1 ), dtype=np.float32) grid *= self.nodata I = np.array(self.x - self.xmin, dtype=np.int) J = np.array(self.y - self.ymin, dtype=np.int) for k in xrange(I.size): i, j, d = I[k], J[k], z[k] grid[j,i] = d return grid
| 473,360
|
def isValidVolume(filename): """Tests whether a filename is a valid geoprobe file. Returns boolean True/False.""" try: testvol = vol(filename) except: return False volID = testvol.magic volSize = os.stat(filename).st_size predSize = testvol.nx*testvol.ny*testvol.nz + _headerLength # VolID == 43970 is a version 2 geoprobe volume (The only type currently supported) if (volID!=43970) or (volSize!=predSize): return False else: return True
|
def isValidVolume(filename): """Tests whether a filename is a valid geoprobe file. Returns boolean True/False.""" try: testvol = vol(filename) except: return False volID = testvol.magicNum volSize = os.stat(filename).st_size predSize = testvol.nx*testvol.ny*testvol.nz + _headerLength # VolID == 43970 is a version 2 geoprobe volume (The only type currently supported) if (volID!=43970) or (volSize!=predSize): return False else: return True
| 473,361
|
def main(): # Read an existing geoprobe volume vol = geoprobe.volume('data/Volumes/example.vol') # Print some info print_info(vol) # Example plots plot(vol)
|
def main(): # Read an existing geoprobe volume vol = geoprobe.volume(datadir + 'Volumes/example.vol') # Print some info print_info(vol) # Example plots plot(vol)
| 473,362
|
def __call__(self, *args): try: return self.cached_value except AttributeError: self.cached_value = self.function(*args) return self.cached_value
|
def __call__(self, *args): try: value = self.cached_value() if value is None: raise AttributeError except AttributeError: self.cached_value = self.function(*args) return self.cached_value
| 473,363
|
def __call__(self, *args): try: return self.cached_value except AttributeError: self.cached_value = self.function(*args) return self.cached_value
|
def __call__(self, *args): try: return self.cached_value except AttributeError: self.cached_value = self.function(*args) return self.cached_value
| 473,364
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = self._ensure_correct_dtype(args[0]) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = self._ensure_correct_dtype(args[0]) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
| 473,365
|
def _readTraces(self): dtype = [('x', '>f4'), ('y', '>f4'), ('traces', '%i>u1'%self._numSamples)] self._infile.seek(_headerLength) data = np.fromfile(self._infile, dtype=dtype, count=self._numTraces) self.x = data['x'] self.y = data['y'] self.data = data['traces']
|
def _readTraces(self): dtype = [('x', '>f4'), ('y', '>f4'), ('tracenum', '>f4'), ('traces', '%i>u1'%self._numSamples)] self._infile.seek(_headerLength) data = np.fromfile(self._infile, dtype=dtype, count=self._numTraces) self.x = data['x'] self.y = data['y'] self.data = data['traces']
| 473,366
|
def readBinary(self,fmt): """ Read and unpack a binary value from the file based on string fmt (see the struct module for details). """ size = struct.calcsize(fmt) data = self.read(size) # Reading beyond the end of the file just returns '' if len(data) != size: raise EOFError('End of file reached') data = struct.unpack(fmt, data)
|
def readBinary(self,fmt): """ Read and unpack a binary value from the file based on string fmt (see the struct module for details). """ size = struct.calcsize(fmt) data = self.read(size) # Reading beyond the end of the file just returns '' if len(data) != size: raise EOFError('End of file reached') data = struct.unpack(fmt, data)
| 473,367
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes nodata = depth != hor.nodata depth[nodata] -= vol.zmin depth[nodata] /= abs(vol.dz) depth = depth.astype(np.int) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast window_size = upper + lower + 1 subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] return subVolume
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes nodata = depth != hor.nodata depth[nodata] -= vol.zmin depth[nodata] /= abs(vol.dz) depth = depth.astype(np.int) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast window_size = upper + lower + 1 subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] return subVolume.squeeze()
| 473,368
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" try: return self._grid except AttributeError: grid = self.nodata*np.ones((self.data.y.ptp()+1,self.data.x.ptp()+1),dtype=np.float32) I = np.array(self.x-self.xmin,np.int) J = np.array(self.y-self.ymin,np.int) for k in xrange(I.size): i,j,d = I[k],J[k],self.z[k] grid[j,i] = d self._grid = grid return grid
|
def _get_grid(self): """An nx by ny numpy array (dtype=float32) of the z values contained in the horizon file""" try: return self._grid except AttributeError: grid = self.nodata*np.ones((self.y.ptp()+1,self.x.ptp()+1),dtype=np.float32) I = np.array(self.x-self.xmin,np.int) J = np.array(self.y-self.ymin,np.int) for k in xrange(I.size): i,j,d = I[k],J[k],self.z[k] grid[j,i] = d self._grid = grid return grid
| 473,369
|
def _readHorizon(self,filename): self._file = _horizonFile(filename, 'r')
|
def _readHorizon(self,filename): self._file = _horizonFile(filename, 'r')
| 473,370
|
def __init__(self, *args, **kwargs): """Accepts the same argument set as a standard python file object""" # Initalize the file object as normal file.__init__(self, *args, **kwargs)
|
def __init__(self, *args, **kwargs): """Accepts the same argument set as a standard python file object""" # Initalize the file object as normal file.__init__(self, *args, **kwargs)
| 473,371
|
def __init__(self, *args, **kwargs): """Accepts the same argument set as a standard python file object""" # Initalize the file object as normal file.__init__(self, *args, **kwargs)
|
def __init__(self, *args, **kwargs): """Accepts the same argument set as a standard python file object""" # Initalize the file object as normal file.__init__(self, *args, **kwargs)
| 473,372
|
def YSlice(self, Ypos): """Takes a slice of the volume at a constant y-value (i.e. the slice is in the direction of the x-axis) This is a convience function to avoid calling volume.model2index before slicing and transposing (for easier plotting) after. Input: Ypos: Y-Value given in model coordinates Output: A 2D (NZ x NX) numpy array""" Ypos = self.model2index(Ypos) return self.data[:,Ypos,:].transpose()
|
def YSlice(self, Ypos): """Takes a slice of the volume at a constant y-value (i.e. the slice is in the direction of the x-axis) This is a convience function to avoid calling volume.model2index before slicing and transposing (for easier plotting) after. Input: Ypos: Y-Value given in model coordinates Output: A 2D (NZ x NX) numpy array""" Ypos = self.model2index(Ypos, axis='y') return self.data[:,Ypos,:].transpose()
| 473,373
|
def ZSlice(self, Zpos): """Takes a slice of the volume at a constant z-value (i.e. a depth slice) This is a convience function to avoid calling volume.model2index before slicing and transposing (for easier plotting) after. Input: Zpos: Z-Value given in model coordinates Output: A 2D (NY x NX) numpy array""" Zpos = self.model2index(Zpos) return self.data[:,:,Zpos].transpose()
|
def ZSlice(self, Zpos): """Takes a slice of the volume at a constant z-value (i.e. a depth slice) This is a convience function to avoid calling volume.model2index before slicing and transposing (for easier plotting) after. Input: Zpos: Z-Value given in model coordinates Output: A 2D (NY x NX) numpy array""" Zpos = self.model2index(Zpos, axis='z') return self.data[:,:,Zpos].transpose()
| 473,374
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 0: pass elif len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = np.asarray(args[0], dtype=_point_dtype) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 0: pass elif len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = np.asarray(args[0], dtype=_point_dtype) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
| 473,375
|
def init_from_surface_lines(self, surface=None, lines=None): """Make a new horizon object from either a surface array or a list of line arrays""" if surface is not None: surface = np.asarray(surface, dtype=_point_dtype)
|
def _init_from_surface_lines(self, surface=None, lines=None): """Make a new horizon object from either a surface array or a list of line arrays""" if surface is not None: surface = np.asarray(surface, dtype=_point_dtype)
| 473,376
|
def init_from_surface_lines(self, surface=None, lines=None): """Make a new horizon object from either a surface array or a list of line arrays""" if surface is not None: surface = np.asarray(surface, dtype=_point_dtype)
|
def init_from_surface_lines(self, surface=None, lines=None): """Make a new horizon object from either a surface array or a list of line arrays""" if surface is not None: surface = np.asarray(surface, dtype=_point_dtype)
| 473,377
|
def readPoints(self): numPoints = self.readBinary('>I') if numPoints > 0: points = np.fromfile(self, count=numPoints, dtype=self.point_dtype) return points # apparently, len(points) is not 0 when numPoints is 0... else: return []
|
def readPoints(self): numPoints = self.readBinary('>I') if numPoints > 0: points = np.fromfile(self, count=numPoints, dtype=self.point_dtype) return points # apparently, len(points) is not 0 when numPoints is 0... else: return []
| 473,378
|
def sectionType(self): # No idea what the difference between #34 and #28, #2, etc is... (pos, neg, 0, pick??) secFmt = '>I' secID = self.readBinary(secFmt) if secID == 19: sectype = 'Points' else: sectype = 'Lines' return sectype
|
defsectionType(self):#Noideawhatthedifferencebetween#34and#28,#2,etcis...(pos,neg,0,pick??)secFmt='>I'secID=self.readBinary(secFmt)ifsecID==19:sectype='Points'else:sectype='Lines'returnsectype
| 473,379
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
| 473,380
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
| 473,381
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
| 473,382
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
|
def points(self): """A numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon (regardless of whehter it's a manual pick (line) or surface)""" self.readHeader() # Initalize an empty recarray to store things in lines = [] # To store line objects in secType = None self.readHeader() # Jump to start of file, past header
| 473,383
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizion(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes nodata = depth != hor.nodata depth[nodata] -= vol.zmin depth[nodata] /= abs(vol.dz) depth = depth.astype(np.int) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast window_size = upper + lower + 1 subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] return subVolume
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes nodata = depth != hor.nodata depth[nodata] -= vol.zmin depth[nodata] /= abs(vol.dz) depth = depth.astype(np.int) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast window_size = upper + lower + 1 subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] return subVolume
| 473,384
|
def _setVolumeBound(self, value, axis, max=True): axisLetter = ['x','y','z'][axis] n = [self.nx, self.ny, self.nz][axis] d = [self.dx, self.dy, self.dz][axis] offset = [self.x0, self.y0, self.z0][axis] if ((max is True) & (d>0)) or ((max is False) & (d<0)): value = value + (n-1) * d setattr(self, axisLetter+'0', value)
|
def _setVolumeBound(self, value, axis, max=True): axisLetter = ['x','y','z'][axis] n = [self.nx, self.ny, self.nz][axis] d = [self.dx, self.dy, self.dz][axis] offset = [self.x0, self.y0, self.z0][axis] if ((max is True) & (d>0)) or ((max is False) & (d<0)): value = value + (n-1) * abs(d) setattr(self, axisLetter+'0', value)
| 473,385
|
def __init__(self, *args, **kwargs): """Accepts the same argument set as a standard python file object""" # Initalize the file object as normal file.__init__(self, *args, **kwargs)
|
def __init__(self, *args, **kwargs): """Accepts the same argument set as a standard python file object""" # Initalize the file object as normal file.__init__(self, *args, **kwargs)
| 473,386
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = self._ensure_correct_dtype(args[0]) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
|
def _parse_new_horizon_input(self, *args, **kwargs): """Parse input when given something other than a filename""" #-- Parse Arguments --------------------------------------------------- if len(args) == 1: # Assume argument is data (numpy array with dtype of _point_dtype) self.data = self._ensure_correct_dtype(args[0]) self.surface = self.data elif len(args) == 2: # Assume arguments are surface + lines init_from_surface_lines(self, surface=args[0], lines=args[1])
| 473,387
|
def _init_from_xyz(self, x, y, z): """Make a new horizon object from x, y, and z arrays""" x,y,z = [np.asarray(item, dtype=np.float32) for item in [x,y,z]] if x.size == y.size == z.size: self.data = np.zeros(x.size, dtype=self.POINT_DTYPE) self.x = x self.y = y self.z = z self.surface = data else: raise ValueError('x, y, and z arrays must be the same length')
|
def _init_from_xyz(self, x, y, z): """Make a new horizon object from x, y, and z arrays""" x,y,z = [np.asarray(item, dtype=np.float32) for item in [x,y,z]] if x.size == y.size == z.size: self.data = np.zeros(x.size, dtype=self.POINT_DTYPE) self.x = x self.y = y self.z = z self.surface = self.data else: raise ValueError('x, y, and z arrays must be the same length')
| 473,388
|
def _readHorizon(self,filename): self._file = HorizonFile(filename, 'r')
|
def _readHorizon(self,filename): self._file = HorizonFile(filename, 'r')
| 473,389
|
def _set_grid(self, value): print 'Setting!' self._grid = value
|
def _set_grid(self, value): self._grid = value
| 473,390
|
def read_all(self): """ Reads in the entire horizon file and returns a numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon. """ # Note: The total number of points in the file is not directly stored # on disk. Therefore, we must read through the entire file, store # each section's points in a list, and then create a contigious array # from them. Using numpy.append is much simpler, but quite slow.
|
def read(self): """ Reads in the entire horizon file and returns a numpy array with the fields ('x', 'y', 'z', 'conf', 'type', 'herid', 'tileSize') for each point in the horizon. """ # Note: The total number of points in the file is not directly stored # on disk. Therefore, we must read through the entire file, store # each section's points in a list, and then create a contigious array # from them. Using numpy.append is much simpler, but quite slow.
| 473,391
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, overlap between horizion and volume) sub-region to use instead of full extent. Must be a 4-tuple of (xmin, xmax, ymin, ymax) masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
| 473,392
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
| 473,393
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
|
defextractWindow(hor,vol,upper=0,lower=None,offset=0,region=None,masked=False):"""ExtractsawindowaroundahorizionoutofageoprobevolumeInput:hor:ageoprobehorizionobjectorhorizionfilenamevol:ageoprobevolumeobjectorvolumefilenameupper:(default,0)upperwindowintervalaroundhorizionlower:(default,upper)lowerwindowintervalaroundhorizionoffset:(default,0)amount(invoxels)tooffsetthehorizionbyalongtheZ-axisregion:(default,fullextentofhorizion)sub-regiontouseinsteadoffullextentmasked:(default,False)ifTrue,returnamaskedarraywherenodatavaluesinthehorizonaremasked.Otherwise,returnanarraywherethenodatavaluesarefilledwith0.Output:returnsanumpyvolume"flattened"alongthehorizion"""#Ifthelowerwindowisn'tspecified,assumeit'sequaltotheupperwindowiflower==None:lower=upper#Iffilenamesareinputinsteadofvolume/horizionobjects,createtheobjectsiftype(hor)==type('String'):hor=horizon(hor)iftype(vol)==type('String'):vol=volume(vol)#Gah,changedthewayhor.gridworks...Shouldprobablychangeitbackdepth=hor.grid.T#Ifextentsarenotset,usethefullextentofthehorizion(assumeshorizionissmallerthanvolume)ifregion==None:xmin,xmax,ymin,ymax=hor.xmin,hor.xmax,hor.ymin,hor.ymaxelse:xmin,xmax,ymin,ymax=region#--Selectregionofoverlapbetweenvolumeandhorizon#Convertregiontovolumeindiciesxstart,ystart=xmin-vol.xmin,ymin-vol.yminxstop,ystop=xmax-vol.xmin,ymax-vol.ymin#Selectonlythevolumedatawithintheregionofinterestdata=vol.data[xstart:xstop,ystart:ystop,:]#Convertregiontohoriziongridindiciesxstart,ystart=xmin-hor.xmin,ymin-hor.yminxstop,ystop=xmax-hor.xmin,ymax-hor.ymin#Selectonlythevolumedatawithintheregionofinterestdepth=depth[xstart:xstop,ystart:ystop]nx,ny,nz=data.shape#convertzcoordsofhoriziontovolumeindexesdepth-=vol.zmindepth/=abs(vol.dz)depth=depth.astype(np.int)#Initalizetheoutputarraywindow_size=upper+lower+1#Notcreatingamaskedarrayhereduetospeedproblemswheniteratingthroughma'ssubVolume=np.zeros((nx,ny,window_size),dtype=np.uint8)#Usingfancyindexingtodothisusestonsofmemory...#Asitturnsout,simpleiterationismuch,muchmorememoryefficient,andalmostasfastmask=depth.mask#Needtopreservethemaskforlaterdepth=depth.filled()#Iteratingthroughmaskedarraysismuchslower,apparentlyforiinxrange(nx):forjinxrange(ny):ifdepth[i,j]!=hor.nodata:#Whereareweindataindiciesz=depth[i,j]+offsettop=z-upperbottom=z+lower+1#Becarefultoextracttherightverticalregionincaseswherethe#windowgoesoutsidethedatabounds(findregionofoverlap)data_top=max([top,0])data_bottom=min([bottom,nz])window_top=max([0,window_size-bottom])window_bottom=min([window_size,nz-top])#ExtractthewindowoutofdataandstoreitinsubVolumesubVolume[i,j,window_top:window_bottom]=data[i,j,data_top:data_bottom]#IfmaskedisTrue(inputoption),returnamaskedarrayifmasked:nx,ny,nz=subVolume.shapemask=mask.reshape((nx,ny,1))mask=np.tile(mask,(1,1,nz))subVolume=np.ma.array(subVolume,mask=mask)#Ifupper==lower==0,(default)subVolumewillbe(nx,ny,1),soreturn2DarrayinsteadsubVolume=subVolume.squeeze()returnsubVolume
| 473,394
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
| 473,395
|
def extractWindow(hor, vol, upper=0, lower=None, offset=0, region=None, masked=False): """Extracts a window around a horizion out of a geoprobe volume Input: hor: a geoprobe horizion object or horizion filename vol: a geoprobe volume object or volume filename upper: (default, 0) upper window interval around horizion lower: (default, upper) lower window interval around horizion offset: (default, 0) amount (in voxels) to offset the horizion by along the Z-axis region: (default, full extent of horizion) sub-region to use instead of full extent masked: (default, False) if True, return a masked array where nodata values in the horizon are masked. Otherwise, return an array where the nodata values are filled with 0. Output: returns a numpy volume "flattened" along the horizion """ # If the lower window isn't specified, assume it's equal to the upper window if lower == None: lower=upper # If filenames are input instead of volume/horizion objects, create the objects if type(hor) == type('String'): hor = horizon(hor) if type(vol) == type('String'): vol = volume(vol) #Gah, changed the way hor.grid works... Should probably change it back depth = hor.grid.T # If extents are not set, use the full extent of the horizion (assumes horizion is smaller than volume) if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region #-- Select region of overlap between volume and horizon # Convert region to volume indicies xstart, ystart = xmin - vol.xmin, ymin - vol.ymin xstop, ystop = xmax - vol.xmin, ymax - vol.ymin # Select only the volume data within the region of interest data = vol.data[xstart:xstop, ystart:ystop, :] # Convert region to horizion grid indicies xstart, ystart = xmin - hor.xmin, ymin - hor.ymin xstop, ystop = xmax - hor.xmin, ymax - hor.ymin # Select only the volume data within the region of interest depth = depth[xstart:xstop, ystart:ystop] nx,ny,nz = data.shape # convert z coords of horizion to volume indexes depth -= vol.zmin depth /= abs(vol.dz) depth = depth.astype(np.int) # Initalize the output array window_size = upper + lower + 1 # Not creating a masked array here due to speed problems when iterating through ma's subVolume = np.zeros((nx,ny,window_size), dtype=np.uint8) # Using fancy indexing to do this uses tons of memory... # As it turns out, simple iteration is much, much more memory efficient, and almost as fast mask = depth.mask # Need to preserve the mask for later depth = depth.filled() # Iterating through masked arrays is much slower, apparently for i in xrange(nx): for j in xrange(ny): if depth[i,j] != hor.nodata: # Where are we in data indicies z = depth[i,j] + offset top = z - upper bottom = z + lower + 1 # Be careful to extract the right vertical region in cases where the # window goes outside the data bounds (find region of overlap) data_top = max([top, 0]) data_bottom = min([bottom, nz]) window_top = max([0, window_size - bottom]) window_bottom = min([window_size, nz - top]) # Extract the window out of data and store it in subVolume subVolume[i,j,window_top:window_bottom] = data[i,j,data_top:data_bottom] # If masked is True (input option), return a masked array if masked: nx,ny,nz = subVolume.shape mask = mask.reshape((nx,ny,1)) mask = np.tile(mask, (1,1,nz)) subVolume = np.ma.array(subVolume, mask=mask) # If upper==lower==0, (default) subVolume will be (nx,ny,1), so return 2D array instead subVolume = subVolume.squeeze() return subVolume
|
defextractWindow(hor,vol,upper=0,lower=None,offset=0,region=None,masked=False):"""ExtractsawindowaroundahorizionoutofageoprobevolumeInput:hor:ageoprobehorizionobjectorhorizionfilenamevol:ageoprobevolumeobjectorvolumefilenameupper:(default,0)upperwindowintervalaroundhorizionlower:(default,upper)lowerwindowintervalaroundhorizionoffset:(default,0)amount(invoxels)tooffsetthehorizionbyalongtheZ-axisregion:(default,fullextentofhorizion)sub-regiontouseinsteadoffullextentmasked:(default,False)ifTrue,returnamaskedarraywherenodatavaluesinthehorizonaremasked.Otherwise,returnanarraywherethenodatavaluesarefilledwith0.Output:returnsanumpyvolume"flattened"alongthehorizion"""#Ifthelowerwindowisn'tspecified,assumeit'sequaltotheupperwindowiflower==None:lower=upper#Iffilenamesareinputinsteadofvolume/horizionobjects,createtheobjectsiftype(hor)==type('String'):hor=horizon(hor)iftype(vol)==type('String'):vol=volume(vol)#Gah,changedthewayhor.gridworks...Shouldprobablychangeitbackdepth=hor.grid.T#Ifextentsarenotset,usethefullextentofthehorizion(assumeshorizionissmallerthanvolume)ifregion==None:xmin,xmax,ymin,ymax=hor.xmin,hor.xmax,hor.ymin,hor.ymaxelse:xmin,xmax,ymin,ymax=region#--Selectregionofoverlapbetweenvolumeandhorizon#Convertregiontovolumeindiciesxstart,ystart=xmin-vol.xmin,ymin-vol.yminxstop,ystop=xmax-vol.xmin,ymax-vol.ymin#Selectonlythevolumedatawithintheregionofinterestdata=vol.data[xstart:xstop,ystart:ystop,:]#Convertregiontohoriziongridindiciesxstart,ystart=xmin-hor.xmin,ymin-hor.yminxstop,ystop=xmax-hor.xmin,ymax-hor.ymin#Selectonlythevolumedatawithintheregionofinterestdepth=depth[xstart:xstop,ystart:ystop]nx,ny,nz=data.shape#convertzcoordsofhoriziontovolumeindexesdepth-=vol.zmindepth/=abs(vol.dz)depth=depth.astype(np.int)#Initalizetheoutputarraywindow_size=upper+lower+1#Notcreatingamaskedarrayhereduetospeedproblemswheniteratingthroughma'ssubVolume=np.zeros((nx,ny,window_size),dtype=np.uint8)#Usingfancyindexingtodothisusestonsofmemory...#Asitturnsout,simpleiterationismuch,muchmorememoryefficient,andalmostasfastmask=depth.mask#Needtopreservethemaskforlaterdepth=depth.filled()#Iteratingthroughmaskedarraysismuchslower,apparentlyforiinxrange(nx):forjinxrange(ny):ifdepth[i,j]!=hor.nodata:#Whereareweindataindiciesz=depth[i,j]+offsettop=z-upperbottom=z+lower+1#Becarefultoextracttherightverticalregionincaseswherethe#windowgoesoutsidethedatabounds(findregionofoverlap)data_top=max([top,0])data_bottom=min([bottom,nz])window_top=max([0,window_size-bottom])window_bottom=min([window_size,nz-top])#ExtractthewindowoutofdataandstoreitinsubVolumesubVolume[i,j,window_top:window_bottom]=data[i,j,data_top:data_bottom]#IfmaskedisTrue(inputoption),returnamaskedarrayifmasked:nx,ny,nz=subVolume.shapemask=mask.reshape((nx,ny,1))mask=np.tile(mask,(1,1,nz))subVolume=np.ma.array(subVolume,mask=mask)#Ifupper==lower==0,(default)subVolumewillbe(nx,ny,1),soreturn2DarrayinsteadsubVolume=subVolume.squeeze()returnsubVolume
| 473,396
|
def intersects(bbox1, bbox2): # Check for intersection xmin1, xmax1, ymin1, ymax1 = bbox1 xmin2, xmax2, ymin2, ymax2 = bbox2 xdist = abs( (xmin1 + xmax1) / 2.0 - (xmin2 + xmax2) / 2.0 ) ydist = abs( (ymin1 + ymax1) / 2.0 - (ymin2 + ymax2) / 2.0 ) xwidth = (xmax1 - xmin1 + xmax2 - xmin2) / 2.0 ywidth = (ymax1 - ymin1 + ymax2 - ymin2) / 2.0 return (xdist <= xwidth) and (ydist <= ywidth)
|
def intersects(bbox1, bbox2): # Check for intersection xmin1, xmax1, ymin1, ymax1 = bbox1 xmin2, xmax2, ymin2, ymax2 = bbox2 xdist = abs( (xmin1 + xmax1) / 2.0 - (xmin2 + xmax2) / 2.0 ) ydist = abs( (ymin1 + ymax1) / 2.0 - (ymin2 + ymax2) / 2.0 ) xwidth = (xmax1 - xmin1 + xmax2 - xmin2) / 2.0 ywidth = (ymax1 - ymin1 + ymax2 - ymin2) / 2.0 return (xdist <= xwidth) and (ydist <= ywidth)
| 473,397
|
def __init__(self, input): """Takes either a filename or a numpy array"""
|
def __init__(self, input): """Takes either a filename or a numpy array"""
| 473,398
|
def infix_to_prefix(expr): """converts the infix expression to prefix using the shunting yard algorithm""" ops = [] results = [] for token in tokenize(expr): #print ops, results if is_op(token): #If the token is an operator, o1, then: #while there is an operator token, o2, at the top of the stack, and #either o1 is left-associative and its precedence is less than or equal to that of o2, #or o1 is right-associative and its precedence is less than that of o2, #pop o2 off the stack, onto the output queue; #push o1 onto the stack. while len(ops) > 0 and is_op(ops[-1]) and \ ( (associativity(token) == 'left' and precedence(token) <= ops[-1]) \ or (associativity(token) == 'right' and precedence(token) < ops[-1]) ): results.append(ops.pop()) ops.append(token) #If the token is a left parenthesis, then push it onto the stack. elif is_left_paran(token): ops.append(token) #If the token is a right parenthesis: elif is_right_paran(token): #Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. while len(ops) > 0 and not is_left_paran(ops[-1]): results.append(ops.pop()) #Pop the left parenthesis from the stack, but not onto the output queue. #If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. if len(ops) == 0: print "error: mismatched parentheses" exit() if is_left_paran(ops[-1]): ops.pop() else: #If the token is a number, then add it to the output queue. results.append(token) #When there are no more tokens to read: #While there are still operator tokens in the stack: while len(ops) > 0: #If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. if is_right_paran(ops[-1]) or is_left_paran(ops[-1]): print "error: mismatched parentheses" exit() #Pop the operator onto the output queue. results.append(ops.pop()) return results
|
def infix_to_prefix(expr): """converts the infix expression to prefix using the shunting yard algorithm""" ops = [] results = [] for token in tokenize(expr): #print ops, results if is_op(token): #If the token is an operator, o1, then: #while there is an operator token, o2, at the top of the stack, and #either o1 is left-associative and its precedence is less than or equal to that of o2, #or o1 is right-associative and its precedence is less than that of o2, #pop o2 off the stack, onto the output queue; #push o1 onto the stack. while len(ops) > 0 and is_op(ops[-1]) and \ ( (associativity(token) == 'left' and precedence(token) <= precedence(ops[-1])) \ or (associativity(token) == 'right' and precedence(token) < precedence(ops[-1])) ): results.append(ops.pop()) ops.append(token) #If the token is a left parenthesis, then push it onto the stack. elif is_left_paran(token): ops.append(token) #If the token is a right parenthesis: elif is_right_paran(token): #Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. while len(ops) > 0 and not is_left_paran(ops[-1]): results.append(ops.pop()) #Pop the left parenthesis from the stack, but not onto the output queue. #If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. if len(ops) == 0: print "error: mismatched parentheses" exit() if is_left_paran(ops[-1]): ops.pop() else: #If the token is a number, then add it to the output queue. results.append(token) #When there are no more tokens to read: #While there are still operator tokens in the stack: while len(ops) > 0: #If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. if is_right_paran(ops[-1]) or is_left_paran(ops[-1]): print "error: mismatched parentheses" exit() #Pop the operator onto the output queue. results.append(ops.pop()) return results
| 473,399
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.