def calculateDifference(self, fsim, fanl, fout):
        import csv
        xsim, ysim, zsim = [None, None, None]
        xanl, yanl, zanl = [None, None, None]
        tlist = None

        with open(fsim) as f:
            xsim, ysim, zsim = putil.extractData(f, [1, 2, 3])
            xsim = np.array(xsim)
            ysim = np.array(ysim)
            zsim = np.array(zsim)
        with open(fsim) as f:
            tlist = putil.extractData(f)[0]
        with open(fanl) as f:
            xanl, yanl, zanl = putil.extractData(f, [1, 2, 3])
            xanl = np.array(xanl)
            yanl = np.array(yanl)
            zanl = np.array(zanl)

        rsim = np.hypot(xsim, ysim)
        ranl = np.hypot(xanl, yanl)
        rerr = np.abs(ranl - rsim) # / len(ranl)
        zerr = np.abs(zanl - zsim) # / len(zanl)
        #rerr = np.cumsum(rerr)
        #zerr = np.cumsum(zerr)

        with open(fout, 'w') as f:
            writer = csv.writer(f, delimiter=' ')
            for i in xrange(len(tlist)):
                writer.writerow([tlist[i], rerr[i], zerr[i]])
            writer.writerow(['# Mean r err: ', np.mean(rerr)])
            writer.writerow(['# Mean r stdev: ', np.var(rerr)])
            writer.writerow(['# Mean z err: ', np.mean(zerr)])
            writer.writerow(['# Mean z stdev: ', np.var(zerr)])
Example #2
0
    def plotLinearRegression(self, alpha):
        import matplotlib.pyplot as plt
        from itertools import cycle
        from plot_utility import extractData

        s = settings.Settings()

        cols = cycle(['r', 'g', 'b'])

        for particle in self.particles:
            s.outfile = self.filename(particle, alpha)
            c = cols.next()
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                R = np.hypot(np.array(x), np.array(y))
                plt.plot(z,
                         R,
                         '.' + c,
                         markersize=1,
                         label=self.label(particle))
            s.outfile = self.filename(particle, alpha, 'drift_linreg_')
            with open(s.outpath()) as f:
                t, R, z = extractData(f, [0, 1, 2])
                plt.plot(z, R, '-' + c, linewidth=2)
        plt.legend()
        plt.tight_layout()
        plt.show()
 def plotDifferences(self, particle, alphaStart, alphaEnd, alphaStep):
     from os import path
     import matplotlib.pyplot as plt
     import itertools
     from plot_utility import extractData
     
     s = settings.Settings()
     symbols = itertools.cycle(['o', '^', 's'])
     
     alpha = alphaStart
     while alpha < alphaEnd:
         with open(path.join(s.outdir, self.filename(particle, alpha, 'drift_difference_')) + s.outext) as f:
             t, x, y, z = extractData(f, [0, 1, 2, 3])
             t = np.array(t)
             x = np.array(x)
             y = np.array(y)
             z = np.array(z)
             mag = self.magnitude(x, y, z)
             plt.plot(t, mag, '-', label='$\\alpha = {alpha:>02}'.format(alpha=alpha))
         alpha += alphaStep
     plt.xlabel('t')
     plt.ylabel('$\\nabla B$ drift')
     plt.legend(framealpha=0.5)
     plt.tight_layout()
     plt.show()
Example #4
0
    def plotSuperimposed(self, alpha, beta):
        s = settings.Settings()
        app = mag.Application()
        
        field = SmoothField()
        field.alpha = alpha
        field.beta = beta
        field.Bz0 = app.fieldBaseStrength[0]
        
        for particle in self.particles:
            outfile = self.filename(particle, alpha, beta)
            s.outfile = outfile
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                start = len(z) / 4 - 100
                end = len(z) / 4 + 260
#                start = 0
#                end = len(z)
                plt.plot(z[start:end], y[start:end], self.style[particle], 
                         linewidth=1, label=self.label(particle))
#                self.plotField(field, -1.6, 1.6, 0.35, 0.6)
                xmin, xmax = plt.xlim()
                ymin, ymax = plt.ylim()
                self.plotField(field, xmin, xmax, ymin, ymax)
                    
        plt.xlabel('z (m)')
        plt.ylabel('y (m)')
        plt.tight_layout()
        plt.show()
Example #5
0
    def plotDifferences(self, particle, alphaStart, alphaEnd, alphaStep):
        from os import path
        import matplotlib.pyplot as plt
        import itertools
        from plot_utility import extractData

        s = settings.Settings()
        symbols = itertools.cycle(['o', '^', 's'])

        alpha = alphaStart
        while alpha < alphaEnd:
            with open(
                    path.join(
                        s.outdir,
                        self.filename(particle, alpha, 'drift_difference_')) +
                    s.outext) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                t = np.array(t)
                x = np.array(x)
                y = np.array(y)
                z = np.array(z)
                mag = self.magnitude(x, y, z)
                plt.plot(t,
                         mag,
                         '-',
                         label='$\\alpha = {alpha:>02}'.format(alpha=alpha))
            alpha += alphaStep
        plt.xlabel('t')
        plt.ylabel('$\\nabla B$ drift')
        plt.legend(framealpha=0.5)
        plt.tight_layout()
        plt.show()
