Пример #1
0
def associated_legendre():
    n = 2
    m = 1
    x = np.linspace(-1, 1, 1000)

    f = partial(miepy.cpp.special.associated_legendre, n, m, x)
    Tcpp = time_function(f)

    f = partial(miepy.vsh.old_special.associated_legendre(n, m), x)
    Tpy = time_function(f)

    display(f'Associated Legendre (n = {n}, m = {m})', Tcpp, Tpy)
Пример #2
0
def tests(Nmax, step=1):
    Nparticles = np.arange(1, Nmax + 1, step)
    t_force, t_flux, t_build, t_solve, t_source = [
        np.zeros_like(Nparticles, dtype=float) for i in range(5)
    ]
    for i, N in enumerate(Nparticles):
        print(N, Nmax)
        # positions = [[n*separation, 0, 0] for n in range(N)]
        positions = hexagonal_lattice_particles(N) * separation
        mie = miepy.sphere_cluster(position=positions,
                                   radius=radius,
                                   material=Ag,
                                   source=source,
                                   wavelength=600 * nm,
                                   lmax=2)

        t_force[i] = time_function(mie.force)
        t_flux[i] = time_function(mie.cross_sections)
        t_build[i] = time_function(
            partial(miepy.interactions.sphere_aggregate_tmatrix, mie.position,
                    mie.mie_scat, mie.material_data.k_b))

        A = miepy.interactions.sphere_aggregate_tmatrix(
            mie.position, mie.mie_scat, k=mie.material_data.k_b)
        t_solve[i] = time_function(
            partial(solve_linear_system,
                    A,
                    mie.p_src,
                    method=miepy.solver.bicgstab))

        x = np.linspace(0, N * separation, 1)
        y = 2 * radius * np.ones_like(x)
        z = np.zeros_like(x)

        t_source[i] = time_function(mie._solve_source_decomposition)

    fig, ax = plt.subplots()

    ax.plot(Nparticles, t_force * 1e3, '-o', label='force')
    ax.plot(Nparticles, t_flux * 1e3, '-o', label='flux')
    ax.plot(Nparticles, t_build * 1e3, '-o', label='build')
    ax.plot(Nparticles, t_solve * 1e3, '-o', label='solve')
    ax.plot(Nparticles, t_source * 1e3, '-o', label='source')

    ax.legend()
    ax.set(xlabel='number of particles', ylabel='runtime (ms)')

    plt.show()
Пример #3
0
def hankel():
    n = 4
    x = np.linspace(0.3, 0.5, 1000)

    f = partial(miepy.cpp.special.spherical_hn, n, x)
    Tcpp = time_function(f)

    f = partial(miepy.vsh.old_special.spherical_hn, n, x)
    Tpy = time_function(f)

    display(f'Spherical Hankel, small x (n = {n})', Tcpp, Tpy)

    x = np.linspace(10.0, 12.0, 1000)

    f = partial(miepy.cpp.special.spherical_hn, n, x)
    Tcpp = time_function(f)

    f = partial(miepy.vsh.old_special.spherical_hn, n, x)
    Tpy = time_function(f)

    display(f'Spherical Hankel, large x (n = {n})', Tcpp, Tpy)
Пример #4
0
def tests(Nmax, step=1):
    Nparticles = np.arange(1, Nmax+1, step)
    names = ['build', 'solve', 'flux', 'force']
    ftimer = {name: np.zeros_like(Nparticles, dtype=float) for name in names}
    for i,N in enumerate(Nparticles):
        print(N, Nmax)
        positions = [[n*separation, 0, 0] for n in range(N)]
        mie = miepy.sphere_cluster(position=positions,
                                   radius=radius,
                                   material=Ag,
                                   source=source,
                                   wavelength=600*nm,
                                   lmax=2)
        
        ftimer['force'][i] = time_function(mie.force)
        ftimer['flux'][i] = time_function(mie.cross_sections)
        ftimer['build'][i] = time_function(partial(miepy.interactions.sphere_aggregate_tmatrix, 
                              mie.position, mie.mie_scat, mie.material_data.k_b))

        A = miepy.interactions.sphere_aggregate_tmatrix(mie.position, mie.mie_scat, k=mie.material_data.k_b)
        ftimer['solve'][i] = time_function(partial(solve_linear_system, A, mie.p_src, method=miepy.solver.bicgstab))

    return ftimer, Nparticles
