コード例 #1
0
ファイル: __init__.py プロジェクト: rowanc1/oksar
    def get_LOS_vector(self, locations):
        """
            calculate beta - the angle at earth center between reference point
            and satellite nadir
        """

        utmZone = self.location_UTM_zone
        refPoint = vmath.Vector3(self.ref[0], self.ref[1], 0)
        satAltitude = self.satellite_altitude
        satAzimuth = self.satellite_azimuth
        satIncidence = self.ref_incidence
        earthRadius = self.local_earth_radius

        DEG2RAD = np.pi / 180.
        alpha = satIncidence * DEG2RAD
        beta = (earthRadius / (satAltitude + earthRadius)) * np.sin(alpha)
        beta = alpha - np.arcsin(beta)
        beta = beta / DEG2RAD

        # calculate angular separation of (x,y) from satellite track passing
        # through (origx, origy) with azimuth satAzimuth

        # Long lat **NOT** lat long
        origy, origx = utm.to_latlon(refPoint.x,
                                     refPoint.y,
                                     np.abs(utmZone),
                                     northern=utmZone > 0)

        xy = np.array([
            utm.to_latlon(u[0], u[1], np.abs(utmZone), northern=utmZone > 0)
            for u in locations
        ])
        y = xy[:, 0]
        x = xy[:, 1]

        angdist = self._ang_to_gc(x, y, origx, origy, satAzimuth)

        # calculate beta2, the angle at earth center between roaming point and
        # satellite nadir track, assuming right-looking satellite

        beta2 = beta - angdist
        beta2 = beta2 * DEG2RAD

        # calculate alpha2, the new incidence angle

        alpha2 = np.sin(beta2) / (np.cos(beta2) -
                                  (earthRadius / (earthRadius + satAltitude)))
        alpha2 = np.arctan(alpha2)
        alpha2 = alpha2 / DEG2RAD

        # calculate pointing vector

        satIncidence = 90 - alpha2
        satAzimuth = 360 - satAzimuth

        los_x = -np.cos(satAzimuth * DEG2RAD) * np.cos(satIncidence * DEG2RAD)
        los_y = -np.sin(satAzimuth * DEG2RAD) * np.cos(satIncidence * DEG2RAD)
        los_z = np.sin(satIncidence * DEG2RAD)

        return vmath.Vector3(los_x, los_y, los_z)
コード例 #2
0
    def test_vector3(self):
        class HasVec3(properties.HasProperties):
            vec3 = properties.Vector3('simple vector')

        hv3 = HasVec3()
        hv3.vec3 = [1., 2., 3.]
        assert isinstance(hv3.vec3, vmath.Vector3)
        hv3.vec3 = 'east'
        assert np.allclose(hv3.vec3, [1., 0., 0.])
        with self.assertRaises(ValueError):
            hv3.vec3 = 'around'
        with self.assertRaises(ValueError):
            hv3.vec3 = [1., 2.]
        with self.assertRaises(ValueError):
            hv3.vec3 = [[1., 2., 3.]]

        class HasLenVec3(properties.HasProperties):
            vec3 = properties.Vector3('length 5 vector', length=5)

        hv3 = HasLenVec3()
        hv3.vec3 = 'down'
        assert np.allclose(hv3.vec3, [0., 0., -5.])

        assert isinstance(properties.Vector3.from_json([5., 6., 7.]),
                          vmath.Vector3)

        assert properties.Vector3('').equal(vmath.Vector3(1., 2., 3.),
                                            vmath.Vector3(1., 2., 3.))
        assert not properties.Vector3('').equal(vmath.Vector3(1., 2., 3.),
                                                np.array([1., 2., 3.]))
コード例 #3
0
    def test_los(self):

        interferogram_refx = 741140
        interferogram_refy = 4230327
        interferogram_ref_incidence = 23
        local_earth_radius = 6386232
        satellite_altitude = 788792
        satellite_azimuth = 192
        locationUTMzone = 35
        locationE = 706216.0606
        locationN = 4269238.9999

        utmLoc = vmath.Vector3([locationE], [locationN], [0])
        refPoint = vmath.Vector3(interferogram_refx, interferogram_refy, 0)

        LOS = oksar.getLOSvector(
            utmLoc,
            locationUTMzone,
            refPoint,
            satellite_altitude,
            satellite_azimuth,
            interferogram_ref_incidence,
            local_earth_radius
        )

        true = vmath.Vector3([0.427051, -0.090772, 0.899660])
        assert (LOS - true).length < 1e-5