Example #6
0
    def plotSuperimposed(self, alpha, beta, gamma, L, n):
        import matplotlib.patches as mpatches
        import matplotlib.pyplot as plt
        from plot_utility import extractData
        
        s = settings.Settings()
        
        import itertools
        cmap = itertools.cycle(self.cmaps)
        lmap = itertools.cycle(self.lmaps)
        
        handles = []
        labels = []
        for particle in self.particles:
            s.outfile = self.filename(particle, alpha, beta, gamma, L, n)
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                r = np.hypot(np.array(x), np.array(y))
#                plt.plot(z, r, '-', label=self.label(particle))
                plt.scatter(z, r, c=t, cmap=cmap.next())
                handles.append(mpatches.Patch(color=lmap.next()))
                labels.append(self.label(particle))
                    
        plt.xlabel('z (m)')
        plt.ylabel('R (m)')
#        plt.legend(handles, labels, ncol=1, loc=4, framealpha=0.5)
#        plt.legend(ncol=1, loc=4, framealpha=0.5)
        plt.tight_layout()
        plt.show()
Example #7
0
 def animate(self, alpha, beta, L, n, div=32, particle='de+'):
     s = settings.Settings()
     field = SineField()
     field.alpha = alpha
     field.beta = beta
     field.L = L
     field.n = n
     
     outfile = self.filename(particle, alpha, beta, L, n)
     s.outfile = outfile
     with open(s.outpath()) as f:
         t, x, y, z = extractData(f, [0, 1, 2, 3])
         length = len(z) / div
         for i in xrange(div):
             start = i * length
             if i > 0:
                 start = (i-1) * length
             end = (i+1) * length
             plt.plot(z[start:end], y[start:end], 'b-', linewidth=1, label=self.label(particle))
             xmin, xmax = [ -1.15, 1.15 ]
             ymin, ymax = [ -1.0, 1.0 ]
             self.plotField(field, xmin, xmax, ymin, ymax)
             plt.xlabel('$z$ (m)')
             plt.ylabel('$y$ (m)')
             plt.tight_layout()
             s.outext = '_{index:03}.png'.format(index=i)
             plt.text(0.25, 0.8, r'$B_z = B_{z0} \left( 1 + \alpha r + \beta z\ \sin (\frac{n \pi z}{L}) \right)$',
                      fontsize=15)
             plt.text(0.25, 0.7, '$\\alpha = {alp},\\ \\beta = {beta}$'.format(alp=alpha, beta=beta),
                      fontsize=15)
             plt.savefig(s.outpath())
             plt.clf()
Example #8
0
    def plotDeviations(self):
        from os import path
        import matplotlib.pyplot as plt
        import itertools
        from plot_utility import extractData

        s = settings.Settings()
        symbols = itertools.cycle(['o', '^', 's'])

        for particle in self.particles:
            with open(
                    path.join(s.outdir,
                              self.filename(particle, 0, 'drift_mean_')) +
                    s.outext, 'r') as f:
                alphas, means = extractData(f, [0, 1])
                plt.plot(alphas,
                         means,
                         symbols.next(),
                         markersize=8,
                         label=self.label(particle))

        plt.xlabel('$\\alpha$')
        plt.ylabel('$\\nabla B$ drift')
        #        plt.legend(ncol=1, framealpha=0.5, loc=1)
        plt.tight_layout()
        plt.show()
 def calculateDifference(self, alpha):
     from os import path
     import csv
     from plot_utility import extractData
     
     app = mag.Application()
     Bz0 = app.fieldBaseStrength[2]
     Ek = app.kineticEnergy
     
     s = settings.Settings()
     
     for particle in self.particles:
         xdiff = []
         ydiff = []
         zdiff = []
         tlist = []
         with open(path.join(s.outdir, self.filename(particle, alpha)) + s.outext) as f:
             tlist, x, y, z = extractData(f, [0, 1, 2, 3])
             self.prepareAnalytic(Ek, self.mass(particle))
             for i in xrange(len(tlist)):
                 xa, ya, za = self.analytic(tlist[i], Bz0, self.charge(particle), self.mass(particle))
                 xdiff.append(xa - x[i])
                 ydiff.append(ya - y[i])
                 zdiff.append(za - z[i])
         
         with open(path.join(s.outdir, self.filename(particle, alpha, 'drift_difference_')) + s.outext, 'w') as csvfile:
             writer = csv.writer(csvfile, delimiter=' ')
             self.prepareAnalytic(Ek, self.mass(particle))
             for i in range(len(tlist)):
                 writer.writerow([ tlist[i], xdiff[i], ydiff[i], zdiff[i] ])
Example #10
0
    def plotSuperimposed(self, alpha, beta, gamma, L, n):
        import matplotlib.patches as mpatches
        import matplotlib.pyplot as plt
        from plot_utility import extractData

        s = settings.Settings()

        import itertools
        cmap = itertools.cycle(self.cmaps)
        lmap = itertools.cycle(self.lmaps)

        handles = []
        labels = []
        for particle in self.particles:
            s.outfile = self.filename(particle, alpha, beta, gamma, L, n)
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                r = np.hypot(np.array(x), np.array(y))
                #                plt.plot(z, r, '-', label=self.label(particle))
                plt.scatter(z, r, c=t, cmap=cmap.next())
                handles.append(mpatches.Patch(color=lmap.next()))
                labels.append(self.label(particle))

        plt.xlabel('z (m)')
        plt.ylabel('R (m)')
        #        plt.legend(handles, labels, ncol=1, loc=4, framealpha=0.5)
        #        plt.legend(ncol=1, loc=4, framealpha=0.5)
        plt.tight_layout()
        plt.show()
