Example #1
0
    def grid(self, dx=None, dy=None, extents=None, vol=None):

        if extents is None:
            xstart, xstop = self.xmin, self.xmax
            ystart, ystop = self.ymin, self.ymax
        else:
            xstart, xstop, ystart, ystop = extents

        if vol is not None:
            # Interpolate ezfault at volume indicies
            if type(vol) == type('String'):
                vol = volume(vol)
            dx, dy = abs(vol.dx), abs(vol.dy)

            # Make sure we start at a volume index
            xstart, xstop = [vol.index2model(vol.model2index(item))
                            for item in [xstart, xstop] ]
            ystart, ystop= [vol.index2model(
                                vol.model2index(item, axis='y'),
                                axis='y')
                            for item in [ystart, ystop] ]

        else:
            if dx is None: dx = 1
            if dy is None: dy = dx

        X = np.arange(xstart, xstop, dx)
        Y = np.arange(ystart, ystop, dy)
        # Not needed w/ new way of interpolating?
#        X,Y = np.meshgrid(X,Y)
        grid = self.interpolate(X,Y)

#        grid = Z.reshape(X.shape)

        return grid
Example #2
0
    def run(self):
        # make numpy arrays for the solvent and solute
        solute = [] 
        solvent = []
        solute_rad = []
        for atom in self.pdb.atoms:
            if atom['resname'] == self.solventname:
                solvent.append(atom['position'])
            else:
                try:
                    solute_rad.append(self.radii[atom['resname']][atom['atomname']])
                    solute.append(atom['position'])
                except KeyError:
                    print("no radius specified for residue, atom name ({:s}, {:s}). "\
                          "Excluding from volume calculation".format(atom['resname'],
                                                                     atom['atomname']))

        solute = numpy.array(solute, dtype=numpy.float64)
        solvent = numpy.array(solvent, dtype=numpy.float64)
        solute_rad = numpy.array(solute_rad, dtype=numpy.float64)
        

        if self.use_explicit_solvent:
            return volume.volume_explicit_sol(solute, solute_rad, solvent, 
                                              self.solventrad, self.voxel_len)
        else:
            return volume.volume(solute, solute_rad, self.solventrad, 
                                 self.voxel_len)
Example #3
0
    def grid(self, dx=None, dy=None, extents=None, vol=None):

        if extents is None:
            xstart, xstop = self.xmin, self.xmax
            ystart, ystop = self.ymin, self.ymax
        else:
            xstart, xstop, ystart, ystop = extents

        if vol is not None:
            # Interpolate ezfault at volume indicies
            if type(vol) == type('String'): 
                vol = volume(vol)
            dx, dy = abs(vol.dx), abs(vol.dy)

            # Make sure we start at a volume index
            xstart, xstop = [vol.index2model(vol.model2index(item)) 
                            for item in [xstart, xstop] ] 
            ystart, ystop= [vol.index2model(
                                vol.model2index(item, axis='y'), 
                                axis='y') 
                            for item in [ystart, ystop] ] 

        else: 
            if dx is None: dx = 1
            if dy is None: dy = dx

        X = np.arange(xstart, xstop, dx)
        Y = np.arange(ystart, ystop, dy)
        # Not needed w/ new way of interpolating?
#        X,Y = np.meshgrid(X,Y)
        grid = self.interpolate(X,Y)

#        grid = Z.reshape(X.shape)

        return grid
Example #4
0
def status():
    return ''.join([
        ' ', network.status,
        memory_free(spacer),
        volume(spacer), battery.status,
        datetime.datetime.now().strftime('%Y-%m-%d %A %-I:%M %P'), ' '
    ])
Example #5
0
def set_class(queue):
    global class_data
    for node in queue:
        if not node.get('name'):
            class_data.append(
                base.Base(trace_id=node['trace_id'], level=node['level']))
        elif node.get('name') == 'db':
            class_data.append(
                db.DB(node['project'], node['service'], node['level'],
                      node['trace_id'], node['parent_id'], node['starttime'],
                      node['time']))
        elif node.get('name') == 'wsgi':
            class_data.append(
                wsgi.WSGI(node['project'], node['service'], node['level'],
                          node['trace_id'], node['parent_id'],
                          node['starttime'], node['time']))
        elif node.get('name') == 'compute_api':
            class_data.append(
                compute.compute(node['project'], node['service'],
                                node['level'], node['trace_id'],
                                node['parent_id'], node['starttime'],
                                node['time']))
        elif node.get('name') == 'rpc':
            class_data.append(
                rpc.RPC(node['project'], node['service'], node['level'],
                        node['trace_id'], node['parent_id'], node['starttime'],
                        node['time']))
        elif node.get('name') == 'driver':
            class_data.append(
                driver.driver(node['project'], node['service'], node['level'],
                              node['trace_id'], node['parent_id'],
                              node['starttime'], node['time']))
        elif node.get('name') == 'vif_driver':
            class_data.append(
                vif_driver.vif(node['project'], node['service'], node['level'],
                               node['trace_id'], node['parent_id'],
                               node['starttime'], node['time']))
        elif node.get('name') == 'neutron_api':
            class_data.append(
                neutron.neutron(node['project'], node['service'],
                                node['level'], node['trace_id'],
                                node['parent_id'], node['starttime'],
                                node['time']))
        elif node.get('name') == 'volume_api':
            class_data.append(
                volume.volume(node['project'], node['service'], node['level'],
                              node['trace_id'], node['parent_id'],
                              node['starttime'], node['time']))
        elif node.get('name') == 'nova_image':
            class_data.append(
                nova.nova(node['project'], node['service'], node['level'],
                          node['trace_id'], node['parent_id'],
                          node['starttime'], node['time']))
        else:
            class_data.append(
                stack.stack(node['project'], node['service'], node['level'],
                            node['trace_id'], node['parent_id'],
                            node['starttime'], node['time']))
