Exemplo n.º 1
0
sample = {'demagnetizing_factor': demagnetizing_factor,
          'volume': volume,
          'M_saturation': M_saturation}


# magnet collection definition

m1 = Cylinder(mag=[0, 0, 1300],  # 1300mT of magnetization along z axis
              dim=[10, 20],      # 10mm diameter, 20mm height
              pos=[0, 0, -20])   # center is at z = -20mm

m2 = Cylinder(mag=[0, 0, 1300],  # 1300mT of magnetization along z axis
              dim=[10, 20],      # 10mm diameter, 20mm height
              pos=[0, 0, 20])    # center is at z = 20mm

both = Collection(m1, m2)        # arrangement with both magnets


# magnet collection visualisation

displaySystem(both, suppress=True)


# 3D plot of B and F in a 3D space

plot_3D(xs=linspace(-10, 10, 9),
        ys=linspace(-10, 10, 9),
        zs=linspace(-20, 20, 9),
        collections={'z-20': m1,
                     'both': both},
        sample=sample,
Exemplo n.º 2
0
from magpylib import source, Collection
from matplotlib import pyplot

pyplot.ioff()  # Enable interactivity suppression for figure export

cyl = source.magnet.Cylinder(mag=[-1, 0, 0], dim=[2, 1], pos=[0, 0, 2])

b = source.magnet.Box(mag=[1, 0, 0], dim=[1, 1, 0.5], pos=[0, 0, 0])

pivot_position = [0, 0, 4]
pivot_marker = pivot_position + ["anchor"]

col = Collection(b, cyl)

fig = col.displaySystem(
    suppress=True,  # Suppress interactive images
    markers=[pivot_marker],  # Show given markers
    direc=True)  # Show magnetization vectors

fig.suptitle("Cylinder and Box Assembly")
fig.set_size_inches(6, 6)

cyl.rotate(45, (0, 1, 0),
           anchor=pivot_position)  # Rotate just the Cylinder Object

fig2 = col.displaySystem(
    suppress=True,  # Suppress interactive images
    markers=[pivot_marker],  # Show given markers
    direc=True)  # Show magnetization vectors

fig2.suptitle("Cylinder rotated -90° in (0,1,0), pivoting around [0,0,4]")
Exemplo n.º 3
0
                                        pos=position)
    return newTurn

# Define Coil
sizeOfCoil = 3 #mm
turnDistance = 0.1 #mm
diameter = 5 #mm

startMarker = [0,0,0]
endMarker = [0,0,sizeOfCoil] 

## Generate a coil structure
coilStructure = [returnCoilTurn(diameter,[0,0,i]) for i in arange(0,sizeOfCoil, turnDistance)]

## Define Coil
coil = Collection(coilStructure)

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

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

superCollection = Collection(box,sphere,coil)  ## Make a mixed Collection
superCollection.displaySystem()

coil.rotate(45,(0,1,1),anchor=[0,0,0])
superCollection.displaySystem()
Exemplo n.º 4
0
data = pickle.load(open("data/test.p", "rb"))

mag = [0, 0, -575.4]
dim = [6.35, 6.35, 6.35]
sen = []

loops = 150

for i in range(5, loops):
    b = Box(mag=mag,
            dim=dim,
            pos=data[i][0],
            angle=data[i][1],
            axis=data[i][2])
    sen.append(magpy.Sensor(pos=data[i][0], angle=data[i][1], axis=data[i][2]))
    col = Collection(b)
    if (i == (loops - 1)):
        h = 1
        magpy.displaySystem(col, sensors=sen)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

length = 3
for i in range(5, loops):
    x = [1, 0, 0]
    y = [0, 1, 0]
    z = [0, 0, 1]

    pos = data[i][0]
    axis = data[i][2]
