Ejemplo n.º 1
0
 def __init__(self, config, family='S', nTF=16, obj='L'):
     self.nTF = nTF
     self.config = config
     datadir = trim_dir('../../Data')
     file = 'salome_input'  #  config #  +'_{}{}{}'.format(family,nTF,obj)
     self.filename = datadir + '/' + file + '.json'
     self.profile = Profile(config['TF'],
                            family=family,
                            load=True,
                            part='TF',
                            nTF=nTF,
                            obj=obj,
                            npoints=250)
     setup = Setup(config['eq'])
     self.sf = SF(setup.filename)
     self.tf = TF(self.profile, sf=self.sf)
     self.pf = PF(self.sf.eqdsk)
     self.PF_support()  # calculate PF support seats
     self.CS_support()  # calculate CS support seats
     self.Gravity_support()
     self.cage = coil_cage(nTF=nTF,
                           rc=self.tf.rc,
                           ny=3,
                           plasma={'config': config['eq']},
                           coil=self.tf.x['cl'])
     self.eq = EQ(self.sf,
                  self.pf,
                  dCoil=0.5,
                  sigma=0,
                  boundary=self.sf.get_sep(expand=0.5),
                  n=1e3)
     self.eq.plasma()
     self.ff = force_feild(self.pf.index, self.pf.coil, self.eq.coil,
                           self.eq.plasma_coil)
Ejemplo n.º 2
0
 def __init__(self,profile,eqconf='unset',sep='unset',**kwargs):
     self.ny = kwargs.get('ny',3)  # TF filament number (y-dir)
     self.alpha = kwargs.get('alpha',1-1e-4)
     self.color = cycle(sns.color_palette('Set2',10))
     self.profile = profile
     self.loop = self.profile.loop
     self.bound = {}  # initalise bounds
     self.bindex = {'internal':[0],'interior':[0],'external':[0]}  # index
     for side in ['internal','interior','external']:
         self.bound[side] = {'r':[],'z':[]}
         if side in kwargs:
             self.add_bound(kwargs[side],side)
     if self.profile.nTF is not 'unset' and \
     (eqconf is not 'unset' or sep is not 'unset'):
         if eqconf is not 'unset':
             plasma = {'config':eqconf}
             sf = SF(Setup(eqconf).filename)
             self.tf = TF(profile=self.profile,sf=sf)
         else:
             plasma = {'r':sep['r'],'z':sep['z']}
             self.tf = TF(profile=self.profile)
         self.cage = coil_cage(nTF=self.profile.nTF,rc=self.tf.rc,
                               plasma=plasma,ny=self.ny,alpha=self.alpha)
         x = self.tf.get_loops(self.loop.draw())
         self.cage.set_TFcoil(x['cl'],smooth=False)
     else:
         if self.profile.obj is 'E':
             errtxt = 'nTF and SFconfig keywords not set\n'
             errtxt += 'unable to calculate stored energy\n'
             errtxt += 'initalise with \'nTF\' keyword'
             raise ValueError(errtxt)
Ejemplo n.º 3
0
#pl.plot(sf.rbdry,sf.zbdry,color=0.75*np.ones(3),lw=1.5)

for conf in ['SN', 'X', 'SFm', 'SX', 'SXex']:  #
    print(conf)
    setup = Setup(conf)
    sf = SF(setup.filename)
    pf = PF(sf.eqdsk)
    rb = RB(setup, sf)
    rb.firstwall(calc=False, plot=True, debug=False)
    rb.vessel()
    pf.plot(coils=pf.coil, label=True, plasma=False, current=False)
    tf = TF(nTF=18,
            shape={
                'vessel': rb.loop,
                'pf': pf,
                'fit': False,
                'setup': setup,
                'plot': True,
                'config': conf,
                'coil_type': 'A'
            })
    tf.fill()

    pl.plot(tf.Rcl, tf.Zcl)
    coil = {'Rcl': tf.Rcl, 'Zcl': tf.Zcl, 'nTF': tf.nTF, 'Iturn': 1}
    rp = ripple(plasma={'config': 'SN'}, coil=coil)
    rp.plot_loops()
    print(conf, 'ripple', rp.get_ripple())
    L = geom.length(tf.Rcl, tf.Zcl, norm=False)[-1]
    V = loop_vol(tf.Rcl, tf.Zcl)
    print('L {:1.2f}m, V {:1.0f}m3'.format(L, V))
Ejemplo n.º 4
0
nPF, nCS, nTF = 4, 3, 18
config = {'TF': 'dtt', 'eq': 'SN'}
config['TF'] = '{}{}{:d}'.format(config['eq'], config['TF'], nTF)
setup = Setup(config['eq'])
sf = SF(setup.filename)
rb = RB(setup, sf)
pf = PF(sf.eqdsk)

profile = Profile(config['TF'],
                  family='S',
                  part='TF',
                  nTF=nTF,
                  obj='L',
                  load=True)

tf = TF(profile, sf=sf)
eq = EQ(sf, pf, dCoil=2.0, limit=[5.2, 13, -6.5, 6], n=5e3)  #
eq.get_plasma_coil()
eq.run(update=False)

