def CalcField(g): #Vertical Magnetic Field vs Horizontal Position xMin = 0 xMax = 50 nx = 51 xStep = (xMax - xMin) / (nx - 1) yc = 0 zc = 0 x = xMin Points = [] X = [] for i in range(nx): Points.append([x, yc, zc]) X.append(x) x += xStep ByVsX = rad.Fld(g, 'by', Points) #Vertical Magnetic Field vs Longitudinal Position zMin = -400 zMax = 400 nz = 401 zStep = (zMax - zMin) / (nz - 1) xc = 40 yc = 0 z = zMin Z = [] Points = [] for i in range(nz): Points.append([xc, yc, z]) Z.append(z) z += zStep ByVsZ = rad.Fld(g, 'by', Points) return ByVsX, [xMin, xMax, nx], X, ByVsZ, [zMin, zMax, nz], Z
def CalcField(g): #Vertical Magnetic Field vs Longitudinal Position yMin = 0.; yMax = 300.; ny = 301 yStep = (yMax - yMin)/(ny - 1) xc = 0.; zc = 0. #y = yMin #Points = [] #for i in range(ny): # Points.append([xc,y,zc]) # y += yStep #BzVsY = rad.Fld(g, 'bz', Points) #More compact method to do the above: BzVsY = rad.Fld(g, 'bz', [[xc,yMin+iy*yStep,zc] for iy in range(ny)]) #Vertical Magnetic Field Integral (along Longitudinal Position) vs Horizontal Position xMin = 0.; xMax = 400.; nx = 201 xStep = (xMax - xMin)/(nx - 1) zc = 0. #x = xMin #IBzVsX = [] #for i in range(ny): # IBzVsX.append(rad.FldInt(g, 'inf', 'ibz', [x,-300.,zc], [x,300.,zc])) # x += xStep #More compact method to do the above: IBzVsX = [rad.FldInt(g, 'inf', 'ibz', [xMin+ix*xStep,-300.,zc], [xMin+ix*xStep,300.,zc]) for ix in range(nx)] return BzVsY, [yMin, yMax, ny], IBzVsX, [xMin, xMax, nx]
def BfieldStreamPlot(self, fields='bxbz', plotdims=np.array([0, 100, 0, 100])): #region of V magnets Zv, Xv = np.mgrid[plotdims[2]:plotdims[3]:41j, plotdims[0]:plotdims[1]:41j] Bxv = Xv.copy() Bzv = Zv.copy() for i in range(len(Xv)): for j in range(len(Zv)): #print ('coords are {}'.format([Xv[i,j],Zv[i,j]])) Bxv[i, j], Bzv[i, j] = rd.Fld(self.cont.radobj, fields, [Xv[i, j], 0, Zv[i, j]]) #print ('the field at those coords are Bx: {} Bz: {}'.format(Bxv[i,j],Bzv[i,j])) fig = plt.figure(figsize=(7, 9)) gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2]) # Varying density along a streamline ax0 = fig.add_subplot(gs[0, 0]) ax0.streamplot(Xv, Zv, Bxv, Bzv, density=[0.5, 1]) for i in range(2): for j in range(4, 7, 2): ax0.plot(self.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], self.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax0.set_title('Vertical Comp Magnets') ax0.set_aspect('equal') return ax0
def test_radia_simple_magnet(self): rad.UtiDelAll() magnet = rad.ObjRecMag([0,0,0], [1,1,1], [0,1,0]) observed = np.array(rad.Fld(magnet, 'b', [1,2,3]), dtype=np.float32) expected = np.array([0.0006504201540729257, -0.00021819974895862903, 0.0019537852236147252], dtype=np.float32) self.assertTrue(np.allclose(observed, expected))
def save_fieldmap_spectra(radia_object, filename, xlist, ylist, zlist): t0 = _time.time() if isinstance(xlist, (float, int)): xlist = [xlist] if isinstance(ylist, (float, int)): ylist = [ylist] if isinstance(zlist, (float, int)): zlist = [zlist] xlist = _np.round(xlist, decimals=8) ylist = _np.round(ylist, decimals=8) zlist = _np.round(zlist, decimals=8) nx = len(xlist) ny = len(ylist) nz = len(zlist) if len(xlist) == 1: xstep = 0 else: xstep = xlist[1] - xlist[0] if len(ylist) == 1: ystep = 0 else: ystep = ylist[1] - ylist[0] if len(zlist) == 1: zstep = 0 else: zstep = zlist[1] - zlist[0] header_data = [xstep, ystep, zstep, nx, ny, nz] header = '{0:g} {1:g} {2:g} {3:d} {4:d} {5:d}\n'.format(*header_data) with open(filename, 'w') as fieldmap: fieldmap.write(header) line_fmt = '{0:g}\t{1:g}\t{2:g}\n' for x in xlist: for y in ylist: for z in zlist: bx, by, bz = _rad.Fld(radia_object, "b", [x, y, z]) line = line_fmt.format(bx, by, bz) fieldmap.write(line) t1 = _time.time() dt = t1 - t0 return dt
def get_field(self, name, f_type, path): pv_arr = [] p = numpy.reshape(path, (-1, 3)).tolist() b = [] # get every component f = radia.Fld(self.get_geom(name), f_type, path) b.extend(f) b = numpy.reshape(b, (-1, 3)).tolist() for p_idx, pt in enumerate(p): pv_arr.append([pt, b[p_idx]]) return get_field(self.get_geom(name), f_type, path)
def get_field(radia_object, component='b', x=0, y=0, z=0): if isinstance(x, (float, int)): x = [x] if isinstance(y, (float, int)): y = [y] if isinstance(z, (float, int)): z = [z] if sum([len(i) > 1 for i in [x, y, z]]) > 1: raise ValueError('Invalid position arguments.') if len(x) > 1: field = [_rad.Fld(radia_object, component, [xi, y, z]) for xi in x] elif len(y) > 1: field = [_rad.Fld(radia_object, component, [x, yi, z]) for yi in y] elif len(z) > 1: field = [_rad.Fld(radia_object, component, [x, y, zi]) for zi in z] else: field = [_rad.Fld(radia_object, component, [x, y, z])] return _np.array(field)
def compute_fields(points_list, radia_object_id = None, field_component = 'bz'): m = len(points_list) k = m / size ## decompose the domain of the field calcaulation to the different processors and send the arrays if rank == 0: radia_object = rad.UtiDmp([radia_object_id], 'bin') for i in range(1, size): comm.send(radia_object, dest = i) else: radia_object = comm.recv(source = 0) device_id = rad.UtiDmpPrs(radia_object) ## convert the arrrays back into radia friendly format calc_points = np.asarray(points_list[rank::size]) radia_points = np.ndarray.tolist(calc_points) # Compute the fields at the points specified field_result = rad.Fld(device_id, field_component, radia_points) # construct arrays to gather points and field solution for plotting and analysis sendbuf = np.column_stack([calc_points, np.asarray(field_result)]) row,col = sendbuf.shape recvbuf = None if rank == 0: recvbuf = np.empty([size, k+1, col]) # Gather the arrays from the different processors comm.Gather(sendbuf, recvbuf, root = 0) # Return the field result if rank == 0: # clean up the data after collecting it data_out = recvbuf.reshape([size * (k + 1), col]) bad_points = np.where((data_out > 1.0e20) + (data_out < -1.0e20) ) data_out = np.delete(data_out, bad_points[0], axis = 0) # sort the data before returning, sort by x, then y, then z indices = np.lexsort((data_out[:,0], data_out[:,1], data_out[:,2])) data_out = [data_out[i,:]for i in indices] return np.asarray(data_out) else: return None
def build_model(self): """Build a Radia or Opera model with the current result set.""" length = self.length_spinbox.value() if self.build_button.text() == 'Radia': rad.UtiDelAll() item = self.listview.selectedItems()[0] # build magnet geometry magnet = rad.ObjCnt([rad.ObjThckPgn(0, length, pg[2:].reshape((4, 2)).tolist(), "z", list(pg[:2]) + [0, ]) for pg in self.state['results'][tuple(item.text().split(', '))]]) rad.MatApl(magnet, rad.MatStd('NdFeB', next(c for c in self.controls if c.switch == 'Br').control.value())) # plot geometry in 3d ax = self.plot3d.axes ax.cla() ax.set_axis_off() polygons = rad.ObjDrwVTK(magnet)['polygons'] vertices = np.array(polygons['vertices']).reshape((-1, 3)) # [x, y, z, x, y, z] -> [[x, y, z], [x, y, z]] [set_lim(vertices.min(), vertices.max()) for set_lim in (ax.set_xlim3d, ax.set_ylim3d, ax.set_zlim3d)] vertices = np.split(vertices, np.cumsum(polygons['lengths'])[:-1]) # split to find each face ax.add_collection3d(Poly3DCollection(vertices, linewidths=0.1, edgecolors='black', facecolors=self.get_colour(), alpha=0.2)) # add arrows magnetisation = np.array(rad.ObjM(magnet)).reshape((-1, 6)).T # reshape to [x, y, z, mx, my, mz] for end in (-1, 1): # one at each end of the block, not in the middle magnetisation[2] = end * length / 2 ax.quiver(*magnetisation, color='black', lw=1, pivot='middle') self.tab_control.setCurrentIndex(2) # switch to '3d' tab # solve the model try: rad.Solve(magnet, 0.00001, 10000) # precision and number of iterations except RuntimeError: self.statusBar().showMessage('Radia solve error') # get results dx = 0.1 multipoles = [mpole_names.index(c.label) for c in self.controls if c.label.endswith('pole') and c.get_arg()] i = multipoles[-1] xs = np.linspace(-dx, dx, 4) fit_field = np.polyfit(xs / 1000, [rad.Fld(magnet, 'by', [x, 0, 0]) for x in xs], i) fit_int = np.polyfit(xs / 1000, [rad.FldInt(magnet, 'inf', 'iby', [x, 0, -1], [x, 0, 1]) * 0.001 for x in xs], i) text = '' for j, (l, c, ic, u, iu) in enumerate( zip(mpole_names, fit_field[::-1], fit_int[::-1], units[1:], units[:-1])): if j in multipoles: f = factorial(j) # 1 for dip, quad; 2 for sext; 6 for oct text += f'{l} field = {c * f:.3g} {u}, integral = {ic * f:.3g} {iu}, length = {ic / c:.3g} m\n' ax.text2D(1, 1, text, transform=ax.transAxes, va='top', ha='right', fontdict={'size': 8}) self.plot3d.canvas.draw()
def get_field(g_id, f_type, path): if len(path) == 0: return [] pv_arr = [] p = numpy.reshape(path, (-1, 3)).tolist() b = [] # get every component f = radia.Fld(g_id, f_type, path) b.extend(f) b = numpy.reshape(b, (-1, 3)).tolist() for p_idx, pt in enumerate(p): pv_arr.append([pt, b[p_idx]]) return pv_arr
def get_field(geom, f_type, path): #pkdp('GET FIELD FOR {} TYPE {} PATH {}', geom, f_type, path) if len(path) == 0: return [] pv_arr = [] p = numpy.reshape(path, (-1, 3)).tolist() b = [] # get every component f = radia.Fld(geom, f_type, path) b.extend(f) b = numpy.reshape(b, (-1, 3)).tolist() for p_idx, pt in enumerate(p): pv_arr.append([pt, b[p_idx]]) return pv_arr
def eval_hybrid_und(_gap, _gap_ofst, _nper, _air, _pole_width, _lp, _ch_p, _np, _np_tip, _mp, _cp, _lm, _ch_m_xz, _ch_m_yz, _ch_m_yz_r, _nm, _mm, _cm, _use_ex_sym=False): from mpi4py import MPI comMPI = MPI.COMM_WORLD size = comMPI.Get_size() rank = comMPI.Get_rank() rad.UtiMPI('in') _lp = [_pole_width, *_lp] # Set up material properties if they weren't created by a pre-process function if not _mp or not _mm: # Pole Material # B [G] vs H [G] data from NEOMAX BvsH_G = [[0., 0], [0.5, 5000], [1, 10000], [1.5, 13000], [2, 15000], [3, 16500], [4, 17400], [6, 18500], [8, 19250], [10, 19800], [12, 20250], [14, 20600], [16, 20900], [18, 21120], [20, 21250], [25, 21450], [30, 21590], [40, 21850], [50, 22000], [70, 22170], [100, 22300], [200, 22500], [300, 22650], [500, 23000], [1000, 23900], [2000, 24900]] MvsH_T = [[BvsH_G[i][0]*1.e-4, (BvsH_G[i][1]-BvsH_G[i][0])*1.e-4] for i in range(len(BvsH_G))] _mp = rad.MatSatIsoTab(MvsH_T) # Magnet Material magBr = 1.67 # Remanent Magnetization _mm = rad.MatLin({0.05, 0.15}, magBr) grp = HybridUndCenPart(_gap, _gap_ofst, _nper, _air, _lp, _ch_p, _np, _np_tip, _mp, _cp, _lm, _ch_m_xz, _ch_m_yz, _ch_m_yz_r, _nm, _mm, _cm, _use_ex_sym) # Construct Interaction Matrix t0 = time.time() IM = rad.RlxPre(grp) # Perform the Relaxation t0 = time.time() res = rad.RlxAuto(IM, 0.001, 5000) # Synchronizing all processes rad.UtiMPI('barrier') Bz0 = rad.Fld(grp, 'bz', [0,0,0]) if rank <= 0: print("Bz0:", Bz0) if size > 1: if rank == 0: np.save(NP_FILENAME, Bz0) rad.UtiMPI('off') return Bz0
def get_field(g_id, f_type, path): if len(path) == 0: return [] pv_arr = [] p = numpy.reshape(path, (-1, 3)).tolist() b = [] # get every component (meaning e.g. passing 'B' and not 'Bx' etc.) f = radia.Fld(g_id, f_type, path) # a dummy value returned by parallel radia if f == 0: f = numpy.zeros(len(path)) b.extend(f) b = numpy.reshape(b, (-1, 3)).tolist() for p_idx, pt in enumerate(p): pv_arr.append([pt, b[p_idx]]) return pv_arr
def CalcField(g, per, numPer): #Vertical Magnetic Field vs Longitudinal Position yMax = per * (numPer + 1) / 2 yMin = -yMax ny = 301 yStep = (yMax - yMin) / (ny - 1) xc = 0 zc = 0 #y = yMin #Points = [] #for i in range(ny): # Points.append([xc,y,zc]) # y += yStep #BzVsY = rad.Fld(g, 'bz', Points) #A more compact way: BzVsY = rad.Fld(g, 'bz', [[xc, yMin + iy * yStep, zc] for iy in range(ny)]) return BzVsY, [yMin, yMax, ny]
def save_fieldmap(radia_object, filename, xlist, ylist, zlist, header=None): t0 = _time.time() if header is None: header = [] if isinstance(xlist, (float, int)): xlist = [xlist] if isinstance(ylist, (float, int)): ylist = [ylist] if isinstance(zlist, (float, int)): zlist = [zlist] xlist = _np.round(xlist, decimals=8) ylist = _np.round(ylist, decimals=8) zlist = _np.round(zlist, decimals=8) with open(filename, 'w') as fieldmap: for line in header: fieldmap.write(line) fieldmap.write('X[mm]\tY[mm]\tZ[mm]\tBx[T]\tBy[T]\tBz[T]\n') fieldmap.write('----------------------------------------' + '----------------------------------------' + '----------------------------------------' + '----------------------------------------\n') line_fmt = '{0:g}\t{1:g}\t{2:g}\t{3:g}\t{4:g}\t{5:g}\n' for z in zlist: for y in ylist: for x in xlist: bx, by, bz = _rad.Fld(radia_object, "b", [x, y, z]) line = line_fmt.format(x, y, z, bx, by, bz) fieldmap.write(line) t1 = _time.time() dt = t1 - t0 return dt
def undulatorK_simple(obj, per, pf_loc=None, prec=1e-5, maxIter=10000, lprint=False): """ compute undulator K value arguments: obj = undulator object per = undulator period / m pf_loc = peak field location [x, y, z]. Defaults to [0, 0, 0] if not given. prec = precision goal for this computation maxIter = maximum allowed iterations lprint: whether or not to print results return: K = (e B_0 \lambda_u) / (2\pi m_e c) """ if pf_loc is None: pf_loc = [0, 0, 0] res = rad.Solve(obj, prec, maxIter) peak_field = abs(rad.Fld(obj, 'bz', pf_loc)) # peak field / T k = sc.e * peak_field * per * 1e-3 / (2 * np.pi * sc.m_e * sc.c) if lprint: print("peak field:", peak_field, "(calculated at given location", pf_loc, ")\nperiod is", per, "(given input)\nk is", k) return k
def calc_trajectory(radia_object, energy, r0, zmax, rkstep, dz=0, on_axis_field=False): if radia_object is None: return None electron_rest_energy, light_speed = _utils.get_constants() r1 = _np.zeros(6, dtype=float) r2 = _np.zeros(6, dtype=float) r3 = _np.zeros(6, dtype=float) beta = _np.sqrt(1 - 1 / ((energy * 1e9 / electron_rest_energy)**2)) brho = energy * 1e9 / light_speed a = 1 / brho / beta # from mm to m r = _np.array(r0, dtype=float) r[0] = r[0] / 1000 r[1] = r[1] / 1000 r[2] = (r[2] + dz) / 1000 step = rkstep / 1000 trajectory = [] trajectory.append( [r[0] * 1000, r[1] * 1000, r[2] * 1000, r[3], r[4], r[5]]) while r[2] < zmax / 1000: pos = [p * 1000 for p in r[:3]] if on_axis_field: pos[0], pos[1] = 0, 0 b = _rad.Fld(radia_object, "b", pos) drds1 = newton_lorentz_equation(a, r, b) r1 = r + (step / 2) * drds1 pos1 = [p * 1000 for p in r1[:3]] if on_axis_field: pos1[0], pos1[1] = 0, 0 b1 = _rad.Fld(radia_object, "b", pos1) drds2 = newton_lorentz_equation(a, r1, b1) r2 = r + (step / 2) * drds2 pos2 = [p * 1000 for p in r2[:3]] if on_axis_field: pos2[0], pos2[1] = 0, 0 b2 = _rad.Fld(radia_object, "b", pos2) drds3 = newton_lorentz_equation(a, r2, b2) r3 = r + step * drds3 pos3 = [p * 1000 for p in r3[:3]] if on_axis_field: pos3[0], pos3[1] = 0, 0 b3 = _rad.Fld(radia_object, "b", pos3) drds4 = newton_lorentz_equation(a, r3, b3) r = r + (step / 6) * (drds1 + 2 * drds2 + 2 * drds3 + drds4) trajectory.append( [r[0] * 1000, r[1] * 1000, r[2] * 1000, r[3], r[4], r[5]]) trajectory = _np.array(trajectory) return trajectory
np5 = ceil(np3 / 2) print() nr5 = ny t0 = time() rad.UtiDelAll() ironmat = rad.MatSatIsoFrm([2000, 2], [0.1, 2], [0.1, 2]) g = Geom() size = rad.ObjDegFre(g) t1 = time() Nmax = 10000 res = rad.Solve(g, 0.00001, Nmax) t2 = time() Bz = rad.Fld(g, 'Bz', [0, 1, 0]) * 1000 Iz = rad.FldInt(g, 'inf', 'ibz', [-1, 1, 0], [1, 1, 0]) Iz1 = rad.FldInt(g, 'inf', 'ibz', [-1, 10, 0], [1, 10, 0]) / 10 print('M_Max H_Max N_Iter = ', round(res[1], 4), 'T', round(res[2], 4), 'T', round(res[3])) if (res[3] == Nmax): print('Unstable or Incomplete Relaxation') print('Built & Solved in ', round(t1 - t0, 3), '&', round(t2 - t1, 3), ' seconds') print('Interaction Matrix : ', size, 'X', size, 'or', round(size * size * 4 / 1000000, 3), 'MB') print('Gradient = ', round(Bz, 4), 'T/m') print('Int. Quad. @ 1 mm = ', round(Iz, 5), 'T') print('Delta Int. Quad. @ 10 mm = ', round(100 * (Iz1 / Iz - 1), 2), '%') #Display the Geometry
############################################################################# # RADIA Python Example #1: Magnetic field created by rectangular parallelepiped with constant magnetization over volume # v 0.02 ############################################################################# from __future__ import print_function #Python 2.7 compatibility import radia as rad print('RADIA Library Version:', rad.UtiVer(), '\n') print('RADIA Python Example #1:') print('This is the simplest example. A magnetized cube is placed at position [0,0,0].') print('It is 1 mm in size and is magnetized according to the vector [-0.5,1,0.7] in Tesla.') print('The three components of the field at position [0.52,0.6,0.7] are computed.') print('Values close to [0.12737,0.028644,0.077505] are expected.') print('') m = rad.ObjRecMag([0,0,0], [1,1,1], [-0.5,1,0.7]) B = rad.Fld(m, "b", [0.52,0.6,0.7]) print(B)
print('Interaction Matrix was set up in:', round(time.time() - t0, 2), 's') #Perform the Relaxation t0 = time.time() res = rad.RlxAuto(IM, 0.001, 5000) if (rank <= 0): print('Relaxation took:', round(time.time() - t0, 2), 's') print('Relaxation Results:', res) #Synchronizing all processes rad.UtiMPI('barrier') print(' After Relaxation: rank=', rank, ' t=', time.time()) #Calculate Magnetic Field after the Relaxation Bz0 = rad.Fld(grp, 'bz', [0, 0, 0]) if (rank <= 0): print('Bz0=', Bz0) t0 = time.time() nyPer = 200 yMax = 0.7 * nPer * per ny = int(1.4 * nPer * nyPer) + 1 yStep = 2 * yMax / (ny - 1) Bz = rad.Fld(grp, 'bz', [[0, -yMax + iy * yStep, 0] for iy in range(ny)]) #Synchronizing all processes rad.UtiMPI('barrier') print(' After Field Calculation: rank=', rank, ' t=', time.time()) if (rank <= 0):
def XY_field_sheet(model, linewidth=1): #5 plots on A4 #vertical upper compensation magnets (Q1, Q2) #vertical lower compensation magnet (Q3, Q4) #horizontal bank side (-X) (Q1, Q3) #horizontal structure side (+X) (Q2, Q4) #define important values for plot scales extreme_X = model.model_parameters.nominal_fmagnet_dimensions[ 2] + model.model_parameters.nominal_hcmagnet_dimensions[ 2] + 3 * model.model_parameters.compappleseparation / 2.0 + model.model_parameters.rowtorowgap mid_X = model.model_parameters.nominal_fmagnet_dimensions[ 2] + model.model_parameters.compappleseparation / 2.0 + model.model_parameters.rowtorowgap short_X = model.model_parameters.nominal_vcmagnet_dimensions[ 0] + model.model_parameters.rowtorowgap / 2.0 + model.model_parameters.compappleseparation / 2.0 extreme_Z = model.model_parameters.nominal_fmagnet_dimensions[ 0] + model.model_parameters.nominal_vcmagnet_dimensions[ 2] + 3 * model.model_parameters.compappleseparation / 2.0 + model.model_parameters.rowtorowgap mid_Z = model.model_parameters.nominal_fmagnet_dimensions[ 2] + model.model_parameters.compappleseparation / 2.0 + model.model_parameters.rowtorowgap short_Z = model.model_parameters.nominal_vcmagnet_dimensions[ 0] + model.model_parameters.gap / 2.0 + model.model_parameters.compappleseparation / 2.0 #plot for V compensation Magnets Q1, Q2 plotdims = np.array([-short_X, short_X, mid_Z, extreme_Z]) fields = 'bxbz' axsQ1Q2 = model.BfieldStreamPlot(fields, plotdims) Zv, Xv = np.mgrid[20:40:41j, -10:10:41j] Bxv = Xv.copy() Bzv = Zv.copy() for i in range(len(Xv)): for j in range(len(Zv)): #print ('coords are {}'.format([Xv[i,j],Zv[i,j]])) Bxv[i, j], Bzv[i, j] = rd.Fld(model.cont.radobj, 'bxbz', [Xv[i, j], 0, Zv[i, j]]) #print ('the field at those coords are Bx: {} Bz: {}'.format(Bxv[i,j],Bzv[i,j])) fig = plt.figure(figsize=(7, 9)) gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2]) # Varying density along a streamline ax0 = fig.add_subplot(gs[0, 0]) ax0.streamplot(Xv, Zv, Bxv, Bzv, density=[0.5, 1]) for i in range(2): for j in range(4, 7, 2): ax0.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax0.set_title('Vertical Comp Magnets') ax0.set_aspect('equal') # Varying color along a streamline ax1 = fig.add_subplot(gs[0, 1]) strm = ax1.streamplot(Xv, Zv, Bxv, Bzv, color=Bzv, linewidth=2, cmap='autumn') fig.colorbar(strm.lines) for i in range(2): for j in range(4, 7, 2): ax1.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax1.set_title('Vertical Comp Magnets') #region of H magnets Zh, Xh = np.mgrid[-10:10:41j, 20:40:41j] BXh = Xh.copy() BZh = Zh.copy() for i in range(len(Xh)): for j in range(len(Zh)): #print ('coords are {}'.format([X[i,j],Y[i,j]])) BXh[i, j], BZh[i, j] = rd.Fld(model.cont.radobj, 'bxbz', [Xh[i, j], 0, Zh[i, j]]) #print ('the field at those coords are Bx: {} Bz: {}'.format(a,b)) ax1.set_aspect('equal') # Varying density along a streamline ax2 = fig.add_subplot(gs[1, 0]) ax2.streamplot(Xh, Zh, BXh, BZh, density=[0.5, 1]) ax2.set_title('Horizontal Comp Magnets') for i in range(2): for j in range(7, 12, 4): ax2.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax2.set_aspect('equal') # Varying color along a streamline ax3 = fig.add_subplot(gs[1, 1]) strm = ax3.streamplot(Xh, Zh, BXh, BZh, color=BZh, linewidth=2, cmap='autumn') fig.colorbar(strm.lines) for i in range(2): for j in range(7, 12, 4): ax3.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax3.set_title('Horizontal Comp Magnets') ax3.set_aspect('equal') #region of Functional magnets Zf, Xf = np.mgrid[-40:40:81j, -40:40:81j] BXf = Xf.copy() BZf = Zf.copy() for i in range(len(Xf)): for j in range(len(Zf)): #print ('coords are {}'.format([X[i,j],Y[i,j]])) BXf[i, j], BZf[i, j] = rd.Fld(model.cont.radobj, 'bxbz', [Xf[i, j], 0, Zf[i, j]]) #print ('the field at those coords are Bx: {} Bz: {}'.format(a,b)) # Varying density along a streamline ax4 = fig.add_subplot(gs[2, 0]) ax4.streamplot(Xf, Zf, BXf, BZf, density=[0.5, 1]) ax4.set_title('Functional Magnets') for i in range(3): for j in range(4): ax4.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') for i in range(2): for j in range(4, 12): ax4.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax4.set_aspect('equal') # Varying color along a streamline ax5 = fig.add_subplot(gs[2, 1]) #strm = ax5.streamplot(Xf, Zf, BXf, BZf, color=BZf, linewidth=1, cmap='autumn') #fig.colorbar(strm.lines) ax5.set_title('Functional Magnets') for i in range(3): for j in range(4): ax5.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') for i in range(2): for j in range(4, 12): ax5.plot(model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 0], model.cont.objectlist[j].objectlist[0].objectlist[0]. objectlist[i].vertices[:, 2], color='k') ax5.set_aspect('equal') plt.show()
apple_clampcut=3.0, comp_magnet_chamfer=[3.0, 0.0, 3.0], magnets_per_period=4, gap=2, rowshift=0, shiftmode='circular') a = compensatedAPPLEv2(testparams) #draw object rd.ObjDrwOpenGL(a.cont.radobj) #solve object a.cont.wradSolve() #calculate field at a point aa = rd.Fld(a.cont.radobj, 'bxbybz', [0, 0, 10]) #define line start and end points linestart = [0, -60, 0] lineend = [0, 60, 0] #calculate field on a line bb = rd.FldLst(a.cont.radobj, 'bxbybz', linestart, lineend, int(1 + (lineend[1] - linestart[1]) / 0.1), 'arg', linestart[1]) #make that list a numpy array bbn = np.array(bb) #plot the calculated field plt.plot(bbn[:, 0], bbn[:, 1:4])
t0 = time() rad.UtiDelAll() ironmat = rad.MatSatIsoFrm([20000, 2], [0.1, 2], [0.1, 2]) t = Geom(1) size = rad.ObjDegFre(t) #Display the geometry rad.ObjDrwOpenGL(t) #Solve the geometry t1 = time() res = rad.Solve(t, 0.0001, 1500) t2 = time() #Print the results b0 = rad.Fld(t, 'Bz', [0, 0, 0]) bampere = (-4 * pi * current / gap) / 10000 r = b0 / bampere print( 'Solving results for the segmentation by elliptical cylinders in the corners:' ) print('Mag_Max H_Max N_Iter =', round(res[1], 5), 'T ', round(res[2], 5), 'T ', round(res[3])) print('Built & Solved in', round(t1 - t0, 2), '&', round(t2 - t1, 2), 'seconds') print('Interaction Matrix :', size, 'X', size, 'or', round(size * size * 4 / 1000000, 3), 'MBytes') print('Bz =', round(b0, 4), 'T, Bz Computed / Bz Ampere Law =', round(r, 4))
return rad.ObjMltExtPgn(allSlicePgns, _M) #*********************************Entry point if __name__ == "__main__": #Build the Geometry aSpherMag = SphericalVolume(1, 15, 15, [1, 0, 0]) #Apply Color to it rad.ObjDrwAtr(aSpherMag, [0, 0.5, 0.8]) #Display the Geometry in 3D Viewer rad.ObjDrwOpenGL(aSpherMag) #Calculate Magnetic Field print('Field in the Center = ', rad.Fld(aSpherMag, 'b', [0, 0, 0])) #Horizontal Field vs Longitudinal Position yMin = -0.99 yMax = 0.99 ny = 301 yStep = (yMax - yMin) / (ny - 1) BxVsY = rad.Fld(aSpherMag, 'bx', [[0, yMin + i * yStep, 0] for i in range(ny)]) #Plot the Results uti_plot1d( BxVsY, [yMin, yMax, ny], ['Longitudinal Position [mm]', 'Bx [T]', 'Horizontal Magnetic Field']) uti_plot_show() #show all graphs
from mpi4py import MPI comm = MPI.COMM_WORLD comm.Barrier() if comm.rank == 0: print( f'{comm.rank:04d} of {comm.size:04d} : Test Radia on each process...') comm.Barrier() print(f'{comm.rank:04d} of {comm.size:04d} : Radia version: {rad.UtiVer()}') rad.UtiDelAll() magnet = rad.ObjRecMag([0, 0, 0], [1, 1, 1], [0, 1, 0]) observed = np.array(rad.Fld(magnet, 'b', [1, 2, 3]), dtype=np.float32) expected = np.array( [0.0006504201540729257, -0.00021819974895862903, 0.0019537852236147252], dtype=np.float32) print( f'{comm.rank:04d} of {comm.size:04d} : Radia success: {np.allclose(observed, expected)}' ) comm.Barrier() if comm.rank == 0: print( f'{comm.rank:04d} of {comm.size:04d} : Test communication on each process...' )
#Magnetic Materials mp, mm = Materials() #Build the Structure und, pole, magnet = Und(lp, mp, np, cp, lm, mm, nm, cm, gap, gapOffset, numPer) #Show the Structure in 3D Viewer rad.ObjDrwOpenGL(und) #Solve the Magnetization Problem t0 = time.time() res = rad.Solve(und, 0.0003, 1000) print('Solved for Magnetization in', round(time.time() - t0, 2), 's') print('Relaxation Results:', res) print('Peak Magnetic Field:', round(rad.Fld(und, 'bz', [0, 0, 0]), 5), 'T') #Calculate Magnetic Field BzVsY, MeshY = CalcField(und, per, numPer) #Extracting Characteristics of Magnetic Materials MeshH_Pole = [-0.002, 0.002, 201] M_Pole = GetMagnMaterCompMvsH(MeshH_Pole, pole, 'x', 'x') MeshH_Mag = [-1, 1, 201] Mpar_Mag = GetMagnMaterCompMvsH(MeshH_Mag, magnet, 'y', 'y') Mper_Mag = GetMagnMaterCompMvsH(MeshH_Mag, magnet, 'x', 'x') #Plot the Results uti_plot1d(M_Pole, MeshH_Pole, [ 'Magnetic Field Strength (mu0*H)', 'Magnetization', 'Pole Material M vs H'
def central_gradient(self): """Return the gradient (in T) at the centre of the magnet.""" if self.solve_state < SolveState.SOLVED: self.solve() x = 0.1 return rad.Fld(self.radia_object, 'by', [x, 0, 0]) / x