Exemplo n.º 5
0
    magnets = Collection(gen_magnets(balljoint_config['field_strength'],balljoint_config['magnet_dimension'],balljoint_config['magnet_pos'],balljoint_config['magnet_pos_offsets'], \
                                     balljoint_config['magnet_angle'],balljoint_config['magnet_angle_offsets']))
    magnets.rotate(rot[0], (1, 0, 0), anchor=(0, 0, 0))
    magnets.rotate(rot[1], (0, 1, 0), anchor=(0, 0, 0))
    magnets.rotate(rot[2], (0, 0, 1), anchor=(0, 0, 0))
    data = []
    for sens in sensors:
        val = sens.getB(magnets)
        if normalize_magnetic_strength:
            val /= np.linalg.norm(val)
        data.append(val)
    if (iter % 1000 == 0):
        print("%d/%d" % (iter, iterations))
    return (data, rot)

magnets = Collection(gen_magnets(balljoint_config['field_strength'],balljoint_config['magnet_dimension'],balljoint_config['magnet_pos'],balljoint_config['magnet_pos_offsets'], \
                                balljoint_config['magnet_angle'],balljoint_config['magnet_angle_offsets']))

data_norm = []
data = []
for sens in sensors:
    val0 = sens.getB(magnets)
    val1 = sens.getB(magnets)
    data.append(val0)
    val1 /= np.linalg.norm(val1)
    data_norm.append(val1)
print(
    "sensor values:\n%.3f %.3f %.3f\n%.3f %.3f %.3f\n%.3f %.3f %.3f\n%.3f %.3f %.3f\n"
    % (data[0][0], data[0][1], data[0][2], data[1][0], data[1][1], data[1][2],
       data[2][0], data[2][1], data[2][2], data[3][0], data[3][1], data[3][2]))
