Example #1
0
def check_phi(PHI):
    p = PHI.p
    PHI = PHI.blocks
    for m in range(1, m_max):
        list = integrate(PHI[m], p, mode='list')
        if not is_symmetric(trim(list)):
            return False

    return True
Example #2
0
def step_sphere(params, st, u):
    '''
    st = [x, y, z, q0, q1, q2, q3, .... ]
    params is dictionary and it has various meta-data related to sphere and optimisation 
    u is any other forces 
    '''

    h = params.h
    mu = params.mu
    m = params.m
    r = params.r

    step_fun = params.step_fun

    M = m * np.diag(
        [1, 1, 1, (2 / 5) * (r**2), (2 / 5) * (r**2), (2 / 5) * (r**2)])

    # Extract pose and velocity
    q = st[0:7]
    v = st[7:13]

    # Gravitational, external and other forces
    omega = v[3:6]
    I = M[3:6, 3:6]
    Fext = np.hstack((np.array([0, 0, -9.81 * m
                                ]), -np.cross(omega, np.matmul(I, omega)))) + u

    # Contact normal distances
    psi = q[2] - r

    # Contact Jacobian
    J = np.array([[0, 0, 1, 0, 0, 0], [1, 0, 0, 0, r, 0], [0, 1, 0, -r, 0, 0]])

    R = quat2mat(q[3:7])

    J[:, 3:6] = np.matmul(J[:, 3:6], R)

    if psi < 0.1:
        v_next, x = solver_ncp(v, Fext, M, J, np.array([mu]), psi, h)
    else:
        M_inv = np.linalg.inv(M)
        v_next = v + h * np.matmul(M_inv, Fext)

    q_next = integrate(q, v_next, h)

    st_next = np.hstack((q_next, v_next))

    return st_next
import sys

from algorithms.poisson.integrator import integrate

print(
    "Do not use this script. it hasn't been updated and may break something.")
assert (False)
# Load pre-defined normals from a CSV (exported from MATLAB).
# Use psereo.get_normals(images, lights) to obtain normals using photometric
# stereo.
normals, W, H = pstereo.load_from_csv(sys.argv[1] + "/normal_field")

normals[:, :, 2] = -normals[:, :, 2]

# Integrate normals into a heightfield.
zfield = integrate(normals, 0.0)

# Some stats.
print("zmax: ", np.max(zfield))
print("zmin: ", np.min(zfield))

# Create a mesh from the heightfield.
mesh = z2mesh.z2mesh(-zfield, -1.0, 1.0, -1.0, 1.0)

new_vertices, new_normals, new_indices = mesh

if "--keep-normals" in sys.argv:
    normals = np.flip(normals, axis=1)
    normals[:, :, 2] = -normals[:, :, 2]
    normals = -normals
    normals = normals.reshape((W * H, 3))
coordx = 'okada/vertical_fault_coord_x'
coordy = 'okada/vertical_fault_coord_y'
coordz = 'okada/vertical_fault_coord_z'
faultfile = 'okada/hn_okada_cmt_sources.csv'

#columns containing data in csv file
g.pt_cols = [9, 10, 11]
g.disp_bench_cols = [6, 7, 8]
g.disp_sem_cols = [0, 1, 2]
g.ngllx = 3  #change if other number is used
g.ngll = g.ngllx**3

#elmt spacing
g.mesh_spacing = 1000.0
#number of fault sources
g.npatches = 200

dat, coords, elmt, fault_pts = import_data(data_file, data_len, connectivity,
                                           coordx, coordy, coordz, faultfile)
print "read in all data"
gll_weights, gll_points = gll_quadrature()
print "computed gll quadrature"
dshape_hex8 = dshape_function_hex8(gll_points)
print "computed shape function"
normx, normy, normz, norm = integrate(coords, dat, fault_pts, dshape_hex8,
                                      gll_weights, elmt)

f = open('okada/hn_okada_cmt_errors.txt', 'w')
f.write('norm=%3.3f, normx=%3.3f, normy=%3.3f, normz=%3.3f' %
        (norm, normx, normy, normz))