inv = INV(sf, eq, tf)
Lpf = inv.grid_PF(nPF=nPF)
Lcs = inv.grid_CS(nCS=nCS, Zbound=[-12, 8], gap=0.1)
Lo = np.append(Lpf, Lcs)
inv.update_coils()
inv.fit_PF(offset=0.3)
'''
inv.fix_boundary_psi(N=31,alpha=1-1e-4,factor=1)  # add boundary points
inv.fix_boundary_feild(N=31,alpha=1-1e-4,factor=1)  # add boundary points
inv.add_null(factor=3,point=sf.Xpoint)
Rex,arg = 1.5,40
Ejemplo n.º 5
0
class Shape(object):
    
    def __init__(self,profile,eqconf='unset',sep='unset',**kwargs):
        self.ny = kwargs.get('ny',3)  # TF filament number (y-dir)
        self.alpha = kwargs.get('alpha',1-1e-4)
        self.color = cycle(sns.color_palette('Set2',10))
        self.profile = profile
        self.loop = self.profile.loop
        self.bound = {}  # initalise bounds
        self.bindex = {'internal':[0],'interior':[0],'external':[0]}  # index
        for side in ['internal','interior','external']:
            self.bound[side] = {'r':[],'z':[]}
            if side in kwargs:
                self.add_bound(kwargs[side],side)
        if self.profile.nTF is not 'unset' and \
        (eqconf is not 'unset' or sep is not 'unset'):
            if eqconf is not 'unset':
                plasma = {'config':eqconf}
                sf = SF(Setup(eqconf).filename)
                self.tf = TF(profile=self.profile,sf=sf)
            else:
                plasma = {'r':sep['r'],'z':sep['z']}
                self.tf = TF(profile=self.profile)
            self.cage = coil_cage(nTF=self.profile.nTF,rc=self.tf.rc,
                                  plasma=plasma,ny=self.ny,alpha=self.alpha)
            x = self.tf.get_loops(self.loop.draw())
            self.cage.set_TFcoil(x['cl'],smooth=False)
        else:
            if self.profile.obj is 'E':
                errtxt = 'nTF and SFconfig keywords not set\n'
                errtxt += 'unable to calculate stored energy\n'
                errtxt += 'initalise with \'nTF\' keyword'
                raise ValueError(errtxt)
            
    def add_bound(self,x,side):
        for var in ['r','z']:
            self.bound[side][var] = np.append(self.bound[side][var],x[var])
        self.bindex[side].append(len(self.bound[side]['r']))
        
    def add_interior(self,r_gap=0.001):  # offset minimum internal radius
        argmin = np.argmin(self.bound['internal']['r'])
        self.add_bound({'r':self.bound['internal']['r'][argmin]-r_gap,
                        'z':self.bound['internal']['z'][argmin]},
                        'interior')  
            
    def add_vessel(self,vessel,npoint=80,offset=[0.12,0.2]):
        rvv,zvv = geom.rzSLine(vessel['r'],vessel['z'],npoint)
        rvv,zvv = geom.offset(rvv,zvv,offset[1])
        rmin = np.min(rvv)
        rvv[rvv<=rmin+offset[0]] = rmin+offset[0]
        self.add_bound({'r':rvv,'z':zvv},'internal')  # vessel
        self.add_bound({'r':np.min(rvv)-5e-3,'z':0},'interior')  # vessel
            
    def clear_bound(self):
        for side in self.bound:
            for var in ['r','z']:
                self.bound[side][var] = np.array([])
            
    def plot_bounds(self):
        for side,marker in zip(['internal','interior','external'],
                               ['.-','d','s']):
            index = self.bindex[side]
            for i in range(len(index)-1):
                pl.plot(self.bound[side]['r'][index[i]:index[i+1]],
                        self.bound[side]['z'][index[i]:index[i+1]],
                        marker,markersize=6,color=next(self.color))
  
    def minimise(self,verbose=False,ripple_limit=0.6,ripple=False,acc=0.002):
        tic = time.time()
        xnorm,bnorm = set_oppvar(self.loop.xo,self.loop.oppvar)  # normalize
        xnorm = fmin_slsqp(self.fit,xnorm,f_ieqcons=self.constraint_array,
                           bounds=bnorm,acc=acc,iprint=-1,
                           args=(False,ripple_limit))
        if ripple:  # re-solve with ripple constraint
            if self.profile.nTF == 'unset':
                raise ValueError('requre \'nTF\' to solve ripple constraint')
            print('with ripple')
            xnorm = fmin_slsqp(self.fit,xnorm,f_ieqcons=self.constraint_array,
                               bounds=bnorm,acc=acc,iprint=-1,
                               args=(True,ripple_limit))  
        xo = get_oppvar(self.loop.xo,self.loop.oppvar,xnorm)  # de-normalize
        if hasattr(self,'tf'):
            x = self.tf.get_loops(self.loop.draw(x=xo))  # update tf
            self.cage.set_TFcoil(x['cl'])  # update coil cage
        self.loop.set_input(x=xo)  # inner loop
        self.profile.write()  # store loop
        if verbose:
            self.toc(tic)

    def toc(self,tic):
        print('optimisation time {:1.1f}s'.format(time.time()-tic))
        print('noppvar {:1.0f}'.format(len(self.loop.oppvar)))
        if self.profile.nTF is not 'unset':
            self.cage.output()
            
    def constraint_array(self,xnorm,*args):
        ripple,ripple_limit = args
        xo = get_oppvar(self.loop.xo,self.loop.oppvar,xnorm)  # de-normalize
        if ripple:  # constrain ripple contour
            x = self.tf.get_loops(self.loop.draw(x=xo))  #npoints
            dot = np.array([])
            for side,key in zip(['internal','interior','external'],
                                ['in','in','out']):
                dot = np.append(dot,self.dot_diffrence(x[key],side))
            self.cage.set_TFcoil({'r':x['cl']['r'],'z':x['cl']['z']})
            max_ripple = self.cage.get_ripple()
            edge_ripple = self.cage.edge_ripple(npoints=10)
            dot = np.append(dot,ripple_limit-edge_ripple)
            dot = np.append(dot,ripple_limit-max_ripple)
        else:  # without tf object (no ripple or energy)
            x = self.loop.draw(x=xo)
            dot = self.dot_diffrence(x,'internal')
            dot = np.append(dot,self.dot_diffrence(x,'interior'))
        return dot
        
    def fit(self,xnorm,*args):
        xo = get_oppvar(self.loop.xo,self.loop.oppvar,xnorm)  # de-normalize
        if hasattr(self,'xo'):
            self.xo = np.vstack([self.xo,xo])
        else:
            self.xo = xo
        x = self.loop.draw(x=xo)
        if self.profile.obj is 'L':  # coil length
            objF = geom.length(x['r'],x['z'],norm=False)[-1]
        elif self.obj is 'E':  # stored energy
            x = self.tf.get_loops(x=x)
            self.cage.set_TFcoil(x['cl'])
            objF = 1e-9*self.cage.energy()
        else:  # coil volume
            objF = geom.loop_vol(x['r'],x['z'])
        return objF
   
    def dot_diffrence(self,x,side):
        Rloop,Zloop = x['r'],x['z']  # inside coil loop
        switch = 1 if side is 'internal' else -1
        nRloop,nZloop,Rloop,Zloop = geom.normal(Rloop,Zloop)
        R,Z = self.bound[side]['r'],self.bound[side]['z']
        dot = np.zeros(len(R))
        for j,(r,z) in enumerate(zip(R,Z)):
            i = np.argmin((r-Rloop)**2+(z-Zloop)**2)
            dr = [Rloop[i]-r,Zloop[i]-z]  
            dn = [nRloop[i],nZloop[i]]
            dot[j] = switch*np.dot(dr,dn)
        return dot
        
    def movie(self,filename):
        fig,ax = pl.subplots(1,2,figsize=(12,8))
        demo = DEMO()
        moviename = '../Movies/{}'.format(filename)
        moviename += '.mp4'
        FFMpegWriter = manimation.writers['ffmpeg']
        writer = FFMpegWriter(fps=20, bitrate=5000,codec='libx264',
                              extra_args=['-pix_fmt','yuv420p'])
        with writer.saving(fig,moviename,100): 
            nS = len(self.xo)
            to = time.time()
            width = 35
            for i,xo in enumerate(self.xo):
                self.frame(ax,demo,xo)
                writer.grab_frame()
        
                if i%1 == 0 and i > 0:
                    elapsed = time.time()-to
                    remain = int((nS-i)/i*elapsed)
                    prog_str = '\r{:1.0e}'.format(i)
                    prog_str += ' elapsed {:0>8}s'.format(str(\
                    datetime.timedelta(seconds=int(elapsed))))
                    prog_str += ' remain {:0>8}s'.format(str(\
                    datetime.timedelta(seconds=remain)))
                    prog_str += ' complete {:1.1f}%'.format(1e2*i/nS)
                    nh = int(i/nS*width)
                    prog_str += ' |'+nh*'#'+(width-nh)*'-'+'|'
                    sys.stdout.write(prog_str)
                    sys.stdout.flush()
                    
    def frames(self,filename):
        fig,ax = pl.subplots(1,2,figsize=(12,8))
        demo = DEMO()
        figname = '../Figs/{}'.format(filename)
        self.frame(ax,demo,xo=self.xo[0])
        pl.savefig(figname+'_s.png')
        self.frame(ax,demo,xo=self.xo[-1])
        pl.savefig(figname+'_e.png')
        
                
    def frame(self,ax,demo,**kwargs):
        xo = kwargs.get('xo',self.xo[-1])
        pl.sca(ax[0])
        #pl.cla()
        pl.plot([3,18],[-10,10],'ko',alpha=0)
        demo.fill_part('Blanket')
        demo.fill_part('Vessel')
        
        self.loop.set_input(x=xo)
        #self.plot_bounds()
        self.update()
        #self.tf.fill()
        geom.polyfill(self.cage.plasma_loop[:,0],
                      self.cage.plasma_loop[:,2],
                      alpha=0.3,color=sns.color_palette('Set2',5)[3])
        #self.cage.plot_loops(sticks=False)
        if len(ax) > 1:
            pl.sca(ax[1])
            pl.cla()
            plot_oppvar(shp.loop.xo,shp.loop.oppvar)
Ejemplo n.º 6
0
class SALOME(object):
    def __init__(self, config, family='S', nTF=16, obj='L'):
        self.nTF = nTF
        self.config = config
        datadir = trim_dir('../../Data')
        file = 'salome_input'  #  config #  +'_{}{}{}'.format(family,nTF,obj)
        self.filename = datadir + '/' + file + '.json'
        self.profile = Profile(config['TF'],
                               family=family,
                               load=True,
                               part='TF',
                               nTF=nTF,
                               obj=obj,
                               npoints=250)
        setup = Setup(config['eq'])
        self.sf = SF(setup.filename)
        self.tf = TF(self.profile, sf=self.sf)
        self.pf = PF(self.sf.eqdsk)
        self.PF_support()  # calculate PF support seats
        self.CS_support()  # calculate CS support seats
        self.Gravity_support()
        self.cage = coil_cage(nTF=nTF,
                              rc=self.tf.rc,
                              ny=3,
                              plasma={'config': config['eq']},
                              coil=self.tf.x['cl'])
        self.eq = EQ(self.sf,
                     self.pf,
                     dCoil=0.5,
                     sigma=0,
                     boundary=self.sf.get_sep(expand=0.5),
                     n=1e3)
        self.eq.plasma()
        self.ff = force_feild(self.pf.index, self.pf.coil, self.eq.coil,
                              self.eq.plasma_coil)

    def write(self):
        print('writing', self.filename, self.nTF)
        color = sns.color_palette('Set2', 12)
        data = {
            'p': self.profile.loop.p,
            'section': self.tf.section,
            'pf': self.pf.coil,
            'nTF': self.nTF,
            'color': color,
            'PFsupport': self.PFsupport,
            'CSsupport': self.CSsupport,
            'Gsupport': self.Gsupport,
            'OISsupport': self.OISsupport
        }

        with open(self.filename, 'w') as f:
            json.dump(data, f, indent=4)

    def CS_support(self):
        depth = self.tf.section['winding_pack']['depth']
        side = self.tf.section['case']['side']
        width = self.tf.section['winding_pack']['width']
        inboard = self.tf.section['case']['inboard']
        nose = self.tf.section['case']['nose']
        segment = self.profile.loop.p[0]
        ro, zo = segment['p0']['r'], segment['p0']['z']
        theta = np.pi / self.nTF
        rsep = (depth / 2 + side) / np.tan(theta)
        rnose = ro - (width + inboard + nose)
        rwp = ro - (width + inboard)
        if rsep <= rnose:
            ynose = depth / 2 + side
        else:
            ynose = rnose * np.tan(theta)
        if rsep <= rwp:
            ywp = depth / 2 + side
        else:
            ywp = rwp * np.tan(theta)

        self.tf.loop_interpolators(offset=0)  # construct TF interpolators
        TFloop = self.tf.fun['out']
        L = minimize_scalar(SALOME.cs_top,
                            method='bounded',
                            args=(rwp, TFloop),
                            bounds=[0.5, 1]).x
        ztop = float(TFloop['z'](L))
        self.CSsupport = {
            'rnose': rnose,
            'ynose': ynose,
            'rwp': rwp,
            'ywp': ywp,
            'ztop': ztop,
            'zo': zo,
            'dt': side
        }

    def cs_top(L, rwp, TFloop):
        err = abs(TFloop['r'](L) - rwp)
        return err

    def support_arm(L, coil, TFloop):
        dl = np.sqrt((coil['r'] - TFloop['r'](L))**2 +
                     (coil['z'] - TFloop['z'](L))**2)
        return dl

    def intersect(x, xc, nhat, TFloop):
        L, s = x  # unpack
        rTF, zTF = TFloop['r'](L), TFloop['z'](L)
        rs, zs = s * nhat + xc
        err = np.sqrt((rTF - rs)**2 + (zTF - zs)**2)
        return err

    def connect(self, coil, loop, edge=0.15, hover=0.1, argmin=60):
        L = minimize_scalar(SALOME.support_arm,
                            method='bounded',
                            args=(coil, loop),
                            bounds=[0, 1]).x
        rTF, zTF = loop['r'](L), loop['z'](L)
        nhat = np.array([rTF - coil['r'], zTF - coil['z']])
        ndir = 180 / np.pi * np.arctan(abs(nhat[1] / nhat[0]))  # angle, deg
        if ndir < argmin:  # limit absolute support angle
            nhat = np.array([
                np.sign(nhat[0]),
                np.tan(argmin * np.pi / 180) * np.sign(nhat[1])
            ])
        nhat /= np.linalg.norm(nhat)
        above = np.sign(np.dot(nhat, [0, 1]))
        zc = coil['z'] + above * (coil['dz'] / 2 + hover)
        nodes = [[] for _ in range(4)]
        for i, sign in enumerate([-1, 1]):  #  inboard / outboard
            rc = coil['r'] + sign * (coil['dr'] / 2 + edge)
            nodes[i] = [rc, zc]
            xc = np.array([rc, zc])
            xo = np.array([L, 0.5])
            res = minimize(SALOME.intersect,
                           xo,
                           method='L-BFGS-B',
                           bounds=([0, 1], [0, 15]),
                           args=(xc, nhat, loop))
            rs, zs = res.x[1] * nhat + xc
            nodes[3 - i] = [rs, zs]
        return nodes

    def PF_support(self):
        self.tf.loop_interpolators(offset=-0.15)  # construct TF interpolators
        TFloop = self.tf.fun['out']
        self.PFsupport = {}
        for name in self.pf.index['PF']['name']:
            coil = self.pf.coil[name]
            nodes = self.connect(coil, TFloop, edge=0.15, hover=0.1, argmin=60)
            self.PFsupport[name] = nodes

    def GS_placement(L, radius, TFloop):
        return abs(radius - TFloop['r'](L))

    def Gravity_support(self, radius=13, width=0.75):
        self.tf.loop_interpolators(offset=-0.15)  # construct TF interpolators
        TFloop = self.tf.fun['out']
        self.tf.loop_interpolators(offset=0)
        Sloop = self.tf.fun['out']
        L = minimize_scalar(SALOME.GS_placement,
                            method='bounded',
                            args=(radius - width / 2, Sloop),
                            bounds=[0, 0.5]).x
        coil = {
            'r': Sloop['r'](L) + width / 2,
            'z': Sloop['z'](L) - width / 2,
            'dr': width,
            'dz': width
        }
        nodes = self.connect(coil, TFloop, edge=0, hover=0, argmin=90)
        self.Gsupport = {'base': nodes}
        z = [[self.pf.coil[name]['z']-self.pf.coil[name]['dz']/2]\
             for name in self.pf.coil]
        floor = np.min(z) - 1
        self.Gsupport['zbase'] = float(Sloop['z'](L))
        self.Gsupport['zfloor'] = floor
        self.Gsupport['radius'] = radius
        self.Gsupport['width'] = width

    def OIS_placment(L, TFloop, point):
        err = (point[0] - TFloop['r'](L))**2 + (point[1] - TFloop['z'](L))**2
        return err

    def draw_OIS(self, L, width, thickness, TFloop):
        dl = width / TFloop['L']
        rcl = np.array([TFloop['r'](L - dl / 2), TFloop['r'](L + dl / 2)])
        zcl = np.array([TFloop['z'](L - dl / 2), TFloop['z'](L + dl / 2)])
        ro, zo = np.mean(rcl), np.mean(zcl)
        L = minimize_scalar(SALOME.OIS_placment,
                            method='bounded',
                            args=(TFloop, (ro, zo)),
                            bounds=[0, 1]).x
        dr, dz = TFloop['r'](L) - ro, TFloop['z'](L) - zo
        rcl += dr / 2
        zcl += dz / 2
        dt = np.array([rcl[1] - rcl[0], 0, zcl[1] - zcl[0]])
        dt /= np.linalg.norm(dt)
        dn = np.cross(dt, np.array([0, 1, 0]))

        rcl = np.append(rcl + dn[0] * thickness / 2,
                        rcl[::-1] - dn[0] * thickness / 2)
        zcl = np.append(zcl + dn[2] * thickness / 2,
                        zcl[::-1] - dn[2] * thickness / 2)
        nodes = [[rcl[i], zcl[i]] for i in range(4)]
        return nodes

    def OIS(self, width=3.5, thickness=0.15, rmin=10):
        self.tf.loop_interpolators(offset=0)  # construct TF interpolators
        TFloop = self.tf.fun['cl']
        self.OISsupport = {}
        for i, (L, width) in enumerate(zip([0.4, 0.64], [4.5, 2.5])):
            nodes = self.draw_OIS(L, width, thickness, TFloop)
            self.OISsupport['OIS{:d}'.format(i)] = nodes

    def plot(self):
        self.tf.fill()
        self.pf.plot(coils=self.pf.coil, label=True, current=True)
        self.pf.plot(coils=self.eq.coil, plasma=True)
        for name in self.PFsupport:
            nodes = np.array(self.PFsupport[name])
            geom.polyfill(nodes[:, 0], nodes[:, 1], color=0.4 * np.ones(3))
        nodes = np.array(self.Gsupport['base'])
        geom.polyfill(nodes[:, 0], nodes[:, 1], color=0.4 * np.ones(3))
        pl.plot(self.Gsupport['radius'] * np.ones(2),
                [self.Gsupport['zbase'], self.Gsupport['zfloor']],
                'o-',
                color=0.4 * np.ones(3),
                lw=4)
        for name in self.OISsupport:
            nodes = np.array(self.OISsupport[name])
            geom.polyfill(nodes[:, 0], nodes[:, 1], color=0.4 * np.ones(3))
        rnose = self.CSsupport['rnose']
        rwp = self.CSsupport['rwp']
        zo = self.CSsupport['zo']
        ztop = self.CSsupport['ztop']
        rCS = [rnose, rwp, rwp, rnose]
        zCS = [zo, zo, ztop, ztop]
        geom.polyfill(rCS, zCS, color=0.4 * np.ones(3))

    def ansys(self, plot=False, nl=250, nr=5, ny=5):
        filename = '../../Data/TFload_{:d}'.format(self.nTF)
        ans = table(filename)
        ans.f.write('! loading tables for {:d}TF coil concept\n'.format(
            self.nTF))
        ans.f.write('! loop length parameterized from 0-1\n')
        ans.f.write('! loop starts at the inboard midplane\n')
        ans.f.write('! loop progresses in the anti-clockwise direction\n')
        ans.f.write('! tables defined with cylindrical coordinate system\n')
        ans.f.write(
            '! body applied to nodes of winding-pack in cartisean system x,y,z\n'
        )
        ans.f.write(
            '! winding-pack must be labled as named-selection \'wp\'\n')
        ans.f.write('\nlocal,11,1,{:1.9f},0,{:1.9f},0,90,0'\
                    .format(self.sf.mo[0],self.sf.mo[1]))
        ans.f.write('  ! define local cylindrical coordinate system\n')
        ans.f.write('csys,0  ! restore to cartesian\n')

        ans.f.write('\n! per-TF PF coil forces (Fr,Fz) [N]\n')
        ans.f.write('! order as numbered in plots\n')
        F = self.ff.get_force()['F']
        ans.load('F_coil', F / self.nTF)
        ans.write_array()
        ans.f.write('\n/nopr  ! suppress large table output\n')

        self.tf.loop_interpolators(offset=0,
                                   full=True)  # construct TF interpolators
        TFloop = self.tf.fun['cl']

        ngrid = {'nr': 20, 'nt': 150}  #  coordinate interpolation grid
        ndata = {
            'nl': nl,
            'nr': nr,
            'ny': ny
        }  #  coordinate interpolation grid
        l = np.linspace(0, 1, 250)  # calculate grid extent
        xin, zin = self.tf.fun['in']['r'](l), self.tf.fun['in']['z'](l)
        rin = np.sqrt((xin - self.sf.mo[0])**2 + (zin - self.sf.mo[1])**2)
        rmin = np.min(rin)  # minimum radius
        xout, zout = self.tf.fun['out']['r'](l), self.tf.fun['out']['z'](l)
        rout = np.sqrt((xout - self.sf.mo[0])**2, (zout - self.sf.mo[1])**2)
        rmax = np.max(rout)  # maximum radius

        radius = np.linspace(rmin, rmax, ngrid['nr'])
        theta = np.linspace(-np.pi, np.pi, ngrid['nt'])
        l_map = np.zeros((ngrid['nr'], ngrid['nt']))
        dr_map = np.zeros((ngrid['nr'], ngrid['nt']))
        for i in range(ngrid['nr']):
            for j in range(ngrid['nt']):
                x = self.sf.mo[0] + radius[i] * np.cos(theta[j])
                z = self.sf.mo[1] + radius[i] * np.sin(theta[j])
                L = minimize_scalar(SALOME.OIS_placment,
                                    method='bounded',
                                    args=(TFloop, (x, z)),
                                    bounds=[0, 1]).x
                xl, zl = TFloop['r'](L), TFloop['z'](L)
                l_map[i, j] = L
                dr_map[i,j] = np.sqrt((x-xl)**2+(z-zl)**2)*\
                np.sign(np.dot([x-xl,z-zl],[x-self.sf.mo[0],z-self.sf.mo[1]]))

        width = self.tf.section['winding_pack']['width']
        depth = self.tf.section['winding_pack']['depth']
        cross_section = width * depth
        l_data = np.linspace(0, 1, ndata['nl'])
        if ndata['nr'] > 1:
            dr_data = np.linspace(-width / 2, width / 2, ndata['nr'])
        else:
            dr_data = np.array([0])
        if ndata['ny'] > 1:
            dy_data = np.linspace(-depth / 2, depth / 2, ndata['ny'])
        else:
            dy_data = np.array([0])
        Fbody = {}
        for var in ['x', 'y', 'z']:
            Fbody[var] = np.zeros((ndata['nl'], ndata['nr'], ndata['ny']))

        self.tf.loop_interpolators(offset=0, full=True)  # centreline
        Jturn = self.cage.Iturn / cross_section
        for i, l in enumerate(l_data):
            iter_str = '\rcalculating TF body force:'
            iter_str += 'segment {:d} of {:d}'.format(i, ndata['nl'])
            sys.stdout.write(iter_str)
            sys.stdout.flush()
            xo = self.tf.fun['cl']['r'](l)
            zo = self.tf.fun['cl']['z'](l)
            dxo = self.tf.fun['cl']['dr'](l)
            dzo = self.tf.fun['cl']['dz'](l)
            that = np.array([dxo, 0, dzo])
            that /= np.linalg.norm(that)
            J = Jturn * that  # current density vector
            nhat = np.array([that[2], 0, -that[0]])
            for j, dr in enumerate(dr_data):
                for k, dy in enumerate(dy_data):
                    point = np.array([xo, dy, zo]) + dr * nhat
                    Fb = self.ff.topple(point,
                                        J,
                                        self.cage,
                                        self.eq.Bpoint,
                                        method='BS')  # body force
                    for m, var in enumerate(['x', 'y', 'z']):  # store
                        Fbody[var][i, j, k] = Fb[m]
                    if plot:
                        Fvec = Fb / np.linalg.norm(Fb)
                        Fvec = that
                        pl.arrow(point[0],
                                 point[2],
                                 Fvec[0],
                                 Fvec[2],
                                 head_width=0.15,
                                 head_length=0.3)
        print('\n',
              np.sum(Fbody['x'][:-1, :, :]) * 1e-9,
              np.sum(Fbody['y'][:-1, :, :]) * 1e-9,
              np.sum(Fbody['z'][:-1, :, :]) * 1e-9)

        ans.f.write('\n! parametric coil length, fn(theta)\n')
        ans.load('l_map', l_map, [radius, theta])
        ans.write(['radus', 'theta'])
        ans.f.write('\n! parametric coil offset, fn(theta)\n')
        ans.load('dr_map', dr_map, [radius, theta])
        ans.write(['radus', 'theta'])
        for var in ['x', 'y', 'z']:
            ans.f.write(
                '\n! winding-pack body force, Fbody_{} [N/m3]\n'.format(var))
            ans.load('Fbody_{}'.format(var), Fbody[var],
                     [l_data, dr_data, dy_data])
            ans.write(['l_map', 'dr_map', 'offset'])
        ans.f.write('/gopr  ! enable output\n')

        apdlstr = '''