print(
    "sensor values normalized:\n%.3f %.3f %.3f\n%.3f %.3f %.3f\n%.3f %.3f %.3f\n%.3f %.3f %.3f\n"
Exemplo n.º 6
0
import matplotlib.pyplot as plt
from magpylib.source.magnet import Cylinder
from magpylib.source.current import Circular
from magpylib import Collection 

TURNS = 15
s = 91
LENGTH = 3
CURRENT = 1

# create magnets
s2 = Cylinder(mag=(0,0,500), dim=(3,5))
coil1 = [Circular(curr=CURRENT,dim=LENGTH,pos=[0,0,z]) for z in np.linspace(-3,3,TURNS)]

# create collection 
c1 = Collection(coil1)

xs = np.linspace(0, 0,6)
ys = np.linspace(0, 0,6)
zs = np.linspace(-9, 9, s)
F_POS = np.array([(x,y,z) for x in xs for y in ys for z in zs])

B = c1.getB(F_POS)[:s]
mags = [ math.sqrt(sum(i**2 for i in x)) for x in B ]
z_pos = [d for d in zs]
derivative = np.diff(mags)/np.diff(zs)
print(mags)


plt.plot(z_pos, mags, 'blue', label='B(x)')
plt.plot(z_pos[1:], derivative, 'red', label="B'(x)")
Exemplo n.º 7
0
# taken from https://magpylib.readthedocs.io/en/latest/_pages/2_guideExamples/

import numpy as np
import matplotlib.pyplot as plt
from magpylib.source.magnet import Box, Cylinder
from magpylib import Collection, displaySystem

# create magnets
s1 = Box(mag=(0, 0, 600), dim=(3, 3, 3), pos=(-4, 0, 3))
s2 = Cylinder(mag=(0, 0, 500), dim=(3, 5))

# create collection
c = Collection(s1, s2)

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

# manipulate collection
c.move((-2, 0, 0))

# calculate B-field on a grid
xs = np.linspace(-10, 10, 33)
zs = np.linspace(-10, 10, 44)
POS = np.array([(x, 0, z) for z in zs for x in xs])
Bs = c.getB(POS).reshape(44, 33, 3)  #<--VECTORIZED

# create figure
fig = plt.figure(figsize=(9, 5))
ax1 = fig.add_subplot(121, projection='3d')  # 3D-axis
ax2 = fig.add_subplot(122)  # 2D-axis
Exemplo n.º 8
0
s2 = Box(mag=[-500, 0, -500],
         dim=[3, 3, 3],
         pos=[0, 0, -3],
         angle=45,
         axis=[0, 1, 0])
s3 = Box(mag=[500, 0, -500],
         dim=[4, 4, 4],
         pos=[4, 0, 0],
         angle=45,
         axis=[0, 1, 0])
s4 = Box(mag=[-500, 0, 500],
         dim=[4, 4, 4],
         pos=[-4, 0, 0],
         angle=45,
         axis=[0, 1, 0])
c = Collection(s1, s2, s3, s4)

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

#calculate fields
Bs = c.getBsweep(posis)

#reshape array and calculate amplitude
Bs = Bs.reshape([100, 100, 3])
Bamp = np.linalg.norm(Bs, axis=2)

##define figure with 2d and 3d axes
fig = plt.figure(figsize=(8, 4))
Exemplo n.º 9
0
def displaySystem(sources, markers=listOfPos, subplotAx=None,
                        sensors=listOfSensors, suppress=False, 
                        direc=False, figsize=(8, 8)):
    """
    Shows the collection system in an interactive pyplot and returns a matplotlib figure identifier.

    WARNING
    -------
    As a result of an inherent problem in matplotlib the 
    Poly3DCollections z-ordering fails when bounding boxes intersect.


    Parameters
    ----------
    markers : list[scalar,scalar,scalar,[label]]
        List of position vectors to add visual markers to the display, optional label.
        Default: [[0,0,0]]

    Example
    -------
    >>> from magpylib import Collection, source
    >>> c=source.current.Circular(3,7)
    >>> x = Collection(c)
    >>> marker0 = [0,0,0,"Neutral Position"]
    >>> marker1 = [10,10,10]
    >>> x.displaySystem(markers=[ marker0,
    ...                           marker1])

    Parameters
    ----------
    sensors : list[sensor]
        List of :class:`~magpylib.Sensor` objects to add the display.
        Default: None

    Example
    -------
    >>> from magpylib import Collection, source
    >>> c=source.current.Circular(3,7)
    >>> x = Collection(c)
    >>> sensor0 = Sensor()
    >>> sensor1 = Sensor(pos=[1,2,3], angle=180)
    >>> x.displaySystem(sensors=[ sensor0,
    ...                           sensor1])


    Parameters
    ----------
    suppress : bool
        If True, only return Figure information, do not show. Interactive mode must be off.
        Default: False.


    Example
    -------
    >>> ## Suppress matplotlib.pyplot.show() 
    >>> ## and returning figure from showing up
    >>> from matplotlib import pyplot 
    >>> pyplot.ioff()
    >>> figureData = Collection.displayFigure(suppress=True)

    Parameters
    ----------
    direc : bool
        Set to True to show current directions and magnetization vectors.
        Default: False


    Return    
    ------
    matplotlib Figure object
        graphics object is displayed through plt.show()

    Example
    -------
    >>> from magpylib import source, Collection
    >>> pm1 = source.magnet.Box(mag=[0,0,1000],dim=[1,1,1],pos=[-1,-1,-1],angle=45,axis=[0,0,1])
    >>> pm2 = source.magnet.Cylinder(mag=[0,0,1000],dim=[2,2],pos=[0,-1,1],angle=45,axis=[1,0,0])
    >>> pm3 = source.magnet.Sphere(mag=[0,0,1000],dim=3,pos=[-2,1,2],angle=45,axis=[1,0,0])
    >>> C1 = source.current.Circular(curr=100,dim=6)
    >>> col = Collection(pm1,pm2,pm3,C1)
    >>> col.displaySystem()
    
    Parameters
    ----------
    subplotAx : matplotlib subplot axe instance
        Use an existing matplotlib subplot instance to draw the 3D system plot into.
        Default: None
    
    Example
    -------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from magpylib.source.magnet import Box
    >>> from magpylib import Collection
    >>> #create collection of one magnet
    >>> s1 = Box(mag=[ 500,0, 500], dim=[3,3,3], pos=[ 0,0, 3], angle=45, axis=[0,1,0])
    >>> c = Collection(s1)
    >>> #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 fields
    >>> Bs = c.getBsweep(posis)
    >>> #reshape array and calculate amplitude
    >>> Bs = np.array(Bs).reshape([100,100,3])
    >>> Bamp = np.linalg.norm(Bs,axis=2)
    >>> X,Z = np.meshgrid(xs,zs)
    >>> # Define figure
    >>> fig = plt.figure()
    >>> ## Define ax for 2D
    >>> ax1 = fig.add_subplot(1, 2, 1, axisbelow=True)
    >>> ## Define ax for 3D displaySystem
    >>> ax2 = fig.add_subplot(1, 2, 2, axisbelow=True,projection='3d')
    >>> ## field plot 2D
    >>> ax1.contourf(X,Z,Bamp,100,cmap='rainbow')
    >>> U,V = Bs[:,:,0], Bs[:,:,2]
    >>> ax1.streamplot(X, Z, U, V, color='k', density=2)
    >>> ## plot Collection system in 3D ax subplot
    >>> c.displaySystem(subplotAx=ax2)
    
    Raises
    ------
    AssertionError
        If Marker position list is poorly defined. i.e. listOfPos=(x,y,z) instead of lisOfPos=[(x,y,z)]
    """
    
    collection = Collection(sources)

    if subplotAx is None:
        fig = plt.figure(dpi=80, figsize=figsize)
        ax = fig.gca(projection='3d')
    else:
        ax = subplotAx

    # count magnets
    Nm = 0
    for s in collection.sources:
        if type(s) is Box or type(s) is Cylinder or type(s) is Sphere:
            Nm += 1
    
    cm = plt.cm.hsv  # Linter complains about this but it is working pylint: disable=no-member
    # select colors
    colors = [cm(x) for x in linspace(0, 1, Nm+1)]

    ii = -1
    SYSSIZE = finfo(float).eps  # Machine Epsilon for moment
    dipolesList = []
    magnetsList = []
    sensorsList = []
    currentsList = []
    markersList = []

    # Check input and Add markers to the Markers list before plotting
    for m in markers:
        assert isDisplayMarker(m), "Invalid marker definition in displaySystem:" + str(
            m) + ". Needs to be [vec3] or [vec3,string]"
        markersList += [m]
    
    for s in sensors:    
        if s == sensor1:
            continue
        else:
            assert isSensor(s), "Invalid sensor definition in displaySystem:" + str(
            s) 
            sensorsList.append(s)

    for s in collection.sources:
        if type(s) is Box:
            ii += 1  # increase color counter
            P = s.position
            D = s.dimension/2
            # create vertices in canonical basis
            v0 = array([D, D*array([1, 1, -1]), D*array([1, -1, -1]), D*array([1, -1, 1]),
                        D*array([-1, 1, 1]), D*array([-1, 1, -1]), -D, D*array([-1, -1, 1])])
            # rotate vertices + displace
            v = array([angleAxisRotation_priv(s.angle, s.axis, d)+P for d in v0])
            # create faces
            faces = [[v[0], v[1], v[2], v[3]],
                        [v[0], v[1], v[5], v[4]],
                        [v[4], v[5], v[6], v[7]],
                        [v[2], v[3], v[7], v[6]],
                        [v[0], v[3], v[7], v[4]],
                        [v[1], v[2], v[6], v[5]]]
            # plot
            boxf = Poly3DCollection(
                faces, facecolors=colors[ii], linewidths=0.5, edgecolors='k', alpha=1)
            ax.add_collection3d(boxf)
            # check system size
            maxSize = amax(abs(v))
            if maxSize > SYSSIZE:
                SYSSIZE = maxSize

            if direc is True:
                s.color = colors[ii]
                magnetsList.append(s)
        elif type(s) is Cylinder:
            ii += 1  # increase color counter
            P = s.position
            R, H = s.dimension/2

            resolution = 20

            # vertices
            phis = linspace(0, 2*pi, resolution)
            vertB0 = array([[R*cos(p), R*sin(p), -H] for p in phis])
            vertT0 = array([[R*cos(p), R*sin(p), H] for p in phis])
            # rotate vertices+displacement
            vB = array(
                [angleAxisRotation_priv(s.angle, s.axis, d)+P for d in vertB0])
            vT = array(
                [angleAxisRotation_priv(s.angle, s.axis, d)+P for d in vertT0])
            # faces
            faces = [[vT[i], vB[i], vB[i+1], vT[i+1]]
                        for i in range(resolution-1)]
            faces += [vT, vB]
            # plot
            coll = Poly3DCollection(
                faces, facecolors=colors[ii], linewidths=0.5, edgecolors='k', alpha=1)
            ax.add_collection3d(coll)
            # check system size
            maxSize = max([amax(abs(vB)), amax(abs(vT))])
            if maxSize > SYSSIZE:
                SYSSIZE = maxSize

            if direc is True:
                s.color = colors[ii]
                magnetsList.append(s)

        elif type(s) is Sphere:
            ii += 1  # increase color counter
            P = s.position
            R = s.dimension/2

            resolution = 12

            # vertices
            phis = linspace(0, 2*pi, resolution)
            thetas = linspace(0, pi, resolution)
            vs0 = [[[R*cos(phi)*sin(th), R*sin(phi)*sin(th), R*cos(th)]
                    for phi in phis] for th in thetas]
            # rotate vertices + displacement
            vs = array(
                [[angleAxisRotation_priv(s.angle, s.axis, v)+P for v in vss] for vss in vs0])
            # faces
            faces = []
            for j in range(resolution-1):
                faces += [[vs[i, j], vs[i+1, j], vs[i+1, j+1], vs[i, j+1]]
                            for i in range(resolution-1)]
            # plot
            boxf = Poly3DCollection(
                faces, facecolors=colors[ii], linewidths=0.5, edgecolors='k', alpha=1)
            ax.add_collection3d(boxf)
            # check system size
            maxSize = amax(abs(vs))
            if maxSize > SYSSIZE:
                SYSSIZE = maxSize

            if direc is True:
                s.color = colors[ii]
                magnetsList.append(s)

        elif type(s) is Line:
            P = s.position
            vs0 = s.vertices
            # rotate vertices + displacement
            vs = array(
                [angleAxisRotation_priv(s.angle, s.axis, v)+P for v in vs0])
            # plot
            ax.plot(vs[:, 0], vs[:, 1], vs[:, 2], lw=1, color='k')
            # check system size
            maxSize = amax(abs(vs))
            if maxSize > SYSSIZE:
                SYSSIZE = maxSize

            if direc is True:
                # These don't move in the original object,
                sCopyWithVertices = deepcopy(s)
                sCopyWithVertices.vertices = vs  # We just draw the frame rotation, discard changes
                currentsList.append(sCopyWithVertices)

        elif type(s) is Circular:
            P = s.position
            R = s.dimension/2

            resolution = 20

            # vertices
            phis = linspace(0, 2*pi, resolution)
            vs0 = array([[R*cos(p), R*sin(p), 0] for p in phis])
            # rotate vertices + displacement
            vs = array(
                [angleAxisRotation_priv(s.angle, s.axis, v)+P for v in vs0])
            # plot
            ax.plot(vs[:, 0], vs[:, 1], vs[:, 2], lw=1, color='k')
            # check system size
            maxSize = amax(abs(vs))
            if maxSize > SYSSIZE:
                SYSSIZE = maxSize

            if direc is True:
                # Send the Circular vertice information
                sCopyWithVertices = deepcopy(s)
                sCopyWithVertices.vertices = vs  # to the object drawing list
                currentsList.append(sCopyWithVertices)

        elif type(s) is Dipole:
            P = angleAxisRotation(s.position, s.angle, s.axis)
            maxSize = amax(abs(P))
            if maxSize > SYSSIZE:
                SYSSIZE = maxSize

            dipolesList.append(s)

    for m in markersList:  # Draw Markers
        ax.scatter(m[0], m[1], m[2], s=20, marker='x')
        if(len(m) > 3):
            zdir = None
            ax.text(m[0], m[1], m[2], m[3], zdir)
        # Goes up to 3rd Position
        maxSize = max([abs(pos) for pos in m[:3]])
        if maxSize > SYSSIZE:
            SYSSIZE = maxSize

    for s in sensorsList: # Draw Sensors
        maxSize = max([abs(pos) for pos in s.position])
        if maxSize > SYSSIZE:
            SYSSIZE = maxSize
        drawSensor(s,SYSSIZE,ax)

    for d in dipolesList:
        drawDipole(d.position, d.moment,
                    d.angle, d.axis,
                    SYSSIZE, ax)

    if direc is True:  # Draw the Magnetization axes and current directions
        drawCurrentArrows(currentsList, SYSSIZE, ax)
        drawMagAxis(magnetsList, SYSSIZE, ax)

    #for tick in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels()+ax.zaxis.get_ticklabels():
    #    tick.set_fontsize(12)
    ax.set_xlabel('x[mm]')#, fontsize=12)
    ax.set_ylabel('y[mm]')#, fontsize=12)   #change font size through rc parameters
    ax.set_zlabel('z[mm]')#, fontsize=12)
    ax.set(
        xlim=(-SYSSIZE, SYSSIZE),
        ylim=(-SYSSIZE, SYSSIZE),
        zlim=(-SYSSIZE, SYSSIZE),
    )
    
    plt.tight_layout()

    if suppress == True:
        return plt.gcf()
    else:
        plt.show()
    def optimize(self):
        res = least_squares(self.func, self.initial,\
            bounds = (self.lower_bound, self.upper_bound),\
            ftol=1e-8, \
            xtol=1e-8,verbose=2,\
            max_nfev=self.balljoint_config['calibration']['max_nfev'])

        field_strength = self.balljoint_config['field_strength']
        magnet_pos = self.balljoint_config['magnet_pos']
        magnet_angle = self.balljoint_config['magnet_angle']

        sensor_pos = self.balljoint_config['sensor_pos']
        sensor_angle = self.balljoint_config['sensor_angle']

        field_strength, magnet_pos_offsets, magnet_angle_offsets, sensor_pos_offsets, sensor_angle_offsets = self.decode(
            res.x)

        sensors = self.gen_sensors(sensor_pos, sensor_pos_offsets,
                                   sensor_angle, sensor_angle_offsets)

        print("b_field_error with calibration: %f\n" % self.func(res.x)[0])

        j = 0
        pos = self.sensor_log['position']
        for target in self.sensor_log['sensor_values']:
            print("target b_field for %f %f %f" %
                  (pos[j][0], pos[j][1], pos[j][2]))
            i = 0
            for sens in sensors:
                print('%.4f    %.4f    %.4f' %
                      (target[i][0], target[i][1], target[i][2]))
                i = i + 1
            print("b_field with calibration:")
            c = Collection(self.gen_magnets(field_strength,magnet_pos,magnet_pos_offsets, \
                                            magnet_angle,magnet_angle_offsets))
            c.rotate(angle=pos[j][0] * 180.0 / math.pi,
                     axis=(1, 0, 0),
                     anchor=(0, 0, 0))
            c.rotate(angle=pos[j][1] * 180.0 / math.pi,
                     axis=(0, 1, 0),
                     anchor=(0, 0, 0))
            c.rotate(angle=pos[j][2] * 180.0 / math.pi,
                     axis=(0, 0, 1),
                     anchor=(0, 0, 0))
            for sens in sensors:
                mag = sens.getB(c)
                print('%.4f    %.4f    %.4f' % (mag[0], mag[1], mag[2]))
            print('----------------------------------')
            j = j + 1

        print("\noptimization results:\n")
        for c in self.calib:
            if c == 0:
                print('field_strength')
                print(field_strength)
                self.balljoint_config['field_strength'] = field_strength
            if c == 1:
                print('magnet_pos_offsets')
                print(magnet_pos_offsets)
                self.balljoint_config[
                    'magnet_pos_offsets'] = magnet_pos_offsets
            if c == 2:
                print('magnet_angle_offsets')
                print(magnet_angle_offsets)
                self.balljoint_config[
                    'magnet_angle_offsets'] = magnet_angle_offsets
            if c == 3:
                print('sensor_pos_offsets')
                print(sensor_pos_offsets)
                self.balljoint_config[
                    'sensor_pos_offsets'] = sensor_pos_offsets
            if c == 4:
                print('sensor_angle_offsets')
                print(sensor_angle_offsets)
                self.balljoint_config[
                    'sensor_angle_offsets'] = sensor_angle_offsets

        timestamp = time.strftime("%Y%m%d-%H%M%S")
        input("Enter to write optimization to config file %s_%s..." %
              (timestamp, self.config_file))

        with open(timestamp + '_' + self.config_file, 'w') as file:
            documents = dump(self.balljoint_config, file)
            dim=(10, 10, 10),
            pos=(10.392304845, -6, 0),
            angle=60,
            axis=(0, 0, 1)),
        Box(mag=(0, 0, 500),
            dim=(10, 10, 10),
            pos=(-10.392304845, -6, 0),
            angle=-60,
            axis=(0, 0, 1))
    ]


