示例#1
0
def get_bfield(ys, zlocs):
    sources = {}

    for i in range(11):
        if i in range(6, 9):
            sources['{}tr'.format(i)] = Cylmag(
                loc=[xoffset, ylocs[i], zlocs[i] + zoffset], ori=oris[i])
            sources['{}br'.format(i)] = Cylmag(
                loc=[-xoffset, ylocs[i], zlocs[i] + zoffset], ori=oris[i])
            sources['{}tl'.format(i)] = Cylmag(
                loc=[xoffset, ylocs[i], -zlocs[i] - zoffset], ori=oris[i])
            sources['{}bl'.format(i)] = Cylmag(
                loc=[-xoffset, ylocs[i], -zlocs[i] - zoffset], ori=oris[i])
        else:
            sources['{}r'.format(i)] = Cylmag(
                loc=[0, ylocs[i], zlocs[i] + zoffset], ori=oris[i])
            sources['{}l'.format(i)] = Cylmag(
                loc=[0, ylocs[i], -zlocs[i] - zoffset], ori=oris[i])

    C = magpy.Collection()

    for sc in sources:
        C.addSources(sources[sc])

    Y = [[0, y, 0] for y in ys]
    BZy = C.getBsweep(Y)  # mT

    return BZy[:, 2] * 10.0
示例#2
0
    def PlaceMagnets(self):

        self.magnets = []
        self.sensors = []

        init_linspace = np.linspace(0,self.chain._segment_count-1,num=self.chain._segment_count)
        init_pose = self.chain.GetPoints(init_linspace)
        init_orient = self.chain.GetOrientations(init_linspace)

        final_linspace = np.linspace(1,self.chain._segment_count,num=self.chain._segment_count)
        final_pose = self.chain.GetPoints(final_linspace)
        final_orient = self.chain.GetOrientations(final_linspace)

        for i in range(self.chain._segment_count):
            #Put sensor at end of line segment
            if(isinstance(self.chain._segments[i],LineSegment)):
                self.sensors.append(magpy.Sensor(pos=init_pose[i],axis=[0,1,0],angle=90))

                rotvec_orient = init_orient[i].as_rotvec()
                if np.array_equal(init_orient[i].apply([1.,0.,0.]),[1.,0.,0.]) is False and np.sum(np.absolute(rotvec_orient)) is not 0:
                    self.sensors[len(self.sensors)-1].rotate(axis=rotvec_orient,angle=(np.linalg.norm(rotvec_orient)*180)/np.pi)
                    f

            #Put magnet at end of chain
            if(isinstance(self.chain._segments[i],CircleSegment)):
                self.magnets.append(Box(mag=self.magnetization,dim=self.dimension,pos=final_pose[i],axis=[0,1,0],angle=90))

                rotvec_orient = final_orient[i].as_rotvec()
                if np.array_equal(final_orient[i].apply([1.,0.,0.]),[1.,0.,0.]) is False and np.sum(np.absolute(rotvec_orient)) is not 0:
                    self.magnets[len(self.magnets)-1].rotate(axis=rotvec_orient,angle=(np.linalg.norm(rotvec_orient)*180)/np.pi)

        self.collection = magpy.Collection(self.magnets)
        return self.collection
示例#3
0
    def clearAll(self):
        '''
		Required for looping through different shapes
		'''

        self.data[0].dot_positions.clear()
        self.data[0].u_mag_positions.clear()
        self.data[0].magnetisation = tuple()
        self.data[0].ext_field = tuple()
        self.data[0].magnet_collection.qubit_positions = list()
        self.data[0].magnet_collection.qubit_positions.clear()
        self.data[0].magnet_collection.magnets = list()
        self.data[0].magnet_collection.magnets.clear()
        self.data[0].magnet_collection.coll = magpy.Collection()

        self.data[0].magnet_collection: any = None

        return None
#4-coil config
coil0 = magpy.source.current.Line(curr=I * 26, vertices=squarePts)
coil1 = magpy.source.current.Line(curr=I * 11, vertices=squarePts)
coil2 = magpy.source.current.Line(curr=I * 11, vertices=squarePts)
coil3 = magpy.source.current.Line(curr=I * 26, vertices=squarePts)

coil0.move([0, 0, .5055 * d])
coil1.move([0, 0, .1281 * d])
coil2.move([0, 0, -.1281 * d])
coil3.move([0, 0, -.5055 * d])

#ensuring d=a for homogenous magnetic field from hemoltz coils
#s1.move([0,0,a/2.])
#s2.move([0,0,-a/2.])

c = magpy.Collection(coil0, coil1, coil2, coil3)

#magpy.displaySystem(c,direc=True)

r = [[0, 0, z] for z in np.linspace(-d, d, 100)]

r = np.asarray(r)
Bfield = c.getB(r) * 10.  #convert from mT to guass
Bfield = Bfield / (c.getB([0, 0, 0])[2] * 10)

print(c.getB([0, 0, 0])[2] * 10)

plt.plot(r[:, 2] / d, Bfield[:, 2])  #plot z comp of field along z axis
plt.show()

# # create positions
示例#5
0
 def __init__(self):
     self.coll = magpy.Collection()
     self.magnets = list()
     self.qubit_positions = list()
    Bcenter = zCoil.getB([0, 0, 0.000001])

    print('\nFor "z", getB([0,0,0]) = ', Bcenter, ' mT:')
    print('Internal Distance between coil = ', zCoilIntDiameter / 2, ' mm')
    print('Coil internal diameter = ', zCoilIntDiameter, ' mm')
    print('Coil width = ', (AllCoilsWireDiameter * zLoopsInEachEvenLayer),
          'mm')
    print('min Coil height = ', (zCoilExtDiameter - zCoilIntDiameter), 'mm')
    print('Coil resistence ~= ' + str(zCoilResistence) + ' ohms')
    print('Coil power dissipation ~= ' + str(zCoilMaxPower) + ' W')
    print('Wire lenght necessary to construct the coil ~= ' +
          str(zWireLenghtMeters) + ' m')

    singleCoilWidth = 0

    connectorsCollection = magpy.Collection()
    connectorsCollection = constructAccess(
        I=zCoilCurrent,
        coilExtDiameter=zCoilExtDiameter,
        wireDiameter=AllCoilsWireDiameter,
        centralPointBetweenHelmCoils=[0, 0, 0],
        lengthBetweenCoils=zCoilIntDiameter / 2,
        singleCoilWidth=singleCoilWidth,
        helmCoil=connectorsCollection,
        relativeDistance=relativeDistance)