コード例 #4
0
def test_Vec3_subtraction_operator():
    components1 = np.random.rand(3)
    components2 = np.random.rand(3)
    vec3_1py = vectormath.Vector3(*components1)
    vec3_2py = vectormath.Vector3(*components2)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_2cpp = NumCpp.Vec3(*components2)
    assert np.array_equal(
        np.round(vec3_1py - vec3_2py, DECIMALS_TO_ROUND),
        np.round((NumCpp.Vec3_minusVec3(vec3_1cpp,
                                        vec3_2cpp)).toNdArray().flatten(),
                 DECIMALS_TO_ROUND))

    components = np.random.rand(3)
    scaler = np.random.rand(1).item()
    vec3py = vectormath.Vector3(*components)
    vec3cpp = NumCpp.Vec3(*components)
    assert np.array_equal(
        np.round(vec3py - scaler, DECIMALS_TO_ROUND),
        np.round((NumCpp.Vec3_minusVec3Scaler(vec3cpp,
                                              scaler)).toNdArray().flatten(),
                 DECIMALS_TO_ROUND))

    components = np.random.rand(3)
    scaler = np.random.rand(1).item()
    vec3py = vectormath.Vector3(*components)
    vec3cpp = NumCpp.Vec3(*components)
    assert np.array_equal(
        np.round(-vec3py + scaler, DECIMALS_TO_ROUND),
        np.round((NumCpp.Vec3_minusScalerVec3(vec3cpp,
                                              scaler)).toNdArray().flatten(),
                 DECIMALS_TO_ROUND))
コード例 #5
0
def test_Vec3_cross():
    components1 = np.random.rand(3)
    components2 = np.random.rand(3)
    vec3_1py = vectormath.Vector3(*components1)
    vec3_2py = vectormath.Vector3(*components2)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_2cpp = NumCpp.Vec3(*components2)
    assert np.array_equal(np.round(vec3_1py.cross(vec3_2py), DECIMALS_TO_ROUND),
                          np.round(vec3_1cpp.cross(vec3_2cpp).toNdArray().flatten(), DECIMALS_TO_ROUND))
コード例 #6
0
def test_Vec3_distance():
    components1 = np.random.rand(3)
    components2 = np.random.rand(3)
    vec3_1py = vectormath.Vector3(*components1)
    vec3_2py = vectormath.Vector3(*components2)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_2cpp = NumCpp.Vec3(*components2)
    assert (round((vec3_2py - vec3_1py).length, DECIMALS_TO_ROUND) ==
            round(vec3_1cpp.distance(vec3_2cpp), DECIMALS_TO_ROUND))
コード例 #7
0
ファイル: __init__.py プロジェクト: rowanc1/oksar
    def simulation_grid(self):

        self.assert_valid

        vec, shape = vmath.ouv2vec(vmath.Vector3(self.O[0], self.O[1], 0),
                                   vmath.Vector3(self.U[0], self.U[1], 0),
                                   vmath.Vector3(self.V[0], self.V[1], 0),
                                   self.shape)
        return vec
コード例 #8
0
def test_Vec3_dot():
    components1 = np.random.rand(3)
    components2 = np.random.rand(3)
    vec3_1py = vectormath.Vector3(*components1)
    vec3_2py = vectormath.Vector3(*components2)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_2cpp = NumCpp.Vec3(*components2)
    assert (round(vec3_1py.dot(vec3_2py), DECIMALS_TO_ROUND) ==
            round(vec3_1cpp.dot(vec3_2cpp), DECIMALS_TO_ROUND))
コード例 #9
0
def test_Vec3_norm():
    components = np.random.rand(3)
    vec3py = vectormath.Vector3(*components)
    vec3cpp = NumCpp.Vec3(*components)
    assert (round(vec3py.length,
                  DECIMALS_TO_ROUND) == round(vec3cpp.norm(),
                                              DECIMALS_TO_ROUND))