mlab.options.offscreen = True
fig = mlab.figure(bgcolor=(1, 1, 1), size=(1500, 1500), fgcolor=(0, 0, 0))
for iter in range(126, 360):
    c = Collection(gen_magnets())
    c.rotate(iter, (0, 1, 0), (0, 0, 0))
    x_lower, x_upper = -20, 20
    y_lower, y_upper = -20, 20
    z_lower, z_upper = -20, 20
    grid_spacing_value = 1  #0.25
    xd = int((x_upper - x_lower) / grid_spacing_value)
    yd = int((y_upper - y_lower) / grid_spacing_value)
    zd = int((z_upper - z_lower) / grid_spacing_value)

    x, y, z = np.mgrid[x_lower:x_upper:xd * 1j, y_lower:y_upper:yd * 1j,
                       z_lower:z_upper:zd * 1j]

    xs = np.linspace(x_lower, x_upper, xd)
    ys = np.linspace(y_lower, y_upper, yd)
    zs = np.linspace(z_lower, z_upper, zd)
        Box(mag=(0, 500, 0), dim=(10, 10, 10), pos=(0, 12, 0)),
        Box(mag=(0, 500, 0),
            dim=(10, 10, 10),
            pos=(10.392304845, -6, 0),
            angle=60,
            axis=(0, 0, 1)),
        Box(mag=(0, 500, 0),
            dim=(10, 10, 10),
            pos=(-10.392304845, -6, 0),
            angle=-60,
            axis=(0, 0, 1))
    ]
    # return [Box(mag=(0,500,0),dim=(10,10,10),pos=(0,12,0)), Box(mag=(0,-500,0),dim=(10,10,10),pos=(10.392304845,-6,0),angle=60, axis=(0,0,1)), Box(mag=(0,0,500),dim=(10,10,10),pos=(-10.392304845,-6,0),angle=-60, axis=(0,0,1))]


