예제 #1
0
파일: MainApp.py 프로젝트: OmarKRostom/Nino
def callMethod(methodNum):
    if methodNum.get() == 1:
        Fletcher_Reeves.main()
    elif methodNum.get() == 2:
        Newton.main()
    elif methodNum.get() == 3:
        Uni_variate.main()
    elif methodNum.get() == 4:
        res = gradientDescent.main()
        restxt = ""
        for i in range(len(res)):
            restxt += str(res[i])
            restxt += '\n'
        result = Label(inpOutFrame, text=restxt, bg='white', height=20)
        result.grid(row=1, column=1)
예제 #2
0
    def solve(self):
        X = [None] * (self.polynomiaOrder)
        Y = [None] * (self.polynomiaOrder)
        for i in range(1, self.polynomiaOrder + 1):
            X[i - 1] = float((self.entryX[i - 1]).get())
            Y[i - 1] = float((self.entryY[i - 1]).get())

        x = float((self.solve_for_x_entry).get())
        window = Toplevel(root)
        window.title("Newton")
        window.geometry('500x500')
        functionLabel = Label(window, text="Output function ").place(x=10,
                                                                     y=15)
        solveLabel = Label(window, text=("Output at X = " + str(x) +
                                         "  is")).place(x=10, y=50)
        l = None
        n = None
        if self.var.get() == 2:
            method = "Lagrange"
            l = Lagrange.Lagrange(X, Y, x)
            l.lagrange()
            outputLabel = Label(window, text=str(l.poly())).place(x=105, y=15)
            solveOutput = Label(window,
                                text=(str(l.calc_value(x)))).place(x=125, y=50)

        if self.var.get() == 1:
            method = "Newton"
            n = Newton.Newton(X, Y, self.polynomiaOrder)
            ot = str(n.createFormula())
            op = str(n.solve(x))
            print(ot)
            print(op)
            outputLabel = Label(window, text=ot).place(x=105, y=15)
            solveOutput = Label(window, text=op).place(x=125, y=50)
        self.plot(X, l, n, method, window)
예제 #3
0
def RunAndPlot(func,
               xs,
               ys,
               initial=None,
               iterations=10,
               precision=0.01,
               method='GN'):
    if method is 'GN' or method is '*':
        (result, CoD) = GaussNewton.Run(func, xs, ys, initial, iterations,
                                        precision)
    elif method is 'N':
        (result, CoD) = Newton.Run(func, xs, ys, initial, iterations,
                                   precision)

    try:
        print("Constants = " + str(result))
        print("CoD = " + str(CoD))
        PlotData(func, result, xs, ys)
    except:
        input("No results found. Press Enter to continue")

    # If method is '*', repeat with Newton
    if method is '*':
        (r, c) = RunAndPlot(func,
                            xs,
                            ys,
                            initial,
                            iterations,
                            precision,
                            method='N')
        return [(result, CoD), (r, c)]
    else:
        return (result, CoD)
예제 #4
0
def TimeFunctions(func,
                  consts,
                  initial=None,
                  min=0,
                  max=30,
                  count=100,
                  variance=1,
                  iterations=10,
                  precision=0.01,
                  repeats=10):
    # Time for Gauss-Newton method
    gntime = 0
    # Time for Newton method
    ntime = 0
    for i in range(repeats):
        (xs, ys) = GetRandomData(func, consts, min, max, count, variance)
        start = time.clock()
        GaussNewton.Run(func, xs, ys, initial, iterations, precision)
        gntime += time.clock() - start
        start = time.clock()
        Newton.Run(func, xs, ys, initial, iterations, precision)
        ntime += time.clock() - start

        # Windows only
        os.system('cls')
        print(str(i) + " done")

    print("Gauss-Newton took: " + str(gntime))
    print("Newton took: " + str(ntime))
예제 #5
0
    def screened_newton(self, vplus, vminus):
        n = self.nplus(vplus, vminus, 0)

        def f1(v):
            return (v[1] -
                    vminus) + (q / (4 * self.C)) * self.nminusT0(v[0], v[1])

        def f2(v):
            return n - self.nplus(v[0], v[1], 0)

        v = Newton.Newton2D(f1, f2, np.array([vplus, vminus]))

        return v
예제 #6
0
파일: calc.py 프로젝트: dankiy/CompMath
def test(k, kmax=1e3):
    print("\n Test k = " + str(k) + ", kmax = " + str(kmax))
    time0 = time.time()
    newton, num = Newton.Newton(funcSystem, x0, k, kmax=kmax)
    time1 = time.time()
    print("Newton: ")
    print(newton)
    print("Number of iterations: ")
    print(num)
    print("Elapsed time: ")
    elp = time1 - time0
    elpL.append(elp)
    print(elp)
    print()
예제 #7
0
    def readFromFile(self):
        X = []
        Y = []
        T = 0

        file_path = filedialog.askopenfilename()

        f = open(file_path, "r")
        i = 0
        method = ""
        for x in f:
            if i == 0:
                method = str(x)
            elif i == 1:
                T = float(x)
            else:
                a = x.split(" ")
                X.append(float(a[0]))
                Y.append(float(a[1]))
            i += 1

        window = Toplevel(root)
        window.title("Solution")
        window.geometry('500x500')
        functionLabel = Label(window, text="Output function ").grid(row=0,
                                                                    column=1)
        solveLabel = Label(window,
                           text=("Output at X = " + str(T))).grid(row=1,
                                                                  column=1)
        l = None
        n = None
        if method.__contains__("Lagrange"):
            l = Lagrange.Lagrange(X, Y, T)
            l.lagrange()
            outputLabel = Label(window, text=str(l.poly())).grid(row=0,
                                                                 column=3)
            solveOutput = Label(window,
                                text=(str(l.calc_value(T)))).grid(row=1,
                                                                  column=3)

        elif method.__contains__("Newton"):
            n = Newton.Newton(X, Y, len(X))
            outputLabel = Label(window,
                                text=str(n.createFormula())).grid(row=0,
                                                                  column=3)
            solveOutput = Label(window, text=(str(n.solve(T)))).grid(row=1,
                                                                     column=3)
        self.plot(X, l, n, method, window)
예제 #8
0
def Basis_Func(n):
    #Generates the polynomial basis functions for the reference space [-1,1] of
    #degree n
    #Inputs:    n=degree of basis functions to be generated
    #Outputs:   Coeff: Coefficient matrix of polynomial basis functions
    #                  Each column of Coeff corresponds to a unique basis
    #==========================================================================
    vec = Linspace(-1, 1, n + 1)
    V = Vandermonde(vec)
    b = np.matrix(np.zeros((n + 1, 1), dtype=float))
    Coeff = np.matrix(np.zeros((n + 1, n + 1), dtype=float))
    for i in range(0, n + 1):
        b[i] = 1
        Coeff[:, i] = Newton.Linear_Solve(V, b)
        b[i] = 0
    return Coeff