コード例 #10
0
def test_Vec3_multiplication_operator():
    components = np.random.rand(3)
    scaler = np.random.rand(1).item()
    vec3py = vectormath.Vector3(*components)
    vec3cpp = NumCpp.Vec3(*components)
    assert np.array_equal(np.round(vec3py * scaler, DECIMALS_TO_ROUND),
                          np.round((NumCpp.Vec3_multVec3Scaler(vec3cpp, scaler)).toNdArray().flatten(),
                                   DECIMALS_TO_ROUND))

    components = np.random.rand(3)
    scaler = np.random.rand(1).item()
    vec3py = vectormath.Vector3(*components)
    vec3cpp = NumCpp.Vec3(*components)
    assert np.array_equal(np.round(vec3py * scaler, DECIMALS_TO_ROUND),
                          np.round((NumCpp.Vec3_multScalerVec3(vec3cpp, scaler)).toNdArray().flatten(),
                                   DECIMALS_TO_ROUND))
コード例 #11
0
def test_Vec3_normalize():
    components = np.random.rand(3)
    vec3py = vectormath.Vector3(*components)
    vec3cpp = NumCpp.Vec3(*components)
    assert np.array_equal(
        np.round(vec3py.normalize(), DECIMALS_TO_ROUND),
        np.round(vec3cpp.normalize().toNdArray().flatten(), DECIMALS_TO_ROUND))