c = Collection(gen_magnets())

# calculate B-field on a grid
xs = np.linspace(-30, 30, 33)
zs = np.linspace(-30, 30, 44)
POS = np.array([(x, 0, z) for z in zs for x in xs])

# create figure
fig = plt.figure(figsize=(9, 5))
ax1 = fig.add_subplot(121, projection='3d')  # 3D-axis
ax2 = fig.add_subplot(122)  # 2D-axis

Bs = c.getB(POS).reshape(44, 33, 3)  #<--VECTORIZED
X, Z = np.meshgrid(xs, zs)
U, V = Bs[:, :, 0], Bs[:, :, 2]
ax2.streamplot(X, Z, U, V, color=np.log(U**2 + V**2))
Exemplo n.º 13
0
record = open("/home/letrend/workspace/roboy3/" + body_part + "_data0.log",
              "w")
record.write(
    "mx0 my0 mz0 mx1 my1 mz1 mx2 my2 mz3 mx3 my3 mz3 roll pitch yaw\n")

first = True

for iter in range(iterations):
    rot = [
        random.uniform(-50, 50),
        random.uniform(-50, 50),
        random.uniform(-90, 90)
    ]

    c = Collection(gen_magnets())
    c.rotate(rot[0], (1, 0, 0), anchor=(0, 0, 0))
    c.rotate(rot[1], (0, 1, 0), anchor=(0, 0, 0))
    c.rotate(rot[2], (0, 0, 1), anchor=(0, 0, 0))

    data = []
    for sens in sensors:
        data.append(sens.getB(c))

    record.write(
        str(data[0][0]) + " " + str(data[0][1]) + " " + str(data[0][2]) + " " +
        str(data[1][0]) + " " + str(data[1][1]) + " " + str(data[1][2]) + " " +
        str(data[2][0]) + " " + str(data[2][1]) + " " + str(data[2][2]) + " " +
        str(data[3][0]) + " " + str(data[3][1]) + " " + str(data[3][2]) + " " +
        str(rot[0] / 180.0 * math.pi) + " " + str(rot[1] / 180.0 * math.pi) +
        " " + str(rot[2] / 180.0 * math.pi) + "\n")