pi = 4*atan(1)
csys,11  ! switch to cylindrical coordinate system
esel,s,elem,,wp  ! select winding pack (requires named selection 'wp')
*get,nel,elem,0,count
*vget,el_sel,elem,,esel  ! selection mask
*vget,el_id,elem,,elist  ! winding pack selection array
*vget,el_vol,elem,,geom  ! element volume
*vget,el_radius,elem,,cent,x  ! element radius
*vget,el_theta,elem,,cent,y  ! element theta
*vget,el_offset,elem,,cent,z  ! element axial offset
*voper,el_theta,el_theta,mult,pi/180  ! convert to radians
csys,0  ! return coordinate system

! compress selections
*dim,el_v,array,nel
*dim,el_r,array,nel
*dim,el_t,array,nel
*dim,el_o,array,nel
*dim,el_l,array,nel
*dim,el_dr,array,nel

*vmask,el_sel
*vfun,el_v,comp,el_vol  ! volume
*vmask,el_sel
*vfun,el_r,comp,el_radius  ! radius
*vmask,el_sel
*vfun,el_t,comp,el_theta  ! theta
*vmask,el_sel
*vfun,el_o,comp,el_offset  ! offset
*vitrp,el_l,l_map,el_r,el_t  ! interpolate l_map table
*vitrp,el_dr,dr_map,el_r,el_t !  interpolate dr_map table