Example #11
0
    def calculateDeviations(self, alphaStart, alphaEnd, alphaStep):
        from os import path
        import csv
        from plot_utility import extractData

        s = settings.Settings()

        for particle in self.particles:
            gradient = []
            alphas = []
            alpha = alphaStart
            while alpha < alphaEnd:
                s.outfile = self.filename(particle, alpha, 'drift_linreg_')
                with open(s.outpath()) as f:
                    t, R, z = extractData(f, [0, 1, 2])
                    g = (R[-1] - R[0]) / (t[-1] - t[0])
                    gradient.append(g)
                alphas.append(alpha)
                alpha += alphaStep

            with open(
                    path.join(s.outdir,
                              self.filename(particle, 0, 'drift_mean_')) +
                    s.outext, 'w') as f:
                writer = csv.writer(f, delimiter=' ')
                for i in xrange(len(alphas)):
                    writer.writerow([alphas[i], gradient[i]])
Example #12
0
    def plotSuperimposed(self, alpha, beta, gamma, eps, rho, L, n, particle):
        s = settings.Settings()

        field = Fields.TokamakField()
        field.setupField(alpha=alpha, beta=beta, gamma=gamma, eps=eps, rho=rho, L=L, n=n)

        s.outfile = self.filename(particle, alpha, beta, gamma, eps, rho, L, n)
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            
            plt.plot(x, y, self.style[particle], label=self.label(particle))
            plt.xlabel('$x$ m')
            plt.ylabel('$y$ m')
            xmin, xmax = [ -0.5, 0.5 ]
            ymin, ymax = [ -0.5, 0.5 ]
#            xmin, xmax = plt.xlim()
#            ymin, ymax = plt.ylim()
            self.plotField(field, xmin, xmax, ymin, ymax, orientation='front')
            s.outext = '_front.pdf'
            plt.savefig(s.outpath())
            plt.show()
            
            plt.plot(z, y, self.style[particle], label=self.label(particle))
            plt.xlabel('$z$ m')
            plt.ylabel('$y$ m')
            xmin, xmax = [ -0.5, 0.5 ]
            ymin, ymax = [ -0.5, 0.5 ]
#            xmin, xmax = plt.xlim()
#            ymin, ymax = plt.ylim()
            self.plotField(field, xmin, xmax, ymin, ymax, orientation='right')
            s.outext = '_right.pdf'
            plt.savefig(s.outpath())
            plt.show()
Example #13
0
    def plotSuperimposed(self, alpha, beta, L, n):
        s = settings.Settings()
        field = SineField()
        field.alpha = alpha
        field.beta = beta
        field.L = L
        field.n = n
        
        for particle in self.particles:
            outfile = self.filename(particle, alpha, beta, L, n)
            s.outfile = outfile
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                #start = len(z) / 4 + 250
                #end = len(z) / 4 + 180
                start = 0
                end = len(z)
                plt.plot(z[start:end], y[start:end], self.style[particle], 
                         linewidth=1, label=self.label(particle))
        xmin, xmax = [ -0.4, 0.4 ]
        ymin, ymax = [ 0.1, 0.3 ]
#        xmin, xmax = plt.xlim()
#        ymin, ymax = plt.ylim()
        self.plotField(field, xmin, xmax, ymin, ymax)
                    
        plt.xlabel('$z$ (m)')
        plt.ylabel('$y$ (m)')
#        plt.text(0.25, 0.8, r'$B_z = B_{z0} \left( 1 + \alpha r + \beta z\ \sin (\frac{n \pi z}{L}) \right)$',
#                 fontsize=15)
#        plt.text(0.25, 0.7, '$\\alpha = {alp},\\ \\beta = {beta}$'.format(alp=alpha, beta=beta),
#                 fontsize=15)
        plt.tight_layout()
        s.outext = '.pdf'
        plt.savefig(s.outpath())
        plt.show()