Exemplo n.º 14
0
"""
Define and display the Electromagnetic Field contour of 
a Dipole moment.
"""

from magpylib import source, Collection
import numpy as np
from matplotlib import pyplot as plt
d = source.moment.Dipole((100, 20, 300))

pmc = Collection(d)
fig = pmc.displaySystem(direc=True)

fig.suptitle("Source Moment")

xs = np.linspace(-15, 15, 50)
zs = np.linspace(-15, 15, 50)
Bs = np.array([[pmc.getB([x, 0, z]) for x in xs] for z in zs])

# display fields
fig = plt.figure(figsize=(10, 8), facecolor='w', dpi=80)
AXS = [fig.add_subplot(1, 1, i, axisbelow=True) for i in range(1, 2)]
ax1 = AXS[0]

X, Y = np.meshgrid(xs, zs)
U, V = Bs[:, :, 0], Bs[:, :, 2]
amp = np.sqrt(U**2 + V**2)
ax1.contourf(X, Y, amp, np.linspace(0, 130, 100), cmap=plt.cm.brg)  # pylint: disable=no-member
ax1.streamplot(X, Y, U, V, color='w', density=3, linewidth=0.8)

ax1.set(title='B-field of Dipole Moment',
Exemplo n.º 15
0
def MagneticSensorCallback(data):
    global k
    global j
    global pbar
    global sensor_value_counter
    global values

    if k >= len(ball_pos):
        rospy.signal_shutdown("no more")
        return

    if data.id is not int(balljoint_config['id']):
        return
    sensor_value_counter = sensor_value_counter + 1

    if sensor_value_counter < 10:
        pbar = tqdm(total=average_samples)
        j = 0
        i = 0
        values = []
        for sens in data.x:
            values.append([data.x[i], data.y[i], data.z[i]])
            i = i + 1
        return

    if j < average_samples:
        pbar.update(1)
        i = 0
        for sens in data.x:
            values[i][0] = values[i][0] + data.x[i]
            values[i][1] = values[i][1] + data.y[i]
            values[i][2] = values[i][2] + data.z[i]
            i = i + 1
        j = j + 1
        return
    j = 0
    i = 0
    for sens in data.x:
        values[i][0] = values[i][0] / average_samples
        values[i][1] = values[i][1] / average_samples
        values[i][2] = values[i][2] / average_samples
        i = i + 1
    sensor_value_counter = 0
    sensor_log['position'].append(ball_pos[k])
    sensor_log['sensor_values'].append(values)

    print(sensor_log)

    magnets = Collection(gen_magnets(balljoint_config['field_strength'],balljoint_config['magnet_dimension'],balljoint_config['magnet_pos'],balljoint_config['magnet_pos_offsets'], \
                                    balljoint_config['magnet_angle'],balljoint_config['magnet_angle_offsets']))
    magnets.rotate(ball_pos[k][0] * 180 / math.pi, (1, 0, 0), anchor=(0, 0, 0))
    magnets.rotate(ball_pos[k][1] * 180 / math.pi, (0, 1, 0), anchor=(0, 0, 0))
    magnets.rotate(ball_pos[k][2] * 180 / math.pi, (0, 0, 1), anchor=(0, 0, 0))
    print('simulated:')
    for sens in sensors:
        print(sens.getB(magnets))
    print('recorded:')
    for v in values:
        print(v)
    k = k + 1
    input("Press Enter for next ball position: %f %f %f" %
          (ball_pos[k][0], ball_pos[k][1], ball_pos[k][2]))