# ------------------------------------------------------------------------------------------------------------------------------------------------
#%% DESIGN OF THE SECOND HELMHOLTZ COIL ('y') -----------------------------------------------------------------------------------------------
if YDESIGN:

    yCoil, yCoilIntDiameter, yCoilExtDiameter, yCoilResistence, yCoilMaxPower, yWireLenghtMeters = coilDesign(
def coil(color='k',
         I=1,
         coilIntDiameter=1,
         referencePosition=[0, 0, 0],
         wireDiameter=1,
         loopsInEachEvenLayer=1,
         evenLayers=1,
         oddLayers=1,
         collectionToAdd=magpy.Collection()):
    """ 
    Return the model of a rolled coil around the 'z' axis.
    
    Parameters
    ----------
    I : float
        The Coil Current in Amperes.
    coilIntDiameter : {non-zero int}
        The Diameter of the coil's inner loops, in mm.
    referencePosition : List, default [0,0,0]
        A List containing 3 coordinates.
    wireDiameter : float, default 1
        Diameter of the coil wire in mm.
    loopsInEachEvenLayer : non-zero integer, default 1 
        How many loops in a single even layer
    evenLayers : integer, default 1
        Integer number of even layers.
    oddLayers : integer, default 1
        Integer number of odd layers.
    collectionToAdd : Magpy Collection, default empty
        Append coil source to a magpy collection.
    
    Example
    ---------
    test = coil(I = 4, coilIntDiameter = 77.26 , referencePosition=[0,0,0], wireDiameter=1.59, 
                loopsInEachEvenLayer=3, evenLayers = 3, oddLayers = 3, collectionToAdd = magpy.Collection())
    test.displaySystem()
    
    """

    # Initialization for the loop
    even = True  # Flag if the coil rolling is in even format
    singleCoilWidth = wireDiameter * loopsInEachEvenLayer
    centerPosition = referencePosition[
        2]  # The center position of the coil in Z
    initPosEven = centerPosition - singleCoilWidth / 2 + wireDiameter / 2  # Initial position in the 'even' form of rolling the coil
    initPosOdd = centerPosition - singleCoilWidth / 2 + wireDiameter  # Initial position in the 'odd' form of rolling the coil
    stepPos = wireDiameter  # The position increment
    finalPosEven = centerPosition + singleCoilWidth / 2 - wireDiameter / 2 + stepPos  # Final position in the 'even' form of rolling the coil
    finalPosOdd = centerPosition + singleCoilWidth / 2 - wireDiameter + stepPos  # Final position in the 'odd' form of rolling the coil
    stepDiameter = 2 * (wireDiameter**2 -
                        (wireDiameter / 2)**2)**0.5  # The diameter increment
    subLoops = np.int64(
        singleCoilWidth / wireDiameter
    )  # The max value of the loops in the 'even' rolling, the odd max value is (subLoops - 1)
    coilIntDiameter += wireDiameter

    if loopsInEachEvenLayer == 1:
        nLoops = evenLayers + oddLayers
    else:
        nLoops = loopsInEachEvenLayer * evenLayers + (
            loopsInEachEvenLayer -
            1) * oddLayers  # Total number of loops in each coil
    # ----------------------------

    # Starting to roll the coil
    while nLoops > 0:  # loop that counts the number of wireLoops already done
        if (even == 1) | (
                singleCoilWidth == wireDiameter
        ):  # The statement that says if the rolling is in the 'even' or 'odd' form
            zs = np.arange(
                initPosEven, finalPosEven, stepPos
            )  # The 'zs' is the variable that will be used for rolling loop position
            for n in range(0, subLoops):
                coilLoop = magpy.source.current.Circular(curr=I,
                                                         dim=coilIntDiameter,
                                                         pos=[0, 0, zs[n]])
                collectionToAdd.addSources(coilLoop)
                nLoops = nLoops - 1
                if nLoops <= 0:
                    break
            even = False
            coilIntDiameter = coilIntDiameter + stepDiameter

        else:  # The statement that says if the rolling is in the 'even' or 'odd' form
            zs = np.arange(
                initPosOdd, finalPosOdd, stepPos
            )  # The 'zs' is the variable that will be used for rolling loop position
            for n in range(0, subLoops - 1):
                coilLoop = magpy.source.current.Circular(curr=I,
                                                         dim=coilIntDiameter,
                                                         pos=[0, 0, zs[n]])
                collectionToAdd.addSources(coilLoop)
                nLoops = nLoops - 1
                if nLoops <= 0:
                    break
            even = True
            coilIntDiameter = coilIntDiameter + stepDiameter

    return collectionToAdd
示例#8
0
#imports
import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy

#create magnets
s1 = magpy.source.magnet.Box(mag=[0, 0, 600], dim=[3, 3, 3], pos=[-4, 0, 3])
s2 = magpy.source.magnet.Cylinder(mag=[0, 0, 500], dim=[3, 5])

#manipulate magnets
s1.rotate(45, [0, 1, 0], anchor=[0, 0, 0])
s2.move([5, 0, -4])

#create collection
c = magpy.Collection(s1, s2)

#display system geometry
fig1 = c.displaySystem(suppress=True)
fig1.set_size_inches(6, 6)

#calculate B-field on a grid
xs = np.linspace(-10, 10, 30)
zs = np.linspace(-10, 10, 30)
Bs = np.array([[c.getB([x, 0, z]) for x in xs] for z in zs])

#display field in xz-plane using matplotlib
fig2, ax = plt.subplots()
X, Z = np.meshgrid(xs, zs)
U, V = Bs[:, :, 0], Bs[:, :, 2]
ax.streamplot(X, Z, U, V, color=np.log(U**2 + V**2), density=2)
plt.show()
示例#9
0
# taken from https://magpylib.readthedocs.io/en/latest/_pages/2_guideExamples/

from magpylib.source.magnet import Box
import magpylib as magpy

# fixed magnet parameters
M = [0, 0, 1]  #magnetization
D = [4, 2, 2]  #dimension

# magnets with Euler angle orientations
s1 = Box(mag=M, dim=D, pos=[-4, 0, 4])
s2 = Box(mag=M, dim=D, pos=[4, 0, 4], angle=45, axis=[0, 0, 1])
s3 = Box(mag=M, dim=D, pos=[-4, 0, -4], angle=45, axis=[0, 1, 0])
s4 = Box(mag=M, dim=D, pos=[4, 0, -4], angle=45, axis=[1, 0, 0])

# collection
c = magpy.Collection(s1, s2, s3, s4)

# display collection
magpy.displaySystem(c, direc=True, figsize=(6, 6))
示例#10
0
def get_bfield(ys, zlocs, ylocs, xoffset, oris, return_magnets=False):
    sources = {}

    M = 6335.0 / (4.0 * 1.26) * np.ones(len(zlocs))
    D = 0.50 * 25.4 * np.ones(len(zlocs))
    L = 0.75 * 25.4 * np.ones(len(zlocs))

    D[[0, 1, 11]] = 0.8 * 25.4
    L[[0, 1, 11]] = 0.8 * 25.4

    # needs fixing
    zoffset = 2.5 / 2 * 25.4 + L / 2.0  # mm, radius of nipple plus half the magnet

    if return_magnets:
        return (M, D, L)

    for i in range(len(zlocs)):
        if i in range(6, 9):
            sources['{}tr'.format(i)] = Cylmag(
                loc=[xoffset, ylocs[i], zlocs[i] + zoffset[i]],
                ori=oris[i],
                d=D[i],
                l=L[i],
                m=M[i])
            sources['{}br'.format(i)] = Cylmag(
                loc=[-xoffset, ylocs[i], zlocs[i] + zoffset[i]],
                ori=oris[i],
                d=D[i],
                l=L[i],
                m=M[i])
            sources['{}tl'.format(i)] = Cylmag(
                loc=[xoffset, ylocs[i], -zlocs[i] - zoffset[i]],
                ori=oris[i],
                d=D[i],
                l=L[i],
                m=M[i])
            sources['{}bl'.format(i)] = Cylmag(
                loc=[-xoffset, ylocs[i], -zlocs[i] - zoffset[i]],
                ori=oris[i],
                d=D[i],
                l=L[i],
                m=M[i])
        else:
            sources['{}r'.format(i)] = Cylmag(
                loc=[0, ylocs[i], zlocs[i] + zoffset[i]],
                ori=oris[i],
                d=D[i],
                l=L[i],
                m=M[i])
            sources['{}l'.format(i)] = Cylmag(
                loc=[0, ylocs[i], -zlocs[i] - zoffset[i]],
                ori=oris[i],
                d=D[i],
                l=L[i],
                m=M[i])

    C = magpy.Collection()

    for sc in sources:
        C.addSources(sources[sc])

    Y = [[0, y, 0] for y in ys]
    BZy = C.getBsweep(Y)  # mT

    return BZy[:, 2] * 10.0
示例#11
0
NearFarV = np.asarray(
    [[a * np.cos(angles[-1]), a * np.sin(angles[-1]), 0.4 * a],
     [a * np.cos(angles[-1]), a * np.sin(angles[-1]), 1.64 * a]])
FarNearV = np.asarray(
    [[a * np.cos(angles[0]), a * np.sin(angles[0]), 1.64 * a],
     [a * np.cos(angles[0]), a * np.sin(angles[0]), 0.4 * a]])

#collection of wire loops
LCs = []
for i in [I, -I, -I, I]:
    arcNearXplus = magpy.source.current.Line(curr=i, vertices=arcNearXplusV)
    arcFarXplus = magpy.source.current.Line(curr=i, vertices=arcFarXplusV)
    NearFar = magpy.source.current.Line(curr=i, vertices=NearFarV)
    FarNear = magpy.source.current.Line(curr=i, vertices=FarNearV)

    LCs.append(magpy.Collection(arcNearXplus, NearFar, arcFarXplus, FarNear))
#rotating them to proper positions
LCs[1].rotate(angle=180, axis=[1, 0, 0], anchor=[0, 0, 0])
LCs[2].rotate(angle=180, axis=[0, 0, 1], anchor=[0, 0, 0])
LCs[3].rotate(angle=180, axis=[0, 1, 0], anchor=[0, 0, 0])

c = magpy.Collection(*LCs)

#rotate collection to create Gy gradient instead of Gx
c.rotate(angle=90, axis=[0, 0, 1], anchor=[0, 0, 0])

#print(c.sources)

#magpy.displaySystem(c,direc=True)

# r=[[0,y,0] for y in np.linspace(-a,a,100)]
示例#12
0
import magpylib
b = magpylib.source.magnet.Box(mag=[1, 2, 3],
                               dim=[4, 5, 6],
                               pos=[7, 8, 9],
                               angle=90,
                               axis=(0, 0, 1))

col = magpylib.Collection(b)
col.displaySystem()
def helmholtzCoil(
    color='k',
    collectionToAdd='NULL',
    I=1,
    coilIntDiameter=1,
    wireDiameter=1,
    loopsInEachEvenLayer=1,
    evenLayers=1,
    oddLayers=1,
    coilsDistance=1,
    orientation='z',
    relativeDistance=0.5,
):
    ### (_TO DO: make the helmholtz coil do not touch each other_)
    """ 
    Generate and add 2 coils to a collection , with r distance (in mm) between both coils.
    Return a colection with the helmholtz coil inside
    
    Parameters
    ----------
    I : float
        The Helmhotz Coil Current in Amperes.
    coilIntDiameter : float
        The internal diameter of the coil in mm
    wireDiameter : float, optimizationional
        Diameter of the coil wire in mm.
    loopsInEachEvenLayer : non-zero integer, default 1 
        How many loops in a single even layer
    evenLayers : integer, default 1
        Integer number of even layers.
    oddLayers : integer, default 1
        Integer number of odd layers.
    collectionToAdd : Magpy Collection, default empty
        Append coil source to a magpy collection.
    coilsDistance : float , default 1
        Distance between the coil of the helmholtz coil
    orientation : {'x', 'y', 'z'}, optimizationional
        Change the orientation of the resulting coil having its center parallel with Plane X, Y, or Z.
    
    *OBS: the odd layers always must be evenLayers -1 or = evenLayers 
    
    Example
    ---------
    test = helmholtzCoil(I = 4, coilIntDiameter = 77.26, wireDiameter=1.59, 
                     loopsInEachEvenLayer=3, evenLayers=3, oddLayers=3, 
                     collectionToAdd=magpy.Collection(), coilsDistance = 77.26/2, orientation = 'x')
    test.displaySystem()
    """
    # seting some values to do the calculations after that
    if collectionToAdd == 'NULL':
        collectionToAdd = magpy.Collection()

    helmoltzRotationCenterXYZ = [0, 0, 0]
    singleCoilWidth = wireDiameter * loopsInEachEvenLayer

    # doing the inverse rotations to change the helmhotz coil orientation (because this function only create the coil in 'z' orientation)
    if orientation == 'y':
        collectionToAdd.rotate(90, [1, 0, 0], anchor=helmoltzRotationCenterXYZ)
        collectionToAdd.rotate(90, [0, 0, 1], anchor=helmoltzRotationCenterXYZ)
    elif orientation == 'x':
        collectionToAdd.rotate(-90, [0, 0, 1],
                               anchor=helmoltzRotationCenterXYZ)
        collectionToAdd.rotate(-90, [1, 0, 0],
                               anchor=helmoltzRotationCenterXYZ)
    # ---------------------------------------------------------------------

    # construct the two coils of a helmholtz coil ----------------------------------------------------------------------------
    collectionToAdd = coil(
        I=I,
        color=color,
        coilIntDiameter=coilIntDiameter,
        referencePosition=[0, 0, -coilsDistance / 2 - singleCoilWidth / 2],
        wireDiameter=wireDiameter,
        loopsInEachEvenLayer=loopsInEachEvenLayer,
        evenLayers=evenLayers,
        oddLayers=oddLayers,
        collectionToAdd=collectionToAdd)
    collectionToAdd = coil(
        I=I,
        color=color,
        coilIntDiameter=coilIntDiameter,
        referencePosition=[0, 0, coilsDistance / 2 + singleCoilWidth / 2],
        wireDiameter=wireDiameter,
        loopsInEachEvenLayer=loopsInEachEvenLayer,
        evenLayers=evenLayers,
        oddLayers=oddLayers,
        collectionToAdd=collectionToAdd)
    # ------------------------------------------------------------------------------------------------------------------------
    '''
    # construct the access of supply wires to the two coils of a helmholtz coil ----------------------------------------------
    stepRadius = (wireDiameter**2 - (wireDiameter/2)**2)**0.5
    coilExtDiameter = coilIntDiameter + (wireDiameter + (evenLayers + oddLayers -1)*stepRadius)*2    # calculate the external diameter of the coil
    collectionToAdd = constructAccess(I = I, coilExtDiameter = coilExtDiameter, wireDiameter = wireDiameter, 
                                      centralPointBetweenHelmCoils = [0,0,0], lengthBetweenCoils = coilsDistance, 
                                      singleCoilWidth = singleCoilWidth, helmCoil = collectionToAdd, 
                                      relativeDistance = relativeDistance)
    # ------------------------------------------------------------------------------------------------------------------------
    '''

    # doing the rotations to change the helmhotz coil orientation
    if orientation == 'y':
        collectionToAdd.rotate(-90, [0, 0, 1],
                               anchor=helmoltzRotationCenterXYZ)
        collectionToAdd.rotate(-90, [1, 0, 0],
                               anchor=helmoltzRotationCenterXYZ)
    elif orientation == 'x':
        collectionToAdd.rotate(90, [1, 0, 0], anchor=helmoltzRotationCenterXYZ)
        collectionToAdd.rotate(90, [0, 0, 1], anchor=helmoltzRotationCenterXYZ)
    # ---------------------------------------------------------------------

    return collectionToAdd
示例#14
0
def magnet_sim(sources,
               manipulation,
               axis={
                   'x': np.linspace(-10, 10, 30),
                   'y': np.linspace(-10, 10, 30)
               },
               density=2,
               title="Magnetic Simulation",
               figsize1=[6, 6],
               figsize2=[6, 5],
               set_color=lambda U, V: np.log(U**2 + V**2),
               supress=True,
               ticklabels=[[], []],
               rotation=[0, 0],
               va=['top', 'top'],
               ha=['right', 'right'],
               fontsize=[10, 10],
               axis_show='on',
               xlabel='',
               ylabel='',
               pad=[10, 10],
               which=['major', 'major'],
               show=True):

    frame = inspect.currentframe().f_back

    #manipulation of Magnets
    exec(str(manipulation), frame.f_globals, frame.f_locals)

    #create collection
    magnets_collection = magpy.Collection(*sources)

    #display system geometry
    fig1 = magnets_collection.displaySystem(suppress=supress)
    fig1.set_size_inches(figsize1[0], figsize1[1])

    #calculate B-field on a grid
    Bfield = np.array([[magnets_collection.getB([x, 0, y]) for x in axis['x']]
                       for y in axis['y']])

    #display field in xz-plane using matplotlib
    fig2, ax = plt.subplots()
    X, Z = np.meshgrid(axis['x'], axis['y'])
    U, V = Bfield[:, :, 0], Bfield[:, :, 2]
    fig2.set_size_inches(figsize2[0], figsize2[1])
    ax.streamplot(X, Z, U, V, color=set_color(U, V), density=density)
    ax.set_title(title)
    if ticklabels != [[], []]:
        ax.set_xticklabels(ticklabels[0],
                           rotation=rotation[0],
                           fontsize=fontsize[0],
                           va=va[0],
                           ha=ha[0])
        ax.set_yticklabels(ticklabels[1],
                           rotation=rotation[1],
                           fontsize=fontsize[1],
                           va=va[1],
                           ha=ha[1])
    plt.tick_params(axis='x', which=which[0], pad=pad[0])
    plt.tick_params(axis='y', which=which[1], pad=pad[1])
    plt.axis(axis_show)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    #show plots
    if show:
        plt.show()
示例#15
0
import magpylib
pointToCalculate = [-3, -2,
                    -1]  # Position Vector of the field point to calculate

box = magpylib.source.magnet.Box(mag=[1, 2, 3], dim=[4, 5, 6], pos=[7, 8, 9])

sphere = magpylib.source.magnet.Sphere(
    mag=[1, 2, 3],
    dim=5,
    pos=[-7, -8, -9],
)

col = magpylib.Collection(box,
                          sphere)  ## Make a Collection of 2 source objects
sampleValue = col.getB(
    pointToCalculate)  ## Field Sample from the 2 item Collection
## Output: [0.02236098 0.02485036 0.02734824]

markerZero = [0, 0, 0] + ["Zero Mark"]  ## A Marker On Zero Coordinates
markerSample = pointToCalculate + [str(sampleValue)
                                   ]  ## A Marker On the Field sample

col.displaySystem(markers=[markerZero, markerSample],
                  direc=True)  ## Direc kwarg shows magnetization
## vector
def desiredCoilDiameter(nIteration=1000,
                        breakCondition=0.005,
                        desiredField=1,
                        initialValue=0,
                        I=1,
                        coilIntDiameter=1,
                        wireDiameter=1,
                        loopsInEachEvenLayer=3,
                        evenLayers=3,
                        oddLayers=3,
                        orientation='z',
                        relativeDistance=0.5):
    """ 
    Returns a Collection that is a previous Collection with a twisted pair plus that
    *OBS: still have to fix the rotations
    
    Parameters
    ----------
    nIteration : integer
        Determine how many iterations the loop will do
    breakCondition : float
        It's the B - Ba break condition
    coilIntDiameterStep : float
        The step that the coil diameter tested will increase or decrease
    desiredField : float
        The field amplitude value that the function will search for
    I : float
        The Helmhotz Coil Current in Amperes.
    coilIntDiameter : float
        The internal diameter of the coil in mm (initial value)
    wireDiameter : float, optimizationional
        Diameter of the coil wire in mm.
    loopsInEachEvenLayer : non-zero integer, default 1 
        How many loops in a single even layer
    evenLayers : integer, default 1
        Integer number of even layers.
    oddLayers : integer, default 1
        Integer number of odd layers.
    collectionToAdd : Magpy Collection, default empty
        Append coil source to a magpy collection.
    coilsDistance : float , default 1
        Distance between the coil of the helmholtz coil
    orientation : {'x', 'y', 'z'}, optimizationional
        Change the orientation of the resulting coil having its center parallel with Plane X, Y, or Z.
    
    *OBS: the odd layers always must be evenLayers -1 or = evenLayers 
    
    Example
    ---------
    test = twistedPair(diameter = 2, nPoints = 40, nTurns = 4, I = 4, collectionToAdd = magpy.Collection(), referencePosition= [0,0,0], end = [0,0,3])
    test.displaySystem()
    
    """

    # Setting the initial values of B and Ba
    samplingTime = 100
    previousError = 0
    previousCoilIntDiameter = initialValue
    i = 0
    # The iteration loop that will find the correct HelmoltzCoil to get the I desired with B desired together
    while (1):

        coilIntDiameter = -previousError * samplingTime + previousCoilIntDiameter
        if coilIntDiameter < 0.1:
            coilIntDiameter = 0.1
        #b = WhatTimeIsIt()
        # Creates a new helmholtzCoil, to search for the right coilintDiameter value
        EmptyCol = magpy.Collection()
        Coil = helmholtzCoil(I=I,
                             coilIntDiameter=coilIntDiameter,
                             wireDiameter=wireDiameter,
                             loopsInEachEvenLayer=loopsInEachEvenLayer,
                             evenLayers=evenLayers,
                             oddLayers=oddLayers,
                             collectionToAdd=EmptyCol,
                             coilsDistance=coilIntDiameter / 2,
                             orientation=orientation,
                             relativeDistance=relativeDistance)
        # --------------------------------------------------------------------------------------------
        #a = WhatTimeIsIt()
        #print(a-b)
        # Store the B in Ba and calculate the new B
        field = Coil.getB([0, 0, 0])
        if (orientation == 'z'):
            field = field[2]
        elif (orientation == 'y'):
            field = field[1]
        elif (orientation == 'x'):
            field = field[0]
        else:
            field = norm(field)

        error = desiredField - field
        #print(error)
        #print(coilIntDiameter)
        previousError = error
        previousCoilIntDiameter = coilIntDiameter

        i += 1
        if i > nIteration:
            break
        if np.linalg.norm(error) < breakCondition:
            break
        #print(B)
    # -----------------------------------------------------------------------------------------------------

    return coilIntDiameter
def twistedPair(diameter=2,
                nPoints=40,
                nTurns=10,
                I=4,
                collectionToAdd=magpy.Collection(),
                referencePosition=[0, 0, 0],
                end=[0, 0, 1]):
    """ 
    Returns a Collection that is a previous Collection with a twisted pair plus that
    *OBS: still have to fix the rotations
    
    Parameters
    ----------
    diameter : float
        Diameter of the spiral
    spiralExtremities : list (float) [2]
        The beginning [0], and the end [1] in 'z' orientation of the spiral
    nPoints : float
        Number of points in the spiral, greater the number, more "realistic" model
        of a spiral you get
    nTurns : positive integer 
        Number of the turns that will have in your spiral
    I : float
        The current amplitude that will create the magnetic field
    startingSpiralAng : float (0~180)
        It's the starting angle of the spiral
    rotationSense : integer (-1,1)
        This multiply the angle, so the sense will be positive increasing or negative increasing
    referencePosition : list (float) [3]
        is the starting point where the spiral will be created, in 'z' orientation
          
    Example
    ---------
    test = twistedPair(diameter = 2, nPoints = 40, nTurns = 4, I = 4, collectionToAdd = magpy.Collection(), referencePosition= [0,0,0], end = [0,0,3])
    test.displaySystem()
    
    """

    # Find the rotations angles for the right positioning of the twisted pair ------------------------------
    spiralExtremities = np.zeros(2)
    spiralExtremities[0] = 0
    spiralExtremities[1] = ((end[0] - referencePosition[0])**2 +
                            (end[1] - referencePosition[1])**2 +
                            (end[2] - referencePosition[2])**2)**0.5

    print(spiralExtremities[1])  # debug
    # *OBS: still have to fix the rotations
    """
    phi = -np.arccos((end[2] - referencePosition[2])/spiralExtremities[1])
    print(phi)                          # debug
    teta = np.arccos((end[0] - referencePosition[0])/spiralExtremities[1]/np.sin(phi))*180/pi
    print(teta)                         # debug
    phi = phi*180/pi
    
    # -------------------------------------------------------------------------------------
    
    # Doing the inverse rotations -------------------------------------
    collectionToAdd.rotate(-teta,[0,0,1],anchor=referencePosition)
    collectionToAdd.rotate(-phi,[1,0,0],anchor=referencePosition)
    # -------------------------------------------------------------------------------------
    """
    # Doing one spiral in the 'z' positive orientation
    spi = spiral(
        diameter=diameter,
        spiralExtremities=[spiralExtremities[0], spiralExtremities[1]],
        nPoints=nPoints,
        nTurns=nTurns,
        I=I,
        startingSpiralAng=0,
        referencePosition=referencePosition)
    collectionToAdd.addSources(spi)

    # Doing the second spiral in the 'z' negative orientation
    spi = spiral(
        diameter=diameter,
        spiralExtremities=[spiralExtremities[1], spiralExtremities[0]],
        nPoints=nPoints,
        nTurns=nTurns,
        I=I,
        startingSpiralAng=180,
        rotationSense=-1,
        referencePosition=referencePosition)
    collectionToAdd.addSources(spi)
    """
    # Doing the rotations -------------------------------------
    collectionToAdd.rotate(phi,[1,0,0],anchor=referencePosition)
    collectionToAdd.rotate(teta,[0,0,1],anchor=referencePosition)
    # -------------------------------------------------------------------------------------
    """
    return collectionToAdd
def plotBxyz(collectionToPlot,
             collectionToCompare=magpy.Collection(),
             plotBounds=[0, 10, 0, 10],
             orientation='z',
             orderMagnitude='mT',
             fieldDif=False,
             figureSize=[10, 8],
             nPlotPoints=40,
             xyz0=0,
             figureTittle='Figure',
             compareToCenter=False,
             centerToCompare=[0, 0, 0]):
    """ 
    Plot in a 2d (x,z) in a y0 = constant graphic with 2 screens the [module %, angles º(related to the z direction)] 
    diference of the B in [0,0,0] and the other points of the graphic
    
    Parameters
    ----------
    collectionToPlot : Magpy Collection
        The collection used to caculate the plots
    plotBounds : float list [4]
        its the initial and final X and Z boundaries
        plotBound[0] = initialX, plotBound[1] = finalX
        plotBound[2] = initialZ, plotBound[3] = finalZ
    percent : bool
        If True, plot the percent diference relative to the B = [0,0,0] field
        If False, plot the true field in every point of the graphic
    optimization : bool
        If True, plot based in an eliptical line in the screen
        If False, plot every point related to the field in each point
    figureSize : list(integers) [2]
        Define the size of the entire figure
    nPlotPoints : integer
        Number of point that will be used to plot the figure in each axis
    y0 : float
        The plot made is an 2d 'z' by 'x', this select where in 'y' the plot will be made 
    figureTittle : string
        Define the entire figure tittle
        
    Example
    ---------
    test = helmholtzCoil(I = 4, coilIntDiameter = 77.26, wireDiameter=1.59, 
                         loopsInEachEvenLayer=3, evenLayers=3, oddLayers=3, 
                         collectionToAdd=magpy.Collection(), coilsDistance = 77.26/2, orientation = 'z')
    plotB(collectionToPlot = test, optimization= True, figureTittle = 'Test figure', nPlotPoints = 10, percent = True)
        
    test.displaySystem()
    """
    if orderMagnitude == 'uT':
        multiplier = 1000
    else:
        multiplier = 1
    # Here creates the screens and name the axis
    fig = plt.figure(figsize=(figureSize[0], figureSize[1]), dpi=80)
    fig.suptitle(figureTittle, fontsize=16)
    if compareToCenter:
        AXS = [fig.add_subplot(2, 2, i, axisbelow=True) for i in range(1, 5)]
        subPlot1, subPlot2, subPlot3, subPlot4 = AXS
    else:
        subPlot1 = fig.add_subplot(1, 1, 1, axisbelow=True)

    if orientation == 'y':
        subPlot1.set_xlabel('x axis (mm)')
        subPlot1.set_ylabel('z axis (mm)')

    elif orientation == 'x':
        subPlot1.set_xlabel('z axis (mm)')
        subPlot1.set_ylabel('y axis (mm)')
        collectionToPlot.rotate(90, [0, 1, 0], anchor=[0, 0, 0])
        collectionToCompare.rotate(90, [0, 1, 0], anchor=[0, 0, 0])
        collectionToPlot.rotate(90, [1, 0, 0], anchor=[0, 0, 0])
        collectionToCompare.rotate(90, [1, 0, 0], anchor=[0, 0, 0])

    elif orientation == 'z':
        subPlot1.set_xlabel('y axis (mm)')
        subPlot1.set_ylabel('x axis (mm)')
        collectionToPlot.rotate(-90, [0, 1, 0], anchor=[0, 0, 0])
        collectionToCompare.rotate(-90, [0, 1, 0], anchor=[0, 0, 0])
        collectionToPlot.rotate(-90, [0, 0, 1], anchor=[0, 0, 0])
        collectionToCompare.rotate(-90, [0, 0, 1], anchor=[0, 0, 0])

    # Here the process to create the plot arrays
    xs = linspace(plotBounds[0], plotBounds[1], nPlotPoints)
    zs = linspace(plotBounds[2], plotBounds[3], nPlotPoints)

    X, Z = meshgrid(xs, zs)

    # Here the process to take the points of the amplitude error and degree error
    Bs = array([[
        collectionToPlot.getB([xs[x], xyz0, zs[z]]) for x in range(0, len(xs))
    ] for z in range(0, len(zs))])
    Bs = Bs * multiplier
    amp = Bs[:, :, 2]

    if fieldDif:
        Bs2 = array([[
            collectionToCompare.getB([xs[x], xyz0, zs[z]])
            for x in range(0, len(xs))
        ] for z in range(0, len(zs))])
        Bs2 = Bs2 * multiplier

        if orientation == 'x':
            amp2 = Bs2[:, :, 2]
            #subPlot1.set_title('shows the % difference\n B1tc and B2tp, relative to B2tp \n(comparition in "y" orientation)')
            # shows the 'y' comparation
        elif orientation == 'z':
            amp2 = Bs2[:, :, 2]
            #subPlot1.set_title('shows the % difference\n B1tc and B2tp, relative to B2tp \n(comparition in "x" orientation)')
            # shows the 'x' comparation
        elif orientation == 'y':
            amp2 = Bs2[:, :, 2]
            #subPlot1.set_title('shows the % difference\n B1tc and B2tp, relative to B2tp \n(comparition in "z" orientation)')
            # shows the 'z' comparation
        ampDif = np.abs(amp2 - amp) / amp
        subPlot1.contourf(X, Z, ampDif, 10, cmap=plt.cm.jet)
        cp = subPlot1.contour(X,
                              Z,
                              ampDif,
                              30,
                              colors=('k', 'k'),
                              linestyles=('-', '-'),
                              linewidths=(1, 1))
        subPlot1.clabel(cp, fontsize=10, inline=True, fmt='%4.3f')

    elif compareToCenter:
        # calculating the diffence of the the comparing point to the whole map
        Bcenter = collectionToPlot.getB(centerToCompare)
        Bcenter = Bcenter * multiplier
        Bs = array([[
            collectionToPlot.getB([xs[x], xyz0, zs[z]])
            for x in range(0, len(xs))
        ] for z in range(0, len(zs))])
        Bs = Bs * multiplier
        BsNorm = ((Bs[:, :, 0])**2 + (Bs[:, :, 1])**2 + (Bs[:, :, 2])**2)**0.5
        BcenterNorm = ((Bcenter[0])**2 + (Bcenter[1])**2 +
                       (Bcenter[2])**2)**0.5

        normDif = (BsNorm - BcenterNorm) / BcenterNorm * 100
        # ---------------------------------------------------------------------------
        # Here the process to actualy plot int the screen
        subPlot1.set_title(
            'B vector amplitude Error realative to the "center" (%)')
        subPlot1.contourf(X, Z, normDif, 10, cmap=plt.cm.jet)
        cp = subPlot1.contour(X,
                              Z,
                              normDif,
                              30,
                              colors=('k', 'k'),
                              linestyles=('-', '-'),
                              linewidths=(1, 1))
        subPlot1.clabel(cp, fontsize=10, inline=True, fmt='%4.3f')

        # Here calculate the angle to plot

        if orientation == 'y':
            subPlot1.set_xlabel('.')
            subPlot2.set_xlabel('.')
            subPlot2.set_ylabel('z axis (mm)')
            subPlot3.set_xlabel('x axis (mm)')
            subPlot3.set_ylabel('z axis (mm)')
            subPlot4.set_xlabel('x axis (mm)')
            subPlot4.set_ylabel('z axis (mm)')
            Bsx = Bs[:, :, 0]
            Bsy = Bs[:, :, 1]
            Bsz = Bs[:, :, 2]

        elif orientation == 'x':
            subPlot1.set_xlabel('.')
            subPlot2.set_xlabel('.')
            subPlot2.set_ylabel('y axis (mm)')
            subPlot3.set_xlabel('z axis (mm)')
            subPlot3.set_ylabel('y axis (mm)')
            subPlot4.set_xlabel('z axis (mm)')
            subPlot4.set_ylabel('y axis (mm)')
            Bsx = Bs[:, :, 1]
            Bsy = Bs[:, :, 2]
            Bsz = Bs[:, :, 0]

        elif orientation == 'z':
            subPlot1.set_xlabel('.')
            subPlot2.set_xlabel('.')
            subPlot2.set_ylabel('x axis (mm)')
            subPlot3.set_xlabel('y axis (mm)')
            subPlot3.set_ylabel('x axis (mm)')
            subPlot4.set_xlabel('y axis (mm)')
            subPlot4.set_ylabel('x axis (mm)')
            Bsx = Bs[:, :, 2]
            Bsy = Bs[:, :, 0]
            Bsz = Bs[:, :, 1]

        if orderMagnitude == 'uT':
            subPlot2.set_title('x component (uT)')
            subPlot3.set_title('y component (uT)')
            subPlot4.set_title('z component (uT)')

        else:
            subPlot2.set_title('x component (mT)')
            subPlot3.set_title('y component (mT)')
            subPlot4.set_title('z component (mT)')
        #print(Bs)
        subPlot2.contourf(X, Z, Bsx, 10, cmap=plt.cm.jet)
        cp = subPlot2.contour(X,
                              Z,
                              Bsx,
                              30,
                              colors=('k', 'k'),
                              linestyles=('-', '-'),
                              linewidths=(1, 1))
        subPlot2.clabel(cp, fontsize=10, inline=True, fmt='%4.3f')

        subPlot3.contourf(X, Z, Bsy, 10, cmap=plt.cm.jet)
        cp = subPlot3.contour(X,
                              Z,
                              Bsy,
                              30,
                              colors=('k', 'k'),
                              linestyles=('-', '-'),
                              linewidths=(1, 1))
        subPlot3.clabel(cp, fontsize=10, inline=True, fmt='%4.3f')

        subPlot4.contourf(X, Z, Bsz, 10, cmap=plt.cm.jet)
        cp = subPlot4.contour(X,
                              Z,
                              Bsz,
                              30,
                              colors=('k', 'k'),
                              linestyles=('-', '-'),
                              linewidths=(1, 1))
        subPlot4.clabel(cp, fontsize=10, inline=True, fmt='%4.3f')
    else:
        if orderMagnitude == 'uT':
            subPlot1.set_title('B vector amplitude (uT)')
        else:
            subPlot1.set_title('B vector amplitude (mT)')
        subPlot1.contourf(X, Z, amp, 10, cmap=plt.cm.jet)
        cp = subPlot1.contour(X,
                              Z,
                              amp,
                              30,
                              colors=('k', 'k'),
                              linestyles=('-', '-'),
                              linewidths=(1, 1))
        subPlot1.clabel(cp, fontsize=10, inline=True, fmt='%4.3f')

    if orientation == 'x':
        collectionToPlot.rotate(-90, [1, 0, 0], anchor=[0, 0, 0])
        collectionToCompare.rotate(-90, [1, 0, 0], anchor=[0, 0, 0])
        collectionToPlot.rotate(-90, [0, 1, 0], anchor=[0, 0, 0])
        collectionToCompare.rotate(-90, [0, 1, 0], anchor=[0, 0, 0])

    elif orientation == 'z':
        collectionToPlot.rotate(90, [0, 0, 1], anchor=[0, 0, 0])
        collectionToCompare.rotate(90, [0, 0, 1], anchor=[0, 0, 0])
        collectionToPlot.rotate(90, [0, 1, 0], anchor=[0, 0, 0])
        collectionToCompare.rotate(90, [0, 1, 0], anchor=[0, 0, 0])
示例#19
0
                                   pos=[0, 6 * yo, -.421 * 25.4 - zo - L])
