def solve(self): """Solve the model.""" if self.solve_state < SolveState.BUILT: self.build() # print('solving') res = rad.Solve(self.radia_object, 0.00001, 10000) # precision and number of iterations self.solve_state = SolveState.SOLVED
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 _solve(self, b): self._disable_controls() self.solve_res_label.value = '' self.solve_spinner.layout.display = None start = datetime.datetime.now() # move all radia refs to tk? try: res = radia.Solve(self.mgr.get_geom(self.current_geom), self.solve_prec.value, self.solve_max_iter.value, self.solve_method.value) except RuntimeError as ex: self.rserr('Solve failed: {}'.format(ex)) #self._do_raise(ex) return finally: self.solve_spinner.layout.display = 'none' self._enable_controls() self.display() d = datetime.datetime.now() - start self.solve_res_label.value = 'Done {} steps ({}.{:06}s): Max |M| {:.4}A/m; Max |H| {:.4}A/m'.format( int(res[3]), d.seconds, d.microseconds, res[1], res[2])
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 wradSolve(self, prec_r=0.001, iter_r=1000): rd.Solve(self.radobj, prec_r, iter_r) self.solved = 1 #if __name__ == '__main__': # tr = 5 # ve = 3 # # x = wradObjThckPgn(2,2,[[-tr,-ve],[-tr,ve],[tr,ve],[tr,-ve]],'x',[4,3,2]) # print(x.vertices) # # y = wradObjThckPgn(2,2,[[-tr,-ve],[-tr,ve],[tr,ve],[tr,-ve]],'y',[4,3,2]) # print(y.vertices) # # z = wradObjThckPgn(2,2,[[-tr,-ve],[-tr,ve],[tr,ve],[tr,-ve]],'z',[4,3,2]) # print(z.vertices) # # rd.ObjDrwOpenGL(x.radobj) # rd.ObjDrwOpenGL(y.radobj) # rd.ObjDrwOpenGL(z.radobj) # # input("Press Enter to continue...")
def solve(g_id, prec, max_iter, solve_method): return radia.Solve(g_id, float(prec), int(max_iter), int(solve_method))
def solve(radia_object, prec=0.00001, max_iter=1000): return _rad.Solve(radia_object, prec, max_iter)
lm = [65, ll, 45] nm = [1, 3, 1] cm = [0, 1, 1] #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
#rad.ObjDrwOpenGL(coil) rad.TrfZerPara(yoke, [0, 0, 0], [1, 0, 0]) rad.TrfZerPara(yoke, [0, 0, 0], [0, 1, 0]) rad.TrfZerPerp(yoke, [0, 0, 0], [0, 0, 1]) rad.TrfZerPara(coil, [0, 0, 0], [1, 0, 0]) rad.TrfZerPara(coil, [0, 0, 0], [0, 1, 0]) full = rad.ObjCnt([yoke, coil]) #rad.ObjDrwOpenGL(full) t0 = time.time() res = rad.Solve(full, 0.0001, 10000) # No workers should exit rad.Solve assert mpi4py.MPI.COMM_WORLD.Get_rank() == 0 #print('Solved for Magnetizations in', round(time.time() - t0, 2), 's') expect = [ 9.991124106723865e-05, 1.7586937018625115, 0.009296872940670615, 744.0 ] assert expect == res, \ '{} expected != actual {}'.format(expect, res) #print('Relaxation Results:', res) #ByVsX, MeshX, ByVsZ, MeshZ=CalcField(coil) #ByVsX, MeshX,xx, ByVsZ, MeshZ,zz=CalcField(full) #csvfile = "xaxis.csv"
def wradSolve(self, prec_r, iter_r): self.solved = 1 rd.Solve(self.radobj, prec_r, iter_r)
np3 = 2 nr3 = ny n4 = [nx, 3, ny] 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')
n5 = [nx, 2, 2] n6 = [nx, 2, 2] #inside the coil #Build the geometry 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',
def solve(geom, prec, max_iter, solve_method): #pkdp('SOLVE g {} p {} i {} m {}', geom, prec, max_iter, solve_method) return radia.Solve(geom, float(prec), int(max_iter), int(solve_method))