コード例 #12
0
ファイル: lightmap.py プロジェクト: PietPtr/MarsMap
def lightmap(nm, cm, light, ambient):
    width, height = nm.size
    cwidth, cheight = cm.size

    if cwidth != width or cheight != height:
        print("Resolutions do not match.")
        exit()

    shaded = Image.new('RGBA', (width, height), color=(0, 0, 0, 0))

    for y in range(0, height):
        if y % (height // 100) == 0:
            print("lm", y / height * 100)
        for x in range(0, width):
            (cr, cg, cb, ca) = cm.getpixel((x, y))
            (r, g, b, a) = nm.getpixel((x, y))
            if a != 0:
                normal = vmath.Vector3(\
                    (r/255 - 0.5) * 2,
                    (g/255 - 0.5) * 2,
                    (b/255 - 0.5) * 2)
                angle = normal.angle(light, 'deg')
                illumination = 1 - (angle / 180)
                illumination = ambient + (1 - ambient) * illumination
                cr = int(illumination * cr)
                cg = int(illumination * cg)
                cb = int(illumination * cb)
                shaded.putpixel((x, y), (cr, cg, cb, ca))

    return shaded
コード例 #13
0
ファイル: zed2pcl.py プロジェクト: lab-china/zed2
def get_quaternion_from_vectors(target=None, source=None):
    """
    参考URL
    https://knowledge.shade3d.jp/knowledgebase/2%E3%81%A4%E3%81%AE%E3%83%99%E3%82%AF%E3%83%88%E3%83%AB%E3%81%8C%E4%BD%9C%E3%82%8B%E5%9B%9E%E8%BB%A2%E8%A1%8C%E5%88%97%E3%82%92%E8%A8%88%E7%AE%97-%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%83%88
    ベクトルaをbに向かせるquaternionを求める.
  """
    qw, qx, qy, qz = 1.0, 0.0, 0.0, 0.0
    normalize = lambda x: np.array(vmath.Vector3(x).normalize())
    src_vec = normalize(source)
    target_vec = normalize(target)
    cross_vec = np.cross(target_vec, src_vec)
    cross_vec_norm = -np.linalg.norm(cross_vec)
    cross_vec = normalize(cross_vec)
    epsilon = 0.0002
    inner_vec = np.dot(src_vec, target_vec)
    if -epsilon < cross_vec_norm or 1.0 < inner_vec:
        if inner_vec < (epsilon - 1.0):
            trans_axis_src = np.array([-src_vec[1], src_vec[2], src_vec[0]])
            c = normalize(np.cross(trans_axis_src, src_vec))
            qw = 0.0
            qx = c[0]
            qy = c[1]
            qz = c[2]
    else:
        e = cross_vec * math.sqrt(0.5 * (1.0 - inner_vec))
        qw = math.sqrt(0.5 * (1.0 + inner_vec))
        qx = e[0]
        qy = e[1]
        qz = e[2]
    return np.quaternion(qw, qx, qy, qz)
コード例 #14
0
def test_Vec3_division_assignment_operator():
    components1 = np.random.rand(3)
    scaler = np.random.rand(1).item()
    vec3_1py = vectormath.Vector3(*components1)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_1cpp /= scaler
    assert np.array_equal(np.round(vec3_1py / scaler, DECIMALS_TO_ROUND),
                          np.round(vec3_1cpp.toNdArray().flatten(), DECIMALS_TO_ROUND))
コード例 #15
0
def distance(player, enemy):
    diff = vectors.Vector3(0.0, 0.0, 0.0)
    diff.x = enemy.x - player.x
    diff.y = enemy.y - player.y
    diff.z = enemy.z - player.z

    distance = sqrt(diff.x**2 + diff.y**2 + diff.z**2)

    return abs(distance)
コード例 #16
0
    def test_los(self):

        dinar, dinar_fwd = oksar.example()

        dinar.ref = [741140, 4230327]
        dinar.ref_incidence = 23
        dinar.local_earth_radius = 6386232
        dinar.satellite_altitude = 788792
        dinar.satellite_azimuth = 192
        dinar.location_UTM_zone = 35

        utmLoc = vmath.Vector3([706216.0606, 4269238.9999, 0])
        # refPoint = vmath.Vector3(dinar.ref.x, dinar.ref.y, 0)
        LOS = dinar.get_LOS_vector(utmLoc)

        # compare against fortran code.
        true = vmath.Vector3([0.427051, -0.090772, 0.899660])
        assert (LOS - true).length < 1e-5
コード例 #17
0
def test_Vec3_subtraction_assignment_operator():
    components1 = np.random.rand(3)
    components2 = np.random.rand(3)
    vec3_1py = vectormath.Vector3(*components1)
    vec3_2py = vectormath.Vector3(*components2)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_2cpp = NumCpp.Vec3(*components2)
    vec3_1cpp -= vec3_2cpp
    assert np.array_equal(np.round(vec3_1py - vec3_2py, DECIMALS_TO_ROUND),
                          np.round(vec3_1cpp.toNdArray().flatten(), DECIMALS_TO_ROUND))

    components1 = np.random.rand(3)
    scaler = np.random.rand(1).item()
    vec3_1py = vectormath.Vector3(*components1)
    vec3_1cpp = NumCpp.Vec3(*components1)
    vec3_1cpp -= scaler
    assert np.array_equal(np.round(vec3_1py - scaler, DECIMALS_TO_ROUND),
                          np.round(vec3_1cpp.toNdArray().flatten(), DECIMALS_TO_ROUND))
コード例 #18
0
def press_key_handler(arg1, x, y, z):
    global is_pressed
    inputVector = vmath.Vector3(x, y, z)
    print(arg1, x, y, z, inputVector.length)
    if inputVector.length > 15 and not is_pressed:
        keyboard.send('space')
        is_pressed = True
    elif is_pressed:
        is_pressed = False
コード例 #19
0
    def test_dynamic_getter(self):
        class HasDynamicProperty(properties.HasProperties):
            my_int = properties.Integer('an int')

            @properties.Integer('a dynamic int')
            def my_doubled_int(self):
                if self.my_int is None:
                    raise ValueError('my_doubled_int depends on my_int')
                return self.my_int * 2

            @properties.Vector3('a vector')
            def my_vector(self):
                self.validate()
                if self.my_int is None:
                    raise ValueError('my_vector depends on my_int')
                val = [
                    float(val)
                    for val in [self.my_int, self.my_int, self.my_doubled_int]
                ]
                return val

            @properties.Integer('another dynamic int')
            def my_tripled_int(self):
                if self.my_int:
                    return self.my_int * 3

        hdp = HasDynamicProperty()
        with self.assertRaises(ValueError):
            hdp.my_doubled_int
        assert hdp.my_tripled_int is None
        hdp.my_int = 10
        assert hdp.my_doubled_int == 20
        assert isinstance(hdp.my_vector, vectormath.Vector3)
        assert hdp.validate()

        with self.assertRaises(AttributeError):
            hdp.my_doubled_int = 50

        with self.assertRaises(AttributeError):
            del hdp.my_doubled_int

        assert HasDynamicProperty._props['my_vector'].equal(
            vectormath.Vector3(0, 1, 2), vectormath.Vector3(0, 1, 2))
コード例 #20
0
    def displacement_vector(self):

        self.assert_valid

        vec = self.simulation_grid
        x, y = vec.x, vec.y

        DEG2RAD = 0.017453292519943
        alpha = (self.beta + self.mu) / (self.beta + 2.0 * self.mu)

        #  Here we could loop over models

        flt_x = self.center[0]
        flt_y = self.center[1]
        strike = self.strike
        dip = self.dip
        rake = self.rake
        slip = self.slip
        length = self.length
        hmin = self.depth_top
        hmax = self.depth_bottom

        rrake = (rake+90.0)*DEG2RAD
        sindip = np.sin(dip*DEG2RAD)
        w = (hmax-hmin)/sindip
        ud = slip*np.cos(rrake)
        us = -slip*np.sin(rrake)
        halflen = length/2.0
        al2 = halflen
        al1 = -al2
        aw1 = hmin/sindip
        aw2 = hmax/sindip

        if(hmin < 0.0):
            raise Exception('ERROR: Fault top above ground surface')

        if(hmin == 0.0):
            hmin = 0.00001

        sstrike = (strike+90.0)*DEG2RAD

        ct = np.cos(sstrike)
        st = np.sin(sstrike)

        X = ct * (-flt_x + x) - st * (-flt_y + y)
        Y = ct * (-flt_y + y) + st * (-flt_x + x)

        u = self._dc3d3(alpha, X, Y, -dip, al1, al2, aw1, aw2, us, ud)

        UX = ct*u.x + st*u.y
        UY = -st*u.x + ct*u.y
        UZ = u.z

        return vmath.Vector3(UX, UY, UZ)
コード例 #21
0
def press_key_handler(address, *args):
    global is_pressed
    global window
    inputVector = vmath.Vector3(args[0], args[1], args[2])
    window.FindElement('_DEBUG_').Update(f'{address} {inputVector.length}\r\n',
                                         append=True)
    # print(arg1, x, y, z, inputVector.length)
    if inputVector.length > 15 and not is_pressed:
        keyboard.send('space')
        is_pressed = True
    elif is_pressed:
        is_pressed = False
コード例 #22
0
def main():
    with open("./inputs/day12.txt") as file:
        raw_input = file.read()

    names = ["Io", "Europa", "Ganymede", "Callisto"]
    moons = OrderedDict()
    matches = re.findall(r"^<x=(-*\d+), y=(-*\d+), z=(-*\d+)>$", raw_input,
                         re.MULTILINE)
    for match in matches:
        moons[names.pop(0)] = {
            'position': vmath.Vector3(int(match[0]), int(match[1]),
                                      int(match[2])),
            'velocity': vmath.Vector3(0, 0, 0)
        }

    answer = 1
    for dimension in ["x", "y", "z"]:
        steps = step_until_velocity_zero(copy.deepcopy(moons), dimension)
        answer = lcm(answer, steps)

    print(answer)
コード例 #23
0
def main():
    with open("./inputs/day12.txt") as file:
        raw_input = file.read()

    names = ["Io", "Europa", "Ganymede", "Callisto"]
    moons = OrderedDict()
    matches = re.findall(r"^<x=(-*\d+), y=(-*\d+), z=(-*\d+)>$", raw_input,
                         re.MULTILINE)
    for match in matches:
        moons[names.pop(0)] = {
            'position': vmath.Vector3(int(match[0]), int(match[1]),
                                      int(match[2])),
            'velocity': vmath.Vector3(0, 0, 0)
        }

    for step in range(1, 1001):
        gravity = calculate_gravity(moons)
        moons = apply_gravity(moons, gravity)
        moons = apply_velocities(moons)

        if step == 1000:
            moons = calculate_energies(moons)
            print(int(sum([x['energy'] for _, x in moons.items()])))
コード例 #24
0
def sobel(x, y, hm, sobelscale):
    s = []
    for ny in range(1, -2, -1):
        for nx in range(-1, 2):
            value = hm.getpixel((x + nx, y + ny))
            s.append(value)
            # if value != -2147483648:
            # else:
            # samples.append(hm.getpixel)

    normal = vmath.Vector3(0, 0, 0)
    scale = sobelscale
    normal.x = scale * -(s[2] - s[0] + 2 * (s[5] - s[3]) + s[8] - s[6])
    normal.y = scale * -(s[6] - s[0] + 2 * (s[7] - s[1]) + s[8] - s[2])
    normal.z = 1
    normal.normalize()

    normal.x = normal.x * 0.5 + 0.5
    normal.y = normal.y * 0.5 + 0.5
    normal.z = normal.z + 0.5

    return normal
コード例 #25
0
def calculate_gravity(moons):
    moon_pairs = get_moon_pairs(tuple(moons.keys()))
    gravity = {name: [] for name in moons}
    for pair in moon_pairs:
        gravity[pair[0]].append(
            vmath.Vector3(
                get_velocity(moons[pair[0]]['position'].x,
                             moons[pair[1]]['position'].x), 0, 0))
        gravity[pair[1]].append(
            vmath.Vector3(
                get_velocity(moons[pair[1]]['position'].x,
                             moons[pair[0]]['position'].x), 0, 0))

        gravity[pair[0]].append(
            vmath.Vector3(
                0,
                get_velocity(moons[pair[0]]['position'].y,
                             moons[pair[1]]['position'].y), 0))
        gravity[pair[1]].append(
            vmath.Vector3(
                0,
                get_velocity(moons[pair[1]]['position'].y,
                             moons[pair[0]]['position'].y), 0))

        gravity[pair[0]].append(
            vmath.Vector3(
                0, 0,
                get_velocity(moons[pair[0]]['position'].z,
                             moons[pair[1]]['position'].z)))
        gravity[pair[1]].append(
            vmath.Vector3(
                0, 0,
                get_velocity(moons[pair[1]]['position'].z,
                             moons[pair[0]]['position'].z)))

    return gravity
コード例 #26
0
ファイル: __init__.py プロジェクト: rowanc1/oksar
              dip=50,
              rake=90,
              slip=0.5,
              length=11578.907244622129,
              center=[773728.2977967655, 4223586.816611591],
              depth_top=0,
              depth_bottom=15000,
              O=[706216.0606, 4187318.9999],
              U=[81920, 0],
              V=[0, 81920],
              shape=(300, 200))

    wv = 0.028333
    rigidity = 30000000000

    LOS = vmath.Vector3(0.3825, 0.0780, 0.9205)

    n = 300
    O = vmath.Vector3(706216.0606, 4187318.9999, 0)
    U = vmath.Vector3(81920, 0, 0)
    V = vmath.Vector3(0, 81920, 0)

    vec, shape = vmath.ouv2vec(O, U, V, n)

    print(vec.shape)
    # strike=254
    # dip=40
    # rake=130
    # slip=0.9209931290545376
    # length=16384
    # center=747176.0606,4228278.9999