s73 = magpy.source.magnet.Cylinder(mag=[0, 0, M],
                                   dim=[D, L],
                                   pos=[0, 6 * yo, +.421 * 25.4 + zo])

s81 = magpy.source.magnet.Cylinder(mag=[0, 0, M],
                                   dim=[D, L],
                                   pos=[0, 7 * yo, -.948 * 25.4 - zo - L])
s83 = magpy.source.magnet.Cylinder(mag=[0, 0, M],
                                   dim=[D, L],
                                   pos=[0, 7 * yo, +.948 * 25.4 + zo])

time.sleep(1)

print('Initializing collections...          ', end='\r')
c1 = magpy.Collection(s11, s12, s13, s14)
c2 = magpy.Collection(s21, s22, s23, s24)
c3 = magpy.Collection(s31, s32, s33, s34)
c4 = magpy.Collection(s41, s42, s43, s44)
c5 = magpy.Collection(s51, s53)
c6 = magpy.Collection(s61, s63)
c7 = magpy.Collection(s71, s73)
c8 = magpy.Collection(s81, s83)

cz = magpy.Collection(s11, s12, s13, s14, s21, s22, s23, s24, s31, s32, s33,
                      s34, s41, s42, s43, s44, s51, s53, s61, s63, s71, s73,
                      s81, s83)