예제 #9
0
def init_globals(material, show3d=False):
    global nh, nb, rhc, rbc, rhelix, rdh, rcap, ncap, thcap, dzb, bturn, brise, \
    dthb, dsb, dz, dth, majorgroove, minorgroove, dthgroove, strutangle, \
    strutlength, strutrise, proptwist, inclination, extend5prime, extend3prime, \
    extendcoil, rcaphead, ndye, ddye, rdye, cmap, colors, color_names, icolors

    golden = 1.61803399
    e = 2.71828183
    pi = math.pi
    cbrt2 = math.pow(2., 0.2)
    if show3d:
        #~ print "show3d=%s"%show3d
        rhc = 1.5  # radius of helix chain
        rbc[0] = .3  # major radius of base pair strut (elliptical: .5 default)
        rbc[1] = .25  # minor radius of base pair strut (elliptical: .2 default)
        if material == 1:  # A DNA (RNA/RNA duplex or RNA/DNA duplex)
            rhelix = 13.0  # radius of double helix to outside of chain axis
            dzb = 2.6  # stacking height per base along helix
            bturn = 10.0  # bases per turn in the helix (10 is default value)
            majorgroove = .45 * dzb * bturn  # height of major groove along helix axis in angstroms (less than .5 for narrow, deep major groove)
            inclination = -19 * math.pi / 180  # angle of strut relative x axis (spinning around y axis)
            # should tilt down from 5' (start
            # of A chain) to 3' (start of B
            # chain) strand
            proptwist = 11.8 * math.pi / 180  # prop twist around base pair axis in ccw direction
        elif material == 2:  # B DNA
            rhelix = 10.  # radius of double helix to outside of chain axis
            dzb = 3.4  # stacking height per base along helix
            bturn = 10.5  # bases per turn in the helix (10.5 is modern value)
            majorgroove = 22. / 34. * (
                dzb * bturn
            )  # height of major groove along helix axis in angstroms (22 is default, 17 for symmetric debugging)
            # take ratio of 22/34 and multiply by
            # modern value of brise
            inclination = 1.2 * math.pi / 180  # angle of strut relative x axis (spinning around y axis)
            # should tilt up from 5' (start
            # of A chain) to 3' (start of B
            # chain) (1.2 for B DNA)
            proptwist = 11.4 * math.pi / 180  # prop twist around base pair axis in ccw direction %11.4
    else:
        rhc = 0.5  # radius of helix chain
        rbc[0] = .5 / 3  # major radius of base pair strut (elliptical: .5 default)
        rbc[1] = .25 / 3  # minor radius of base pair strut (elliptical: .2 default)

        if material == 1:  # A DNA (RNA/RNA duplex or RNA/DNA duplex)
            rhelix = 3.0  # radius of double helix to outside of chain axis
            dzb = rhelix  # stacking height per base along helix
            bturn = 10.0  # bases per turn in the helix (10 is default value)
            majorgroove = .45 * dzb * bturn  # height of major groove along helix axis in angstroms (less than .5 for narrow, deep major groove)
            inclination = -19 * math.pi / 180  # angle of strut relative x axis (spinning around y axis)
            # should tilt down from 5' (start
            # of A chain) to 3' (start of B
            # chain) strand
            proptwist = 11.8 * math.pi / 180  # prop twist around base pair axis in ccw direction
        elif material == 2:  # B DNA
            rhelix = 2.6  # radius of double helix to outside of chain axis
            dzb = 3.0  # stacking height per base along helix
            bturn = 9.5  # bases per turn in the helix (10.5 is modern value)
            majorgroove = 22. / 34. * (
                dzb * bturn
            )  # height of major groove along helix axis in angstroms (22 is default, 17 for symmetric debugging)
            # take ratio of 22/34 and multiply by
            # modern value of brise
            inclination = 1.2 * math.pi / 180  # angle of strut relative x axis (spinning around y axis)
            # should tilt up from 5' (start
            # of A chain) to 3' (start of B
            # chain) (1.2 for B DNA)
            proptwist = 11.4 * math.pi / 180  # prop twist around base pair axis in ccw direction %11.4

    extend5prime = 1 * rbc[
        0]  # extension of chain at end so that strut doesn't hit cap
    extend3prime = 3 * rbc[
        0]  # extension of chain at end so that strust doesn't hit cap
    # if majorgroove=minorgroove then works with
    # both = rbc[0]
    extendcoil = 1 * rbc[
        0]  # for coil can be same at each end becauses no major/minor groove issue

    rdh = rhelix - rhc  # radius of helix to center of chain
    rcap = .5  # radius of capping corner
    ncap = 30  # number of points along cap corners as function of r
    thcap = 55 * math.pi / 180  # degrees of cone at 3' end of chain
    rcaphead = 1.25 * rhc + rcap  # radius of arrowhead at 3' end of chain

    brise = dzb * bturn  # rise along helix axis per full turn
    dthb = 2 * math.pi / bturn  # stacking twist per base along helix
    dsb = cbrt2 * math.sqrt(math.pow(rdh * dthb, 2) + math.pow(
        dzb, 2))  # arc length along chain for one base
    dz = dzb / (nh[0] - 1)  # patch increment along chain
    dth = 2 * math.pi / (nh[1] - 1)  # patch increment around chain
    rdye = 2 * rhc  # radius of dye molecule
    ddye = math.sqrt(math.pow(rdye, 2) - math.pow(
        rhc, 2))  # displacement of dye center along chain axis from last base
    ndye = 50  # resolution of dye sphere
    minorgroove = brise - majorgroove
    #~print "minorgroove=%f majorgroove=%f"%(minorgroove, majorgroove)
    dthgroove,strutrise,strutlength,strutangle = \
      Newton.groove(inclination, rdh, brise, minorgroove)
예제 #10
0
import LSE as LSE
import Newton as Newton
import others as others

case = 0
while (1):
    case += 1
    # filepath=input("File path:")
    filepath = "testfile.txt"
    degree = int(input("n:"))
    lm = input("Lambda:")
    print("Case {}: n={}, lambda={}".format(case, degree, lm))
    (x, y) = others.ReadFile(filepath)
    print("LSE:")
    lse = LSE.LSE(x, y, degree, lm)
    lse.run()
    print("Newton' Method:")
    newton = Newton.Newton(x, y, degree)
    newton.run()
예제 #11
0
from Newton import *
from scitools.std import *

f = [
    lambda x: sin(x), lambda x: sin(x) - x, lambda x: sin(x) - x**5,
    lambda x: x**4 * sin(x), lambda x: x**4, lambda x: x**10,
    lambda x: tanh(x) - x**10
]

df = [
    lambda x: cos(x), lambda x: cos(x) - 1, lambda x: cos(x) - 5 * x**4,
    lambda x: 4 * x**3 * sin(x) + x**4 * cos(x), lambda x: 4 * x**3,
    lambda x: 10 * x**9, lambda x: 1. / cosh(x)**2 - 10 * x**9
]

x0 = 0.1
data = [[]] * len(f)
for i in range(len(f)):
    x, info = Newton(f=f[i], x=x0, dfdx=df[i], \
     epsilon=1.0E-12, N=100, store=True)
    for j in range(len(info)):
        data[i] = append(data[i], info[j][-1])

for i in range(len(f)):
    figure()
    plot(range(len(data[i])), data[i])

raw_input('Press Enter to quit: ')
예제 #12
0
from Newton import *
from scitools.std import *

f = lambda x: x**6 * sin(pi*x)
df = lambda x: 6*x**5 * sin(pi*x) + x**6 * pi * cos(pi*x)