Example #6
0
def main(p, detector):
    detector.terminate()
    print('\033[1;32m     识别成功,随便说说吧! \033[0m')
    # 播放提示语
    volume.play_prompt_not_loop(init_prompt)
    # 录音
    volume_in = volume.volume(p)
    # 语音识别
    i_said_json = eval('yuyinshibie.%s(i_said)' % shibie_tts)
    # 判断是否识别成功(这里我本来想直接用变量的,但不知道为什么第二个if的赋值赋不出来,就先用数组代替)
    shibie_suc = []
    if shibie_tts == 'baidu':
        if int(i_said_json['err_no']) == 0:
            shibie_suc.append('1')
    elif shibie_tts == 'xunfei':
        if int(i_said_json['code']) == 0:
            shibie_suc.append('1', '2')
    if len(shibie_suc) == 1 or len(shibie_suc) == 2:
        # 判断有无声源输入
        if len(shibie_suc) == 1:
            i_said_text = i_said_json['result'][0]
        elif len(shibie_suc) == 2:
            i_said_text = i_said_json['data']
        if i_said_text == '':
            volume.play_prompt(none_prompt)
        else:
            keyword = isKeyword.main_1(i_said_text)
            hecheng_keyword = isKeyword.main_2(i_said_text, hecheng_tts)
            # 判断是否包含控制家具关键字
            if keyword == 1 and hecheng_keyword == 1:
                alexa_said_text = tuling.robot(i_said_text)
                print('      %s' % alexa_said_text)
                # 把我和alexa的对话记录到日志
                logs.suc('i_said%s\n    alexa_said:%s' % i_said_text,
                         alexa_said_text)
                # 语音合成阶段的错误处理
                hecheng = eval('yuyinhecheng.%s(alexa_said_text)' %
                               hecheng_tts)
                if hecheng == 1:
                    volume.play_prompt(alexa_said)
                else:
                    logs.yuyin_err('语音合成发生了错误,以下是具体信息:\n%s' % hecheng)
                    volume.play_prompt(play_hecheng_failed)
    else:
        logs.yuyin_err('语音识别发生了错误,以下是具体信息:\n%s' % i_said_json)
        volume.play_prompt(play_shibie_failed)
Example #7
0
    def test_volume(self):
        #Valid Inputs
        #Rounds to the 6th decimal point
        self.assertEqual(volume(2), 8)
        self.assertEqual(volume(12.21), 1820.316861)

        #Code can run string format version of float value
        self.assertEqual(volume("1.2"), 1.728)

        #Invalid inputs
        #Code returns -1 on invalid input

        #String
        self.assertEqual(volume("a"), -1)
        self.assertEqual(volume("]'\'"), -1)
        self.assertEqual(volume(""), -1)
        self.assertEqual(volume("12.21.3"), -1)

        #Negative
        self.assertEqual(volume(-12), -1)

        #Zero (treated as invalid)
        self.assertEqual(volume(0), -1)
Example #8
0
    def toGeotiff(self, filename, vol=None, nodata=None, zscale=None):
        """
        Create and write a geotiff file from the geoprobe horizon object.
        The Z values in the output tiff will be stored as 32bit floats.
        Input:
            filename:  Output filename
            vol (optional): A geoprobe volume object or path to a geoprobe 
                volume file.  If vol is specified, the geotiff will be
                georeferenced based on the data in the volume header (and will
                therefore be in same projection as the volume's world
                coordinates).  Otherwise the geotiff is created using the model
                coordinates stored in the geoprobe horizon file.
            nodata (default=self.nodata (-9999)): Value to use for NoData.
            zscale (optional): Scaling factor to use for the Z-values.  If vol
                is specified, and vol.dz is negative, this defaults to -1.
                Otherwise this defaults to 1.
        """
        if vol is not None:
            if type(vol) == type('string'): 
                vol = volume(vol)
            Xoffset, Yoffset = vol.model2world(self.xmin, self.ymin)
            transform = vol
        else:
            Xoffset, Yoffset = 0,0
            transform = None

        if nodata==None: 
            nodata = self.nodata

        # Zscale is not 1 by default, as I want the default to be set by vol.dz 
        # and any specified value to override the default
        if zscale is None:
            if vol is None: zscale = 1
            elif vol.dz > 0: zscale = 1
            elif vol.dz < 0: zscale = -1

        data = self.grid
        data.fill_value = nodata
        data *= zscale
        data = data.filled()

        array2geotiff(data, filename, nodata=nodata, 
                      extents=(Xoffset, Yoffset), transform=transform)