ymin = -yo
ymax = 9 * yo
nys = 100
示例#20
0
# Millimeter for lengths
# Degree for angles
# Millitesla for magnetization/remanence, magnetic moment and magnetic field,
# Ampere for currents.

#create sources
#magnetization is in x dir with magnitude 1 in CHECK UNITS LATER
#dimesions are [diameter, height]=[4,5] (mm)
#make cylinder with center 5 mm above origin in z direction
s1 = magpy.source.magnet.Cylinder(mag=[1, 0, 0], dim=[10, 5], pos=[0, 0, 5])

#makes loop in x-y plane
s3 = magpy.source.current.Circular(
    curr=1,
    dim=10)  #current is one amp clockwise (in z direction), dimension is 10 mm

#create collection
c = magpy.Collection(s1,
                     s3)  #now the system can be moved and manipulated as one

#display system

#specify markers to show places of interest:
markerPos = [(0, 0, 0, 'origin'), (10, 10, 10), (-10, -10, -10)]

#Evaluate field at orign
print(c.getB([0, 0, 0]))

#show the collection
magpy.displaySystem(c, markers=markerPos, direc=True)
示例#21
0
# taken from https://magpylib.readthedocs.io/en/latest/_pages/2_guideExamples/

import magpylib as magpy
from magpylib.source.current import Circular
from numpy import linspace