x0 = sort([-2.6, -1.2, 1.5, 1.7, 0.6])
for i in x0:
	x, info = Newton(f, i, df, epsilon=1e-13, N = 100, store=True)
	# we assume convergence for this exercise
	info = transpose(info)
	x_values = info[0]
	f_values = info[1]
	figure()
	plot(range(len(x_values)), x_values,
		xlabel='Iteration Number',
		ylabel='x-value',
		title='Newton''s Method f = x**6 * sin(pi*x), x0 = %.1f' % i)
	figure()
	plot(range(len(f_values)), f_values,
		xlabel='Iteration Number',
		ylabel='f(x_i)',
		title='Newton''s Method f = x**6 * sin(pi*x), x0 = %.1f' % i)
raw_input('Press Enter to quit: ')
예제 #13
0
        print('')
        sumaLambda = sumaLambdaFunc(n1, n2)
        print('La suma Lambda es: ', sumaLambda)

        text = str(input('Texto a mayusculas con lambda: '))
        print('El texto es: ', toUpperLambdaFunc(text))
        break

    except ValueError:
        print("No es un numero entero")
        input("\nTecla para continuar.... \n")
"""

CREAR UN OBJETO DE LA CLASE INSTRUMENTOS

"""
import Instrumento
import Newton

guitarra = Instrumento.Instrumento(10, 10, 10, 10, False)

competidor1 = Newton.Newton(0, 220, 0, 150, 450)

print('')
print('La energía cinética es: ', competidor1.energiaCinetica())
print('La energia potencial es: ', competidor1.energiaPotencial())
print('La distancia recorrida es: ', competidor1.distancia())
print('La aceleración es: ', competidor1.aceleracion())
print('La fuerza es: ', competidor1.fuerza())
예제 #14
0
    def find_branch(self, x0, k0, ds, nsteps, progress_bar=False, **kwargs):
        """Continues along the branch of values for which :math:`f(x,k)=0` via pseudo-arclength continuation

        Args:
            x0 (array): the initial x vector
            k0 (float): the initial parameter value
            ds (float): the arclength step size
            nsteps (int): the total number of arclength steps to take
            progress_bar (bool): whether or not to show a progress bar as iterations proceed

        Returns:
            Numpy array of dimension (nsteps, n+1), each row of which contains first the length-n value of x and then the scalar parameter value at which a point on the branch was found

        .. note::
            If :math:`f(x_0,k_0) \\neq 0`, this method automatically searches for an appropriate starting point via a Newton iteration at :math:`k=k_0`
        """

        # fig = plt.figure()
        # ax = fig.add_subplot(111)
        # ax.hold(True)

        # TODO: faster method than defining lambda fn?
        n = x0.shape[0]
        f_init = lambda x: self._f(x, k0)[:n]
        Df_init = lambda x: self._Df(x, k0)[:n, :n]
        # find initial point on branch
        newton_solver = Newton.Newton(f_init, Df_init)
        try:
            xstart = newton_solver.find_zero(x0, **kwargs)
        except CustomErrors.EvalError as e:
            print e.msg
            raise CustomErrors.PSAError(
                'Initial newton encountered an EvalError')
        except CustomErrors.ConvergenceError as e:
            raise CustomErrors.PSAError('Initial newton failed to converge')
        # append parameter value
        xstart = np.hstack((xstart, k0))
        # find initial slopes
        # pretend initial slopes are 0 in x, 1 in k
        tempslopes = np.zeros(n + 1)
        tempslopes[n] = 1
        # note that tempslopes is also rhs of initial slope calc (see Auto notes)
        try:
            xprime = spla.gmres(self._Df_arclength(xstart, tempslopes),
                                tempslopes)[0]
        except (CustomErrors.EvalError, CustomErrors.ConvergenceError):
            raise CustomErrors.PSAError('Initial slope not found')
        # normalize
        xprime_start = xprime / np.linalg.norm(xprime)
        # update newton to new functions
        newton_solver = Newton.Newton(self._f_arclength, self._Df_arclength)
        halfnsteps = nsteps / 2
        branch_pts = np.empty((2 * halfnsteps + 1, n + 1))
        branch_pts[-1] = np.copy(xstart)
        # take nsteps/2 forward and backward from the initial point
        # in case the inner loop over 'i' exits prematurely, keep track of how many were successfully obtained
        ncompleted_pts = 0

        # TESTING
        total_pts = 0
        # TESTING

        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # The error handling in this double loop is as follows:
        # The inner loop might raise an EvalError from the 'find_zero' function
        # which will be caught in the outer loop. If this happens, we must adjust
        # 'ncompleted_pts' accordingly, to reflect how many iterations were successful
        # before the error. Then, we continue in the opposite direction (k==1). Again,
        # an error could be raised, in which case we return whatever was
        # found to that point. Otherwise, return the partial branch from (k==0)
        # and the full branch from (k==1).
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        ds0 = ds
        max_ds_divisions = 4
        count = 0
        for k in range(2):
            # flip ds to continue in both directions
            ds0 = -ds0
            ds = ds0
            # move x back to "center" of branch
            x = np.copy(xstart)
            xprime = np.copy(xprime_start)
            count = 0
            ds_divisions = 0
            try:
                for i in range(halfnsteps):
                    if progress_bar:
                        uf.progress_bar(k * halfnsteps + i + 1, nsteps)
                    # initial guess for next point on branch
                    x0 = x + xprime * ds
                    # save previous value for arclength eqn
                    xprev = np.copy(x)
                    # update parameter values for f and Df in newton solver
                    newton_solver.change_parameters([xprev, xprime, ds],
                                                    [xprime])
                    try:
                        x = newton_solver.find_zero(x0, **kwargs)
                    except CustomErrors.EvalError as e:
                        print e.msg
                        raise
                    except CustomErrors.ConvergenceError:
                        # raise
                        # do some ad-hoc stepsize reduction
                        if ds_divisions > max_ds_divisions:
                            raise
                        else:
                            x = xprev
                            ds = ds / 10.0
                            ds_divisions = ds_divisions + 1
                            continue
                    else:

                        # ax.plot([branch_pts[k*ncompleted_pts + count - 1][0], x0[0]], [branch_pts[k*ncompleted_pts + count - 1][1], x0[1]], color='r')

                        # use finite diff approx for xprime
                        xprime = (x - xprev) / ds
                        # normalize
                        xprime = xprime / np.linalg.norm(xprime)
                        branch_pts[total_pts] = np.copy(x)
                        # branch_pts[total_pts] = np.copy(x)
                        count = count + 1
                        total_pts = total_pts + 1
            except (CustomErrors.EvalError, CustomErrors.ConvergenceError):
                # continue from ncompleted_pts
                if k == 0:
                    ncompleted_pts = count
                    continue
                # k == 1, copy initial point from end of 'branch' and return whatever was successfully found
                else:
                    branch_pts[:ncompleted_pts] = branch_pts[ncompleted_pts -
                                                             1::-1]
                    branch_pts[ncompleted_pts + 1:ncompleted_pts + count +
                               1] = branch_pts[ncompleted_pts:ncompleted_pts +
                                               count]
                    branch_pts[ncompleted_pts] = np.copy(xstart)
                    return branch_pts[:ncompleted_pts + count + 1]
            else:
                if k == 0:
                    ncompleted_pts = count

        # could have encountered error when k==0, no error when k==1: adjust accordingly
        branch_pts[:ncompleted_pts] = branch_pts[ncompleted_pts - 1::-1]
        branch_pts[ncompleted_pts + 1:ncompleted_pts + count +
                   1] = branch_pts[ncompleted_pts:ncompleted_pts + count]
        branch_pts[ncompleted_pts] = np.copy(xstart)
        return branch_pts[:ncompleted_pts + count + 1]  #[:total_pts + 1]