xyz = 'x','y','z'  ! axes
fcum,add  ! accumulate nodal forces
*do,i,1,nel  ! apply forces to loads
  esel,s,elem,,el_id(i)
  nsle  ! select nodes attached to element
  nsel,r,node,,wp  ! ensure all nodes from winding pack
  *get,nnd,node,0,count  ! count nodes
  *do,j,1,3  ! Fx,Fy,Fz - all nodes attached to element
      F,all,F%xyz(j)%,Fbody_%xyz(j)%(el_l(i),el_dr(i),el_o(i))*el_v(i)*el_v(i)/nnd
  *enddo
*enddo
allsel  
        '''
        ans.f.write(apdlstr)
        ans.close()
Ejemplo n.º 7
0
sns.set(context='paper',
        style='white',
        font='sans-serif',
        palette='Set2',
        font_scale=7 / 8,
        rc=rc)
Color = cycle(sns.color_palette('Set2'))

nTF = 18  #,nPF,nCS = 18,6,5
config = {'TF': 'dtt', 'eq': 'SFp'}
config, setup = select(config, nTF=nTF, update=False)  # nPF=nPF,nCS=nCS

sf = SF(setup.filename)
rb = RB(setup, sf)
pf = PF(sf.eqdsk)
tf = TF(
    Profile(config['TF'], family='S', part='TF', nTF=nTF, obj='L', load=True))
rb.firstwall(symetric=True, DN=True, plot=True)
#pf.plot(coils=pf.coil,label=False,plasma=False,current=True)
tf.fill()

#sf.cpasma *= 1.1
eq = EQ(sf, pf, dCoil=1.5, sigma=0, boundary=sf.get_sep(expand=1.1), n=3e3)
eq.gen_bal()
#eq.gen_opp()

sf.contour()

inv = INV(sf, eq, tf)
L = inv.grid_coils(offset=0.3)
#pf.plot(coils=pf.coil,label=False,plasma=False,current=True)
Ejemplo n.º 8
0
import numpy as np
from DEMOxlsx import DEMO
from nova.coils import TF
from amigo import geom
import pylab as pl
import seaborn as sns

tf = TF('DEMO_SN', coil_type='S', nTF=16, objective='L', npoints=5000)
x = tf.coil.draw()
r, z = x['r'], x['z']
l = geom.length(r, z)
dl = np.mean(np.diff(l))

dr = np.gradient(r, dl)
dz = np.gradient(z, dl)
ddr = np.gradient(dr, dl)
ddz = np.gradient(dz, dl)

Rv, Zv = tf.coil.verticies()[:2]

index = np.zeros(len(Rv), dtype=int)
for i, (rv, zv) in enumerate(zip(Rv, Zv)):
    index[i] = np.argmin((r - rv)**2 + (z - zv)**2)

tf.coil.plot()

pl.figure(figsize=(10, 7))
k = (dr * ddz - dz * ddr) / (dr**2 + dz**2)**(3 / 2)
pl.plot(l, k)
pl.plot(l[index], k[index], 's')
pl.xlabel('normalised length (anit-clockwise from inboard midplane)')
Ejemplo n.º 9
0
        'lines.linewidth': 1.5
    }
    sns.set(context='poster',
            style='white',
            font='sans-serif',
            palette='Set2',
            font_scale=7 / 8,
            rc=rc)
    color = sns.color_palette('Set2')

    demo = DEMO()
    demo.fill_loops()

    config = 'DEMO_SN'

    tf = TF(config, coil_type='S', npoints=80)

    #tf.coil.set_input(inputs={'upper':0.8,'top':0.5})

    x = tf.coil.draw()
    tf.get_loops(x)
    tf.fill()

    cage = coil_cage(nTF=18,
                     rc=tf.rc,
                     plasma={'config': config},
                     coil={'cl': tf.x['cl']})

    tic = time.time()
    print('ripple {:1.3f}%'.format(cage.get_ripple()))
    print('time {:1.3f}s'.format(time.time() - tic))
Ejemplo n.º 10
0
name = 'SX'

nTF, ripple = 18, True
base = {'TF': 'dtt', 'eq': 'DTT_SN', 'name': name}
config, setup = select(base, nTF=nTF, update=False)

sf = SF(setup.filename)
pf = PF(sf.eqdsk)

for coil in pf.index['CS']['name']:
    pf.coil[coil]['r'] = 2.7
    pf.coil[coil]['dr'] = 0.8

profile = Profile(config['TF'], family='S', part='TF', nTF=nTF, obj='L')
tf = TF(profile=profile, sf=sf)
#tf.adjust_xo('dz',value=-2)
#tf.fill()

eq = EQ(sf,
        pf,
        dCoil=2.0,
        sigma=0,
        boundary=sf.get_sep(expand=1.0),
        zmin=-10,
        n=2e3)

inv = INV(pf, tf, dCoil=0.25)
inv.load_equlibrium(sf)

inv.fix_boundary()
Ejemplo n.º 11
0
        font_scale=7 / 8,
        rc=rc)
Color = cycle(sns.color_palette('Set2'))

base = {'TF': 'dtt', 'eq': 'DN'}
config, setup = select(base=base, update=False, nTF=18, nPF=4, nCS=3)

config['TF'] = config['TF'].replace('DN', 'SN')

sf = SF(setup.filename)
rb = RB(setup, sf)
pf = PF(sf.eqdsk)
tf = TF(
    Profile(config['TF'],
            family='S',
            part='TF',
            nTF=config['nTF'],
            obj='L',
            load=True))
#tf.fill()

eq = EQ(sf,
        pf,
        dCoil=1.5,
        sigma=0,
        n=5e3,
        boundary=sf.get_sep(expand=1.1),
        zmin=-abs(sf.Xpoint[1]) - 2,
        zmax=abs(sf.Xpoint[1]) + 2)
#eq.gen_opp(Zerr=5e-4)
eq.gen_bal(Zerr=5e-4, tol=1e-4)
Ejemplo n.º 12
0
rc = {'figure.figsize':[8*10/16,8],'savefig.dpi':150, #*12/16
      'savefig.jpeg_quality':100,'savefig.pad_inches':0.1,
      'lines.linewidth':0.75}
sns.set(context='paper',style='white',font='sans-serif',palette='Set2',
        font_scale=7/8,rc=rc)

nTF = 16
config = {'TF':'SN','eq':'DEMO_SNb'}
          

profile = Profile(config['TF'],family='S',load=True,part='TF',
                       nTF=nTF,obj='L',npoints=250)
setup = Setup(config['eq'])
sf = SF(setup.filename)
tf = TF(profile,sf=sf)   
pf = PF(sf.eqdsk)
rb = RB(setup,sf)

cage = coil_cage(nTF=nTF,rc=tf.rc,plasma={'config':config['eq']},coil=tf.x['cl'])
 
demo = DEMO()
demo.fill_part('Vessel')
demo.fill_part('Blanket')
demo.fill_part('TF_Coil')
demo.plot_ports()
demo.plot_limiter()  

sf.contour(Nlevel=51,plot_vac=False,lw=0.5)
pl.plot(sf.rbdry,sf.zbdry,color=0.75*np.ones(3),lw=1)
Ejemplo n.º 13
0
        rc=rc)
Color = cycle(sns.color_palette('Set2'))

nTF, nPF, nCS = 18, 6, 5
config = {'TF': 'demo', 'eq': 'SN'}  # SN2017_SOF
config, setup = select(config, nTF=nTF, nPF=nPF, nCS=nCS, update=False)

sf = SF(setup.filename)

print('b', sf.eqdsk['bcentr'], 'r', sf.eqdsk['rcentr'], 'br',
      sf.eqdsk['bcentr'] * sf.eqdsk['rcentr'])

rb = RB(setup, sf)
pf = PF(sf.eqdsk)
profile = Profile(config['TF'], family='S', part='TF', nTF=nTF, obj='L')
tf = TF(profile=profile)

#pf.plot(coils=pf.coil,label=False,plasma=False,current=True)

demo = DEMO()
demo.fill_part('Vessel')
demo.fill_part('Blanket')
#demo.fill_part('TF_Coil')
demo.plot_ports()
demo.plot_limiter()

pl.axis('off')
tf.fill()

eq = EQ(sf, pf, dCoil=1.5, sigma=0, boundary=sf.get_sep(expand=1.5), n=5e3)
eq.gen_opp()
Ejemplo n.º 14
0
from nova.loops import Profile
from nova.force import force_feild
import seaborn as sns
rc = {'figure.figsize':[8*12/16,8],'savefig.dpi':120, # 
      'savefig.jpeg_quality':100,'savefig.pad_inches':0.1,
      'lines.linewidth':2}
sns.set(context='talk',style='white',font='sans-serif',palette='Set2',
        font_scale=7/8,rc=rc)

nTF,nPF,nCS = 18,4,3
config = {'TF':'dtt','eq':'SN'}
config,setup = select(config,nTF=nTF,nPF=nPF,nCS=nCS,update=False)
profile = Profile(config['TF'],family='S',part='TF',
                  nTF=nTF,obj='L',load=True,npoints=50)
sf = SF(setup.filename)
tf = TF(profile,sf=sf)
tf.fill()

#rb = RB(setup,sf)
pf = PF(sf.eqdsk)
eq = EQ(sf,pf,boundary=tf.get_loop(expand=0.5),n=1e3,sigma=0)  
eq.get_plasma_coil()
ff = force_feild(pf.index,pf.coil,eq.coil,eq.plasma_coil)
        
#eq.run()
#eq.plotj()
#pf.coil['Coil6']['r'] -= 1.5
#eq.coils()
#eq.gen_opp(sf.Mpoint[1])
#eq.resample()
#eq.plotb(alpha=1)
Ejemplo n.º 15
0
from nova.coils import PF, TF
from time import time
from nova import loops
import scipy.optimize as op
from amigo.addtext import linelabel
from nova.loops import Profile

config = 'SN'
setup = Setup(config)

sf = SF(setup.filename)
rb = RB(setup, sf)
pf = PF(sf.eqdsk)

profile = Profile(config, family='S', part='TF', nTF=18, objective='L')
tf = TF(profile)

eq = EQ(sf, pf, dCoil=2.5, sigma=0, boundary=sf.get_sep(expand=0.5), n=5e2)
eq.get_plasma_coil()
eq.run(update=False)

inv = INV(sf, eq, tf)
inv.initialize_log()

Lpf = inv.grid_PF(nPF=5)
Lcs = inv.grid_CS(nCS=5)
Lo = np.append(Lpf, Lcs)
inv.update_coils()

inv.fit_PF(offset=0.3)