def plotTop(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of z = f(x)
    """
    t, x, z = extractData(fn, [0, 1, 3])
    plt.scatter(x[skipline::skiprow], z[skipline::skiprow], c=t[skipline::skiprow], cmap='gray_r')
    plt.xlabel('x (m)')
    plt.ylabel('z (m)')
    plt.savefig(out)
Example #15
0
def _extract(filename):
    with open(filename) as f:
        t, x, y, z = extractData(f, [0, 1, 2, 3])
        t = np.array(t)
        x = np.array(x)
        y = np.array(y)
        z = np.array(z)
    return [t, x, y, z]
def plotRight(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of y = f(z)
    """
    t, y, z = extractData(fn, [0, 2, 3])
    plt.scatter(z[skipline::skiprow], y[skipline::skiprow], c=t[skipline::skiprow], cmap='gray_r')
    plt.xlabel('z (m)')
    plt.ylabel('y (m)')
    plt.savefig(out)
def plotFront(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of y = f(x)
    """
    t, x, y = extractData(fn, [0, 1, 2])
    plt.scatter(x[skipline::skiprow], y[skipline::skiprow], c=t[skipline::skiprow],
             cmap='gray')
    plt.xlabel('x (m)')
    plt.ylabel('y (m)')
    plt.savefig(out)
def plotPoloid(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of R = x**2 + y**2 vs z
    """
    t, x, y, z = extractData(fn, [0, 1, 2, 3])
    x = np.array(x)
    y = np.array(y)
    R = np.hypot(x, y)
    plt.scatter(R[skipline::skiprow], z[skipline::skiprow], c=t[skipline::skiprow], cmap='gray_r')
    plt.xlabel('R (m)')
    plt.ylabel('z (m)')
    plt.savefig(out)
def plotFront(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of y = f(x)
    """
    t, x, y = extractData(fn, [0, 1, 2])
    plt.scatter(x[skipline::skiprow],
                y[skipline::skiprow],
                c=t[skipline::skiprow],
                cmap='gray')
    plt.xlabel('x (m)')
    plt.ylabel('y (m)')
    plt.savefig(out)
def plotRight(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of y = f(z)
    """
    t, y, z = extractData(fn, [0, 2, 3])
    plt.scatter(z[skipline::skiprow],
                y[skipline::skiprow],
                c=t[skipline::skiprow],
                cmap='gray_r')
    plt.xlabel('z (m)')
    plt.ylabel('y (m)')
    plt.savefig(out)
def plotTop(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of z = f(x)
    """
    t, x, z = extractData(fn, [0, 1, 3])
    plt.scatter(x[skipline::skiprow],
                z[skipline::skiprow],
                c=t[skipline::skiprow],
                cmap='gray_r')
    plt.xlabel('x (m)')
    plt.ylabel('z (m)')
    plt.savefig(out)
 def calculateAnalytic(self, fin, fout):
     """Calculate analytic solution for given simulation result file fin
     """
     import csv
     tlist = None
     with open(fin) as f:
         tlist = putil.extractData(f)[0]
     with open(fout, 'w') as csvfile:
         writer = csv.writer(csvfile, delimiter=' ')
         for t in tlist:
             x, y, z = self.analytic(t)
             writer.writerow([t, x, y, z])
    def plotSuperimposed(self, fsims, fanl):
        for i in range(len(fsims)):
            with open(fsims[i]) as f:
                t, x, y, z = putil.extractData(f, [0, 1, 2, 3])
                x = np.array(x)
                y = np.array(y)
#                r = np.hypot(x, y)
                plt.plot(z, y, 'o--', label='{step} $\\tau_c$'.format(step=(i+1)*self.step))

        with open(fanl) as f:
            t, x, y, z = putil.extractData(f, [0, 1, 2, 3])
            x = np.array(x)
            y = np.array(y)
#            r = np.hypot(x, y)
            plt.plot(z, y, 'k-', linewidth=1.5, label='Analytic')

        plt.xlabel('$z$ (m)')
        plt.ylabel('$y$ (m)')
        plt.legend(ncol=2, loc=4, framealpha=0.5)
        plt.tight_layout()
        plt.show()
Example #24
0
 def plot3d(self, alpha, beta, gamma, eps, rho, L, n):
     from mpl_toolkits.mplot3d import Axes3D
     
     s = settings.Settings()
     fig = plt.figure()
     ax = fig.add_subplot(111, projection='3d')
     for particle in self.particles:
         s.outfile = self.filename(particle, alpha, beta, gamma, eps, rho, L, n)
         with open(s.outpath()) as f:
             t, x, y, z = extractData(f, [0, 1, 2, 3])
             ax.plot(x, y, z)
     plt.show()
 def plotGuidingCenter(self, alpha):
     from os import path
     import matplotlib.pyplot as plt
     from plot_utility import extractData
     
     s = settings.Settings()
     
     for particle in self.particles:
         with open(path.join(s.outdir, self.filename(particle, alpha, 'drift_center')) + s.outext) as f:
             t, R = extractData(f, [0, 1])
             plt.plot(t, R, '--', label=self.label(particle))
             
     plt.show()
 def plotLinearRegression(self, alpha):
     import matplotlib.pyplot as plt
     from itertools import cycle
     from plot_utility import extractData
     
     s = settings.Settings()
     
     cols = cycle([ 'r', 'g', 'b' ])
     
     for particle in self.particles:
         s.outfile = self.filename(particle, alpha)
         c = cols.next()
         with open(s.outpath()) as f:
             t, x, y, z = extractData(f, [0, 1, 2, 3])
             R = np.hypot(np.array(x), np.array(y))
             plt.plot(z, R, '.' + c, markersize=1, label=self.label(particle))
         s.outfile = self.filename(particle, alpha, 'drift_linreg_')
         with open(s.outpath()) as f:
             t, R, z = extractData(f, [0, 1, 2])
             plt.plot(z, R, '-' + c, linewidth=2)
     plt.legend()
     plt.tight_layout()
     plt.show()
def plotPoloid(fn, out, comment='#', skipline=1, skiprow=2):
    """Plot of R = x**2 + y**2 vs z
    """
    t, x, y, z = extractData(fn, [0, 1, 2, 3])
    x = np.array(x)
    y = np.array(y)
    R = np.hypot(x, y)
    plt.scatter(R[skipline::skiprow],
                z[skipline::skiprow],
                c=t[skipline::skiprow],
                cmap='gray_r')
    plt.xlabel('R (m)')
    plt.ylabel('z (m)')
    plt.savefig(out)
Example #28
0
    def plotGuidingCenter(self, alpha):
        from os import path
        import matplotlib.pyplot as plt
        from plot_utility import extractData

        s = settings.Settings()

        for particle in self.particles:
            with open(
                    path.join(s.outdir,
                              self.filename(particle, alpha, 'drift_center')) +
                    s.outext) as f:
                t, R = extractData(f, [0, 1])
                plt.plot(t, R, '--', label=self.label(particle))

        plt.show()
Example #29
0
    def animate(self, alpha, div=4, particle='tr+'):
        s = settings.Settings()
        app = mag.Application()

        field = RadialField()
        field.alpha = alpha
        field.Bz0 = app.fieldBaseStrength[2]
        
        outfile = self.filename(particle, alpha)
        s.outfile = outfile
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            length = len(z) / div
            for i in xrange(div):
#                start = i * length
#                if i > 0:
#                    start = (i) * length
                start=0
                end = (i+1) * length
                
                # Plot front view, no real way to refactor these *sigh*
                plt.plot(x[start:end], y[start:end], self.style[particle], 
                         linewidth=1, label=self.label(particle))
                xmin, xmax = [ -0.03, 0.03 ]
                ymin, ymax = [ -0.03, 0.03 ]
                self.plotField(field, xmin, xmax, ymin, ymax, orientation='front')
                plt.xlabel('$x$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                s.outext = '_long_front_{index:03}.pdf'.format(index=i)
                plt.savefig(s.outpath())
                plt.show()
                plt.clf()
                
                # Plot right view, no real way to refactor these *sigh*
                plt.plot(z[start:end], y[start:end], self.style[particle], 
                         linewidth=1, label=self.label(particle))
                xmin, xmax = [ 0.0, 25 ]
                ymin, ymax = [ -0.03, 0.03 ]
                self.plotField(field, xmin, xmax, ymin, ymax, orientation='right')
                plt.xlabel('$z$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                s.outext = '_long_right_{index:03}.pdf'.format(index=i)
                plt.savefig(s.outpath())
                plt.show()
                plt.clf()
 def errorPlots(self):
     """Plot errors to answer hypothesis
     """
     s = settings.Settings()
     for i in range(1, self.count):
         errfile = os.path.join(s.outdir,
         'Error1_{ct:0>2}'.format(ct=i)) + s.outext
         with open(errfile) as f:
             t, r, z = putil.extractData(f, [0, 1, 2])
             r = np.array(r)
             z = np.array(z)
             t = np.array(t) * 10**6
             plt.plot(t, r, '--', label='{step} $\\tau_c$'.format(step=i*self.step))
     plt.xlabel('Time ($\\mu$s)')
     plt.ylabel('Error Accumulation')
     plt.legend(loc=2, ncol=2, framealpha=0.5)
     plt.tight_layout()
     plt.show()
Example #31
0
 def savePlot(self, alpha, beta, gamma, L, n):
     import numpy as np
     import matplotlib.pyplot as plt
     from plot_utility import extractData
     
     s = settings.Settings()
     for particle in self.particles:
         s.outfile = self.filename(particle, alpha, beta, gamma, L, n)
         with open(s.outpath()) as f:
             t, x, y, z = extractData(f, [0, 1, 2, 3])
             R = np.hypot(np.array(x), np.array(y))
             plt.plot(z, R, '-', label=self.label(particle))
     plt.xlabel('z (m)')
     plt.ylabel('R (m)')
     plt.legend(loc=0)
     s.outext = '.png'
     plt.savefig(s.outpath())
     plt.clf()
Example #32
0
    def calculateGuidingCenter(self, particle, alpha):
        from os import path
        import csv
        from plot_utility import extractData

        app = mag.Application()
        s = settings.Settings()

        gyro_period = self.gyro_period(app.fieldBaseStrength[2],
                                       self.charge(particle),
                                       self.mass(particle))
        center = []
        tp = []
        print gyro_period

        with open(
                path.join(s.outdir, self.filename(particle, alpha)) +
                s.outext) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            R = np.hypot(x, y)
            period = 0
            Rs = []
            for i in xrange(len(t)):
                if period > gyro_period:
                    c = np.mean(Rs)
                    center.append(c)
                    Rs = []
                    if len(tp) == 0:
                        tp.append(period)
                    else:
                        tp.append(tp[-1] + period)
                    period = 0
                Rs.append(R[i])
                if i > 0:
                    period += t[i] - t[i - 1]

        with open(
                path.join(s.outdir,
                          self.filename(particle, alpha, 'drift_center')) +
                s.outext, 'w') as f:
            writer = csv.writer(f, delimiter=' ')
            for i in xrange(len(center)):
                writer.writerow([tp[i], center[i]])
Example #33
0
    def animate(self, alpha, beta, gamma, eps, rho, L, n, div=32, particle='de+'):
        field = Fields.TokamakField()
        field.setupField(alpha=alpha, beta=beta, gamma=gamma, eps=eps, rho=rho, L=L, n=n)

        s = settings.Settings()
        s.outfile = self.filename(particle, alpha, beta, gamma, eps, rho, L, n)
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            length = len(z) / div
            for i in xrange(div):
                start = i * length
                if i > 0:
                    start = (i-1) * length
                end = (i+1) * length
                plt.subplot(121)
                plt.plot(x[start:end], y[start:end], '-b', label=self.label(particle))
                plt.xlabel('x')
                plt.ylabel('y')
                min, max = [-0.5, 0.5]
                levels = np.arange(4.2, 6.3, 0.4)
                XX = np.arange(min, max, (max-min)/1000)
                YY = np.arange(min, max, (max-min)/1000)
                X, Y = np.meshgrid(XX, YY)
                Z = 0.1
                F = field.zField(X, Y, Z)
                CS = plt.contour(X, Y, F, levels)
                plt.clabel(CS, fontsize=9, colors='k', inline=1)
                plt.subplot(122)
                plt.plot(z[start:end], y[start:end], '-b', label=self.label(particle))
                plt.xlabel('z')
                plt.ylabel('y')
                min, max = [-2.2, 2.0]
                ZZ = np.arange(min, max, (max-min)/1000)
                min, max = [-0.5, 0.5]
                YY = np.arange(min, max, (max-min)/1000)
                Z, Y = np.meshgrid(ZZ, YY)
                X = 0.1
                F = field.zField(X, Y, Z)
                CS = plt.contour(Z, Y, F, levels)
                plt.clabel(CS, fontsize=9, colors='k', inline=1)
                s.outext = '_{index:03}.png'.format(index=i)
                plt.savefig(s.outpath())
                plt.clf()
    def plotDeviations(self):
        from os import path
        import matplotlib.pyplot as plt
        import itertools
        from plot_utility import extractData
        
        s = settings.Settings()
        symbols = itertools.cycle(['o', '^', 's'])
        
        for particle in self.particles:
            with open(path.join(s.outdir, self.filename(particle, 0, 'drift_mean_')) + s.outext, 'r') as f:
                alphas, means = extractData(f, [0, 1])
                plt.plot(alphas, means, symbols.next(), markersize=8, label=self.label(particle))
        
        plt.xlabel('$\\alpha$')
        plt.ylabel('$\\nabla B$ drift')
#        plt.legend(ncol=1, framealpha=0.5, loc=1)
        plt.tight_layout()
        plt.show()
Example #35
0
    def animate(self, alpha, beta, L, n, div=32, particle='de+'):
        s = settings.Settings()
        field = SineField()
        field.alpha = alpha
        field.beta = beta
        field.L = L
        field.n = n

        outfile = self.filename(particle, alpha, beta, L, n)
        s.outfile = outfile
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            length = len(z) / div
            for i in xrange(div):
                start = i * length
                if i > 0:
                    start = (i - 1) * length
                end = (i + 1) * length
                plt.plot(z[start:end],
                         y[start:end],
                         'b-',
                         linewidth=1,
                         label=self.label(particle))
                xmin, xmax = [-1.15, 1.15]
                ymin, ymax = [-1.0, 1.0]
                self.plotField(field, xmin, xmax, ymin, ymax)
                plt.xlabel('$z$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                s.outext = '_{index:03}.png'.format(index=i)
                plt.text(
                    0.25,
                    0.8,
                    r'$B_z = B_{z0} \left( 1 + \alpha r + \beta z\ \sin (\frac{n \pi z}{L}) \right)$',
                    fontsize=15)
                plt.text(0.25,
                         0.7,
                         '$\\alpha = {alp},\\ \\beta = {beta}$'.format(
                             alp=alpha, beta=beta),
                         fontsize=15)
                plt.savefig(s.outpath())
                plt.clf()
    def plotMirrorPoints(self):
        import matplotlib.pyplot as plt
        import itertools
        from plot_utility import extractData
        
        symbols = itertools.cycle(['--bo', '--g^', '--rs'])
        
        s = settings.Settings()
        
        for particle in self.particles:
            s.outfile = self.filename(particle, 0, 0, 0, 0, 'sine_mirrors_')
            with open(s.outpath()) as f:
                beta, mx, mn = extractData(f, [0, 1, 2])
                sym = symbols.next()
                plt.plot(beta, mx, sym, markersize=8, label=self.label(particle))
                plt.plot(beta, mn, sym, markersize=8)
        plt.xlabel('$\\beta$')
        plt.ylabel('Mirror points (m)')
#        plt.legend(loc=0)
        plt.show()
Example #37
0
    def plotSuperimposed(self, alpha):
        s = settings.Settings()
        app = mag.Application()

        field = RadialField()
        field.alpha = alpha
        field.Bz0 = app.fieldBaseStrength[2]
        
        for particle in self.particles:
            outfile = self.filename(particle, alpha)
            s.outfile = outfile
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                plt.plot(x, y, self.style[particle], label=self.label(particle))
                xmin, xmax = [ -0.03, 0.03 ]
                ymin, ymax = [ -0.03, 0.03 ]
                self.plotField(field, xmin, xmax, ymin, ymax)
                plt.xlabel('$z$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                plt.show()
Example #38
0
    def calculateLinearRegression(self, particle, alpha):
        from numpy import linalg
        import csv
        from plot_utility import extractData

        s = settings.Settings()
        s.outfile = self.filename(particle, alpha)
        z = []
        t = []
        m = 0.0
        c = 0.0
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            R = np.hypot(np.array(x), np.array(y))
            A = np.vstack([t, np.ones(len(t))]).T
            m, c = linalg.lstsq(A, R)[0]

        s.outfile = self.filename(particle, alpha, 'drift_linreg_')
        with open(s.outpath(), 'w') as f:
            writer = csv.writer(f, delimiter=' ')
            for i in xrange(len(t)):
                writer.writerow([t[i], m * t[i] + c, z[i]])
    def calculateLinearRegression(self, particle, alpha):
        from numpy import linalg
        import csv
        from plot_utility import extractData

        s = settings.Settings()        
        s.outfile = self.filename(particle, alpha)
        z = []
        t = []
        m = 0.0
        c = 0.0
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            R = np.hypot(np.array(x), np.array(y))
            A = np.vstack([t, np.ones(len(t))]).T
            m, c = linalg.lstsq(A, R)[0]
        
        s.outfile = self.filename(particle, alpha, 'drift_linreg_')
        with open(s.outpath(), 'w') as f:
            writer = csv.writer(f, delimiter=' ')
            for i in xrange(len(t)):
                writer.writerow([ t[i], m*t[i] + c, z[i] ])
Example #40
0
    def plotSuperimposed(self, alpha, beta, L, n):
        s = settings.Settings()
        field = SineField()
        field.alpha = alpha
        field.beta = beta
        field.L = L
        field.n = n

        for particle in self.particles:
            outfile = self.filename(particle, alpha, beta, L, n)
            s.outfile = outfile
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                #start = len(z) / 4 + 250
                #end = len(z) / 4 + 180
                start = 0
                end = len(z)
                plt.plot(z[start:end],
                         y[start:end],
                         self.style[particle],
                         linewidth=1,
                         label=self.label(particle))
        xmin, xmax = [-0.4, 0.4]
        ymin, ymax = [0.1, 0.3]
        #        xmin, xmax = plt.xlim()
        #        ymin, ymax = plt.ylim()
        self.plotField(field, xmin, xmax, ymin, ymax)

        plt.xlabel('$z$ (m)')
        plt.ylabel('$y$ (m)')
        #        plt.text(0.25, 0.8, r'$B_z = B_{z0} \left( 1 + \alpha r + \beta z\ \sin (\frac{n \pi z}{L}) \right)$',
        #                 fontsize=15)
        #        plt.text(0.25, 0.7, '$\\alpha = {alp},\\ \\beta = {beta}$'.format(alp=alpha, beta=beta),
        #                 fontsize=15)
        plt.tight_layout()
        s.outext = '.pdf'
        plt.savefig(s.outpath())
        plt.show()
Example #41
0
    def calculateDifference(self, alpha):
        from os import path
        import csv
        from plot_utility import extractData

        app = mag.Application()
        Bz0 = app.fieldBaseStrength[2]
        Ek = app.kineticEnergy

        s = settings.Settings()

        for particle in self.particles:
            xdiff = []
            ydiff = []
            zdiff = []
            tlist = []
            with open(
                    path.join(s.outdir, self.filename(particle, alpha)) +
                    s.outext) as f:
                tlist, x, y, z = extractData(f, [0, 1, 2, 3])
                self.prepareAnalytic(Ek, self.mass(particle))
                for i in xrange(len(tlist)):
                    xa, ya, za = self.analytic(tlist[i], Bz0,
                                               self.charge(particle),
                                               self.mass(particle))
                    xdiff.append(xa - x[i])
                    ydiff.append(ya - y[i])
                    zdiff.append(za - z[i])

            with open(
                    path.join(
                        s.outdir,
                        self.filename(particle, alpha, 'drift_difference_')) +
                    s.outext, 'w') as csvfile:
                writer = csv.writer(csvfile, delimiter=' ')
                self.prepareAnalytic(Ek, self.mass(particle))
                for i in range(len(tlist)):
                    writer.writerow([tlist[i], xdiff[i], ydiff[i], zdiff[i]])
Example #42
0
    def animate(self, alpha, beta, div=4, particle='tr+'):
        s = settings.Settings()
        app = mag.Application()

        field = SmoothField()
        field.alpha = alpha
        field.beta = beta
        field.Bz0 = app.fieldBaseStrength[0]
        
        outfile = self.filename(particle, alpha, beta)
        s.outfile = outfile
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            length = len(z) / div
            for i in xrange(div):
                start = i * length
#                if i > 0:
#                    start = (i-1) * length
#                start=0
                end = (i+1) * length
                
                if i > 0:
                    plt.plot(z[0:start], y[0:start], 'm-', alpha=0.5,
                             linewidth=0.5, label=self.label(particle))
                plt.plot(z[start:end], y[start:end], self.style[particle], 
                         linewidth=1, label=self.label(particle))
                self.plotField(field, -1.6, 1.6, 0.35, 0.6)
#                xmin, xmax = plt.xlim()
#                ymin, ymax = plt.ylim()
#                self.plotField(field, xmin, xmax, ymin, ymax)
                plt.xlabel('$z$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                s.outext = '_{index:03}.pdf'.format(index=i)
                plt.savefig(s.outpath())
                plt.show()
                plt.clf()
 def calculateGuidingCenter(self, particle, alpha):
     from os import path
     import csv
     from plot_utility import extractData
     
     app = mag.Application()
     s = settings.Settings()
     
     gyro_period = self.gyro_period(app.fieldBaseStrength[2], self.charge(particle), self.mass(particle))
     center = []
     tp = []
     print gyro_period
     
     with open(path.join(s.outdir, self.filename(particle, alpha)) + s.outext) as f:
         t, x, y, z = extractData(f, [0, 1, 2, 3])
         R = np.hypot(x, y)
         period = 0
         Rs = []
         for i in xrange(len(t)):
             if period > gyro_period:
                 c = np.mean(Rs)
                 center.append(c)
                 Rs = []
                 if len(tp) == 0:
                     tp.append(period)
                 else:
                     tp.append(tp[-1] + period)
                 period = 0
             Rs.append(R[i])
             if i > 0:
                 period += t[i] - t[i-1]
                 
     with open(path.join(s.outdir, self.filename(particle, alpha, 'drift_center')) + s.outext, 'w') as f:
         writer = csv.writer(f, delimiter=' ')
         for i in xrange(len(center)):
             writer.writerow([ tp[i], center[i] ])
Example #44
0
    def plotMirrorPoints(self):
        import matplotlib.pyplot as plt
        import itertools
        from plot_utility import extractData

        symbols = itertools.cycle(['--bo', '--g^', '--rs'])

        s = settings.Settings()

        for particle in self.particles:
            s.outfile = self.filename(particle, 0, 0, 0, 0, 'sine_mirrors_')
            with open(s.outpath()) as f:
                beta, mx, mn = extractData(f, [0, 1, 2])
                sym = symbols.next()
                plt.plot(beta,
                         mx,
                         sym,
                         markersize=8,
                         label=self.label(particle))
                plt.plot(beta, mn, sym, markersize=8)
        plt.xlabel('$\\beta$')
        plt.ylabel('Mirror points (m)')
        #        plt.legend(loc=0)
        plt.show()
Example #45
0
    def plotSuperimposed(self, alpha):
        s = settings.Settings()
        app = mag.Application()

        field = RadialField()
        field.alpha = alpha
        field.Bz0 = app.fieldBaseStrength[2]

        for particle in self.particles:
            outfile = self.filename(particle, alpha)
            s.outfile = outfile
            with open(s.outpath()) as f:
                t, x, y, z = extractData(f, [0, 1, 2, 3])
                plt.plot(x,
                         y,
                         self.style[particle],
                         label=self.label(particle))
                xmin, xmax = [-0.03, 0.03]
                ymin, ymax = [-0.03, 0.03]
                self.plotField(field, xmin, xmax, ymin, ymax)
                plt.xlabel('$z$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                plt.show()
    def calculateDeviations(self, alphaStart, alphaEnd, alphaStep):
        from os import path
        import csv
        from plot_utility import extractData

        s = settings.Settings()
                       
        for particle in self.particles:
            gradient = []
            alphas = []
            alpha = alphaStart
            while alpha < alphaEnd:
                s.outfile = self.filename(particle, alpha, 'drift_linreg_')
                with open(s.outpath()) as f:
                    t, R, z = extractData(f, [0, 1, 2])
                    g = (R[-1] - R[0]) / (t[-1] - t[0])
                    gradient.append(g)                    
                alphas.append(alpha)
                alpha += alphaStep
                
            with open(path.join(s.outdir, self.filename(particle, 0, 'drift_mean_')) + s.outext, 'w') as f:
                writer = csv.writer(f, delimiter=' ')
                for i in xrange(len(alphas)):
                    writer.writerow([ alphas[i], gradient[i] ])
Example #47
0
    def animate(self, alpha, div=4, particle='tr+'):
        s = settings.Settings()
        app = mag.Application()

        field = RadialField()
        field.alpha = alpha
        field.Bz0 = app.fieldBaseStrength[2]

        outfile = self.filename(particle, alpha)
        s.outfile = outfile
        with open(s.outpath()) as f:
            t, x, y, z = extractData(f, [0, 1, 2, 3])
            length = len(z) / div
            for i in xrange(div):
                #                start = i * length
                #                if i > 0:
                #                    start = (i) * length
                start = 0
                end = (i + 1) * length

                # Plot front view, no real way to refactor these *sigh*
                plt.plot(x[start:end],
                         y[start:end],
                         self.style[particle],
                         linewidth=1,
                         label=self.label(particle))
                xmin, xmax = [-0.03, 0.03]
                ymin, ymax = [-0.03, 0.03]
                self.plotField(field,
                               xmin,
                               xmax,
                               ymin,
                               ymax,
                               orientation='front')
                plt.xlabel('$x$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                s.outext = '_long_front_{index:03}.pdf'.format(index=i)
                plt.savefig(s.outpath())
                plt.show()
                plt.clf()

                # Plot right view, no real way to refactor these *sigh*
                plt.plot(z[start:end],
                         y[start:end],
                         self.style[particle],
                         linewidth=1,
                         label=self.label(particle))
                xmin, xmax = [0.0, 25]
                ymin, ymax = [-0.03, 0.03]
                self.plotField(field,
                               xmin,
                               xmax,
                               ymin,
                               ymax,
                               orientation='right')
                plt.xlabel('$z$ (m)')
                plt.ylabel('$y$ (m)')
                plt.tight_layout()
                s.outext = '_long_right_{index:03}.pdf'.format(index=i)
                plt.savefig(s.outpath())
                plt.show()
                plt.clf()