コード例 #27
0
ファイル: main.py プロジェクト: leafunes/raytracing
from PIL import Image
import numpy as np
import vectormath as vmath
import math
from sphere import Sphere

h, w = 800, 600
image = np.ndarray((w, h, 3), dtype=np.uint8)
origin = vmath.Vector3(0, 0, 0)
resolution = vmath.Vector2(w, h)

sphere1 = Sphere(0, 0, 4, 1.0)
sphere2 = Sphere(1.3, 1.3, 8, 1.0)

spheres = [sphere1, sphere2]

def normalize(min_val, max_val, val):
    return (val - min_val) / (max_val - min_val)


def get_color(ray):

    distances = []
    for s in spheres:
        distances.append(s.intesect(origin, ray))
    
    min_distance = None

    for d in distances:
        if(d is not None):
            if(min_distance is None or d[0] < min_distance[0]):
コード例 #28
0
    def _dc3d3(self, alpha, X, Y, dip, al1, al2, aw1, aw2, disl1, disl2):
        F0 = 0.0
        F1 = 1.0
        F2 = 2.0
        PI2 = 6.283185307179586
        EPS = 1.0E-6

        u = vmath.Vector3(F0, F0, F0)
        dub = vmath.Vector3(F0, F0, F0)

        #  %%dccon0 subroutine
        #  Calculates medium and fault dip constants
        c0_alp3 = (F1 - alpha) / alpha
        #  PI2/360
        pl8 = 0.017453292519943
        c0_sd = np.sin(dip*pl8)
        c0_cd = np.cos(dip*pl8)

        if(np.abs(c0_cd) < EPS):
            c0_cd = F0
            if(c0_sd > F0):
                c0_sd = F1

            if(c0_sd < F0):
                c0_sd = -F1

        c0_cdcd = c0_cd * c0_cd
        c0_sdcd = c0_sd * c0_cd

        #  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        p = Y * c0_cd
        q = Y * c0_sd

        jxi = ((X - al1) * (X - al2)) <= F0  # BOOLEAN
        jet = ((p - aw1) * (p - aw2)) <= F0  # BOOLEAN

        for k in [1., 2.]:
            et = 0.0
            if(k == 1):
                et = p-aw1
            else:
                et = p-aw2

            for j in [1., 2.]:
                xi = 0.0
                if(j == 1):
                    xi = X-al1
                else:
                    xi = X-al2

                # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                # %%dccon2 subroutine
                # % calculates station geometry constants for finite source

                dc_max = np.max(np.abs(np.c_[xi, et, q]))

                # dc_max = max(np.abs(xi),max(np.abs(et),np.abs(q)))

                xi[(np.abs(xi/dc_max) < EPS) | (np.abs(xi) < EPS)] = F0

                et[(np.abs(et/dc_max) < EPS) | (np.abs(et) < EPS)] = F0

                q[(np.abs(q/dc_max) < EPS) | (np.abs(q) < EPS)] = F0

                dc_xi = xi
                dc_et = et
                dc_q = q
                c2_r = np.sqrt(dc_xi*dc_xi + dc_et*dc_et + dc_q*dc_q)

                if np.any(c2_r == F0):
                    raise Exception('singularity error ???')

                c2_y = dc_et * c0_cd + dc_q * c0_sd
                c2_d = dc_et * c0_sd - dc_q * c0_cd
                c2_tt = np.arctan(dc_xi * dc_et / (dc_q * c2_r))
                c2_tt[dc_q == F0] = F0

                rxi = c2_r + dc_xi
                c2_x11 = F1/(c2_r*rxi)
                c2_x11[(dc_xi < F0) & (dc_q == F0) & (dc_et == F0)] = F0

                ret = c2_r + dc_et
                if np.any(ret < 1e-14):
                    raise Exception('dccon2 b %f %f %f %f' % (
                        ret, c2_r, dc_et, dc_q, dc_xi
                    ))

                c2_ale = np.log(ret)
                c2_y11 = F1/(c2_r*ret)

                ind = (dc_et < F0) & (dc_q == F0) & (dc_xi == F0)

                # if((c2_r-dc_et) < 1e-14):
                #     raise Exception('dccon2 a %f %f %f %f %f' % (
                #         c2_3-dc_et, c2_r, dc_et, dc_q, dc_xi)
                #     )

                c2_ale[ind] = -np.log(c2_r[ind]-dc_et[ind])
                c2_y11[ind] = F0

                # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

                if np.any(
                    (
                        (q == F0) &
                        (
                            ((jxi) & (et == F0)) |
                            ((jet) & (xi == F0))
                        )
                    ) | (c2_r == F0)
                ):
                    raise Exception('singular problems: 2')

                # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                # ub subroutine
                # part B of displacement and strain at depth due to buried
                # faults in semi-infinite medium

                rd = c2_r + c2_d
                if np.any(rd < 1e-14):
                    raise Exception('ub %f %f %f %f %f %f' % (
                        rd, c2_r, c2_d, xi, et, q
                    ))

                ai3 = 0.0
                ai4 = 0.0
                if(c0_cd != F0):
                    # xx replaces x in original subroutine
                    xx = np.sqrt(xi*xi+q*q)
                    ai4 = F1/c0_cdcd * (xi/rd*c0_sdcd + F2*np.arctan(
                        (
                            et*(xx+q*c0_cd) +
                            xx*(c2_r+xx)*c0_sd
                        ) / (xi*(c2_r+xx)*c0_cd)
                    ))
                    ai4[xi == F0] = F0

                    ai3 = (c2_y*c0_cd/rd - c2_ale + c0_sd*np.log(rd)) / c0_cdcd
                else:
                    rd2 = rd*rd
                    ai3 = (et/rd + c2_y*q/rd2 - c2_ale) / F2
                    ai4 = xi*c2_y/rd2/F2

                ai1 = -xi/rd*c0_cd - ai4*c0_sd
                ai2 = np.log(rd) + ai3*c0_sd
                qx = q*c2_x11
                qy = q*c2_y11

                # strike-slip contribution
                if(disl1 != 0.0):
                    du2x = - xi*qy - c2_tt - c0_alp3 * ai1 * c0_sd
                    du2y = - q/c2_r + c0_alp3*c2_y/rd*c0_sd
                    du2z = q*qy - c0_alp3*ai2*c0_sd
                    du2 = vmath.Vector3(du2x, du2y, du2z)
                    dub = du2 * (disl1 / PI2)
                else:
                    dub = vmath.Vector3()

                # dip-slip contribution
                if(disl2 != F0):
                    du2x = - q/c2_r + c0_alp3 * ai3 * c0_sdcd
                    du2y = - et*qx - c2_tt - c0_alp3 * xi / rd * c0_sdcd
                    du2z = q*qx + c0_alp3 * ai4 * c0_sdcd
                    du2 = vmath.Vector3(du2x, du2y, du2z)
                    dub = dub + (du2 * (disl2 / PI2))

                # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

                dux = dub.x
                duy = dub.y*c0_cd - dub.z*c0_sd
                duz = dub.y*c0_sd + dub.z*c0_cd
                du = vmath.Vector3(dux, duy, duz)
                if((j+k) != 3):
                    u = + du + u
                else:
                    u = - du + u

        return u