예제 #15
0
import Newton

def square(number):
  return number*number

print Newton.square(9)
print square(9)
예제 #16
0
import Newton

space = Newton.Space(
    Newton.Vec2(1000, 750),                         # univer's size -> Vec2(xSize, ySize)
    0.0000000006674                                 # gravity constant
)

space.setConfig(Newton.SimConfig.RANDOM_POSITION_AND_ROTATION)     # Set Stars Behavior

space.populate(400)                                 # populate space with n=200 stars

renderer = Newton.Renderer(
    "render_400s_1dt_400f_1000x750_v1",             # file name
    1                                               # Adjusting rendered image scale
)

sim = Newton.Simulation(
    1,                                              # time step
    400,                                            # numbers of frame (at 30 fps)
    space,                                          # space to compute reference
    renderer,                                       # renderer reference
)

sim.simulate()                                      # start simulation

print()
input("Press ENTER to continue...")

# ################################
# SIDE NOTE :
# ################################
예제 #17
0
                             w_init=w_init,
                             iteration=iteration,
                             lr=lr)
    gd.run()
    y_predict = gd.predict(x_test)
    print('SGD accuracy is: {:.2f}%'.format(gd.accuracy(y_test, y_predict)))
    """
  ### Part4: Newton -----------------------------------------
  """
    alpha = 0.2
    beta = 0.9
    iteration = 5

    newton = Newton.newton(x_train,
                           y_train,
                           w_init=w_init,
                           iteration=iteration,
                           alpha=alpha,
                           beta=beta)
    newton.run()
    y_predict = newton.predict(x_test)
    print('Newton accuracy is: {:.2f}%'.format(
        newton.accuracy(y_test, y_predict)))
    """
  ### Part6: Natural Gradient -------------------------------
  """
    lr = 0.2
    iteration = 5

    ng = Natural_Gradient.ng(x_train,
                             y_train,
                             w_init=w_init,
예제 #18
0
def function(x):
    value = 3 * sin(x[0]) + sin(x[1])
    return value


def gradient(x):
    grad = cos(x[0]) + cos(x[1])
    return grad


def task7():
    x = array([[0], [3]])
    rho = 0.1
    sigma = 0.7
    tau = 0.1
    chi = 9
    problem = OptimizationProblem(rosenbrock)
    method = QuasiNewton(problem)
    s = method.gradient(x)
    res = inexact_linesearch(rosenbrock, x, s, rho, sigma, tau, chi)
    print(res)


problem = OptimizationProblem(rosenbrock)
solution = Newton(problem)
min_point, min_value = solution.solve()
optipoints = solution.values
print(min_point)
contour_rosenbrock(optipoints=optipoints)

# q = QuasiNewton(problem)
예제 #19
0
def f2_ysub(x):
    return f2(x, ysub(x))


def f2_ysub_prime(x):
    return 2 + ysub_prime(x) - (ysub(x)**2) * ysub_prime(x) / 2


def infNorm(x):
    return np.max(np.abs(x))


# In[2]:

import Newton

intervals = Newton.get_intervals_table(0.0, 5.0, f2_ysub, 100)

roots = np.array([(interval[0] + interval[1]) / 2 for interval in intervals])
radii = np.array([
    max((ysub(interval[1]) - ysub(interval[0])) / 2, interval[1] - interval[0])
    for interval in intervals
])

print("x values for starting points: " + str(roots))
print("Sphere radia: " + str(radii))

points = np.array([(root, ysub(root)) for root in roots], dtype=np.double)

print("Starting points: " + str(points))
예제 #20
0
def compute(N, filename, method, Ncell, diabete='N'):

    # cell = [[]]
    # for i in range(Ncell):
    # 	for j in range(N):
    # 		cell[i,j].append(membrane())
    cell = [[membrane() for i in range(N)] for j in range(Ncell)]

    if diabete == 'N':
        for i in range(Ncell):
            for j in range(N):
                cell[i][j].diabete = 'No'
    elif diabete == 'Y':
        for i in range(Ncell):
            for j in range(N):
                cell[i][j].diabete = 'Yes'
    else:
        print('What is diabete status?')

    water_trans = 0
    na_trans = 0
    water_para = 0
    na_para = 0

    #filename=input('Choose a data file: ')

    #method = input('Choose a method: Newton or Broyden: ')

    for i in range(Ncell):
        for j in range(N):
            set_params.read_params(cell[i][j], filename, 0)
            #cell[i].area_init[4][5] = 0.02
            #cell[i].area[4][5] = cell[i].area_init[4][5]*max(cell[i].vol[4]/cell[i].volref[4],1.0)
            #cell[i].area[5][4] = cell[i].area[4][5]

            boundaryBath.boundaryBath(cell[i][j], i)

    for i in range(Ncell - 1):
        celln = copy.deepcopy(cell[i + 1][0])
        dx = 1.0e-3
        if cell[0][0].segment == 'PT':
            x = np.zeros(3 * NS + 7)

            x[0:NS] = cell[i][0].conc[:, 0]
            x[NS:2 * NS] = cell[i][0].conc[:, 1]
            x[2 * NS:3 * NS] = cell[i][0].conc[:, 4]

            x[3 * NS] = cell[i][0].vol[0]
            x[3 * NS + 1] = cell[i][0].vol[1]
            x[3 * NS + 2] = cell[i][0].vol[4]

            x[3 * NS + 3] = cell[i][0].ep[0]
            x[3 * NS + 4] = cell[i][0].ep[1]
            x[3 * NS + 5] = cell[i][0].ep[4]

            x[3 * NS + 6] = cell[i][0].pres[0]
            # x[3 * NS + 6] = cell[i][0].pres[1]

            steadyequations.steadyconservation_init(cell[i][0], cell[i + 1][0],
                                                    celln, dx)
            fvec = steadyequations.steadyconservation_eqs(x, i)
            # print(fvec)

            if method == 'Newton':
                sol = Newton.newton(steadyequations.steadyconservation_eqs, x,
                                    i, cell[i][0].segment)

            if method == 'Broyden':
                sol = Newton.broyden(steadyequations.steadyconservation_eqs, x,
                                     i, cell[i][0].segment)

            if cell[0][0].segment == 'PT':
                cell[i + 1][0].conc[:, 0] = sol[0:NS]
                cell[i + 1][0].conc[:, 1] = sol[NS:NS * 2]
                cell[i + 1][0].conc[:, 4] = sol[NS * 2:NS * 3]

                cell[i + 1][0].vol[0] = sol[3 * NS]
                cell[i + 1][0].vol[1] = sol[3 * NS + 1]
                cell[i + 1][0].vol[4] = sol[3 * NS + 2]

                cell[i + 1][0].ep[0] = sol[3 * NS + 3]
                cell[i + 1][0].ep[1] = sol[3 * NS + 4]
                cell[i + 1][0].ep[4] = sol[3 * NS + 5]

                cell[i + 1][0].pres[0] = sol[3 * NS + 6]
                # cell[i + 1][0].pres[1] = sol[3 * NS + 6]

    # to make mdel works we should do something different
    # to simulate sudden change, we need to change first cell's condition
    # do change as below (change cell[0]'s lumen condition means change boundary condition)

    for j in range(N):
        # cell[0][j].vol[0] = cell[0][j].vol[0] * (1 + 0.1 * math.sin(2 * math.pi * j / 30))
        cell[0][j].conc[14, 0] = cell[0][j].conc[14, 0] * 1.1

    # update in time
    for j in range(1, N):
        print('This is time ' + str(0.1 * j) + 's')
        for i in range(1, Ncell):
            print("   ")
            print('Calculating ' + str(i) + 'th Cell')
            celln = copy.deepcopy(cell[i - 1][j])
            dx = 1.0e-3
            if cell[0][0].segment == 'PT':
                x = np.zeros(3 * NS + 7)

                x[0:NS] = cell[i][j - 1].conc[:, 0]
                x[NS:2 * NS] = cell[i][j - 1].conc[:, 1]
                x[2 * NS:3 * NS] = cell[i][j - 1].conc[:, 4]

                x[3 * NS] = cell[i][j - 1].vol[0]
                x[3 * NS + 1] = cell[i][j - 1].vol[1]
                x[3 * NS + 2] = cell[i][j - 1].vol[4]

                x[3 * NS + 3] = cell[i][j - 1].ep[0]
                x[3 * NS + 4] = cell[i][j - 1].ep[1]
                x[3 * NS + 5] = cell[i][j - 1].ep[4]

                x[3 * NS + 6] = cell[i][j - 1].pres[0]
                # x[3*NS+6]=cell[i-1][j+1].pres[1]

                equations.conservation_init(cell[i][j - 1], cell[i][j], celln,
                                            dx)
                fvec = equations.conservation_eqs(x, j)
                #print(fvec)

                if method == 'Newton':
                    sol = Newton.newton(equations.conservation_eqs, x, i,
                                        cell[i][j].segment)

                if method == 'Broyden':
                    sol = Newton.broyden(equations.conservation_eqs, x, i,
                                         cell[i][j].segment)

                if cell[0][0].segment == 'PT':
                    cell[i][j].conc[:, 0] = sol[0:NS]
                    cell[i][j].conc[:, 1] = sol[NS:NS * 2]
                    cell[i][j].conc[:, 4] = sol[NS * 2:NS * 3]

                    cell[i][j].vol[0] = sol[3 * NS]
                    cell[i][j].vol[1] = sol[3 * NS + 1]
                    cell[i][j].vol[4] = sol[3 * NS + 2]

                    cell[i][j].ep[0] = sol[3 * NS + 3]
                    cell[i][j].ep[1] = sol[3 * NS + 4]
                    cell[i][j].ep[4] = sol[3 * NS + 5]

                    cell[i][j].pres[0] = sol[3 * NS + 6]
                    # cell[i][j+1].pres[1] = sol[3*NS+6]
            #
            # print("KKKKKKK")
            # print(sol[3*NS+5])
            # print(sol[3 * NS + 6])
            # print(sol[0:NS])
            # print( sol[3*NS+2])
            # print(sol[3*NS+5])
            # print("cell concentration")
            # print(sol[3*NS+4])
            # print(sol[3*NS+1])

        # check1=0
        # check2=0
        # stepdiff=np.zeros(3*NS+7)
        # stepdiff[0:NS]=cell[i+1].conc[:,0]-cell[i].conc[:,0]
        # stepdiff[NS:2*NS] = cell[i + 1].conc[:, 1] - cell[i ].conc[:, 1]
        # stepdiff[2*NS:NS*3] = cell[i + 1].conc[:, 4] - cell[i ].conc[:, 4]
        # stepdiff[3*NS]=cell[i+1].vol[0]-cell[i].vol[0]
        # stepdiff[3 * NS+1]=cell[i+1].vol[4]-cell[i].vol[4]
        # stepdiff[3 * NS+2]=cell[i+1].ep[0]-cell[i].ep[0]
        # stepdiff[3 * NS+3]=cell[i+1].ep[1]-cell[i].ep[1]
        # stepdiff[3 * NS+4]=cell[i+1].ep[4]-cell[i].ep[4]
        # stepdiff[3 * NS+5]=cell[i+1].pres[0]-cell[i].pres[0]
        # stepdiff[3 * NS+6]=cell[i+1].pres[1]-cell[i].pres[1]
        #
        # diffrelative=np.zeros(3*NS+7)
        # diffrelative[0:NS] = (cell[i + 1].conc[:, 0] - cell[i ].conc[:, 0])/ cell[i ].conc[:, 0]
        # diffrelative[NS:2 * NS] =( cell[i + 1].conc[:, 1] - cell[i ].conc[:,1])/cell[i].conc[:, 1]
        # diffrelative[2 * NS:NS * 3] =( cell[i + 1].conc[:, 4] - cell[i ].conc[:, 4])/ cell[i ].conc[:, 4]
        # diffrelative[3 * NS] = (cell[i + 1].vol[0] - cell[i].vol[0])/cell[i].vol[0]
        # diffrelative[3 * NS + 1] =( cell[i + 1].vol[4] - cell[i].vol[4])/cell[i].vol[4]
        # diffrelative[3 * NS + 2] = (cell[i + 1].ep[0] - cell[i].ep[0])/cell[i].ep[0]
        # diffrelative[3 * NS + 3] = (cell[i + 1].ep[1] - cell[i].ep[1])/cell[i].ep[1]
        # diffrelative[3 * NS + 4] = (cell[i + 1].ep[4] - cell[i].ep[4])/cell[i].ep[4]
        # diffrelative[3 * NS + 5] = (cell[i + 1].pres[0] - cell[i].pres[0])/cell[i].pres[0]
        # diffrelative[3 * NS + 6] = (cell[i + 1].pres[1] - cell[i].pres[1])/cell[i].pres[1]
        # check1=0
        # # check difference on x should be small enough
        # check1=max(abs(stepdiff))
        # check2=max(abs(diffrelative))
        # if check1<0.001 and check2<0.001:
        # 	N=i+1
        # 	break
        # else:
        # 	print("check1 and check2")
        # 	print(check1)
        # 	print(check2)
        print('\n')

#================================OUTPUT IN TO FILE================================

# if cell[0].segment == 'PT':
# 	file=open('PToutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4],cell[N-1].conc[j,5]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
#
# elif cell[0].segment == 'S3':
# 	file=open('S3outlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'SDL':
# 	file=open('SDLoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'mTAL':
# 	file=open('mTALoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'cTAL':
# 	file=open('cTALoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4],cell[N-1].conc[j,5]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'MD':
# 	file=open('MDoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'DCT':
# 	file=open('DCToutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'CNT':
# 	file=open('CNToutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,2],cell[N-1].conc[j,3],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[2],cell[N-1].vol[3],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[2],cell[N-1].ep[3],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'CCD':
# 	file=open('CCDoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,2],cell[N-1].conc[j,3],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[2],cell[N-1].vol[3],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[2],cell[N-1].ep[3],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'OMCD':
# 	file=open('OMCDoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,2],cell[N-1].conc[j,3],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[2],cell[N-1].vol[3],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[2],cell[N-1].ep[3],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()
# elif cell[0].segment == 'IMCD':
# 	file=open('IMCDoutlet'+cell[0].sex+'.txt','w')
# 	for j in range(NS):
# 		file.write('{} {} {} \n'.format(cell[N-1].conc[j,0],cell[N-1].conc[j,1],cell[N-1].conc[j,4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].vol[0],cell[N-1].vol[1],cell[N-1].vol[4]))
# 	file.write('{} {} {} \n'.format(cell[N-1].ep[0],cell[N-1].ep[1],cell[N-1].ep[4]))
# 	file.write(str(cell[N-1].pres[0]))
# 	file.close()

    number_of_cell = [i for i in range(1, 200)]
    solute = [
        'Na', 'K', 'Cl', 'HCO3', 'H2CO3', 'CO2', 'HPO4', 'H2PO4', 'urea',
        'NH3', 'NH4', 'H', 'HCO2', 'H2CO2', 'glu'
    ]
    compart = ['Lumen', 'Cell', 'ICA', 'ICB', 'LIS', 'Bath']

    return cell
예제 #21
0
def Steady_State(n, deg, A, D, mesh, m_flow, MW, R, P0, h_bc, Cp, U, rough, mu,
                 T_ambient):
    Initial_start = time.time()
    off = (deg + 1) * n
    #Define initial conditions
    u = np.matrix(np.ones(((deg + 1) * n, 1), dtype=float)) * 1
    rho = np.matrix(np.ones(((deg + 1) * n, 1), dtype=float)) * 1
    T = np.matrix(np.ones(((deg + 1) * n, 1), dtype=float)) * 300
    h = np.matrix(np.ones(((deg + 1) * n, 1), dtype=float)) * 300
    P = np.matrix(np.ones(((deg + 1) * n, 1), dtype=float)) * 101000
    f = np.matrix(np.ones(((deg + 1) * n, 1), dtype=float)) * .1
    u_offset = 0 * off
    rho_offset = 1 * off
    P_offset = 2 * off
    T_offset = 3 * off
    h_offset = 4 * off
    f_offset = 5 * off
    offset = [u_offset, rho_offset, T_offset, h_offset, P_offset, f_offset]
    state = np.r_[u, rho, P, T, h, f]
    #Define State Vector
    phi = Basis_Func(deg)

    print("Pre-Calculculating Integrals for Steady State Solver\n")
    Integration_start = time.time()
    Coeff_6_0 = np.matrix(np.zeros((6 * deg + 1, (deg + 1)**6), dtype=float))
    Coeff_5_0 = np.matrix(np.zeros((5 * deg + 1, (deg + 1)**5), dtype=float))
    Coeff_3_1 = np.matrix(np.zeros((4 * deg, (deg + 1)**4), dtype=float))
    Coeff_3_0 = np.matrix(np.zeros((3 * deg + 1, (deg + 1)**3), dtype=float))
    Coeff_2_1 = np.matrix(np.zeros((3 * deg, (deg + 1)**3), dtype=float))
    Coeff_2_0 = np.matrix(np.zeros((2 * deg + 1, (deg + 1)**2), dtype=float))
    Coeff_1_1 = np.matrix(np.zeros((2 * deg, (deg + 1)**2), dtype=float))
    Coeff_1_m1 = np.matrix(np.zeros((3 * deg, (deg + 1)**3), dtype=float))
    Ints_6_0 = np.matrix(np.zeros(((deg + 1)**6, 1), dtype=float))
    Ints_5_0 = np.matrix(np.zeros(((deg + 1)**5, 1), dtype=float))
    Ints_3_1 = np.matrix(np.zeros(((deg + 1)**4, 1), dtype=float))
    Ints_3_0 = np.matrix(np.zeros(((deg + 1)**3, 1), dtype=float))
    Ints_2_1 = np.matrix(np.zeros(((deg + 1)**3, 1), dtype=float))
    Ints_2_0 = np.matrix(np.zeros(((deg + 1)**2, 1), dtype=float))
    Ints_1_1 = np.matrix(np.zeros(((deg + 1)**2, 1), dtype=float))
    Ints_1_m1 = np.matrix(np.zeros(((deg + 1)**3, 1), dtype=float))
    T_ints = Enthalpy_T_Int(phi, mesh, n, deg, T_ambient)
    #Pre-Calculate Integration Parameters
    for j in range(0, deg + 1):
        for m in range(0, deg + 1):
            num = m + (deg + 1) * j
            Coeff_1_1[:, num] = Poly_Mult(phi[:, m], Poly_Diff(phi[:, j]))
            Coeff_2_0[:, num] = Poly_Mult(phi[:, m], phi[:, j])
            Ints_1_1[num, 0] = Gauss(-1, 1, Poly, Coeff_1_1[:, num])
            Ints_2_0[num, 0] = Gauss(-1, 1, Poly, Coeff_2_0[:, num])
            for k in range(0, deg + 1):
                num2 = k + (deg + 1) * m + (deg + 1)**2 * j
                Coeff_2_1[:, num2] = Poly_Mult(phi[:, k], phi[:, m],
                                               Poly_Diff(phi[:, j]))
                Coeff_3_0[:, num2] = Poly_Mult(phi[:, k], phi[:, m], phi[:, j])
                Coeff_1_m1[:, num2] = Poly_Mult(
                    phi[:, m], Poly_Diff(Poly_Mult(phi[:, k], phi[:, j])))
                Ints_2_1[num2, 0] = Gauss(-1, 1, Poly, Coeff_2_1[:, num2])
                Ints_3_0[num2, 0] = Gauss(-1, 1, Poly, Coeff_3_0[:, num2])
                Ints_1_m1[num2, 0] = Gauss(-1, 1, Poly, Coeff_1_m1[:, num2])
                for l in range(0, deg + 1):
                    num3 = l + k * (deg + 1) + m * (deg + 1)**2 + j * (deg +
                                                                       1)**3
                    Coeff_3_1[:, num3] = Poly_Mult(phi[:, l], phi[:, k],
                                                   phi[:, m],
                                                   Poly_Diff(phi[:, j]))
                    Ints_3_1[num3, 0] = Gauss(-1, 1, Poly, Coeff_3_1[:, num3])
                    for r in range(0, deg + 1):
                        num4 = r + l * (deg + 1) + k * (deg + 1)**2 + m * (
                            deg + 1)**3 + j * (deg + 1)**4
                        Coeff_5_0[:, num4] = Poly_Mult(phi[:, r], phi[:, l],
                                                       phi[:, k], phi[:, m],
                                                       phi[:, j])
                        Ints_5_0[num4, 0] = Gauss(-1, 1, Poly, Coeff_5_0[:,
                                                                         num4])
                        for s in range(0, deg + 1):
                            num5 = s + r * (deg + 1) + l * (deg + 1)**2 + k * (
                                deg + 1)**3 + m * (deg + 1)**4 + j * (deg +
                                                                      1)**5
                            Coeff_6_0[:, num5] = Poly_Mult(
                                phi[:, s], phi[:, r], phi[:, l], phi[:, k],
                                phi[:, m], phi[:, j])
                            Ints_6_0[num4, 0] = Gauss(-1, 1, Poly,
                                                      Coeff_6_0[:, num4])

    Integration_end = time.time()
    print("Completed Pre-Integration for Steady State Solver in ",
          Integration_end - Integration_start, "seconds\n")

    def Navier(state, n, deg, phi, mesh, offset, A, m_flow, Coeff_2_1,
               Ints_1_1, Ints_2_1, Ints_3_1, Ints_1_m1, Ints_5_0, Ints_6_0, P0,
               T_ints, R, MW, h_bc, Cp, U, D, rough, mu):
        Cont = SS_Continuity(state, n, deg, offset, A, m_flow)
        Dense = Density(state, n, deg, offset, R, MW)
        Press = Momentum(state, n, deg, offset, P0, A, D, Ints_1_1, Ints_3_1,
                         Ints_5_0)
        Temp = Temperature(state, n, deg, offset, Cp)
        Enth = Enthalpy(state, phi, mesh, n, deg, offset, A, D, h_bc, U,
                        Ints_3_1, Ints_1_m1, Ints_2_0, Ints_2_1, T_ints,
                        Ints_6_0)
        Fric = Friction(state, offset, n, deg, D, rough, mu)
        return np.r_[Cont, Dense, Press, Temp, Enth, Fric]

    Solver_start = time.time()

    Sol = Newton.Fast_Newton_Solve(state, Navier, A, n, deg, phi, mesh, offset,
                                   A, m_flow, Coeff_2_1, Ints_1_1, Ints_2_1,
                                   Ints_3_1, Ints_1_m1, Ints_5_0, Ints_6_0, P0,
                                   T_ints, R, MW, h_bc, Cp, U, D, rough, mu)
    Solver_end = time.time()
    print("Newton Solver converged in ", (Solver_end - Solver_start),
          "seconds\n")
    print("Total run time is ", (Solver_end - Initial_start), "seconds")
    return Sol
예제 #22
0
def calc(rdh,
         dzb,
         loop,
         base,
         stacknickedhelices,
         dsb,
         show3d=False,
         debug=False,
         circle=False):
    if debug:
        print "unpairedcircle=%s" % circle

    nside = 2
    sidelength = numpy.array([2 * rdh, 2 * rdh])
    ds = dzb
    nds = 2
    # get helix parameters
    r, sideangle, ang_ds, f = Newton.loop(nside, sidelength, ds, nds)
    if debug:
        print "-------------- Geometric.calc:"
        print "sideangle=", sideangle
        print "ang_ds=", ang_ds
        print "f=", f

    stacked = stackedClass(r, sideangle, ang_ds)

    nicklength = 3 * rdh
    safe_count = 0
    stem_safe = numpy.zeros([0, 8])
    for iloop in range(len(loop)):
        loop[
            iloop].nickedhelix = False  # put in zeros for all loops and overwrite for nicked helices below
        nside = loop[iloop].nside  # number of stems in loop

        is_stacked      = (nside == 2) and (loop[iloop].sidenbase[0] == 0) \
                          and (loop[iloop].sidenbase[1] == 0)
        is_smallhairpin = (nside == 1) and (loop[iloop].sidenbase[0] == 1
                                            )  # hairpin with 3 bases in loop
        is_hairpin = (nside == 1)  # hairpin
        is_blunthelix   = (nside == 2) and( loop[iloop].sidenbase[0] == -1) and \
                          (loop[iloop].sidenbase[1] == -1)  # exterior loop of size zero

        #~ print "loop[%d].nside=%d, sidenbase=%s"%(iloop, nside, loop[iloop].sidenbase)
        # find out if it is a nicked helix
        is_nickedhelix = False
        if nside == 3:
            # a nicked helix can be recognized by the nick between two of the
            # side ends which are 1 base apart
            total_size = 0
            has_nick = False

            for iside in range(0, nside):
                cur_nick = loop[iloop].nick[:, iside]
                cur_base = loop[iloop].sidebase[iside]
                cur_size = loop[iloop].sidenbase[iside]
                if cur_size >= 0:
                    total_size += cur_size + 1

                prev_side = (iside - 1) % nside
                last_nick = loop[iloop].nick[:, prev_side]
                last_base = loop[iloop].sidebase[prev_side]
                if cur_nick[0] == -5 and cur_nick[1] == 0 and \
                   last_nick[0] == 0 and last_nick[1] == -3 and \
                   abs(cur_base - last_base) == 1:
                    has_nick = True

            if has_nick and total_size == 0:
                is_nickedhelix = True

        if debug:
            l = loop[iloop]
            print "L%d:" % iloop
            print "  nside: %s" % nside
            print "  is_stacked: %s" % is_stacked
            print "  is_smallhairpin: %s" % is_smallhairpin
            print "  is_hairpin: %s" % is_hairpin
            print "  is_blunthelix: %s" % is_blunthelix
            print "  is_nickedhelix: %s" % is_nickedhelix
            print "  sidenbase=%s\n  sideunit=%s" % (l.sidenbase, l.sideunit)
            print "  sidebase=%s\n  coilnum=%s" % (l.sidebase, l.coilnum)
            print "  toloop=%s\n  tohelix=%s" % (l.toloop, l.tohelix)
            print "  center=%s\n  radius=%s" % (l.center, l.radius)
            print "  strand=%s" % (l.strand)
            print "  loop[iloop].nick=%s" % (str(l.nick))

        sidenbase = numpy.zeros(nside)
        for iside in range(nside):
            sidenbase[iside] = loop[iloop].sidenbase[iside]

        if is_stacked:
            if debug: print "is_stacked:"
            r = stacked.radius
            ang_ds = stacked.ang_ds
            sideangle = stacked.sideangle.copy()
            sidelength = numpy.array([2 * rdh, 2 * rdh])
        elif is_smallhairpin:
            if debug: print "is_smallhairpin:"
            r = rdh
            ang_ds = math.pi / 2  # for hairpin of length three array bases on half circle centered at center of paired base
            sideangle[0] = math.pi  # angle between ends of helix
            sidelength[0] = 2 * rdh
        elif is_blunthelix:  # external loop of size zero
            if debug: print "is_blunthelix:"
            r = rdh
            ang_ds = 0  # no angle between bases along strand
            sideangle = [0, 0]
            sideangle[0] = math.pi  # angle between strand ends
            sideangle[1] = math.pi
            sidelength = numpy.array([2 * rdh, 2 * rdh])
        elif stacknickedhelices and is_nickedhelix:  # Broken!
            r = stacked.radius
            ang_ds = stacked.ang_ds
            if loop[iloop].sidebase[0] == 0:
                if loop[iloop].sidenbase[0] == -1:
                    sideangle   = numpy.array([(math.pi-stacked.sideangle[1]), \
                                  stacked.sideangle[0],  stacked.sideangle[1] ])
                    sidelength = numpy.array([2 * rdh, 2 * rdh, 2 * rdh])
                elif loop[iloop].sidenbase[1] == -1:
                    sideangle   = numpy.array([stacked.sideangle[0], \
                                 (math.pi-stacked.sideangle[1]), stacked.sideangle[1] ])
                    sidelength = numpy.array([2 * rdh, dzb, 2 * rdh])
            else:
                if loop[iloop].sidenbase[0] == -1:
                    sideangle   = numpy.array([(math.pi-stacked.sideangle[1]), \
                                  stacked.sideangle[0],  stacked.sideangle[1] ])
                    sidelength = numpy.array([dzb, 2 * rdh, 2 * rdh])
                elif loop[iloop].sidenbase[1] == -1:
                    sideangle   = numpy.array([stacked.sideangle[0], \
                                 (math.pi-stacked.sideangle[1]), stacked.sideangle[1] ])
                    sidelength = numpy.array([2 * rdh, dzb, 2 * rdh])
            if debug:
                print "stacknickedhelices and is_nicked_helix:"
                print "  sidelength: %s" % sidelength
                print "  sideangle=", sideangle
                print "  ang_ds=", ang_ds
                print "r=", r

            loop[iloop].nickedhelix = True
        else:
            nds = 0  # number of gaps
            if nside > 2:
                sidelength = numpy.resize(sidelength, nside)

            for iside in range(nside):
                nds = nds + loop[iloop].sidenbase[iside] + 1
                if loop[iloop].nick[1, iside] == -3:  # space for nick
                    loop[iloop].geo[iside].length = nicklength
                else:  # space for stem
                    loop[iloop].geo[iside].length = 2 * rdh
                sidelength[iside] = loop[iloop].geo[iside].length
            ds = dsb  #use arc length between bases in single-stranded regions

            r, sideangle, ang_ds, f = Newton.loop(nside, sidelength, ds, nds)
            if debug:
                print "After Newton.loop:"
                print "  sidelength: %s" % sidelength
                print "  sideangle=", sideangle
                print "  ang_ds=", ang_ds
                print "  r=", r
                print "show3d=%s, is_hairpin=%s" % (show3d, is_hairpin)

        if iloop == 0:  # taking starting point from global origin
            isideref = 0
            loop[iloop].geo[isideref].xc = numpy.array(
                [0, 0,
                 0]).T  # starting position for secondary structure drawing
            loop[iloop].geo[isideref].nc = numpy.array(
                [0, 1,
                 0]).T  # starting direction for secondary structure drawing
            jsidestart = 1
            jsidestop = nside - 1
        else:  # take starting point from previous loop
            isideref = nside - 1
            prevloop = loop[iloop].toloop[isideref]
            prevside = loop[iloop].toside[isideref]
            loop[iloop].geo[isideref].xc = loop[prevloop].geo[
                prevside].xc.copy()
            loop[iloop].geo[
                isideref].nc = -loop[prevloop].geo[prevside].nc.copy()

            jsidestart = 0
            jsidestop = nside - 2

        # assign stem position and direction for jside stem (by
        # convention this follows the jside single-stranded region)
        #
        xc = loop[iloop].geo[isideref].xc.copy()
        nc = loop[iloop].geo[isideref].nc.copy()
        if show3d and is_hairpin:
            loopcenter = xc - \
                       nc*math.sqrt(math.pow(r,2) - \
                       math.pow(sidelength[isideref]/3,2))
        else:
            loopcenter = xc - \
                       nc*math.sqrt(math.pow(r,2) - \
                       math.pow(sidelength[isideref]/2,2))
        loop[iloop].center = loopcenter
        if show3d and is_hairpin:
            fac = rdh * 2.5 / float(loop[iloop].sidenbase[0] + 1)
            #~ print "fac=%s"%fac
            if fac < r:
                tempR = math.sqrt(math.pow(r,2) - \
                             math.pow(rdh*2.5/float(loop[iloop].sidenbase[0]+1),2))
                #~ print "tempR=%f, r=%f, nside=%d"%(tempR, r, nside)
            else:
                tempR = 0.0
            tempR = max(tempR, rdh * 0.5)
            #~ print "tempR=%f, r=%f"%(tempR, r)
            loop[iloop].radius = tempR
        else:
            loop[iloop].radius = r
        jprev = isideref
        stem_size = jsidestop - jsidestart + 1

        for jside in range(jsidestart, jsidestop + 1):
            jgap = loop[iloop].sidenbase[jside] + 1
            jang = ang_ds * jgap + .5 * (sideangle[jside] + sideangle[jprev])

            ca = math.cos(jang)  # rotation matrix is CW around z axis
            sa = math.sin(jang)
            rmat    = ca*numpy.eye(3) + (1-ca)*numpy.array([[0,0,0],[ 0,0,0],[0,0,1]]) + \
                                  sa*numpy.array([[0,1,0],[-1,0,0],[0,0,0]])
            nc = numpy.dot(rmat, nc)
            xc      = loopcenter + nc*math.sqrt(math.pow(r,2) - \
                      math.pow(sidelength[jside]/2,2))

            loop[iloop].geo[jside].nc = nc.copy()
            loop[iloop].geo[jside].xc = xc.copy()

            jprev = jside
            stem_safe = numpy.vstack([
                stem_safe,
                numpy.hstack([numpy.array([iloop, jside]), xc.T, nc.T])
            ])
            safe_count = safe_count + 1

        #
        # assign base positions for jside single-stranded region
        #
        jprev = nside - 1
        #~ pdb.set_trace()
        for jside in range(nside):
            jbasestart = loop[iloop].sidebase[jside]
            jbasestop = loop[iloop].sidebase[jside] + loop[iloop].sidenbase[
                jside]
            if loop[iloop].nick[1, jside] == -3 or (
                    nside == 1 and loop[iloop].nick[1, jside + 1] == -3):
                jbasestop = jbasestop + 1  # handle base at nick that would not otherwise get assigned an x value

            nc = loop[iloop].geo[jprev].nc
            ang = .5 * sideangle[jprev]
            if len(loop) > 1 or circle:
                for jbase in range(
                        jbasestart, jbasestop + 1
                ):  #loop over paired base and following single-stranded region
                    ca = math.cos(ang)  # rotate CW by ang
                    sa = math.sin(ang)  # rotation matrix is CW around z axis
                    rmat    = ca*numpy.eye(3) + (1-ca)*numpy.array([[0,0,0],[ 0,0,0],[0,0,1]]) + \
                                          sa*numpy.array([[0,1,0],[-1,0,0],[0,0,0]])
                    ncstep = numpy.dot(rmat, nc)
                    base[jbase].x = loop[
                        iloop].center + ncstep * loop[iloop].radius
                    ang = ang + ang_ds
            else:
                l = 2 * math.pi * loop[iloop].radius  # Loop length
                inc = l / (jbasestop + 1 - jbasestart)
                li = 0
                for jbase in range(jbasestart, jbasestop + 1):
                    base[jbase].x = loop[
                        iloop].center + li * inc * numpy.array([1, 0, 0])
                    li += 1

            jprev = jside
예제 #23
0
"""
    12.22.2017 Friday
    created by neonleexiang
    test Newton Method
"""

import Newton
import matPlot4Newton
import matplotlib.pyplot as plt


def f(x):
    return x**3 - 1


df = Newton.divf(f)

# newtonMethod
print Newton.NewtonMethod(f, df, 10, 0.0000001)
output = Newton.NewtonMethod(f, df, 10, 0.000001)
fp = open("newtonMethod", 'w+')
fp.writelines('x*' + '=' + str(output[0]) + '\n')
fp.writelines('xlist' + "=" + str(output[1]) + '\n')
fp.close()
out4x = output[0]
list4x = output[1]
plot1 = matPlot4Newton.plot4Newton(list4x, out4x)
plt.title("newtonMethod")
plt.savefig('newtonMethod.png')

# newtonMethod1