Example #9
0
def test_simple_inexplicit():
    solute_pos = numpy.array(((0, 0, 0), ), dtype=numpy.float64)
    solute_rad = numpy.array((3, ), dtype=numpy.float64)
    solvent_rad = 1.4
    voxel_len = 0.05

    print("Test: single atom of radius 3")
    vol = volume.volume(solute_pos, solute_rad, solvent_rad, voxel_len)

    analytical_vol = numpy.pi * 4. / 3 * (solute_rad[0] + solvent_rad)**3

    print("  calculated volume: {:f}".format(vol))
    print("  analytical volume: {:f}".format(analytical_vol))
    perr = 100 * abs(vol - analytical_vol) / analytical_vol
    print("  percent error:     {:f}%".format(perr))
    if perr < 1:
        print("  TEST PASSED")
        return 0
    else:
        print("  TEST FAILED")
        return 1
def points2strikeDip(x, y, z, vol=None, velocity=None):
    """
    Takes a point cloud defined by 3 vectors and returns a strike and dip 
    following the Right-hand-rule. 
    Input:
        x, y, z: numpy arrays or lists containg the x, y, and z 
            coordinates, respectively
        vol (optional): A geoprobe volume object
            If specified, the x, y, and z units will be converted
            to world units based on the volume's header.
        velocity (optional): Velocity in meters/second
            If specified, the z units will be converted from time
            into depth using the velocity given.  Assumes the z
            units are milliseconds!!
    Output:
        strike, dip (in degrees)
    """
    # Get x,y, and z, converting to world coords if necessary
    if vol is not None:
        # If given a string, assume it's the filename of a volume
        if type(vol) == type('String'):
            vol = volume.volume(vol)
        # Convert coords
        x,y = vol.model2world(x, y)

    #Negate z if depth is positive (which it usually is)
    if vol is None or vol.dz < 0: 
        z = -z

    # Convert to depth using velocity (assumes velocity is in m/s and Z is in milliseconds)
    if velocity is not None:
        z = 0.5 * velocity * z / 1000  

    a,b,c,d = fit_plane(x,y,z)
    strike, dip = normal2SD(a,b,c)

    return strike, dip
Example #11
0
def points2strikeDip(x, y, z, vol=None, velocity=None):
    """
    Takes a point cloud defined by 3 vectors and returns a strike and dip
    following the Right-hand-rule.
    Input:
        x, y, z: numpy arrays or lists containg the x, y, and z
            coordinates, respectively
        vol (optional): A geoprobe volume object
            If specified, the x, y, and z units will be converted
            to world units based on the volume's header.
        velocity (optional): Velocity in meters/second
            If specified, the z units will be converted from time
            into depth using the velocity given.  Assumes the z
            units are milliseconds!!
    Output:
        strike, dip (in degrees)
    """
    # Get x,y, and z, converting to world coords if necessary
    if vol is not None:
        # If given a string, assume it's the filename of a volume
        if type(vol) == type('String'):
            vol = volume.volume(vol)
        # Convert coords
        x,y = vol.model2world(x, y)

    #Negate z if depth is positive (which it usually is)
    if vol is None or vol.dz < 0:
        z = -z

    # Convert to depth using velocity (assumes velocity is in m/s and Z is in milliseconds)
    if velocity is not None:
        z = 0.5 * velocity * z / 1000

    a,b,c,d = fit_plane(x,y,z)
    strike, dip = normal2SD(a,b,c)

    return strike, dip
Example #12
0
 def test_volume_pos_bool(self):
     with self.assertRaises(TypeError):
         volume.volume(1, True, False)
Example #13
0
 def test_values(self):
     self.assertAlmostEqual(volume(2), 33.510321638291124)
     self.assertAlmostEqual(volume(0), 0)
Example #14
0
 def test_volumeNeg(self):
     self.assertEqual(volume(-4), None)
Example #15
0
    def test_volume(self):

        self.assertEqual(volume.volume(5, 5, 5), 125)
        self.assertEqual(volume.volume(2**2, 20, 10), 800)
        # Fail case
        self.assertEqual(volume.volume(1, -2, 1), 2)  # Fail Case
Example #16
0
from volume import volume
from ETFprice import ETFPrice
from option_info import option
from iv_mean import iv_bynet
from iv_mean import iv_mean
from stock import stork_volume
import time

if __name__ == '__main__':
    volume()
    ETFPrice()
    option()
    iv_mean()
    # stork_volume()
    while True:
        # print('alive')
        time.sleep(100)
Example #17
0
class TestVolume(unittest.TestCase):

    def test-volume(self):
        self.assertAlmostEqual(volume.volume(2), 8)
        self.assertAlmostEqual(volume.volume(-2), -8)
        self.assertAlmostEqual(volume.volume(0), 0)
