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 ...
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) ... ...
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 disc...
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 h...
... 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().i...
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 do...
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 a...
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.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) ...
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' % n...
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)...
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_ARRA...
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...
"""
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...
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'], va...
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'], va...
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 manipulatin...
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...
(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])...
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 = 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]
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...
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 geop...
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])...
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...
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,...
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...
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 ...
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...
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.asarra...
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 se...
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 se...
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 se...
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 se...
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,...
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 = 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, ...
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, s...
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 lo...
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 ...
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 lo...
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 + ...
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 lef...
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.Ex...
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 = ...
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 = ...
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 = ...
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 = ...
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.Ex...