# windings of three parts of a coil
coil1a = [Circular(curr=1, dim=3, pos=[0, 0, z]) for z in linspace(-3, -1, 10)]
coil1b = [Circular(curr=1, dim=3, pos=[0, 0, z]) for z in linspace(-1, 1, 10)]
coil1c = [Circular(curr=1, dim=3, pos=[0, 0, z]) for z in linspace(1, 3, 10)]

# create collection and manipulate step by step
c1 = magpy.Collection(coil1a)
c1.move([-1, -1, 0])
c1.addSources(coil1b)
c1.move([-1, -1, 0])
c1.addSources(coil1c)
c1.move([-1, -1, 0])

# windings of three parts of another coil
coil2a = [Circular(curr=1, dim=3, pos=[3, 3, z]) for z in linspace(-3, -1, 15)]
coil2b = [Circular(curr=1, dim=3, pos=[3, 3, z]) for z in linspace(-1, 1, 15)]
coil2c = [Circular(curr=1, dim=3, pos=[3, 3, z]) for z in linspace(1, 3, 15)]

# create individual sub-collections
c2a = magpy.Collection(coil2a)
c2b = magpy.Collection(coil2b)
c2c = magpy.Collection(coil2c)

# combine sub-collections to one big collection
c2 = magpy.Collection(c2a, c2b, c2c)
示例#22
0
import magpylib as magpy
from magpylib.source.current import Circular
import numpy as np
from matplotlib import pyplot as plt
from skimage import measure