Example #18
0
def dadiab(theta, y):

    # indices of the y, dy vectors
    P = 0
    TC = 1
    TE = 2
    QK = 3
    QR = 4
    QH = 5
    WC = 6
    WE = 7
    WB = 8
    W = 9
    VC = 10
    VE = 11
    VB = 12
    VGE = 13
    MC = 14
    MK = 15
    MR = 16
    MH = 17
    MGE = 18
    MB = 19
    TCK = 20
    THE = 21
    MCK = 22
    MKR = 23
    MRH = 24
    MHGE = 25
    MBC = 26
    #-----------------------------------------------
    # volume and volume derivatives
    dy = np.zeros((20, 37))
    y[VC], y[VE], y[VB], dy[VC], dy[VE], dy[VB] = volume.volume(theta)

    # pressure and pressure derivatives
    y[P] = m * r / ((y[VC] + y[VB]) / y[TC] + vt + y[VGE] / y[TE])
    top = -y[P] * (dy[VC] + dy[VB]) / y[TCK] + dy[VE] / y[THE]
    bottom = ((y[VC] + y[VB]) / (y[TCK] * gama) + vt + y[VE] / (y[THE] * gama))
    dy[P] = top / bottom

    # mass and mass flow
    y[MC] = y[P] * y[VC] / (r * y[TC])
    y[MK] = y[P] * vk / (r * tk)
    y[MR] = y[P] * vr / (r * tr)
    y[MH] = y[P] * vh / (r * th)
    y[MGE] = y[P] * y[VGE] / (r * y[TE])
    dy[MC] = (y[P] * dy[VC] + y[VC] * dy[P] / gama) / (r * y[TCK])
    dy[MGE] = (y[P] * dy[VGE] + y[VE] * dy[P] / gama) / (r * y[THE])
    dpop = dy[P] / y[P]
    dy[MK] = y[MK] * dpop
    dy[MR] = y[MR] * dpop
    dy[MH] = y[MH] * dpop

    # mass flow between cells
    y[MBC] = -dy[MB]
    y[MCK] = -dy[MC] - dy[MB]
    y[MHGE] = dy[MGE]
    y[MRH] = dy[MGE] + dy[MH]
    y[MKR] = dy[MR] + dy[MH] + dy[MGE]

    # temperature between cells
    y[TCK] = tk
    if (y[MCK].any() > 0): y[TCK] = y[TC]
    y[THE] = y[TC]
    if (y[MHGE].any() > 0): y[THE] = th

    # working space temperature
    dy[TC] = y[TC] * (dpop + dy[VC] / y[VC] - dy[MC] / y[MC])
    dy[TE] = y[TE] * (dpop + dy[VGE] / y[VGE] - dy[MGE] / y[MGE])

    # energy
    dy[QK] = vk * dy[P] * cv / r - cp * (y[TCK] * y[MCK] - tk * y[MKR])
    dy[QR] = vr * dy[P] * cv / r - cp * (tk * y[MKR] - th * y[MRH])
    dy[QH] = vh * dy[P] * cv / r - cp * (th * y[MRH] - y[THE] * y[MHGE])
    dy[WC] = y[P] * dy[VC]
    dy[WE] = y[P] * dy[VGE]
    dy[WB] = y[P] * dy[VB]

    # net work done
    dy[W] = dy[WC] + dy[WB]
    y[W] = y[WC] + y[WB]

    return y, dy
