rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
sage: [ ker * lp.facet_normal(i) for i in range(0,4) ] | sage: [ker * p.facet_normal(i) for i in range(p.nfacets())] | def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. |
sage: matrix([lp.facet_normal(i) for i in range(0,4)]) * lp.vertices() [ 0 0 -20 0] [ 0 -20 0 0] [ 10 10 10 0] [-20 0 0 0] sage: matrix([[ lp.facet_normal(i)*lp.vertex(j) + lp.facet_constant(i) for i in range(0,4)] for j in range(0,4)]) [ 0 0 0 -20] [ 0 -20 0 0] [-20 0 0 0] [ 0 0 -10 0] | Now we manually compute the distance matrix of this polytope. Since it is a simplex, each line (corresponding to a facet) should consist of zeros (indicating generating vertices of the corresponding facet) and a single positive number (since our normals are inner):: sage: matrix([[p.facet_normal(i) * p.vertex(j) ... + p.facet_constant(i) ... for j in range(p.nvertices())] ... for i in range(p.nfacets())]) [ 0 0 0 20] [ 0 0 20 0] [ 0 20 0 0] [10 0 0 0] | def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. |
.. rubric:: Common Usage: | .. rubric:: Common use case: | ... def __repr__(self): |
A priori, since they are mostly called during user interaction, there is no particular need to write fast ``__repr__`` methods, and indeed there are some objects ``x`` whose call ``x.__repr__()`` is quite time expensive. However, there are several use case where it is actually called and when the results is simply discarded. In particular writing ``"%s"%x`` actually calls ``x.__repr__()`` even the results is not printed. A typical use case is during tests when there is a tester which tests an assertion and prints an error message on failure:: | Most of the time, ``__repr__`` methods are only called during user interaction, and therefore need not be fast; and indeed there are objects ``x`` in Sage such ``x.__repr__()`` is time consuming. There are however some uses cases where many format strings are constructed but not actually printed. This includes error handling messages in :mod:`unittest` or :class:`TestSuite` executions:: | ... def __repr__(self): |
Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points. | Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points. Used internally by the :meth:`~rank`, :meth:`~rank_bounds` and :meth:`~gens` methods. | def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points. |
Uses Denis Simon's GP/PARI scripts from \url{http://www.math.unicaen.fr/~simon/}. | Uses Denis Simon's GP/PARI scripts from http://www.math.unicaen.fr/~simon/. | def simon_two_descent(self, verbose=0, lim1=5, lim3=50, limtriv=10, maxprob=20, limbigprime=30): r""" Computes lower and upper bounds on the rank of the Mordell-Weil group, and a list of independent points. |
I | i | def _sympy_(self): """ Converts pi to sympy pi. |
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().is_prime()`` to find out for sure whether this quotient ring is really not an integral domain, of if Sage is unable to determine the answer. EXAMPLES:: sage: R = Integers(8) sage: R.is_integral_domain() | def is_integral_domain(self, proof=True): r""" With ``proof`` equal to ``True`` (the default), this function may raise a ``NotImplementedError``. When ``proof`` is ``False``, if ``True`` is returned, then self is definitely an integral domain. If the function returns ``False``, then either self is not an integral domain or it was unable to determine whether or not self is an integral domain. EXAMPLES:: sage: R.<x,y> = QQ[] sage: R.quo(x^2 - y).is_integral_domain() True sage: R.quo(x^2 - y^2).is_integral_domain() | def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. |
sage: R.<a,b,c> = ZZ['a','b','c'] sage: I = R.ideal(a,b) sage: Q = R.quotient_ring(I) | sage: R.quo(x^2 - y^2).is_integral_domain(proof=False) False sage: R.<a,b,c> = ZZ[] sage: Q = R.quotient_ring([a, b]) | def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. |
return self.defining_ideal.is_prime() except AttributeError: return False | return self.defining_ideal().is_prime() | def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. |
assert z.denominator() == 1, "bug in global_integral_model: %s" % ai | assert z.is_integral(), "bug in global_integral_model: %s" % list(ai) | def global_integral_model(self): r""" Return a model of self which is integral at all primes. |
self._dual = Cone(rays, lattice=self.lattice().dual(), check=False) | self._dual = Cone(rays, lattice=self.dual_lattice(), check=False) | def dual(self): r""" Return the dual cone of ``self``. |
Let `M=` ``self.lattice().dual()`` be the lattice dual to the | Let `M=` ``self.dual_lattice()`` be the lattice dual to the | def orthogonal_sublattice(self, *args, **kwds): r""" The sublattice (in the dual lattice) orthogonal to the sublattice spanned by the cone. |
def edge_boundary(self, vertices1, vertices2=None, labels=True): | def edge_boundary(self, vertices1, vertices2=None, labels=True, sort=True): | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
sage: G = graphs.PetersenGraph() | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
|
""" vertices1 = [v for v in vertices1 if v in self] output = [] | sage: G.edge_boundary([2], [0]) [(0, 2, {})] """ vertices1 = set([v for v in vertices1 if v in self]) | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
output.extend(self.outgoing_edge_iterator(vertices1,labels=labels)) | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
|
output = [e for e in output if e[1] in vertices2] | vertices2 = set([v for v in vertices2 if v in self]) output = [e for e in self.outgoing_edge_iterator(vertices1,labels=labels) if e[1] in vertices2] | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
output = [e for e in output if e[1] not in vertices1] return output | output = [e for e in self.outgoing_edge_iterator(vertices1,labels=labels) if e[1] not in vertices1] | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
output.extend(self.edge_iterator(vertices1,labels=labels)) output2 = [] | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
|
for e in output: if e[0] in vertices1: if e[1] in vertices2: output2.append(e) elif e[0] in vertices2: output2.append(e) | vertices2 = set([v for v in vertices2 if v in self]) output = [e for e in self.edge_iterator(vertices1,labels=labels) if (e[0] in vertices1 and e[1] in vertices2) or (e[1] in vertices1 and e[0] in vertices2)] | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
for e in output: if e[0] in vertices1: if e[1] not in vertices1: output2.append(e) elif e[0] not in vertices1: output2.append(e) return output2 | output = [e for e in self.edge_iterator(vertices1,labels=labels) if e[1] not in vertices1 or e[0] not in vertices1] if sort: output.sort() return output | def edge_boundary(self, vertices1, vertices2=None, labels=True): """ Returns a list of edges `(u,v,l)` with `u` in ``vertices1`` and `v` in ``vertices2``. If ``vertices2`` is ``None``, then it is set to the complement of ``vertices1``. |
Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. | Returns an iterator over edges. The iterator returned is over the edges incident with any vertex given in the parameter ``vertices``. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. | def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. |
- ``ignore_direction`` - (default False) only applies | - ``ignore_direction`` - bool (default: False) - only applies | def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. |
for e in self._backend.iterator_out_edges(vertices, labels): yield e for e in self._backend.iterator_in_edges(vertices, labels): yield e | from itertools import chain return chain(self._backend.iterator_out_edges(vertices, labels), self._backend.iterator_in_edges(vertices, labels)) | def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. |
for e in self._backend.iterator_out_edges(vertices, labels): yield e | return self._backend.iterator_out_edges(vertices, labels) | def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. |
for e in self._backend.iterator_edges(vertices, labels): yield e def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices | return self._backend.iterator_edges(vertices, labels) def edges_incident(self, vertices=None, labels=True, sort=True): """ Returns incident edges to some vertices. If ``vertices` is a vertex, then it returns the list of edges incident to that vertex. If ``vertices`` is a list of vertices then it returns the list of all edges adjacent to those vertices. If ``vertices`` | def edge_iterator(self, vertices=None, labels=True, ignore_direction=False): """ Returns an iterator over the edges incident with any vertex given. If the graph is directed, iterates over edges going out only. If vertices is None, then returns an iterator over all edges. If self is directed, returns outgoing edges only. |
- ``label`` - if False, each edge is a tuple (u,v) of vertices. | - ``vertices`` - object (default: None) - a vertex, a list of vertices or None. - ``labels`` - bool (default: True) - if False, each edge is a tuple (u,v) of vertices. - ``sort`` - bool (default: True) - if True the returned list is sorted. | def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges. |
v = list(self.edge_boundary(vertices, labels=labels)) v.sort() return v | if sort: return sorted(self.edge_iterator(vertices=vertices,labels=labels)) return list(self.edge_iterator(vertices=vertices,labels=labels)) | def edges_incident(self, vertices=None, labels=True): """ Returns a list of edges incident with any vertex given. If vertices is None, returns a list of all edges in graph. For digraphs, only lists outward edges. |
Morphism from module over Integer Ring with invariants (2, 0, 0) to module with invariants (0, 0, 0) that sends the generators to [(0, 0, 0), (0, 0, 1), (0, 1, 0)] | Morphism from module over Integer Ring with invariants (2, 0, 0) to module with invariants (0, 0, 0) that sends the generators to [(0, 0, 0), (1, 0, 0), (0, 1, 0)] | def hom(self, im_gens, codomain=None, check=True): """ Homomorphism defined by giving the images of ``self.gens()`` in some fixed fg R-module. |
(0, 0, 1) | (1, 0, 0) | def hom(self, im_gens, codomain=None, check=True): """ Homomorphism defined by giving the images of ``self.gens()`` in some fixed fg R-module. |
This can be very helpful in showing certain features of plots. | This can be very helpful in showing certain features of plots. :: sage: plot(1.5/(1+e^(-x)), (x, -10, 10)) | sage: def maple_leaf(t): |
sage: plot(1.5/(1+e^(-x)), (x, -10, 10)) | sage: def maple_leaf(t): |
|
def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): | def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=None): | def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points. |
- ``previous_row`` -- (default: ``[]``) This option is only relevant | - ``previous_row`` -- (default: ``None``) This option is only relevant | def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points. |
The return value should always be an element of ``self'', in the case of ``divided_difference'', or a list of elements of ``self'', in the case of ``neville'':: | Make sure that ticket be an element of ``self`` in the case of ``divided_difference``, or a list of elements of ``self`` in the case of ``neville``. :: | def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=[]): """ Return the Lagrange interpolation polynomial in ``self`` associated to the given list of points. |
""" | r""" | def strip_answer(self, s): """ Returns the string s with Matlab's answer prompt removed. |
for i in xrange(0, l - 2): | for i in xrange(0, l-1): | def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise. |
This function is an automatic generated pexpect wrapper around the Singular | This function is an automatically generated pexpect wrapper around the Singular | def _sage_doc_(self): """ EXAMPLES:: |
module.include_dirs.append(sage_inc) | 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]) |
|
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) module.library_dirs.extend([sage_lib]) |
|
print_message( 'numpy 1.1 or later is required; you have %s' % numpy.__version__) return False | if not int(nn[0]) >= 1: print_message( 'numpy 1.1 or later is required; you have %s' % numpy.__version__) return False | 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 |
tk_lib_dir = tcl_lib_dir.replace('Tcl', 'Tk').replace('tcl', 'tk') | (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') | 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 |
define_macros=[('PY_ARRAYAUNIQUE_SYMBOL', 'MPL_ARRAY_API')]) | define_macros=[('PY_ARRAY_UNIQUE_SYMBOL', 'MPL_ARRAY_API')]) | 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 |
sage: c = c2 = 1 | sage: c == c2 calling __eq__ defined in Metaclass True """ def __eq__(self, other): print "calling __eq__ defined in Metaclass" return (type(self) == type(other)) and (self.reduce_args == other.reduce_args) | 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 |
|
self.data = self._fixAxes(data.astype(np.uint8)) | self.data = self._fixAxes(data) | 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.""" |
self._infile = BinaryFile(filename, 'w') | outfile = BinaryFile(filename, 'w') | 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) |
self._infile.seek(info['offset']) self._infile.writeBinary(info['type'], value) self._infile.seek(_headerLength) self.data.ravel('F').tofile(self._infile, format='B') self._infile.close() | outfile.seek(info['offset']) outfile.writeBinary(info['type'], value) outfile.seek(_headerLength) self.data.T.tofile(outfile, format='B') outfile.close() | 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) |
newData = np.asarray(newData).astype(np.uint8) | newData = np.asarray(newData, dtype=np.uint8) | 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 |
self.data = self._file.read() | self.data = self._file.read_all() | def _readHorizon(self,filename): self._file = HorizonFile(filename, 'r') |
def read(self): | def read_all(self): | 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. |
(self.originalNx, self.originalNy, self.originalNz) = data.shape | (self.originalnx, self.originalny, self.originalnz) = data.shape | 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.""" |
self.x = self.data['x'] self.y = self.data['y'] self.z = self.data['z'] | def __init__(self, input): """Takes either a filename or a numpy array""" |
|
surface = kwargs.pop('surface', None), | surface = kwargs.pop('surface', None) | 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]) |
grid = np.ones((self.y.ptp() + 1, self.x.ptp() +1 ), dtype=np.float32) | x, y, z = self.x, self.y, self.z grid = np.ones((y.ptp() + 1, x.ptp() +1 ), dtype=np.float32) | 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 |
I = np.array(self.x - self.xmin, dtype=np.int) J = np.array(self.y - self.ymin, dtype=np.int) | I = np.array(x - x.min(), dtype=np.int) J = np.array(y - y.min(), dtype=np.int) | 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 |
i, j, d = I[k], J[k], self.z[k] | i, j, d = I[k], J[k], z[k] | 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 |
volID = testvol.magic | volID = testvol.magicNum | 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 |
vol = geoprobe.volume('data/Volumes/example.vol') | vol = geoprobe.volume(datadir + 'Volumes/example.vol') | def main(): # Read an existing geoprobe volume vol = geoprobe.volume('data/Volumes/example.vol') # Print some info print_info(vol) # Example plots plot(vol) |
return self.cached_value | value = self.cached_value() if value is None: raise AttributeError | def __call__(self, *args): try: return self.cached_value except AttributeError: self.cached_value = self.function(*args) return self.cached_value |
self.cached_value = self.function(*args) return self.cached_value | retval = self.function(*args) self.cached_value = weakref.ref(retval) value = self.cached_value() return value | def __call__(self, *args): try: return self.cached_value except AttributeError: self.cached_value = self.function(*args) return self.cached_value |
init_from_xyz(self, *args) | self._init_from_xyz(self, *args) | 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]) |
dtype = [('x', '>f4'), ('y', '>f4'), ('traces', '%i>u1'%self._numSamples)] | dtype = [('x', '>f4'), ('y', '>f4'), ('tracenum', '>f4'), ('traces', '%i>u1'%self._numSamples)] | 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'] |
data = data.strip('\x00') | item = item.strip('\x00') | 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) |
return subVolume | return subVolume.squeeze() | 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 |
grid = self.nodata*np.ones((self.data.y.ptp()+1,self.data.x.ptp()+1),dtype=np.float32) | grid = self.nodata*np.ones((self.y.ptp()+1,self.x.ptp()+1),dtype=np.float32) | 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 |
self._file = _horizonFile(filename, 'r') | self._file = HorizonFile(filename, 'r') | def _readHorizon(self,filename): self._file = _horizonFile(filename, 'r') |
self._dtype = [] for name, fmt in zip(_pointNames, _pointFormat): self._dtype.append((name,fmt)) | self.point_dtype = [] for name, fmt in zip(self._pointNames, self._pointFormat): self.point_dtype.append((name,fmt)) | 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) |
self._pointSize = sum(map(struct.calcsize, _pointFormat)) | self._pointSize = sum(map(struct.calcsize, self._pointFormat)) | 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) |
Ypos = self.model2index(Ypos) | Ypos = self.model2index(Ypos, axis='y') | 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() |
Zpos = self.model2index(Zpos) | Zpos = self.model2index(Zpos, axis='z') | 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() |
elif ('surface' in kwargs) and ('lines' in kwargs): self._init_from_surface_lines(kwargs['surface'], kwargs['lines']) elif 'surface' in kwargs: self._init_from_surface_lines(surface=surface) elif 'lines' in kwargs: self._init_from_surface_lines(lines=lines) | elif ('surface' in kwargs) or ('lines' in kwargs): surface, lines = kwargs.pop('surface', None), kwargs.pop('lines', None) self._init_from_surface_lines(surface, lines) | 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 init_from_surface_lines(self, surface=None, lines=None): | def _init_from_surface_lines(self, surface=None, lines=None): | 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) |
self.lines.append(info, data[i:i+item.size]) | self.lines.append((info, self.data[i:i+item.size])) i += item.size | 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) |
if numPoints > 0: points = np.fromfile(self, count=numPoints, dtype=self.point_dtype) return points else: return [] | points = np.fromfile(self, count=numPoints, dtype=self.point_dtype) return points | 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 [] |
self.readHeader() lines = [] secType = None self.readHeader() | self.readHeader() | 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 |
points = self.readPoints() | temp_points = [self.readPoints()] | 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 |
lines.append((lineInfo, currentPoints)) np.append(points, currentPoints) | temp_points.append(currentPoints) | 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 |
pass self.lines = lines | pass numpoints = sum(map(np.size, temp_points)) points = np.zeros(numpoints, dtype=self.point_dtype) i = 0 for item in temp_points: points[i : i + item.size] = item i += item.size | 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 |
hor = horizion(hor) | hor = horizon(hor) | 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 |
value = value + (n-1) * d | value = value + (n-1) * abs(d) | 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) |
self._pointSize = struct.calcsize(''.join(_pointFormat)) | self._pointSize = sum(map(struct.calcsize, _pointFormat)) | 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) |
self._init_from_xyz(self, *args) | self._init_from_xyz(*args) | 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]) |
self.surface = data | self.surface = self.data | 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') |
self.data = self._file.read_all() | self.data = self._file.read() | def _readHorizon(self,filename): self._file = HorizonFile(filename, 'r') |
print 'Setting!' | def _set_grid(self, value): print 'Setting!' self._grid = value |
|
def read_all(self): | def read(self): | 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. |
region: (default, full extent of horizion) sub-region to use instead of full extent | 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) | 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 |
if region == None: xmin, xmax, ymin, ymax = hor.xmin, hor.xmax, hor.ymin, hor.ymax else: xmin, xmax, ymin, ymax = region | vol_extents = [vol.xmin, vol.xmax, vol.ymin, vol.ymax] hor_extents = [hor.xmin, hor.xmax, hor.ymin, hor.ymax] extents = bbox_overlap(hor_extents, vol_extents) if extents is None: raise ValueError('Input horizon and volume do not intersect!') if region is not None: extents = bbox_overlap(extents, region) if extents is None: raise ValueError('Specified region does not overlap with horizon and volume') elif len(extents) != 4: raise ValueError('"extents" must be a 4-tuple of (xmin, xmax, ymin, ymax)') xmin, xmax, ymin, ymax = extents | 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 |
print extents | 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) |
|
self.x = self.data.x self.y = self.data.y self.z = self.data.z | self.x = self.data['x'] self.y = self.data['y'] self.z = self.data['z'] | def __init__(self, input): """Takes either a filename or a numpy array""" |
( (associativity(token) == 'left' and precedence(token) <= ops[-1]) \ or (associativity(token) == 'right' and precedence(token) < ops[-1]) ): | ( (associativity(token) == 'left' and precedence(token) <= precedence(ops[-1])) \ or (associativity(token) == 'right' and precedence(token) < precedence(ops[-1])) ): | 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 |
v = obj.Schema().getField(field).get(obj, mimetype="text/plain") | v = obj.Schema().getField(field).getRaw(obj) | def get(self, obj, field, context=None): """ """ v = obj.Schema().getField(field).get(obj, mimetype="text/plain") return v |
f = str(f.data) full_path = os.path.join(parent_path, filename) try: full_path = full_path.encode('ascii') except: try: full_path = full_path.decode('utf-8').encode('ascii') except: pass zip.writestr(full_path, f) | fdata = str(f.data) full_path = os.path.join(parent_path, zip_filename) zip.writestr(full_path, fdata) | def get(self, obj, field, context=None, zip=None, parent_path=''): """ """ f = obj.Schema().getField(field).get(obj) if not f : return '' else: filename = f.filename if zip is not None: #logger.error(obj.Schema().getField(field).getType()) if obj.Schema().getField(field).getType() in \ ("plone.app.blob.subtypes.file.ExtensionBlobField", "Products.Archetypes.Field.FileField", 'Products.AttachmentField.AttachmentField.AttachmentField', "Products.Archetypes.Field.ImageField"): |
obj = getattr(container.aq_explicit, id, None) if obj is None: | oids = container.objectIds() if not id in oids: | def importObject(self, row, specific_fields, type, conflict_winner, export_date, wf_transition, zip, encoding='utf-8', ignore_content_errors=False, plain_format=False): """ """ modified = False is_new_object = False protected = True parent_path = row[0] id = row[1] type_class = row[2] if parent_path == "": container = self.context else: try: container = self.context.unrestrictedTraverse(parent_path) except: raise csvreplicataNonExistentContainer, \ "Non existent container %s " % parent_path |
obj = getattr(container.aq_explicit, id) | def importObject(self, row, specific_fields, type, conflict_winner, export_date, wf_transition, zip, encoding='utf-8', ignore_content_errors=False, plain_format=False): """ """ modified = False is_new_object = False protected = True parent_path = row[0] id = row[1] type_class = row[2] if parent_path == "": container = self.context else: try: container = self.context.unrestrictedTraverse(parent_path) except: raise csvreplicataNonExistentContainer, \ "Non existent container %s " % parent_path |
|
else: | obj = getattr(container.aq_explicit, id, None) if not is_new_object: | def importObject(self, row, specific_fields, type, conflict_winner, export_date, wf_transition, zip, encoding='utf-8', ignore_content_errors=False, plain_format=False): """ """ modified = False is_new_object = False protected = True parent_path = row[0] id = row[1] type_class = row[2] if parent_path == "": container = self.context else: try: container = self.context.unrestrictedTraverse(parent_path) except: raise csvreplicataNonExistentContainer, \ "Non existent container %s " % parent_path |
obj = getattr(container.aq_explicit, id, None) | def importObject(self, row, specific_fields, type, conflict_winner, export_date, wf_transition, zip, encoding='utf-8', ignore_content_errors=False, plain_format=False): """ """ modified = False is_new_object = False protected = True parent_path = row[0] id = row[1] type_class = row[2] if parent_path == "": container = self.context else: try: container = self.context.unrestrictedTraverse(parent_path) except: raise csvreplicataNonExistentContainer, \ "Non existent container %s " % parent_path |
|
zip.writestr(os.path.join(parent_path, filename), f) | full_path = os.path.join(parent_path, filename) try: full_path = full_path.encode('ascii') except: try: full_path = full_path.decode('utf-8').encode('ascii') except: pass zip.writestr(full_path, f) | def get(self, obj, field, context=None, zip=None, parent_path=''): """ """ f = obj.Schema().getField(field).get(obj) if not f : return '' else: filename = f.filename if zip is not None: #logger.error(obj.Schema().getField(field).getType()) if obj.Schema().getField(field).getType() in \ ("plone.app.blob.subtypes.file.ExtensionBlobField", "Products.Archetypes.Field.FileField", 'Products.AttachmentField.AttachmentField.AttachmentField', "Products.Archetypes.Field.ImageField"): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.