def findNextPoint(obj, op, of, cp, cleared, toolPos, toolDir, toolRadiusScaled, stepScaled, targetAreaPerDist, scale_factor): global toolGeometry global iteration_limit_count global total_point_count global total_iteration_count #find valid next tool pos in the pass cuttingAreaPerDist = 0 cuttingArea = 0 iteration = 0 tryCuttingAreaPerDist = 0 tryCuttingArea = 0 MAX_ERROR = 40 / stepScaled + 2 max_interations = 12 Interpolation.reset() predictedAngle = 0.0 if len(deflectionAngleHistory) > 0: #calc average predictedAngle = reduce(lambda x, y: x + y, deflectionAngleHistory) / float( len(deflectionAngleHistory)) while True: total_iteration_count = total_iteration_count + 1 iteration = iteration + 1 deflectionAngle, clamped = Interpolation.getNextAngle( iteration, targetAreaPerDist, predictedAngle, max_interations) tryToolDir = GeomUtils.rotate(toolDir, deflectionAngle) tryToolPos = [ toolPos[0] + int(tryToolDir[0] * stepScaled), toolPos[1] + int(tryToolDir[1] * stepScaled) ] tryCuttingArea, tryCuttingAreaPerDist = calcCutingArea( toolPos, tryToolPos, toolRadiusScaled, cleared) error = 1.0 * (tryCuttingAreaPerDist - targetAreaPerDist) if (math.fabs(error) < MAX_ERROR) or (iteration > max_interations): if iteration > max_interations: iteration_limit_count = iteration_limit_count + 1 total_iteration_count = total_iteration_count - max_interations # dont average those total_point_count = total_point_count - 1 else: deflectionAngleHistory.append(deflectionAngle) if len(deflectionAngleHistory) > 10: deflectionAngleHistory.pop(0) toolDir = tryToolDir toolPos = tryToolPos cuttingAreaPerDist = tryCuttingAreaPerDist cuttingArea = tryCuttingArea break Interpolation.addPoint(iteration, tryCuttingAreaPerDist, deflectionAngle) return toolPos, toolDir, cuttingAreaPerDist, cuttingArea, predictedAngle
def Phong(object1): # interpolate vertex's normals results = Interpolation.ScanConversion(object1) i_buffer, t_buffer = Interpolation.Z_buffer(results) # illmination for y_index, y in enumerate(i_buffer): for x_index, color1 in enumerate(y): if color1 != -1: i_buffer[y_index][x_index] = illuminate( color1, c_pos, light, i_light, ks, ka, kd) pos = t_buffer[y_index][x_index] t_buffer[y_index][x_index] = object1.color # rendering Rendering.renderforpixel(i_buffer, t_buffer)
def testEmptyListReturnedWhenNIsNegative(self): """ Test that an empty list is returned when n is negative. """ parameterList1 = [1.2, 3.4, 4.5] parameterList2 = [2.0, 5, 6.7] self.assertEqual([], Interpolation.linearInterpolation(parameterList1, parameterList2, -10))
def cub_spl_nd(x1, y1): roots = [] x_spline = [] y_spline = [] x_spline_range = [] for i in range(len(x1)): f, x_domain, y_range = inter.cubicSpline(x1[i], y1[i]) x_spline.append(x_domain) y_spline.append(y_range) g = poly_nd_1[i](x_domain) index = 0 h = y_range - g root = 100 while h[index] > 0.5e-1: if index < len(x_domain) - 1: index = index + 1 root = x_domain[index] else: break for j in range(len(x1[i]) - 1): if root > x1[i][j] and root < x1[i][j + 1]: #x_spline_range.append([x[i][j],x[i][j+1],x[i][j+1]-x[i][j]]) x_spline_range.append(x1[i][j + 1] - x1[i][j]) roots.append(root) return roots, x_spline, y_spline, x_spline_range
def do(self): if self.var.get() == 0: st = "sinx" function = f elif self.var.get() == 1: st = "5/(x^2+2)" function = g elif self.var.get() == 2: st = "sin(x) - y" function = z else: st = "x^2 + 2y" function = s euler_method = EulerMethod(float(self.x0.get()), float(self.y0.get()), float(self.accuracy.get()), float(self.xn.get()), function) array_with_dots = euler_method.solve_with_euler_method() plt.title("График") plt.xlabel("x") plt.ylabel("y") plt.grid() if len(array_with_dots) <= MaxCountOfDots: interpolation_method = Interpolation(float(self.x0.get()), float(self.xn.get()), array_with_dots) array = interpolation_method.get_dots_for_function() x = [array[i][0] for i in range(len(array))] y = [array[i][1] for i in range(len(array))] else: x = [array_with_dots[i][0] for i in range(len(array_with_dots))] y = [array_with_dots[i][1] for i in range(len(array_with_dots))] plt.plot(x, y, color='#008B8B', label='результат') if st == "sinx": value_of_function = [] for i in range(len(x)): value_of_function.append(f_true(x[i])) plt.plot(x, value_of_function, color='blue', label="true") for i in range(len(array_with_dots)): plt.scatter(array_with_dots[i][0], array_with_dots[i][1], color='red', s=5, marker='o') plt.legend() plt.show()
def Ground(object1): # vertex's intensites v_intensities = [] for v_normal in object1.v_normals: v_intensities.append( illuminate(v_normal, c_pos, light, i_light, ks, ka, kd)) object1.v_normals = v_intensities # interpolate intensities results = Interpolation.ScanConversion(object1) i_buffer, t_buffer = Interpolation.Z_buffer(results) # illmination for y_index, y in enumerate(i_buffer): for x_index, color1 in enumerate(y): if color1 != -1: t_buffer[y_index][x_index] = object1.color # rendering Rendering.renderforpixel(i_buffer, t_buffer)
def testEmptyListReturnedWhenNIsNegative(self): """ Test that an empty list is returned when n is negative. """ parameterList1 = [1.2, 3.4, 4.5] parameterList2 = [2.0, 5, 6.7] self.assertEqual([], Interpolation.linearInterpolation( parameterList1, parameterList2, -10))
def func_q(inParams): outfile = open("log.txt", "a") print("function func_q called with inputs: {", file=outfile) print(" inParams = ", end='', file=outfile) print("Instance of InputParameters object", file=outfile) print(" }", file=outfile) outfile.close() return Interpolation.func_interpY("TSD.txt", inParams.SD, inParams.w_TNT)
def __init__(self, linedg): self.__linedg = linedg self.__params = linedg.params self.__lim = self.__params.LimitSolution() self.__nnodes = self.__params.nnodes() self.__nquads = self.__params.nquads() self.__nels = self.__params.nels() self.__neqs = self.__params.neqs() self.__dx = linedg.mesh.dx() self.ip = Interpolation.Interpolation(self.__nnodes, self.__nquads)
def testCorrectResultForSimpleList(self): """ Test that a correct result is returned for two small lists. """ parameterList1 = [2, 4, 3] parameterList2 = [12, 9, 3] n = 4 expectedList = [[4, 5, 3], [6, 6, 3], [8, 7, 3], [10, 8, 3]] resultList = Interpolation.linearInterpolation(parameterList1, parameterList2, n) self.assertEqual(expectedList, resultList)
def AddTexture(object1): #data=Texture.textureimage() image = Image.open(imagefile) data = np.asarray(image) # interpolate vertex's normals results = Interpolation.ScanConversion(object1) i_buffer, t_buffer = Interpolation.Z_buffer(results) # illmination for y_index, y in enumerate(i_buffer): for x_index, color1 in enumerate(y): if color1 != -1: i_buffer[y_index][x_index] = illuminate( color1, c_pos, light, i_light, ks, ka, kd) pos = t_buffer[y_index][x_index] t_buffer[y_index][x_index] = data[int(pos[0] * 400 - 1)][int(pos[1] * 600 - 1)] # rendering Rendering.renderforpixel(i_buffer, t_buffer)
def __init__(self, domain, numOfEls, numOfNodes, numOfQuads): self.__xmin = domain[0] self.__xmax = domain[1] self.__K = numOfEls self.__nN = numOfNodes self.__nQ = numOfQuads self.__ip = ip.Interpolation(self.__nN, self.__nQ) self.__dx = (self.__xmax - self.__xmin) / self.__K self.__J = self.__dx self.__detJ = np.abs(self.__J) self.__invJ = 1 / self.__J
def Constant(object1): # polygon's intensities intensities = [] for normal in object1.normals: intensities.append( illuminate(M.normalize(normal), c_pos, light, i_light, ks, ka, kd)) # inerpolation results = Interpolation.ScanConversion(object1) # rendering Rendering.objectcolor = object1.color Rendering.renderforscan(results, intensities)
def testResultForEmptyLists(self): """ Created 11.06.2007, SG Test that a list of n empty lists is returned when two empty lists are used as input. Not sure if this is the intended behaviour though. It's what the method does though. """ n = 50 resultList = Interpolation.linearInterpolation([], [], n) expectedList = [[] for x in range(n)] self.assertEqual(expectedList, resultList) self.assertEqual(n, len(resultList))
def Shock(params, x): ip = Interpolation.Interpolation(params.nnodes(), params.nquads()) uinit = np.zeros([params.nels(), params.nnodes(), params.neqs()]) for i in range(params.nels()): #compute center of cell xc = np.sum(np.matmul(ip.W(), np.matmul(ip.B(), x[i, :]))) # print(xc) if (xc < params.ShockLoc()): uinit[i, :, :] = params.LeftBC() elif (xc >= params.ShockLoc()): uinit[i, :, :] = params.RightBC() return uinit
def DoubleShock(params, x): ip = Interpolation.Interpolation(params.nnodes(), params.nquads()) uinit = np.zeros([params.nels(), params.nnodes(), params.neqs()]) for i in range(params.nels()): xc = np.sum(np.matmul(ip.W(), np.matmul(ip.B(), x[i, :]))) if (xc <= 0.3): uinit[i, :, :] = 4 elif (xc > 0.3 and xc <= 0.6): uinit[i, :, :] = 2 elif (xc > 0.6): uinit[i, :, :] = -1 return uinit
def func_J(inParams, q_hat): outfile = open("log.txt", "a") print("function func_J called with inputs: {", file=outfile) print(" inParams = ", end='', file=outfile) print("Instance of InputParameters object", end='', file=outfile) print(", ", file=outfile) print(" q_hat = ", end='', file=outfile) print(q_hat, file=outfile) print(" }", file=outfile) outfile.close() return Interpolation.func_interpZ("SDF.txt", inParams.AR, q_hat)
def func_q_hat_tol(inParams, J_tol): outfile = open("log.txt", "a") print("function func_q_hat_tol called with inputs: {", file=outfile) print(" inParams = ", end='', file=outfile) print("Instance of InputParameters object", end='', file=outfile) print(", ", file=outfile) print(" J_tol = ", end='', file=outfile) print(J_tol, file=outfile) print(" }", file=outfile) outfile.close() return Interpolation.func_interpY("SDF.txt", inParams.AR, J_tol)
def build(self): root = ScreenManager() root.transition = SwapTransition() root.add_widget(MainMenu()) root.add_widget( bm.BracketMethods(screenManager=root, name='bracket_methods')) root.add_widget(om.OpenMethods(screenManager=root, name='open_methods')) root.add_widget( soe.SystemOfEquations(screenManager=root, name='system_equations')) root.add_widget( ip.Interpolation(screenManager=root, name='interpolation')) root.add_widget(rg.Regression(screenManager=root, name='regression')) return root
def Sod(params, x): ip = Interpolation.Interpolation(params.nnodes(), params.nquads()) # prim array rho, pressure, u Uinit = np.zeros([params.nels(), params.nnodes(), params.neqs()]) for i in range(params.nels()): #compute center of cell xc = np.sum(np.matmul(ip.W(), np.matmul(ip.B(), x[i, :]))) if (xc < params.ShockLoc()): Uinit[i, :, :] = params.LeftBC() elif (xc >= params.ShockLoc()): Uinit[i, :, :] = params.RightBC() print(Uinit) return Uinit
def compute_moments(self, a, b, variable, moment): [weights, roots] = interp1d.compute_lgl_weights(interp1d.legendre_interp, interp1d.lobatto_interp) if variable=='speed': temp = (b-a)/2 integral = 0 new_x = roots*(b-a)/2 + (a+b)/2 for i in range(len(new_x)): integral += weights[i]*self.speed_dist(new_x[i])*(new_x[i]**moment) integral *= temp if moment==2: integral = integral*self.m/(3*self.n*self.k) self.computed_temperature = integral return integral else: self.computed_density = integral return integral
def __init__(self, mesh, params, equations): self.params = params self.__dim = 1 self.__neqs = params.neqs() self.__order = params.order() self.__nnodes = self.__order + 1 self.__nels = params.nels() self.__nquads = params.nquads() self.ip = interpolation.Interpolation(self.__nnodes, self.__nquads) self.mesh = mesh self.mass = np.matmul(np.transpose(self.ip.B()), np.matmul(self.ip.W(), self.ip.B())) self.invMass = np.linalg.inv(self.mass) self.__q = np.zeros([self.__nels, self.__nnodes, self.__neqs]) self.equations = equations self.__leftBC = np.zeros([self.__neqs]) self.__rightBC = np.zeros([self.__neqs])
def Volatility(self, strike, interpolation): if len(self.strikes) == 0: print("Error in interpolation, no points in skew at expiry : ", self.expiryDate) elif len(self.strikes) == 1: print( "Warning: Only one point in skew, returning this value for skew at : ", self.expiryDate) return self.volatilities[0] elif len(self.strikes) == 2: print( "Warning: Only two points in skew, using linear interpolation for skew at : ", self.expiryDate) return Interpolation.LinearInterpolation(strike, self.strikes, self.volatilities) return interpolation(strike, self.strikes, self.volatilities)
def TriangularLinear(triangles, points, U, XY): # Get Triangle FQ = Interpolation.FindTriangle(triangles, points, XY) q = FQ[0] if q < 0: return False else: # Get Local Coordinades P1 = points[triangles[q].item(0)] P2 = points[triangles[q].item(1)] P3 = points[triangles[q].item(2)] J = np.matrix([[-P1.item(0) + P2.item(0), -P1.item(1) + P2.item(1)], [-P1.item(0) + P3.item(0), -P1.item(1) + P3.item(1)]]) P1def = points[triangles[q].item(0)] + np.matrix( [U[triangles[q].item(0)].item(0), U[triangles[q].item(0)].item(1)]) P2def = points[triangles[q].item(1)] + np.matrix( [U[triangles[q].item(1)].item(0), U[triangles[q].item(1)].item(1)]) P3def = points[triangles[q].item(2)] + np.matrix( [U[triangles[q].item(2)].item(0), U[triangles[q].item(2)].item(1)]) Jdef = np.matrix( [[-P1def.item(0) + P2def.item(0), -P1def.item(1) + P2def.item(1)], [-P1def.item(0) + P3def.item(0), -P1def.item(1) + P3def.item(1)]]) # Check that the triangle did not flip (if flipped the linear triangular interpolation is impossible) if np.sign(np.linalg.det(J)) * np.sign(np.linalg.det(Jdef)) > 0: xi = FQ[1][0] nu = FQ[1][1] U_int = [] # Compute interpolated value for the displacement field for i in range(U[0].size): U1 = U[triangles[q].item(0)].item(i) U2 = U[triangles[q].item(1)].item(i) U3 = U[triangles[q].item(2)].item(i) u = U1 * (1 - xi - nu) + U2 * xi + U3 * nu U_int.append(u) return U_int else: return False
def unequal_step_cubic_spline_first_derivative(xs, ys, x): k = Interpolation.cubicspline_curvatures(xs, ys) # bracket using Bisection i = 0 ip = len(xs) - 1 while i + 1 != ip: mid = i + ip // 2 if xs[i] < x < xs[mid]: ip = mid elif xs[mid] < x < xs[ip]: i = mid xi = xs[i] xip = xs[i + 1] yi = ys[i] yip = ys[i + 1] # Evaluate first = (k[i] / 6) * (((3*((x - xip)**2)) / (xi - xip)) - xi + xip) second = (k[i + 1] / 6) * (((3*((x - xi)**2)) / (xi - xip)) - xi + xip) third = (yi - yip) / (xi - xip) return first - second + third
def graphicTable(x, y, func=False): #Spline and Interpolating polinomial calculation #initiates classes data = spl.Spline(x, y) data2 = inter.Interpolation(x, y) spline = data.buildNormalSpline() #calculates the spline for the dataset data2_x, data2_y = data2.interpolateData( ) #calculates the interpolating pol xs = np.arange(x[0], x[-1] + 0.0001, 0.0001) plt.plot(x, y, "o", label="Data") if func: #displays the actual function f plt.plot(xs, f(xs), label='True Value') plt.plot(xs, spline(xs), label="Spline Trace") plt.plot(data2_x, data2_y, label="Interpolation") plt.legend(loc='lower left', ncol=2) plt.grid() plt.show() return data, spline, data2
tList.append(T*i) Graphs.Graph_01 (tList, velList , "T, с", "V, мм/c", "Профиль скорости", "Скорость инструмента", "Профиль скорости") #график #ТЕЛО ИНТЕРПОЛЯЦИИ print("______________________________________________________") print("НАЧАЛО ИНТЕРПОЛЯЦИИ") print("______________________________________________________") segments_Inter = [] #список сегментов после интерполяции xList = [] yList = [] for i in range (len(segments_FControl)): print("______________________________________________________") print("Участок " + str(segments_FControl[i].Num+1)) #вызов функции интерполяции seg = Interpolation.InterpolationStart (segments_FControl[i], T) segments_Inter.append(seg) xList += seg.X #для графика yList += seg.Y #для графика if segments[0].GCode == 4: path_x = [] path_y = [] for i in range (len(NURBS_p)): path_x.append(NURBS_p[i][0]) path_y.append(NURBS_p[i][1]) Graphs.Graph_02 (path_x, path_y, xList, yList, "X, мм", "Y, мм", "Траектория после интерполяции", "Опорный многоугольник", "Интерполяция", "Интерполяция") #график elif segments[0].GCode in [2,3]: path_x = [] path_y = [] path_x += segments_Inter[0].X path_y += segments_Inter[0].Y
def func_J(inParams, q_hat): return Interpolation.func_interpZ("SDF.txt", inParams.AR, q_hat)
def func_q_hat_tol(inParams, J_tol): return Interpolation.func_interpY("SDF.txt", inParams.AR, J_tol)
def func_q(inParams): return Interpolation.func_interpY("TSD.txt", inParams.SD, inParams.w_TNT)
# ------------------------- Incoming heat flux calculations ------------------------------- t_start, t_end, dt = 0, 25000, 0.5 # Set boundary for graph and spline evaluation t_steps = int(t_end / dt) + 1 xx = np.linspace(t_start, t_end, t_steps) # Set datapoints to evaluate splne at splines = np.zeros(shape=(8, t_steps)) for i in range(0, 8): filename, element_number = 'AB2_data/AB2/Mirror_segments.csv', i #CHANGE THIS BASED ON THE LOCATION ON YOUR DEVICE! spline = Interpolation.spline(filename, element_number, xx, t_start, t_end, plotting=False) splines[i - 2] = spline T_front = (splines[0]) / 1 + 273.15 T_back = (splines[1]) / 1 + 273.15 T_avg = (splines[0] + splines[1]) / 2 + 273.15 T_E = np.mean(T_avg) dT_dt = cd_deriv(xx, T_avg)[0] T_front, T_back, T_avg, xx = T_front[1:-1], T_back[1:-1], T_avg[1:-1], xx[1:-1] sigma = 5.670374 * 10**(-8) e_front, e_back, A, m, C = 0.035, 0.05, 1.076 / 4, 6., 690 Q_out, Q_balance = e_front * sigma * (
steps = 50000 import numpy as np from collections import OrderedDict Es = OrderedDict() x = np.linspace(1.35, 1.6, steps) for params in param_sets: print print params print ForceField = Interpolation.InterpolationForceField(\ '../../../Example/grids/LJa.nc', interpolation_type=params['interpolation_type'], inv_power=params['inv_power'], energy_thresh=params['energy_thresh'], scaling_property='test_charge') universe.setForceField(ForceField) universe.atom1.setPosition(Vector(x[0], 0.5, 1.5)) print 'Energy Terms:' print universe.energyTerms() e, g = universe.energyAndGradients() print 'Gradient on Atom 1' print g[universe.atom1] print 'Gradient on Atom 2' print g[universe.atom2]
import Calculations import OutputFormat import ReadTable filename = sys.argv[1] inparams = InputParameters.InputParameters() InputFormat.get_input(filename, inparams) DerivedValues.derived_params(inparams) InputConstraints.check_constraints(inparams) w_array = ReadTable.read_z_array("TSD.txt") data_sd = ReadTable.read_x_array("TSD.txt") data_q = ReadTable.read_y_array("TSD.txt") j_array = ReadTable.read_z_array("SDF.txt") data_asprat = ReadTable.read_x_array("SDF.txt") data_qstar = ReadTable.read_y_array("SDF.txt") q = Interpolation.interpY(data_sd, data_q, w_array, inparams.sd, inparams.wtnt) q_hat = Calculations.calc_q_hat(q, inparams) j_tol = Calculations.calc_j_tol(inparams) j = Interpolation.interpZ(data_asprat, data_qstar, j_array, inparams.asprat, q_hat) q_hat_tol = Interpolation.interpY(data_asprat, data_qstar, j_array, inparams.asprat, j_tol) pb = Calculations.calc_pb(j, inparams) nfl = Calculations.calc_nfl(q_hat_tol, inparams) lr = Calculations.calc_lr(nfl, inparams) is_safe1 = Calculations.calc_is_safe1(pb, inparams) is_safe2 = Calculations.calc_is_safe2(lr, q) OutputFormat.display_output("outputfile.txt", q, j, q_hat_tol, pb, lr, nfl, is_safe1, is_safe2, inparams) print("Main has been executed and the results have been written to 'outputfile.txt'.");
#input data move_type = [0] #type of trajectory for each block (0 - linear, 1 - circular, 2 - curve) trajectory = [[0,0], [100, 100], [100, 90], [100, 0]] #trajectory points feedrate = [30, 15, 30] #list of feedrates for each block feedrate_max = [30, 30, 30] acceleration = [25, 25] #allowable acceleration for each block deceleration = [25, 25] #allowable deceleration for each block jerk = [50, 10] tsample = 0.01 #tolerance linearErr = 0.01 #corner parameters #расчет длины пути blocklen = Interpolation.LengthLinear(trajectory[0], trajectory[1]) print("Длина пути: " + str(blocklen) + " мм.") #предварительный расчет длины разгона и торможения Nm = floor(acceleration[0]/(jerk[0]*tsample)) LengthAcc = AccDecControl.AccDecDisplacement (3, feedrate[1], jerk[0], acceleration[0], tsample, Nm) #LengthDec = AccDecControl.AccDecDisplacement (feedrate[1], 0, jerk[0], acceleration[0], tsample, Nm) print("Предварительная длина разгона: " + str(LengthAcc) + " мм.") #print("кол-во шагов на разгоне " + str(LengthAcc[4][0])) #print("кол-во шагов на постоянн " + str(LengthAcc[4][1])) #print("кол-во шагов на торможе " + str(LengthAcc[4][2])) Profile = AccDecControl.AccVelProfiles (3, feedrate[1], jerk[0], acceleration[0], tsample, Nm) #вывод графического материала timelist = [] time = 0
import LeastSquares as LS import numpy as np from math import exp from scipy.special import jn import matplotlib.pyplot as plt # Exercise 3.6 #******************************************************************* # generate points of Bessel function J(1,x) x = np.arange(0,12,0.5) npts = len(x) bess = [jn(1,i) for i in x] # call cubic spline method from my interpolation module xx,yy = Interp.cubicSpline(x,bess,npts,0.1) # plot data and interpolation plt.figure(1) plt.plot([0,12],[0,0],'k--') plt.plot(3.83,0,'gx',markersize=20) plt.plot(x,bess,'bo',label='Bessel Points') plt.plot(xx,yy,'r',label='Cubic Spline Interpolation') plt.xlabel('x') plt.ylabel('y') plt.annotate('$x=3.83$',fontsize=18,xy=(0.38,0.46),xycoords='figure fraction') plt.legend() #******************************************************************* # Exercise 3.10
def Apply(self): # Boundary Condition Application Method print('Applying boundary condions...') # Get displacement field size x_max = 0 y_max = 0 y_min = 0 x_min = 0 for xy in self.points: if xy[0, 0] > x_max: x_max = xy[0, 0] if xy[0, 0] < x_min: x_min = xy[0, 0] if xy[0, 1] > y_max: y_max = xy[0, 1] if xy[0, 1] < y_min: y_min = xy[0, 1] i = 1 interp = [] tol = 1e-4 # If reversed triangles should be ignored, search them and add them to the IgnoredRegions List IgnoredRegions = [] if self.UI['IgnoreSwitchedTriangles'] == True: for T in self.triangles: # A triangle is reversed if the cross product changes sign after deformation V1 = self.points[T[0, 1]] - self.points[T[0, 0]] V2 = self.points[T[0, 2]] - self.points[T[0, 0]] A0 = V1[0, 0] * V2[0, 1] - V1[0, 1] * V2[0, 0] d1 = self.displacements[T[0, 0]] d2 = self.displacements[T[0, 1]] d3 = self.displacements[T[0, 2]] v1 = self.points[T[0, 1]] + d2[0, 0:2] - self.points[T[ 0, 0]] - d1[0, 0:2] v2 = self.points[T[0, 2]] + d3[0, 0:2] - self.points[T[ 0, 0]] - d1[0, 0:2] A1 = v1[0, 0] * v2[0, 1] - v1[0, 1] * v2[0, 0] if A1 / A0 < 0: P1 = self.points[T[0, 0]] P2 = self.points[T[0, 1]] P3 = self.points[T[0, 2]] IgnoredRegions.append([ np.array([P1[0, 0], P1[0, 1]]), np.array([P2[0, 0], P2[0, 1]]), np.array([P3[0, 0], P3[0, 1]]) ]) # Prepare RBF Interpolation if needed if 'Interpolation' in self.UI.keys() and self.UI['Interpolation'] in [ 'RBF' ]: Points = np.array(self.points) Points = Points[:, 0] D = np.array(self.displacements) D = D[:, 0] if 'BasisFunction' in self.UI.keys(): f = self.UI['BasisFunction'] else: f = 'thin-plate' Interpolator = Interpolation.setRBF(Points, D, self.UI['dot_distance'], f) print('Using RBF interpolation with a ' + f + ' basis function') else: print('Using linear triangluar interpolation') Nlist = [] Nlist_free = [] k = 1 # Define Boundary Conditions for all nodes withing the QD Array for node in self.CAE.getByBoundingBox( 'nodes', x_min - tol, y_min - tol, self.UI['substrate_thickness'] - tol, x_max + tol, y_max + tol, self.UI['substrate_thickness'] + tol): xyz = node.coordinates # Check if the point is inside a ignored region if self.UI['IgnoreSwitchedTriangles'] == True: use = True for T in IgnoredRegions: if self.PointInTriangle([xyz[0], xyz[1]], T[0], T[1], T[2]) == True: use = False break else: use = True # Check that the node is on the surface and shoudl not be ignored if abs(xyz[2] - self.UI['substrate_thickness']) < tol and use == True: # Get interpolated displacement vector for the node if 'Interpolation' in self.UI.keys( ) and self.UI['Interpolation'] in ['RBF']: u = Interpolation.RBFInterp(xyz, Interpolator) else: u = Interpolation.TriangularLinear(self.triangles, self.points, self.displacements, np.matrix(xyz)) # If Everything is fine, apply the nodal BC to the CAE Model if u != False: N = node.label interp.append([xyz[0], xyz[1], xyz[2], u[0], u[1], u[2]]) self.CAE.NodalBC(N, 'Disp' + str(i), u, self.UI['z_constr']) Nlist.append('Disp' + str(i)) if i % 1000 == 0: print('\t' + str(i) + ' BCs...') i += 1 else: Nlist_free.append('Free' + str(k)) self.CAE.CreateSet(node.label, 'Free' + str(k)) k = k + 1 # Create CAE Sets with the constrined Nodes self.CAE.CreateNodalDofSet(Nlist, Nlist_free) print(str(i - 1) + ' Displacement BCs have been applied in total!') self.CAE.Regenerate() # Store interpolated nodal displacement field in file if not os.path.exists('../AppliedData'): os.makedirs('../AppliedData') Functions.CSVWrite( '../AppliedData/' + self.UI['job_name'] + '_AppliedBC.txt', interp)