コード例 #29
0
ファイル: settings.py プロジェクト: PietPtr/MarsMap
import vectormath as vmath
import math
from PIL import Image, ImageDraw

Image.MAX_IMAGE_PIXELS = 1061683200

SCALE = 30

smoothness = 15

gradient = [(0, "#502910"), (35, "#e3b88d"), (50, "#dfdad6")]

sobelScale = -0.000000034

light = vmath.Vector3(1, 0.2, 0.8).normalize()

ambientPercentage = 0.12
コード例 #30
0
    def plot_displacement(self, eq=None, ax=None, wrap=True, mask_opacity=0.2):

        if eq is not None:
            assert isinstance(eq, EarthquakeInterferogram)

        if ax is None:
            plt.figure()
            ax = plt.subplot(111)

        vectorNx = (
            np.r_[
                0,
                np.cumsum(
                    (self.U[0]/self.shape[0],) * self.shape[0]
                )
            ] + self.O[0]
        )
        vectorNy = (
            np.r_[
                0,
                np.cumsum(
                    (self.V[1]/self.shape[1],) * self.shape[1]
                )
            ] + self.O[1]
        )

        DIR = self.displacement_vector
        grid = self.simulation_grid
        if eq is None:
            LOS = vmath.Vector3(0, 0, 1)
        else:
            LOS = eq.get_LOS_vector(grid)
        data = DIR.dot(LOS)
        data = np.flipud(data.reshape(self.shape, order='F').T)
        # data[data == 0] = np.nan
        # data *= self.scaling

        if wrap and eq is not None:
            cmap = plt.cm.hsv
            data = data % eq.satellite_fringe_interval
            vmin, vmax = 0.0, eq.satellite_fringe_interval
        else:
            cmap = plt.cm.jet
            vmin = np.nanmin(data)
            vmax = np.nanmax(data)

        out = ax.pcolormesh(
            vectorNx,
            vectorNy,
            np.ma.masked_where(np.isnan(data), data),
            vmin=vmin,
            vmax=vmax,
            cmap=cmap
        ),

        ax.axis('equal')
        ax.set_xlabel('Easting, m')
        ax.set_ylabel('Northing, m')

        cb = plt.colorbar(out[0], ax=ax)
        cb.set_label('Displacement, m')

        if eq is not None:
            mask = eq.plot_mask(ax=ax, opacity=mask_opacity)
            out = out[0], mask

        return out