# windings of three parts of a coil
coil1a = [
    Circular(curr=1, dim=3, pos=[0, 0, z]) for z in np.linspace(-3, 3, 15)
]

# create collection and manipulate step by step
c1 = magpy.Collection(coil1a)

# magpy.displaySystem(c1, figsize=(6,6))

# create positions
xs = np.linspace(-8, 8, 100)
zs = np.linspace(-6, 6, 100)
posis = [[x, 0, z] for z in zs for x in xs]

# calculate field and amplitude
B = [c1.getB(pos) for pos in posis]
Bs = np.array(B).reshape([100, 100, 3])  #reshape
Bamp = np.linalg.norm(Bs, axis=2)
print(Bamp.shape)
print(Bamp[50, 50])  # field in center

fig = plt.figure(figsize=[5, 5])
ax = fig.add_axes([.1, .1, .8, .8])
    if i in range(6, 9):
        sources['{}tr'.format(i)] = Cylmag(
            loc=[xoffset, ylocs[i], zlocs[i] + zoffset], ori=oris[i])
        sources['{}br'.format(i)] = Cylmag(
            loc=[-xoffset, ylocs[i], zlocs[i] + zoffset], ori=oris[i])
        sources['{}tl'.format(i)] = Cylmag(
            loc=[xoffset, ylocs[i], -zlocs[i] - zoffset], ori=oris[i])
        sources['{}bl'.format(i)] = Cylmag(
            loc=[-xoffset, ylocs[i], -zlocs[i] - zoffset], ori=oris[i])
    else:
        sources['{}r'.format(i)] = Cylmag(
            loc=[0, ylocs[i], zlocs[i] + zoffset], ori=oris[i])
        sources['{}l'.format(i)] = Cylmag(
            loc=[0, ylocs[i], -zlocs[i] - zoffset], ori=oris[i])