Example #19
0
def test_void():
    print("Test: capsid structure with void")
    s = 1.4

    # Make a cube of spheres.  the edge length of the cube is 4*s, where s is
    # the radius of cube.
    #
    #
    #        *      *      *
    #
    #
    #        *      *      *
    #
    #
    #        *      *      *
    # The space between surfaces of spheres on the diagonal is 2*(sqrt(2) - 1)*s
    # Since 2*(sqrt(2)-1) < 1, a water of radius s will not fit through the spaces.
    #

    solute_pos = numpy.array(
        (
            (0, 0, 0),
            (2 * s, 0, 0),
            (4 * s, 0, 0),
            (6 * s, 0, 0),
            (0, 2 * s, 0),
            (2 * s, 2 * s, 0),
            (4 * s, 2 * s, 0),
            (6 * s, 2 * s, 0),
            (0, 4 * s, 0),
            (2 * s, 4 * s, 0),
            (4 * s, 4 * s, 0),
            (6 * s, 4 * s, 0),
            (0, 6 * s, 0),
            (2 * s, 6 * s, 0),
            (4 * s, 6 * s, 0),
            (6 * s, 6 * s, 0),
            (0, 0, 2 * s),
            (2 * s, 0, 2 * s),
            (4 * s, 0, 2 * s),
            (6 * s, 0, 2 * s),
            (0, 2 * s, 2 * s),
            #(2*s,2*s,2*s), # skip this one, since it's in the middle of the cube
            #(4*s,2*s,2*s),
            (6 * s, 2 * s, 2 * s),
            (0, 4 * s, 2 * s),
            #(2*s,4*s,2*s),
            #(4*s,4*s,2*s),
            (6 * s, 4 * s, 2 * s),
            (0, 6 * s, 2 * s),
            (2 * s, 6 * s, 2 * s),
            (4 * s, 6 * s, 2 * s),
            (6 * s, 6 * s, 2 * s),
            (0, 0, 4 * s),
            (2 * s, 0, 4 * s),
            (4 * s, 0, 4 * s),
            (6 * s, 0, 4 * s),
            (0, 2 * s, 4 * s),
            #(2*s,2*s,4*s),
            #(4*s,2*s,4*s),
            (6 * s, 2 * s, 4 * s),
            (0, 4 * s, 4 * s),
            #(2*s,4*s,4*s),
            #(4*s,4*s,4*s),
            (6 * s, 4 * s, 4 * s),
            (0, 6 * s, 4 * s),
            (2 * s, 6 * s, 4 * s),
            (4 * s, 6 * s, 4 * s),
            (6 * s, 6 * s, 4 * s),
            (0, 0, 6 * s),
            (2 * s, 0, 6 * s),
            (4 * s, 0, 6 * s),
            (6 * s, 0, 6 * s),
            (0, 2 * s, 6 * s),
            (2 * s, 2 * s, 6 * s),
            (4 * s, 2 * s, 6 * s),
            (6 * s, 2 * s, 6 * s),
            (0, 4 * s, 6 * s),
            (2 * s, 4 * s, 6 * s),
            (4 * s, 4 * s, 6 * s),
            (6 * s, 4 * s, 6 * s),
            (0, 6 * s, 6 * s),
            (2 * s, 6 * s, 6 * s),
            (4 * s, 6 * s, 6 * s),
            (6 * s, 6 * s, 6 * s)),
        dtype=numpy.float64)

    solute_rad = numpy.ones(solute_pos.shape[0]) * s

    # one solvent outside cube
    solvent_pos = numpy.array(((10 * s, 0, 0), ), dtype=numpy.float64)
    solvent_rad = s

    voxel_len = 0.1

    vol_empty = volume.volume_explicit_sol(solute_pos, solute_rad, solvent_pos,
                                           solvent_rad, voxel_len)
    print("  Calculated volume with solvent only outside cage: {:f}".format(
        vol_empty))

    # Now include a solvent inside the cube.
    solvent_pos = numpy.array(((10 * s, 0, 0), (3 * s, 3 * s, 3 * s)),
                              dtype=numpy.float64)

    vol_filled = volume.volume_explicit_sol(solute_pos, solute_rad,
                                            solvent_pos, solvent_rad,
                                            voxel_len)
    print("  Calculated volume with solvent also inside cage:  {:f}".format(
        vol_filled))

    dv_actual = vol_empty - vol_filled
    # the difference should be between:
    dv_lb = (2 * s)**3
    # based on close packing of spheres in fcc latice; the pitch of tetrahedral
    # arangement of sphere centers is sqrt(6)*d/3, where d=2*s
    dv_ub = (2 * s + 2 * (2 * s - 6.0**(0.5) * 2 * s / 3))**3
    print("  Difference in volumes should be between {:f} and {:f}".format(
        dv_lb, dv_ub))
    print("  Calculated difference in volumes: {:f}".format(vol_empty -
                                                            vol_filled))
    if dv_lb < dv_actual and dv_actual < dv_ub:
        print("  TEST PASSED")
    else:
        print("  TEST FAILED")

    vol_inexplicit = volume.volume(solute_pos, solute_rad, solvent_rad,
                                   voxel_len)
    print("  Calculated volume with solvent automatically placed outside: {:f}"\
          .format(vol_inexplicit))
    if abs(vol_inexplicit - vol_empty) / vol_empty < .01:
        print("  TEST PASSED")
    else:
        print("  TEST FAILED")
Example #20
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zz'

# isothermal model

from engine import *
import volume as vol
vc, ve, vb, dvc, dve, dvb = vol.volume(theta)
vt = vk / tk + vr / tr + vh / th

p0 = 1 / ((vc + vb) / tk + vt + (vpul + ve) / th)
p0 = p0 * pm / np.mean(p0)
p1 = 1 / ((vc + vb) / tk + vt + (vpul + ve - vgclc *
                                 (p0 / pm)**(-1 / gama)) / th)
p1 = p1 * pm / np.mean(p1)

while np.max(np.abs(p1 - p0)) > 1:
    p0 = p1
    p1 = 1 / ((vc + vb) / tk + vt + (vpul + ve - vgclc *
                                     (0.5 * (p0 + p1) / pm)**(-1 / gama)) / th)
    p1 = p1 * pm / np.mean(p1)

p = p1
dp = np.linspace(1, nt, nt)
dp[0] = p[0] - p
vge = vpul + ve - vgclc * (p / pm)**(-1 / gama)
dvge = np.linspace(1, nt, nt)
dvge[0] = vge[0] - vge[-1]
dvge[1:] = vge[1:] - vge[0:nt - 1]
m = p * ((vc + vb) / tk + vt + (vge) / th) / r
Example #21
0
 def test_volume_pos_neg(self):
     self.assertEqual(volume.volume(1, -2, 3), -1)
Example #22
0
 def test_volume_string(self):
     with self.assertRaises(TypeError):
         volume.volume("string", "string", "string")
Example #23
0
 def test3(self):
     self.assertEqual(volume.volume(-10), 0)