Example #5
0
def limbDarkening(filename,
                  wavelow,
                  wavehi,
                  specwave=None,
                  spectrum=None,
                  n_param=4,
                  n_plot=False,
                  stellarmodel='phoenix'):
    '''

    '''
    # Kurucz stellar models
    if stellarmodel == 'kurucz':
        print("Using Kurucz stellar models.")
        spit = np.array((specwave, spectrum))
        coeffs, mu, sum_int = gld.getlimbparam(filename,
                                               0,
                                               n_param,
                                               lamfact=0.1,
                                               spit=spit,
                                               returnmu=True)
        #print(coeffs)
        if n_param == 1:
            model = limbdark.linear(mu, coeffs)
        if n_param == 2:
            model = limbdark.quad(mu, coeffs)
        if n_param == 4:
            model = limbdark.nl(mu, coeffs)
        if n_plot != False:
            plt.figure(n_plot)
            plt.clf()
            plt.plot(mu, sum_int, 'go', label='Intensities')
            plt.plot(mu, model, 'r-', label='Best-Fit Model')
            plt.xlabel('mu')
            plt.ylabel('Normalized Intensity')
            plt.legend(loc='lower right')

    # Phoenix stellar models
    elif stellarmodel == 'phoenix':
        print("Using Phoenix stellar models.")
        # Read file
        hdulist = fits.open(filename)
        lddata = hdulist[1].data

        # Read data
        wave = lddata['wavelength'] / 1e4
        igood = np.where(np.bitwise_and(wave >= wavelow, wave <= wavehi))
        wave = wave[igood]
        intensity = lddata['intensity'][igood].T * wave
        flux = lddata['flux'][igood]
        mu = lddata['intensity'][0]
        n_mu, n_weights = intensity.shape

        if wave != None and spectrum != None:
            # Weight intensities according to the spectrum
            spline = spi.UnivariateSpline(specwave, spectrum)
            newspectrum = spline(wave)
            intbottom = integrate(specwave, spectrum)
            sum_int = np.zeros(n_mu)
            for i in range(n_mu):
                inttop = integrate(wave,
                                   intensity[i] / intensity[-1] * newspectrum)
                sum_int[i] = inttop / intbottom
        else:
            # Sum intensities at each mu
            sum_int = np.sum(intensity, axis=1)

        sum_int /= sum_int.max()

        if n_plot != False:
            plt.figure(n_plot)
            plt.clf()
            plt.plot(mu, sum_int, 'bo', label='Original Intensities')

        # Set stellar limb at 1/e of max intensity
        spline = spi.UnivariateSpline(sum_int, mu, k=1, s=0)
        mu_zero = spline(1. / np.e)
        scale = 1. / np.cos(np.pi / 2 - np.arccos(mu_zero))
        isstar = np.where(mu >= mu_zero)[0]

        # Recalculate angles and intensities
        mu = np.sqrt(1. - (1. - mu[isstar]**2) * scale**2)
        n_mu = mu.size
        sum_int = sum_int[isstar]

        #Trim mu < 0.1
        imu = np.where(mu >= 0.1)[0]
        mu = mu[imu]
        sum_int = sum_int[imu]

        if n_plot != False:
            plt.figure(n_plot)
            plt.plot(mu, sum_int, 'go', label='Rescaled Intensities')

        # Non-Linear Limb Darkening
        # I(mu) / I(1) = 1 - a1(1 - mu^[1/2]) - a2(1 - mu)
        #                  - a3(1 - mu^[3/2]) - a4(1 - mu^2)
        # Therefore:
        # 1 - I(mu) / I(1) =   a1(1 - mu^[1/2]) + a2(1 - mu)
        #                    + a3(1 - mu^[3/2]) + a4(1 - mu^2)
        #
        # Quadratic Limb Darkening
        # I(mu) / I(1) = 1 - a1(1 - mu) - a2(1 - mu)^2

        # Use least sqaures to find parameters (a1, etc.) for best
        # model fit using the above equation
        A = np.zeros((n_mu, n_param))

        #Linear
        if n_param == 1:
            A[:, 0] = (1 - mu)
            coeffs = np.linalg.lstsq(A, 1 - sum_int)[0]
            model = limbdark.linear(mu, coeffs)
        #Quadratic
        if n_param == 2:
            A[:, 0] = (1 - mu)
            A[:, 1] = (1 - mu)**2
            coeffs = np.linalg.lstsq(A, 1 - sum_int)[0]
            model = limbdark.quad(mu, coeffs)
        #Non Linear
        elif n_param == 4:
            A[:, 0] = (1 - mu**0.5)
            A[:, 1] = (1 - mu)
            A[:, 2] = (1 - mu**1.5)
            A[:, 3] = (1 - mu**2.)
            coeffs = np.linalg.lstsq(A, 1 - sum_int)[0]
            model = limbdark.nl(mu, coeffs)
        else:
            print('WARNING: ' + str(n_param) +
                  ' parameter models are not supported.')
            coeffs = np.zeros(n_params)
            model = np.zeros(n_mu)

        if n_plot != False:
            plt.figure(n_plot)
            plt.plot(mu, model, 'r-', label='Best-Fit Model')
            plt.xlabel('mu')
            plt.ylabel('Normalized Intensity')
            plt.legend(loc='lower right')

    else:
        print("Unrecognized stellar models.")
        coeffs = None

    return coeffs
Example #6
0
from phi import *
from intersect import *
from integrate import *
from omegas import *
import numpy as np
from matplotlib import pyplot

p=3

PHI = Phi(1000, p).blocks
sup_list = [float(np.max(integrate(PHI[key], p, mode='list'))) for key in PHI]

pyplot.figure(figsize=(40, 20))
pyplot.plot(sup_list)
pyplot.savefig('sup{}.png'.format(p))
Example #7
0
#        profiler.stop()
#        print(profiler.output_text(unicode=True, color=True))

#        profiler.open_in_browser()
#        profiler.output_html()

    else:
        if (improved == 0):
            lncCoeff = correction(D, ymin, ymax, KS_cutoff, numTerms, lncBasis,
                                  plotFT)
        elif (improved == 1):
            lncCoeff = correction_improved(D, ymin, ymax, KS_cutoff, numTerms,
                                           lncBasis, s, plotFT)

    # Update remainder by adding correction coefficients from current iteration
    lngCoeff = lngCoeff + lncCoeff
    integral = integrate(lngCoeff, lngBasis, xmin, xmax, ymin, ymax, 0.01)
    print('Iteration:', iteration, '\t Integral Estimate: %5.9f' % integral)
    iteration = iteration + 1

    # Plot DOS after each iteration
    if (plotDOS_iter == 1):
        show_DOS_Plot(iteration, lngCoeff, lngBasis, ymin, ymax)

print("Finished!")

# Plot DOS after maxIter Iterations
if (plotDOS_end == 1):
    show_DOS_Plot(iteration, lngCoeff, lngBasis, ymin, ymax)