C = magpy.Collection()

for sc in sources:
    C.addSources(sources[sc])

ymin = 0  # mm
ymax = 11 * 25.4  # mm
ny = 100
ys = np.linspace(ymin, ymax, ny)
Y = [[0, y, 0] for y in ys]
BZy = C.getBsweep(Y)  # mT

plt.figure()
plt.plot(ys / 10, BZy[:, 2] * 10)
plt.xlabel('Beamline Position (cm)')
plt.ylabel('Z Magnetic Field (Gs)')
示例#24
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import magpylib as magpy

# create collection of two magnets
s1 = magpy.source.current.Circular(curr=1, dim=8)
s1.rotate(45, [0, 1, 0], anchor=s1.position
          )  #tilts loop 45 degree about y-axis that passes through its center
c = magpy.Collection(s1)

# create positions
xs = np.linspace(-8, 8, 100)
dxs = xs[1] - xs[0]
zs = np.linspace(-6, 6, 100)
dzs = zs[1] - zs[0]
posis = [[x, 0, z] for z in zs for x in xs]  #increments x first

# calculate field and amplitude
B = [c.getB(pos) for pos in posis]  #
Bs = np.array(B).reshape([100, 100, 3])  #reshape to [z_pos,x_pos,[Bx,By,Bz]]
Bamp = np.linalg.norm(Bs, axis=2)  #comuptes norm of all vectors
Bamp = Bamp * 10  #converts from mT to Gauss

#field at center in guass
print("Field at center in Gauss")
print(np.linalg.norm(c.getB([0, 0, 0]) * 10))

# define figure with a 2d and a 3d axis
fig = plt.figure(figsize=(10, 5))  #fig size
ax1 = fig.add_subplot(121, projection='3d')
示例#25
0
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')

pi = np.pi

seg = Segment()

seg.bend_angle = pi/2
seg.bend_direction = 3*pi

rotvec = [0,0,1]

seg.apply_rotvec(rotvec,[1,0,0])


x = seg.bend_line(rotvec)
ax.plot(x[0],x[1],x[2],color='black')

c = magpy.Collection(seg.magnet)
magpy.displaySystem(c,subplotAx=ax,suppress=True)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
'''
ax.set_xlim(-200,200)
ax.set_ylim(-200,200)
ax.set_zlim(-200,200)
'''
plt.show()
示例#26
0
import magpylib as magpy

# create magnets
magnet1 = magpy.source.magnet.Box(mag=[0, 0, 600],
                                  dim=[3, 3, 3],
                                  pos=[-4, 0, 3])
magnet2 = magpy.source.magnet.Cylinder(mag=[0, 0, 500],
                                       dim=[3, 5],
                                       pos=[0, 0, 0])

# manipulate magnets
magnet1.rotate(45, [0, 1, 0], anchor=[0, 0, 0])
magnet2.move([5, 0, -4])