Example #24
0
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 in voxels
        lower: (default, upper) lower window interval around horizion in voxels
        offset: (default, 0) amount (in voxels) to offset the horizion by along
                the Z-axis
        region: (default, overlap between horizion and volume) sub-region to
                use instead of full extent. Must be a 4-tuple of (xmin, xmax,
                ymin, ymax)
        masked: (default, False) if True, return a masked array where nodata
                values in the horizon are masked. Otherwise, return an array
                where the nodata values are filled with 0.
    Output:
        returns a numpy volume "flattened" along the horizion
    """
    # If the lower window isn't specified, assume it's equal to the
    # upper window
    if lower == None: lower=upper

    # If filenames are input instead of volume/horizion objects, create
    # the objects
    if type(hor) == type('String'):
        hor = horizon.horizon(hor)
    if type(vol) == type('String'):
        vol = volume.volume(vol)

    #Gah, changed the way hor.grid works... Should probably change it back
    depth = hor.grid.T

    # Find the overlap between the horizon and volume
    vol_extents = [vol.xmin, vol.xmax, vol.ymin, vol.ymax]
    hor_extents = [hor.xmin, hor.xmax, hor.ymin, hor.ymax]
    extents = bbox_intersection(hor_extents, vol_extents)

    # Raise ValueError if horizon and volume do not intersect
    if extents is None:
        raise ValueError('Input horizon and volume do not intersect!')

    # Find the overlap between the (optional) subregion current extent
    if region is not None:
        extents = bbox_intersection(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

    # Convert extents to volume indicies and select subset of the volume
    i, j = vol.model2index([xmin, xmax], [ymin, ymax])
    data = vol.data[i[0]:i[1], j[0]:j[1], :]

    # Convert extents to horizion grid indicies and select
    # subset of the horizion

    hxmin, hxmax, hymin, hymax = hor.grid_extents
    xstart, ystart = xmin - hxmin, ymin - hymin
    xstop, ystop = xmax - hxmin, ymax - hymin
    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.copy() # Need to preserve the mask for later
    if not mask.shape:
        mask = np.zeros(depth.shape, dtype=np.bool)
    depth = depth.filled()   # Iterating through masked arrays is much slower.
    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
                if z < 0:
                    mask[i,j] = True
                    continue
                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
Example #25
0
 def test1(self):
     self.assertEqual(volume.volume(5.5), 166.375)
Example #26
0
 def test_volumeInvalid(self):
     self.assertEqual(volume("test"), None)
Example #27
0
 def test_4(self):
     self.assertEqual(volume.volume(5), 25)
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 in voxels 
        lower: (default, upper) lower window interval around horizion in voxels 
        offset: (default, 0) amount (in voxels) to offset the horizion by along
                the Z-axis
        region: (default, overlap between horizion and volume) sub-region to 
                use instead of full extent. Must be a 4-tuple of (xmin, xmax,
                ymin, ymax)
        masked: (default, False) if True, return a masked array where nodata 
                values in the horizon are masked. Otherwise, return an array
                where the nodata values are filled with 0.
    Output:
        returns a numpy volume "flattened" along the horizion
    """
    # If the lower window isn't specified, assume it's equal to the 
    # upper window
    if lower == None: lower=upper

    # If filenames are input instead of volume/horizion objects, create 
    # the objects
    if type(hor) == type('String'):
        hor = horizon.horizon(hor)
    if type(vol) == type('String'):
        vol = volume.volume(vol)

    #Gah, changed the way hor.grid works... Should probably change it back
    depth = hor.grid.T 

    # Find the overlap between the horizon and volume
    vol_extents = [vol.xmin, vol.xmax, vol.ymin, vol.ymax]
    hor_extents = [hor.xmin, hor.xmax, hor.ymin, hor.ymax]
    extents = bbox_intersection(hor_extents, vol_extents)

    # Raise ValueError if horizon and volume do not intersect
    if extents is None:
        raise ValueError('Input horizon and volume do not intersect!')

    # Find the overlap between the (optional) subregion current extent
    if region is not None: 
        extents = bbox_intersection(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

    # Convert extents to volume indicies and select subset of the volume 
    xstart, ystart = xmin - vol.xmin, ymin - vol.ymin
    xstop, ystop = xmax - vol.xmin, ymax - vol.ymin
    data = vol.data[xstart:xstop, ystart:ystop, :]

    # Convert extents to horizion grid indicies and select 
    # subset of the horizion 
    xstart, ystart = xmin - hor.xmin, ymin - hor.ymin
    xstop, ystop = xmax - hor.xmin, ymax - hor.ymin
    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...
    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
Example #29
0
def buildCX(show=True):
    '''create a volume with our neurons of interest'''
    
    vol = volume()
    groups = ['PEN1', 'PEN2', 'EPG', 'PEG', 'D7', 'R']  #neuron types to consider

    #rootnodes for the different neurons and neuropils    
    rootnodes_PEN1 = [ [3126471,3593898,2185557,2181724,2210880,2857643,3513461,12603123],\
                      [5837503,5398965,1948755,2181016,(2215133,2215382),2214922,5627995,3501313],\
                      [6870055,8103838,12900279,12900633,12900783,2418633,7252018,20883674]  ] #PB EB NO
    
    rootnodes_PEN2 = [ [3497680,4178983,2178615,2163389,2207249,2244795,3509336,5237022],\
                     [5908353,3498186,(2177781,2177647),2161670,2424373,2665948,5626946,5464801],\
                     [7019593,12905027,20799546,3299024,2206510,2203193,5564596,5584414]  ] #PB EB NO
    
    
    rootnodes_EPG = [ [ 1753050, 1748660, 3449161, 2905038, 13237900, 2262262, 6902310, 3448054, 27010310, 3554640],\
                     [ 6121805, 5936707, 3466125, 2265604, 2264211, 2864637, 16815483, 3448153, 3515658, 3380387],\
                     [ 2452093, 3309827, 2500612, 2265429, 2263551, 3302643, 20874147, 5101718, 20851318, 7518649] ] #PB EB G
    
    rootnodes_PEG = [ [2102880,4144157,3090295,3982268],\
                     [1777240,4145168,3400032,19562579],\
                     [1777173,4574589,4832222,5039997] ] #PB EB G
    
    rootnodes_D7 = [ [3008985,5289720,3426438,3241000,2849576,6295467,4061178 ],\
                    [2906483,5110398,5269799,3142774,5288727,3376503,4060762],\
                    [3024153,5109132,5997836,6930815,6632029,3376805,3438887] ]
                     
    rootnodes_R = [[21262742,21298056,21477619,22701513,23145018,23151362,23211427],\
                   [21271375,21295105,21487492,22267264,23117229,23161634,23222690]] #add this
    
    rootnodes = [rootnodes_PEN1, rootnodes_PEN2, rootnodes_EPG, rootnodes_PEG, rootnodes_D7, rootnodes_R]
    
    #load locally stored neurons
    for i, group in enumerate(groups):
        print('\n\nAdding group ', group)
        neurons = pickle.load( open('pickled_neurons/'+group+'_pickled', 'rb' ) )
        for j, neuron in enumerate(neurons):
            vol.add_neuron(neuron, subgroup = group,\
            rootnode = [ rootnodes[i][k][j] for k in range(len(rootnodes[i])) ])
    D7n = pickle.load( open('pickled_neurons/D7_pickled', 'rb' ) )
            
    subvolumes = ['PB', 'EB', 'NO'] 
    for v in subvolumes: vol.subvolume(v) #constuct subvolumes

    #split out neurons according to subvolumes    
    PEN1s = []  
    PEN2s = []
    #order PB, EB, NO

    PEN1s.append(vol.split('PEN1-5R', 3126155, 3125538, show=show))
    PEN1s.append(vol.split('PEN1-5L', 3075961, 3075572, show=show))
    PEN1s.append(vol.split('PEN1-6Ra', 2185424, 2184847, show=show))
    PEN1s.append(vol.split('PEN1-6Rb', 2181545, 2180692, show=show))
    PEN1s.append(vol.split('PEN1-6La', 2210651, 2210229, show=show))
    PEN1s.append(vol.split('PEN1-6Lb', 2857292, 2212325, show=show))
    PEN1s.append(vol.split('PEN1-7R', 3513271, 3513176, show=show))
    PEN1s.append(vol.split('PEN1-7L', 12600793, 3501452, show=show))
    
    PEN2s.append(vol.split('PEN2-5R', 3497600, 3498016, show=show))
    PEN2s.append(vol.split('PEN2-5L', 3498351, 3498551, show=show))
    PEN2s.append(vol.split('PEN2-6Ra', 2177934, 2177486, show=show))
    PEN2s.append(vol.split('PEN2-6Rb', 2163182, 2162408, show=show))
    PEN2s.append(vol.split('PEN2-6La', 2206952, 2206635, show=show))
    PEN2s.append(vol.split('PEN2-6Lb', 3389770, 12791980, show=show))
    PEN2s.append(vol.split('PEN2-7R', 3508573, 3508198, show=show))
    PEN2s.append(vol.split('PEN2-7L', 4197201, 5584341, show=show))
    
    EPGs=[]
    PEGs=[]
    #Order PB, EB, G
    EPGs.append(vol.split('EPG-5Ra', 1753455, 1771173, show=show, Type = 'fj'))
    EPGs.append(vol.split('EPG-5Rb', 1732713, 1737390, show=show, Type = 'fj'))
    EPGs.append(vol.split('EPG-5Rc', 1736306, 1741834, show=show, Type = 'fj'))
    EPGs.append(vol.split('EPG-5La', 2264515, 2265192, show=show, Type = 'fj'))
    EPGs.append(vol.split('EPG-5Lb', 2263776, 2263478, show=show, Type = 'd'))
    EPGs.append(vol.split('EPG-5Lc', 2261872, 2261504, show=show, Type = 'fj', reverse = True))
    EPGs.append(vol.split('EPG-6Ra', 3437960, 1760877, show=show, Type = 'fj'))
    EPGs.append(vol.split('EPG-6Rb', 3448088, 3448328, show=show, Type = 'new'))
    EPGs.append(vol.split('EPG-6La', 3515565, 3515922, show=show, Type = 'fj'))
    EPGs.append(vol.split('EPG-6Lb', 3378068, 3516553, show=show, Type = 'fj'))

    PEGs.append(vol.split('PEG-5R', 1777475, 1777052, show=show))
    PEGs.append(vol.split('PEG-5L', 4144656, 4573004, show=show))
    PEGs.append(vol.split('PEG-6R', 3399687, 3400550, show=show))
    PEGs.append(vol.split('PEG-6L', 3983410, 3984407, show=show))
    
    #add to subvolumes (neuropils) as appropriate
    for i, PEN1 in enumerate(PEN1s):
        print('PEN1', i)
        vol.add_to_subvolume(PEN1[0], 'PB', subgroup='PEN1', rootnode = rootnodes_PEN1[0][i], roottype = 'out')
        vol.add_to_subvolume(PEN1[1], 'EB', subgroup='PEN1', rootnode = rootnodes_PEN1[1][i], roottype = 'in')
        vol.add_to_subvolume(PEN1[2], 'NO', subgroup='PEN1', rootnode = rootnodes_PEN1[2][i], roottype = 'in')
        
    for i, PEN2 in enumerate(PEN2s):
        print('PEN2', i)
        vol.add_to_subvolume(PEN2[0], 'PB', subgroup='PEN2', rootnode = rootnodes_PEN2[0][i], roottype = 'out')
        vol.add_to_subvolume(PEN2[1], 'EB', subgroup='PEN2', rootnode = rootnodes_PEN2[1][i], roottype = 'in')
        vol.add_to_subvolume(PEN2[2], 'NO', subgroup='PEN2', rootnode = rootnodes_PEN2[2][i], roottype = 'in')
    
    for i, EPG in enumerate(EPGs):
        print('EPG', i)
        vol.add_to_subvolume(EPG[0], 'PB', subgroup='EPG', rootnode = rootnodes_EPG[0][i], roottype = 'in')
        vol.add_to_subvolume(EPG[1], 'EB', subgroup='EPG', rootnode = rootnodes_EPG[1][i], roottype = 'out')
    
    for i, PEG in enumerate(PEGs):
        print('PEG', i)
        vol.add_to_subvolume(PEG[0], 'PB', subgroup='PEG', rootnode = rootnodes_PEG[0][i], roottype = 'out')
        vol.add_to_subvolume(PEG[1], 'EB', subgroup='PEG', rootnode = rootnodes_PEG[1][i], roottype = 'in')
     
    for D7 in D7n:
        vol.add_to_subvolume(D7, 'PB', subgroup = 'D7')

    for R in ['Ra','Rb','Rc','Rd','Re','Rf','Rg']:
        vol.add_to_subvolume(R, 'EB', subgroup = 'R')
    
    #load connection tables
    vol.cn_tables = pickle.load( open('pickled_neurons/all_cn_tables_LAL_R_pickled', 'rb' ) ) 
    
    #load connection tables for subvolumes (neuropils)
    for key, subvol in vol.subvolumes.items():
        subvol.cn_tables = pickle.load( open('pickled_neurons/'+key+'_cn_tables_LAL_R_pickled', 'rb' )) 
                            
    for subvolume in vol.subvolumes:
        for group in groups:
            if not group in vol.subvolumes[subvolume].groups.keys():
                vol.subvolumes[subvolume].init_subgroup(group)
    
    return vol
Example #30
0
 def test_volume(self):
     self.assertEqual(volume(4), 64)
Example #31
0
 def test_2(self):
     self.assertEqual(volume.volume(-2), 1)
Example #32
0
 def test_1(self):
     self.assertEqual(volume.volume("a"), 1)
Example #33
-1
    def toGeotiff(self, filename, vol=None, nodata=None, zscale=None):
        """
        Create and write a geotiff file from the geoprobe horizon object.
        The Z values in the output tiff will be stored as 32bit floats.
        Input:
            filename:  Output filename
            vol (optional): A geoprobe volume object or path to a geoprobe
                volume file.  If vol is specified, the geotiff will be
                georeferenced based on the data in the volume header (and will
                therefore be in same projection as the volume's world
                coordinates).  Otherwise the geotiff is created using the model
                coordinates stored in the geoprobe horizon file.
            nodata (default=self.nodata (-9999)): Value to use for NoData.
            zscale (optional): Scaling factor to use for the Z-values.  If vol
                is specified, and vol.dz is negative, this defaults to -1.
                Otherwise this defaults to 1.
        """
        if vol is not None:
            if type(vol) == type('string'):
                vol = volume(vol)
            Xoffset, Yoffset = vol.model2world(self.xmin, self.ymin)
            transform = vol
        else:
            Xoffset, Yoffset = 0, 0
            transform = None

        if nodata == None:
            nodata = self.nodata

        # Zscale is not 1 by default, as I want the default to be set by vol.dz
        # and any specified value to override the default
        if zscale is None:
            if vol is None: zscale = 1
            elif vol.dz > 0: zscale = 1
            elif vol.dz < 0: zscale = -1

        data = self.grid
        data.fill_value = nodata
        data *= zscale
        data = data.filled()

        array2geotiff(data,
                      filename,
                      nodata=nodata,
                      extents=(Xoffset, Yoffset),
                      transform=transform)
Example #34
-2
    def test_volume(self):
        self.assertEqual(volume.volume(5, 6, 1), 30)
        self.assertEqual(volume.volume(5, 0, 1), 0)

        self.assertEqual(volume.volume(5, -6, 1), -30)
        self.assertEqual(volume.volume(5, -6, -1), 30)
        self.assertEqual(volume.volume(-5, -6, -1), -30)

        #As far as I know, almost equal is the only way to compare floats
        self.assertAlmostEqual(volume.volume(5.2, 6.5, 1.8), 60.84)
        self.assertAlmostEqual(volume.volume(5.45, -6.80, 1.78), -65.9668)