Пример #5
0
def tests(Nmax, step=1):
    Nparticles = np.arange(1, Nmax+1, step)
    t_force, t_flux, t_build, t_solve, t_expand, t_tmatrix = [np.zeros_like(Nparticles, dtype=float) for i in range(6)]
    for i,N in enumerate(Nparticles):
        print(N, Nmax)
        positions = [[n*separation, 0, 0] for n in range(N)]
        particles = [miepy.spheroid(pos, radius, 0.5*radius, Ag) for pos in positions]
        mie = miepy.cluster(particles=particles,
                                      source=source,
                                      wavelength=600*nm,
                                      lmax=2)
        
        t_force[i] = time_function(mie.force)
        t_flux[i] = time_function(mie.cross_sections)
        t_build[i] = time_function(partial(miepy.interactions.particle_aggregate_tmatrix, 
                              mie.position, mie.tmatrix, mie.material_data.k_b))

        A = miepy.interactions.particle_aggregate_tmatrix(mie.position, mie.tmatrix, k=mie.material_data.k_b)
        t_solve[i] = time_function(partial(solve_linear_system, A, mie.p_src, method=miepy.solver.bicgstab))
        t_tmatrix[i] = time_function(partial(tmatrix_time, mie))
        
        x = np.linspace(0, N*separation, 1)
        y = 2*radius*np.ones_like(x)
        z = np.zeros_like(x)

        t_expand[i] = time_function(partial(mie.E_field, x, y, z))

    fig, ax = plt.subplots()

    ax.plot(Nparticles, t_force, label='force')
    ax.plot(Nparticles, t_flux, label='flux')
    ax.plot(Nparticles, t_build, label='build')
    ax.plot(Nparticles, t_solve, label='solve')
    ax.plot(Nparticles, t_expand, label='expand')
    ax.plot(Nparticles, t_tmatrix, label='tmatrix')

    ax.legend()
    ax.set(xlabel='number of particles', ylabel='runtime (s)')

    plt.show()
Пример #6
0
    x1,y1 = fundamental_solution()
    _x,_y = x1,y1
    while True:
        _x,_y = x1*_x + 2*y1*_y, x1*_y + y1*_x
        yield _x,_y

# if t > 10^12
def f4(N):
    for x,y in pell_solutions():
        b = (y + 1)/2
        t = (x + 1)/2
        if t > N and t//1 == t and b//1 == b:
            return b,t

N = 1e12
print(time_function(f4,N))

# Brute force attempts

def f(N):
    T = int(N)
    while True:
        for r in range(1,T):
            if 2*r*(r-1) == T*(T-1):
                print(r,'/',T,' ',r-1,'/',T-1)
        T += 1

def f1(N):
    T = int(N)
    while True:
        P = T*(T+1)/2
Пример #7
0
def timed_job():
    print('This job is run every 30 seconds.')

    timer.time_function()
    for index, pair in enumerate(histogram):
        if pair[0] == item:
            return index
    return None


# Algorithm complexity: O(n^2)
def histogram(words):
    hist = []
    for word in words:
        index = find(word, hist)
        if index is None:
            hist.append((word, 1))
        else:
            count = hist[index][1]
            new_pair = (word, count + 1)
            hist[index] = new_pair
    return hist


def frequency(word, histogram):
    index = find(word, histogram)
    word = histogram[index][0]
    return word


if __name__ == "__main__":
    hist = histogram(words_list)
    # timer.time_function("frequency('the', hist)")  # 0.000 secs
    timer.time_function("histogram(words_list)")  # 9.175 secs
Пример #9
0
# 31626

# 4/12/17 - rewriting
from math import sqrt

def d(n):
    s = 1
    for i in range(2,int(sqrt(n)) + 1):
        if n%i == 0:
            s += i + n//i
    return s

def solve(N):
    data = {}
    for a in range(N):
        _d = d(a)
        data[a] = _d
    s = []
    for a in range(N):
        if data[a] < N:
            if data[a] != a and data[data[a]] == a:
                s.append(a)
        else:
            if data[a] == d(data[a]):
                s.append(a)
    return sum(set(s))

from timer import time_function
print(time_function(solve,10000))

sys.path.append('../')

import converter
import timer

words_list = converter.convert_to_words_list("../robinson_crusoe_text.txt")