# collect magnets
pmc = magpy.Collection(magnet1, magnet2)

# display system geometry
pmc.displaySystem()

# calculate B-fields on a grid
xs = np.linspace(-10, 10, 20)
zs = np.linspace(-10, 10, 20)
Bs = np.array([[pmc.getB([x, 0, z]) for x in xs] for z in zs])

# display fields using matplotlib
fig, ax = plt.subplots()
X, Y = np.meshgrid(xs, zs)
U, V = Bs[:, :, 0], Bs[:, :, 2]
ax.streamplot(X, Y, U, V, color=np.log(U**2 + V**2), density=1.5)
plt.show()
示例#27
0
s3d1.move([0, 0, -d1 - d2])
s4d1.move([0, 0, -d1 - d2])
s5d1.move([0, 0, -d1 - d2])
s6d1.move([0, 0, -d1 - d2])

s1d2.move([0, 0, -d1 + d2])
s2d2.move([0, 0, -d1 + d2])
s3d2.move([0, 0, -d1 + d2])
s4d2.move([0, 0, -d1 + d2])
s5d2.move([0, 0, -d1 + d2])
s6d2.move([0, 0, -d1 + d2])
print('complete')

print('building collection...', end='')
Cmot = magpy.Collection(s1u1, s2u1, s3u1, s4u1, s5u1, s6u1, s1u2, s2u2, s3u2,
                        s4u2, s5u2, s6u2, s1d1, s2d1, s3d1, s4d1, s5d1, s6d1,
                        s1d2, s2d2, s3d2, s4d2, s5d2, s6d2)

Cmot.displaySystem()
print('complete')

xmin = -2 * rmax
xmax = 2 * rmax
nx = 100
zmin = -2 * d1
zmax = 2 * d1
nz = 100

xs = np.linspace(xmin, xmax, nx)
zs = np.linspace(zmin, zmax, nz)
示例#28
0
cz = magpy.Collection(
    s11,
    #s12,
    s13,
    #s14,
    s21,
    #s22,
    s23,
    #s24,
    s31,
    #s32,
    s33,
    #s34,
    s41,
    #s42,
    s43,
    #s44,
    s51,
    s53,
    s61,
    s63,
    s71,
    s72,
    s73,
    s74,
    s81,
    s82,
    s83,
    s84,
    s91,
    s92,
    s93,
    s94,
    s101,
    s103,
    s111,
    s113)
示例#29
0
piv4 = [-7,0,-5]
anch4 = [-7,0,-2]
s4 = Box(mag=M, dim=D, pos = [-7,-3,-5])

piv5 = [0,0,-5]
anch5 = [0,0,-2]
s5 = Box(mag=M, dim=D, pos = [0,-3,-5])
s5.rotate(-45,[0,0,1],anchor=anch5)

piv6 = [7,0,-5]
anch6 = [7,0,-8]
s6 = Box(mag=M, dim=D, pos = [7,-3,-5])
s6.rotate(-45,[0,0,1],anchor=anch6)

# collect all sources
c = magpy.Collection(s1,s2,s3,s4,s5,s6)

# draw rotation axes
for x in [-7,0,7]:
    for z in [-5,5]:
        ax.plot([x,x],[0,0],[z-3,z+4],color='.3')

# define markers
Ms = [piv1+['piv1'], piv2+['piv2'], piv3+['piv3'], piv4+['piv4'],
      piv5+['piv5'], piv6+['piv6'], anch4+['anch4'],anch5+['anch5'],anch6+['anch6']]

# display system
magpy.displaySystem(c,subplotAx=ax,markers=Ms,suppress=True)

plt.show()
def constructAccess(I=4,
                    centralPointBetweenHelmCoils=[0, 0, 0],
                    coilExtDiameter=1,
                    relativeDistance=1,
                    wireDiameter=1,
                    singleCoilWidth=1,
                    lengthBetweenCoils=1,
                    helmCoil=magpy.Collection()):
    """
    Returns a collection with the wires access in 'x' axis orientation
    to the coils of a helmholtz collection with 'z' field orientation
    
    Parameters
    ----------
    I : float
        The Coil Current in Amperes.
    centralPointBetweenHelmCoils : integer, default 1
        Integer number of odd layers.
    coilExtDiameter : float
        The external diameter of one of the helmholtz coils, in mm.
    relativeDistance : float 0~1, default 1
        The porcentage of the 1.5*coilExtDiameter distance from the 
        centralPointBetweenHelmCoils that the wire will split to the coils
    wireDiameter : float, default 1
        Diameter of the coil wire in mm.
    singleCoilWidth : float, default 1 
        Width of a single coil of helmholtz coil, in mm
    lengthBetweenCoils : float, default 1
        The internal length between the two coils of the helmholtz coil
    helmCoil : Magpy Collection, default empty
        Append the wires to a magpy collection.
    
    Example
    ---------
    test = constructAccess( I = 4, centralPointBetweenHelmCoils = [0,0,0], coilExtDiameter = 1, relativeDistance = 0.5, 
                    wireDiameter = 1, singleCoilWidth = 1, lengthBetweenCoils = 1, helmCoil = magpy.Collection()):
    
    test.displaySystem()
    """

    # distance from the centralPointBetweenHelmCoils to the center of one coil of Helmholtz coil
    halfCoillengthBetweenCoils = (lengthBetweenCoils + singleCoilWidth) / 2

    # Initializing the statingPoint of the wires with the central point of the coil + some distance relative to the coilIntDiameter
    wiresStartingPoint = centralPointBetweenHelmCoils
    wiresStartingPoint[0] += 1.5 * coilExtDiameter

    #  |
    #
    #
    vector = [[
        wiresStartingPoint[0], wiresStartingPoint[1],
        wireDiameter + wiresStartingPoint[2]
    ], [wiresStartingPoint[0] * relativeDistance, 0, wireDiameter]]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _|
    #
    #
    vector = [
        vector[1],
        [
            vector[1][0], vector[1][1],
            vector[1][2] + halfCoillengthBetweenCoils
        ]
    ]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _|
    # |
    # |
    vector = [
        vector[1],
        [coilExtDiameter / 2 - wireDiameter, vector[1][1], vector[1][2]]
    ]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _|
    # |
    # ||
    vector = [[vector[1][0], vector[1][1], vector[1][2] - wireDiameter],
              [
                  vector[0][0] - wireDiameter, vector[0][1],
                  vector[0][2] - wireDiameter
              ]]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    # going to the other side
    #  _|
    # | __
    # ||
    vector = [vector[1], [vector[1][0], vector[1][1], -vector[1][2]]]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _|
    # | __
    # || |
    vector = [
        vector[1],
        [coilExtDiameter / 2 - wireDiameter, vector[1][1], vector[1][2]]
    ]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _|
    # | __ |
    # || ||
    vector = [[vector[1][0], vector[1][1], vector[1][2] - wireDiameter],
              [
                  vector[0][0] + wireDiameter, vector[0][1],
                  vector[0][2] - wireDiameter
              ]]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _|  _
    # | __ |
    # || ||
    vector = [
        vector[1],
        [wiresStartingPoint[0] * relativeDistance, 0, -wireDiameter]
    ]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    #  _| |_
    # | __ |
    # || ||
    vector = [[wiresStartingPoint[0] * relativeDistance, 0, -wireDiameter],
              [
                  wiresStartingPoint[0], wiresStartingPoint[1],
                  -wireDiameter + wiresStartingPoint[2]
              ]]
    line = magpy.source.current.Line(curr=I, vertices=vector)
    helmCoil.addSources(line)

    return helmCoil