# algorithm complexity: 1 (some constant)
def histogram(words_list):
    histogram = {}
    for word in words_list:
        try:
            histogram[word] += 1
        except:
            histogram[word] = 0
    return histogram


def frequency(word, histogram):
    try:
        return histogram[word]
    except:
        print("Word does not exist")


if __name__ == "__main__":
    # histogram = histogram(words_list)
    # timer.time_function("frequency('the', histogram)")  # 0.000 secs
    timer.time_function("histogram(words_list)")  # 0.027 secs
Пример #11
0
                            if digit not in digits and letter not in key:
                                key[letter] = digit
                                digits.append(digit)
                            elif letter not in key or key[letter] != digit:
                                good_key = False
                                break
                        if good_key:
                            sq2 = word_to_num(words[1],key)
                            if sq2 in sqs:
                                f += [int(sq),int(sq2)]
            if len(f) > 0:
                return max(f)
        except KeyError:
            pass

print(time_function(solve,problem_number=98))

"""
def word_to_num(word,key):
    s = ''
    for e in word:
        s += str(key[e])
    if s[0] == '0':
        raise LeadingZeroException()
    return int(s)

def solve():
    anagrams = sort_words()
    M = max(anagrams)
    for l in range(M,0,-1): 
        f = []
Пример #12
0
            sol.append([0 for k in range(len(temp))])

#maze = [[131,673,234,103,18],[201,96,342,965,150],[630,803,746,422,111],[537,699,497,121,956],[805,732,524,37,331]]
#sol = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]

    I = len(maze)
    J = len(maze[0])

    #print J, I

    sol[0][0] = maze[0][0]

    for i in range(I):
            for j in range(J):
                    if i != I - 1:
                            if sol[i+1][j] == 0:
                                    sol[i+1][j] = sol[i][j] + maze[i+1][j]
                            else:
                                    if sol[i][j] + maze[i+1][j] < sol[i+1][j]:
                                            sol[i+1][j] = sol[i][j] + maze[i+1][j]
                    if j != J - 1:
                            if sol[i][j+1] == 0:
                                    sol[i][j+1] = sol[i][j] + maze[i][j+1]
                            else:
                                    if sol[i][j] + maze[i][j+1] < sol[i][j+1]:
                                            sol[i][j+1] = sol[i][j] + maze[i][j+1]
    return sol[-1][-1]

from timer import time_function
print(time_function(solve))
Пример #13
0
            ab.append(k)
    s = [0]*(2*ab[-1]+1)
    for i,a in enumerate(ab):
        for b in ab[i:]:
            s[a+b] = 1
    a = 0
    j = 0
    while j < N:
        if s[j] == 0:
            a += j
        j += 1
    return a


from timer import time_function
print(time_function(solve,28123))

"""
# Old brute force:
def factor(f):
    factor = []
    s = 0
    for i in range(1,f//2 + 1):###<----modify to range(3,f) for primes up to f
        if f%i == 0: 
            s = s + i
    if s > f:
        return True
    else:
        return False

def abundance_list(f):
Пример #14
0
    primes = sieve(int(UPPER))
    mins = {k:(1e100,()) for k in range(2,N+1)}

    for n in range(4,UPPER+1):
        if n not in primes:
            for f in gen_factors(n):
                _k = len(f)
                s = sum(f)
                k = n - s + _k
                if k > N:
                    continue
                if n <= mins[k][0]:
                    mins[k] = (n,f) 
    return sum(set(i[0] for i in mins.values()))
from timer import time_function
print(time_function(solve))
#print(max(i[0] for i in mins.values()))
#print(sum(set(i[0] for i in mins.values())),time.time()-t)

#powers = [0]*len(primes)
#limits = [int(log(UPPER)/log(p)) for p in primes]

def inc(li,k,default=0):
    m = min(li)
    for i,j in enumerate(li):
        if j != m:
            li[i-1] += 1
            li = [default]*(i-1)+li[i-1:]
            return li
    return [default]*(len(li)-1) + [li[-1]+1]
Пример #15
0
from timer import time_function
#!/bin/sh

# P1.py
# ProjectEuler
#
# Created by joe yuan on 3/8/11.
# Copyright 2011 __MyCompanyName__. All rights reserved.

"""
# Original Solution commented out 4/4/17
sum = 0
for i in range(1001):
    if i%3 == 0 or i%5 == 0:
        sum = sum + i
        print i
print sum
"""
def f(N):
    return sum(i for i in range(1,N) if (i%3 == 0 or i%5 == 0))
print(time_function(f,1000)) 
Пример #16
0
        _c = C[n]
        for i,n in enumerate(a[::-1]):
            C[n] = _c + i + 1
    mk,mv = -1,-1
    for k,v in C.items():
        if v > mv:
            mv = v
            mk = k
    return mk

def solve_bf():
    x = []
    for i in range(1000000,0,-1):
        d = []
        d.append(i)
        c = i
        while c != 1:
            if c%2 == 0:
                c = c/2
            else:
                c = 3*c + 1
            d.append(c)
        x.append([len(d),d[0]])
    x.sort()
    return x[-1]

from timer import time_function
print(time_function(solve,int(1e6)))


Пример #17
0
        if is_special(s):
            if sum(s) < m:
                m = sum(s)
                ms = s
        # increment
        last = itr[0]
        itr[0] = (itr[0]-1)%(N+1)
        for i in range(1,7):
            if last == 0:
                last = itr[i]
                itr[i] = (itr[i]-1)%(N+1)
            else:
                break
    return ''.join(str(i) for i in sorted(ms))

print(time_function(nearby_search_solve))

#print(is_special([6, 9, 11, 12, 13]))
import sys
sys.exit()

sp = [1]
N = 1
last = N
for n in range(2,7):
    l = len(sp)
    sp_mid = sorted(sp)[max(0,l//2)]
    n0 = sum(range(1,n+1))
    s0 = n*sp_mid+sum(sp)
    print('n =',n)
    print('sp =',sp,'sp_mid =',sp_mid,'sum(sp) =',sum(sp),'n*sp_mid =',n*sp_mid)
Пример #18
0

def triangle_sum(x):
    y = []
    for i,c in enumerate(x):
        dummy_row = []
        if len(c) > 1: 
            for j,p in enumerate(c):
                if j != 0 and j != (len(c) - 1):
                    a = p + y[-1][j]
                    b = p + y[-1][j-1]
                    if a > b:
                        dummy_row.append(a)
                    else:
                        dummy_row.append(b)
                elif j == 0:
                    dummy_row.append(p + y[-1][j])
                else:
                    dummy_row.append(p + y[-1][-1])
            y.append(dummy_row)
        else:
            y.append(x[i])



    return max(y[-1])

from timer import time_function
print(time_function(triangle_sum,x))

Пример #19
0
    
def palindrome_check(n):
    s = str(n)
    for i in range(len(s)//2 + 1):
        if s[i] != s[-(i+1)]:
            return False
    return True

def base_check(n):
    #if len(str(n)) == 1:
    #    return False
    if palindrome_check(n) and palindrome_check(binary(n)):
        return True
    else:
        return False
        
def main(N=1000000):
    s = 0
    for i in range(N):
        if base_check(i):
            #print i, binary(i), base_check
            s += i
        else:
            pass
    return s
    
from timer import time_function
print(time_function(main))


3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1

How many different ways can one hundred be written as a sum of at least two positive integers?

"""

correct = {
    2:1,
    3:2,
    4:4,
    5:6,
    6:10,
    7:14,
}


def count(N):
    sol = [1]+[0]*(N)
    for i in range(1,N):
        for j in range(i,N+1):
            sol[j] += sol[j - i]
    return sol[-1]
            
count(100)
from timer import time_function
print(time_function(count,100))
Пример #21
0
            puzzles.append(d)
            d = []
        else:
            d.append(i)
    puzzles.append(d)
    puzzles.pop(0)
    


    for j,i in enumerate(puzzles):
        x =[]
        for k,c in enumerate(i):
            d = []
            for h in c:
                d.append(int(h))
            x.append(d)
        puzzles[j] = x
    f = 1
    s = 0
    for i in puzzles:
        #print "##### ", f, " #####"
        c,x = Sudoku(i)
        #puzzprint(x)
        s = s + c
        f = f + 1
    return s

from timer import time_function
print(time_function(euler96))

Пример #22
0
from timer import time_function
from math import factorial
def f(x):
    return 1 if x < 2 else x*f(x-1)

def f1(x):
    return factorial(x) 

N = 100000
s = 0
x = 10
for n in range(N):
    s += time_function(f,x)[1]
print('x*x',s/N)

s = 0
for n in range(N):
    s += time_function(f1,x)[1]
print('x**2',s/N)