def create_grid(source_image, width, height): tp.new_layout() ds = tp.active_frame().create_dataset("Image", ['x', 'y']) zone = ds.add_ordered_zone("ImageZone", (width + 1, height + 1)) # left, bottom, right, top grid_dimensions = [0, 0, width, height] world_file = get_world_file(source_image) if world_file is not None: grid_dimensions = get_world_file_dimensions(world_file, width, height) x = np.linspace(grid_dimensions[0], grid_dimensions[2], width + 1) y = np.linspace(grid_dimensions[1], grid_dimensions[3], height + 1) yy, xx = np.meshgrid(y, x, indexing='ij') zone.values('x')[:] = xx.ravel() zone.values('y')[:] = yy.ravel() tp.data.operate.execute_equation("{r} = 0", value_location=ValueLocation.CellCentered) tp.data.operate.execute_equation("{g} = 0", value_location=ValueLocation.CellCentered) tp.data.operate.execute_equation("{b} = 0", value_location=ValueLocation.CellCentered) return zone
def convert_vtk_file(vtk_file, plt_file, strand=None, solution_time=None): reader = None if vtk_file.endswith(".vtu"): reader = vtk.vtkXMLUnstructuredGridReader() elif vtk_file.endswith(".vtp"): reader = vtk.vtkXMLPolyDataReader() elif vtk_file.endswith(".vts"): reader = vtk.vtkXMLStructuredGridReader() elif vtk_file.endswith(".vti"): reader = vtk.vtkXMLImageDataReader() reader.SetFileName(vtk_file) reader.Update() vtk_dataset = reader.GetOutput() tp.new_layout() tecplot_dataset = tp.active_frame().dataset add_vtk_dataset(vtk_dataset, tecplot_dataset) if tecplot_dataset.num_zones == 0: print("No zones created.") return for z in tecplot_dataset.zones(): z.name = os.path.basename(vtk_file) if strand and solution_time: z.strand = strand z.solution_time = solution_time tp.data.save_tecplot_plt(plt_file, dataset=tecplot_dataset)
def gen_plt(blade_no): node_pos_arr_dict = pickle.load( open( f"../{cii_filename}_node_pos_arr_dict_case{case}_{rotor}_blade{blade_no}.p", "rb" ) ) norm_pos_arr_dict = pickle.load( open( f"../{cii_filename}_norm_pos_arr_dict_case{case}_{rotor}_blade{blade_no}.p", "rb" ) ) for key in node_pos_arr_dict: no_timesteps = np.shape(node_pos_arr_dict[key])[-1] break T = 0.0667 # time period needs to be entered time_steps = np.linspace(0,T,no_timesteps) surf_list =list(node_pos_arr_dict.keys()) with tp.session.suspend(): tp.new_layout() frame = tp.active_frame() dataset = frame.dataset for coord in ['x','y','z','x_normal','y_normal','z_normal']: dataset.add_variable(coord) zones={} for t_idx, t in enumerate(time_steps): print(t_idx) for surf,node_arr in node_pos_arr_dict.items(): norm_arr = norm_pos_arr_dict[surf] # if surf!='lifting-line': # continue ord_zone_tup = (np.size(node_arr,axis=1),np.size(node_arr,axis=0),1) zones[surf+str(t)] = dataset.add_ordered_zone(surf+'_'+"{:5.4f}".format(t), ord_zone_tup, solution_time=t, # strand_id=1+surf_list.index(surf)) strand_id=1) # visualize in Camrad frame x_val = -node_arr[:,:,1,t_idx] y_val = node_arr[:,:,0,t_idx] z_val = node_arr[:,:,2,t_idx] x_val_normal = -norm_arr[:,:,1,t_idx] y_val_normal = norm_arr[:,:,0,t_idx] z_val_normal = norm_arr[:,:,2,t_idx] zones[surf+str(t)].values('x')[:]=x_val.ravel() zones[surf+str(t)].values('y')[:]=y_val.ravel() zones[surf+str(t)].values('z')[:]=z_val.ravel() zones[surf+str(t)].values('x_normal')[:]=x_val_normal.ravel() zones[surf+str(t)].values('y_normal')[:]=y_val_normal.ravel() zones[surf+str(t)].values('z_normal')[:]=z_val_normal.ravel() # frame.add_text('$\psi=$'+"{:3.0f}".format(360*t/T), position=(80, 80), size=10) # frame.add_latex(r'$\psi=$'+"{:3.0f}".format(360*t/T), position=(80, 80), size=10) #variables_to_save = [dataset.variable(var) for var in dataset.variable_names] #print(dataset.variable_names) #print(dataset.zone_names) #print(dataset.solution_times) #zone_to_save = [dataset.zone(z) for z in dataset.zone_names] tp.data.save_tecplot_plt(f'{cii_filename}_case{case}_{rotor}_blade{blade_no}.plt'.format(blade_no), dataset=dataset) #saves all the data added above to the dataset
def __init__(self,LSP_FILEPATH,LSP_FILENAME,FLAGS=()): tp.new_layout() #Zone 0: self.dataset = tp.data.load_tecplot(LSP_FILEPATH + '/' + LSP_FILENAME) if 'WB' in FLAGS: self.WB_P_array = self.dataset.zone(0).values('WB').as_numpy_array() if 'RE_P' in FLAGS: self.RE_P_array = self.dataset.zone(0).values('RE_P').as_numpy_array() if 'Z_GAS_P' in FLAGS: self.Z_GAS_P_array = self.dataset.zone(0).values('Z_GAS_P').as_numpy_array()
def convert_vti_file(src, dst): start = time.time() tp.new_layout() print("Converting: ", src) ds = create_dataset(src) if dst.endswith(".szplt"): tp.data.save_tecplot_szl(dst, dataset=ds) elif dst.endswith(".plt"): tp.data.save_tecplot_plt(dst, dataset=ds) else: print("Unregognized extension. Saving to PLT format") tp.data.save_tecplot_plt(dst + ".plt", dataset=ds) print("Elapsed Time: ", time.time() - start)
def read_tp(flnm, zonesname=None, varsname=None, order='C', file_type=None, case_filenames=None): tp.new_layout() logging.basicConfig(level=logging.INFO) if file_type == 'plt' or flnm[-4:] == '.plt' or flnm[-4:] == '.dat': dset = tp.data.load_tecplot(flnm) elif file_type == 'szplt' or flnm[-6:] == '.szplt': dset = tp.data.load_tecplot_szl(flnm) elif file_type == 'fluent': dset = tp.data.load_fluent(case_filenames=case_filenames, data_filenames=flnm) if zonesname == None: zonesname = [zone.name for zone in dset.zones()] if varsname == None: varsname = [var.name for var in dset.variables()] ## access data data_out = {} print('Reading from %s' % flnm) for zone_name in zonesname: zone = dset.zone(zone_name) print( 'Accessing zone %s of type %s ... \n num of elements = %d, num of points = %d:' % (zone.name, zone.zone_type, zone.num_elements, zone.num_points)) data_out[zone.name] = {} try: nodemap = zone.nodemap data_out[zone.name]['nodemap'] = nodemap_to_array(nodemap) except: print('Nodemap not read!') pass for var_name in varsname: val = zone.values(var_name) print('Accessing variable %s ...' % var_name) data_out[zone_name][var_name] = val.as_numpy_array() try: data_out[zone_name][var_name] = data_out[zone_name][ var_name].reshape(val.shape, order=order) except: print('%s is not reshaped, and therefore flat.' % var_name) pass print('Finished reading from %s' % flnm) return data_out
def make_layout(datafiles, page_specs, equations=None): ''' Clear and configure a layout from a dict-like data structure This function enables construction of a Tecplot layout from dict-like datastructures, e.g. a YAML document. This function manipulates the state of the Tecplot runtime, and will clear any existing plots that have been defined. Arguments: datafiles List(str) of datafile names to be loaded page_spec List(dict) of properties defining each page equations List(str) of equations applied to the dataset Returns: None ''' # Load and pre-process data tp.new_layout() tp.data.load_tecplot(datafiles) if equations: tp.data.operate.execute_equation('\n'.join(equations)) default_page = tp.active_page() # Construct the layout for page_spec in page_specs: frame_specs = page_spec.pop('frames') page = add_page(**page_spec) default_frame = page.active_frame() for frame_spec in frame_specs: lmap_specs = frame_spec.pop('linemaps', {}) axis_specs = frame_spec.pop('axes', {}) plot_spec = frame_spec.pop('plot', {}) frame = add_frame(**frame_spec) xyplot = frame.plot(tpc.PlotType.XYLine) xyplot.activate() xyplot.delete_linemaps() for lmap_spec in lmap_specs: add_xylinemap(xyplot, **lmap_spec) for axis_name, axis_spec in axis_specs.items(): name, index = parse_selector(axis_name) if name.startswith('x'): configure_xylineaxis(xyplot.axes.x_axis(index), **axis_spec) if name.startswith('y'): configure_xylineaxis(xyplot.axes.y_axis(index), **axis_spec) configure_xylineplot(xyplot, **plot_spec) page.delete_frame(default_frame) tp.delete_page(default_page)
def work(datafile): # file name includes input hot water velocity and temperature match = re.search(r'Z(\d+)ZT(\d+)', datafile) Z, ZT = int(match.group(1)), int(match.group(2)) # load data and create a slice downstream of the tee of the pipe tp.new_layout() tp.data.load_tecplot(datafile) pipe_exit = tp.data.extract.extract_slice((0, 0.2, 0), (0, 1, 0)) # get temperature on this slice t = pipe_exit.values('Temperature')[:] # return input velocity, intput temperature # and the stddev of the output temperature return Z, ZT, np.std(t)
def setup_plot(): """ Load the F-18 dataset from Tecplot 360's examples and show the jet surface in 3D. """ tp.new_layout() exdir = tp.session.tecplot_examples_directory() datafile = os.path.join(exdir, 'SimpleData', 'F18.plt') ds = tp.data.load_tecplot(datafile) frame = tp.active_frame() frame.show_border = False plot = frame.plot(PlotType.Cartesian3D) plot.activate() plot.contour(0).variable = ds.variable('S') plot.show_contour = True return plot
def mul_zone2tec_plt(path, filename, FileId, df, time=None, option=1): if option == 1: tp.session.connect() tp.new_layout() # page = tp.active_page() # page.name = 'page1' # frame = page.active_frame() # frame.name = 'frame1' # dataset = frame.create_dataset('data1') # add variable name # for j in range(np.shape(df)[1]): # var = df.columns[j] # dataset.add_variable(var) # link data dataset = tp.active_frame().create_dataset('data1', df.columns) with tp.session.suspend(): # with timer("save data as tecplot .plt"): for i in range(np.shape(FileId)[0]): file = FileId.iloc[i] ind1 = int(file['id1']) ind2 = int(file['id2']) nx = int(file['nx']) ny = int(file['ny']) nz = int(file['nz']) zonename = 'B' + '{:010}'.format(i) # print('creating tecplot zone: '+zonename) zone = dataset.add_ordered_zone(zonename, (nx, ny, nz)) # zone = dataset.add_zone('Ordered', zonename, (nx, ny, nz), # solution_time=time, strand_id=1) if time is not None: zone.strand = 1 zone.solution_time = np.float64(time) data = df.iloc[ind1:ind2 + 1] data = data.sort_values(by=['z', 'y', 'x']) for j in range(np.shape(data)[1]): var = data.columns[j] zone.values(var)[:] = data[var][:] tp.data.save_tecplot_plt(path + filename + '.plt', dataset=dataset) else: dataset = tp.data.load_tecplot(path + filename + '.dat', read_data_option=2) tp.data.save_tecplot_plt(path + filename + '.plt', dataset=dataset)
def write_tp_grouped(filename, data, data_shared, old=False, order='C'): print('Writing ' + filename + '...') logging.basicConfig(level=logging.INFO) tp.new_layout() frame = tp.active_frame() ## useful params sorted_keys = sorted(data.keys()) varname_data = list(next(iter(data.values())).keys()) varname_shared = list(data_shared.keys()) varname_all = varname_data + varname_shared shape = data_shared[varname_shared[0]].shape ## create dset dset = frame.create_dataset('data', var_names=varname_all) ## create data by zone zone_list = [] for zonename in sorted_keys: subdata = data[zonename] zone = dset.add_ordered_zone(zonename, shape) zone_list.append(zone) for name, var in subdata.items(): try: zone.values(name)[:] = var.ravel(order=order) except: print('Failed to write %s ...' % name) ## share variables for name, var in data_shared.items(): zone_list[0].values(name)[:] = var.ravel(order=order) variables_shared = [dset.variable(varname) for varname in varname_shared] dset.share_variables(zone_list[0], zone_list[1:], variables_shared) ## out if old: tp.data.save_tecplot_plt(filename + '.plt') else: tp.data.save_tecplot_szl(filename + '.szplt') print('Finished writing ' + filename + '.')
def test_basic_generators(self): with test.temp_workspace(): tp.new_layout() tp.data.load_tecplot([ test.data_item_path('spec_data/ds1.dat'), test.data_item_path('spec_data/ds2.dat'), ]) default_page = tp.active_page() page = gen.add_page() default_frame = page.active_frame() frame = gen.add_frame( position=[2., 1.], width=7, height=5, ) plot = frame.plot(tpc.PlotType.XYLine) plot.activate() plot.delete_linemaps() gen.add_xylinemap( name='T (ds1)', zone='stag[0]', x_variable='x', y_variable='T', ) gen.add_xylinemap( name='T (ds2)', zone='stag[1]', x_variable='x', y_variable='T', ) tp.delete_page(default_page) page.delete_frame(default_frame) tp.save_layout('test.lay') # Note: we can't really test for much more than simple success # creating the layout file. The fine details of the layout will # depend on whether the user has a tecplot.cfg file available # and we can't force factory settings in PyTecplot at this time. # Therefore, trying to establish a "reference output" is self.assertTrue(exists('test.lay'))
def write_tp(filename, data, old=False, order='C'): if old: filename += '.plt' else: filename += '.szplt' print('Writing ' + filename + '...') logging.basicConfig(level=logging.INFO) tp.new_layout() frame = tp.active_frame() varname = list(data.keys()) dset = frame.create_dataset('data', var_names=varname) zone = dset.add_ordered_zone('zone', data[varname[0]].shape) for name in varname: zone.values(name)[:] = data[name].ravel(order=order) if old: tp.data.save_tecplot_plt(filename) else: tp.data.save_tecplot_szl(filename) print('Finished writing ' + filename + '.')
def create_dataset(filename): reader = vtk.vtkXMLStructuredGridReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() dims = output.GetDimensions() fd = output.GetFieldData() cd = output.GetCellData() pd = output.GetPointData() tp.new_layout() ds = tp.active_frame().create_dataset(name=os.path.basename(filename)) # Add the XYZ variables - a dataset needs one variable before you can add a zone ds.add_variable('x', dtypes = [FieldDataType.Float]) ds.add_variable('y', dtypes = [FieldDataType.Float]) ds.add_variable('z', dtypes = [FieldDataType.Float]) zone_name = os.path.basename(filename) zone = ds.add_ordered_zone(zone_name, dims) # Not sure how to get solution time from VTS files yet #solution_time = float(filename.split('_')[-1].split('.')[0]) #strand = 1 #zone.solution_time = solution_time #zone.strand = strand # Write XYZ values xyz_points = get_points(output) zone.values(0)[:] = xyz_points[0] zone.values(1)[:] = xyz_points[1] zone.values(2)[:] = xyz_points[2] add_point_data(pd, zone) return ds
def load_data(self, *a): with tp.session.suspend(): tp.new_layout() # Load the Mach 0.1 Dataset and capture the associated zones self.dataset = tp.data.load_tecplot("mach_0.1.plt") self.ds1 = list(self.dataset.zones()) for z in self.ds1: z.solution_time = 0.1 # Load the Mach 0.2 Dataset and capture the associated zones tp.data.load_tecplot("mach_0.2.plt") self.ds2 = list(self.dataset.zones())[len(self.ds1):] for z in self.ds2: z.solution_time = 0.2 # Create a 'result' set of zones and capture the associated zones self.ds_result = self.dataset.copy_zones(self.ds1) for z in self.ds_result: z.solution_time = 0 # Set up some default style plot = tp.active_frame().plot(PlotType.Cartesian3D) plot.activate() plot.show_contour = True plot.contour(0).levels.reset_levels( [-1500, -1200, -900, -600, -300, 0, 300, 600, 900, 1200, 1500]) plot.contour(0).colormap_name = 'Diverging - Blue/Red' plot.contour( 0 ).colormap_filter.distribution = ColorMapDistribution.Continuous plot.contour(0).colormap_filter.continuous_min = -1500 plot.contour(0).colormap_filter.continuous_max = 1500 plot.view.rotate_to_angles(115, 115, -80) plot.view.position = (-65, 33.5, -35.4) plot.view.width = 6
# Check if temporary folder already exists, if not create it. if not os.path.isdir(img_fname): os.mkdir(img_fname) img_fpath = os.path.join(path, img_fname) func_file = [None] * f_count grid_file = [None] * f_count for i in range(f_count): ## Read Files print("Reading " + snapshot[i] + " ...") ## Creating function (.fun) and grid (.xyz) files func_file[i] = os.path.join(path, snapshot[i] + '.fun') grid_file[i] = os.path.join(path, snapshot[i] + '.xyz') tp.new_layout() # Deleting old layout and starting a new one # Opening grid and function file in Tecplot dataset = tp.data.load_plot3d(grid_filenames=grid_file[i], function_filenames=func_file[i]) print("\t" + snapshot[i] + " Loaded.") print("\tConfiguring Settings ...") ## Setup frame as Cartesinan 3D frame = tp.active_frame() frame.plot_type = tp.constant.PlotType.Cartesian3D plot = frame.plot() ## Camera View Settings #view = plot.view #view.psi = 65.777
# -*- coding: utf-8 -*- """ Created on Tue Jun 2 14:51:13 2020 @author: ge56beh """ import tecplot from tecplot.constant import * import os import numpy as np # Run this script with "-c" to connect to Tecplot 360 on port 7600 # To enable connections in Tecplot 360, click on: # "Scripting" -> "PyTecplot Connections..." -> "Accept connections" tecplot.new_layout() tecplot.session.connect() examples_dir = tecplot.session.tecplot_examples_directory() datafile = os.path.join(examples_dir, 'OneraM6wing', 'OneraM6_SU2_RANS.plt') dataset = tecplot.data.load_tecplot(datafile) print(dataset.variable_names) print(dataset.zone_names) frame = tecplot.active_frame() plot = frame.plot() plot.show_mesh = True # Turn on only the periodic slices (start, end and intermeidate) # and set them to span the length of the wing #plot.show_slices = True #slices = plot.slice(0)
def get_plt(T, blade_no): """ post blade discretization converts blade nodes and normals, obtained using SONATA, to *plt format for easy verification by viewing the blade deformation in TecPlot over one time period Parameters ------- blade_no : int reference blade number based on CAMRAD II, blade_no=4 referes to blade at 0 azimuth angle at t=0 T : float time period of rotor revolution Returns ------- None ToDo ------- -display azimuth in *.plt file """ print(f'*.p to *.plt :: Blade {blade_no}...') node_pos_arr_dict = pickle.load( open( os.path.dirname(os.path.dirname(__file__)) + "/node_pos_arr_dict_{0}.p".format(blade_no), "rb")) norm_pos_arr_dict = pickle.load( open( os.path.dirname(os.path.dirname(__file__)) + "/norm_pos_arr_dict_{0}.p".format(blade_no), "rb")) for key in node_pos_arr_dict: no_timesteps = np.shape(node_pos_arr_dict[key])[-1] break time_steps = np.linspace(0, T, no_timesteps) with tp.session.suspend(): tp.new_layout() frame = tp.active_frame() dataset = frame.dataset for var in ['x', 'y', 'z', 'x_normal', 'y_normal', 'z_normal']: dataset.add_variable(var) zones = {} for t_idx, t in enumerate(time_steps): # print('time step-->',t_idx,f' of {no_timesteps}' ) for surf, node_arr in node_pos_arr_dict.items(): norm_arr = norm_pos_arr_dict[surf] # if surf!='lifting-line': #just get the lifting-line # continue ord_zone_tup = (np.size(node_arr, axis=1), np.size(node_arr, axis=0), 1) zones[surf + str(t)] = dataset.add_ordered_zone( surf + '_' + "{:5.4f}".format(t), ord_zone_tup, solution_time=t, strand_id=1) # visualize in Camrad frame x_val = -node_arr[:, :, 1, t_idx] y_val = node_arr[:, :, 0, t_idx] z_val = node_arr[:, :, 2, t_idx] x_val_normal = -norm_arr[:, :, 1, t_idx] y_val_normal = norm_arr[:, :, 0, t_idx] z_val_normal = norm_arr[:, :, 2, t_idx] zones[surf + str(t)].values('x')[:] = x_val.ravel() zones[surf + str(t)].values('y')[:] = y_val.ravel() zones[surf + str(t)].values('z')[:] = z_val.ravel() zones[surf + str(t)].values('x_normal')[:] = x_val_normal.ravel() zones[surf + str(t)].values('y_normal')[:] = y_val_normal.ravel() zones[surf + str(t)].values('z_normal')[:] = z_val_normal.ravel() # azimuth=(90*blade_no)+(360*t/T) # macr_str=f"""$!AttachText # AnchorPos # {{ # X = 53.08578008059873 # Y = 66.21761658031089 # }} # TextShape # {{ # IsBold = No # }} # Text = 'Azimuth={azimuth:.1f} deg'""" # tp.macro.execute_command(macr_str) tp.data.save_tecplot_plt( os.path.dirname(os.path.dirname(__file__)) + '/Blade_{0}.plt'.format(blade_no), dataset=dataset) #saves all the data added above to the dataset print(f'... {blade_no} finished')
def work(datafile): tp.new_layout() tp.data.load_tecplot(datafile) tp.active_frame().load_stylesheet('isosurface.sty') imgfile = os.path.basename(datafile).replace('.plt', '.png') tp.save_png(os.path.join('images', imgfile))
def create_dataset(filename): reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() dims = output.GetDimensions() fd = output.GetFieldData() cd = output.GetCellData() pd = output.GetPointData() var_names = ['x', 'y', 'z'] for i in range(pd.GetNumberOfArrays()): arr = pd.GetArray(i) var_names.append(arr.GetName()) tp.new_layout() ds = tp.active_frame().create_dataset(filename) # Add the XYZ variables - a dataset needs one variable before you can add a zone ds.add_variable(var_names[0], dtypes=[FieldDataType.Float]) ds.add_variable(var_names[1], dtypes=[FieldDataType.Float]) ds.add_variable(var_names[2], dtypes=[FieldDataType.Float]) solution_time = float(filename.split('_')[-1].split('.')[0]) strand = 1 zone = ds.add_ordered_zone(filename, dims) zone.solution_time = solution_time zone.strand = strand # Write XYZ values spacing = output.GetSpacing() origin = output.GetOrigin() xvals = np.linspace(origin[0] - spacing[0] * dims[0] / 2, origin[0] + spacing[0] * dims[0] / 2, dims[0]) yvals = np.linspace(origin[1] - spacing[1] * dims[1] / 2, origin[1] + spacing[1] * dims[1] / 2, dims[1]) zvals = np.linspace(origin[2] - spacing[2] * dims[2] / 2, origin[2] + spacing[2] * dims[2] / 2, dims[2]) xx, yy, zz = np.meshgrid(xvals, yvals, zvals, indexing='ij') zone.values(0)[:] = xx.ravel() zone.values(1)[:] = yy.ravel() zone.values(2)[:] = zz.ravel() # Write the Point Data var_num = 3 for i in range(pd.GetNumberOfArrays()): arr = pd.GetArray(i) type = arr.GetDataType() print("Writing: ", arr.GetName()) data = vtk.vtkDoubleArray() arr.GetData(0, arr.GetNumberOfTuples() - 1, 0, 0, data) values = np.zeros(dims) data.ExportToVoidPointer(values) # VTI point data is not in the same IJK order as Tecplot, so we must # "roll" the values to reorder them. values = np.rollaxis(np.rollaxis(values, 1), -1).ravel() fd_type = field_data_type(type) ds.add_variable(var_names[var_num], dtypes=[fd_type]) if fd_type == FieldDataType.Float or fd_type == FieldDataType.Double: zone.values(var_num)[:] = values elif fd_type == FieldDataType.Byte or fd_type == FieldDataType.Int16: zone.values(var_num)[:] = values.astype(int) var_num += 1 return ds
tp.macro.execute_command(str) def order_zone_by_z(in_zn, dataset, z_var_number): # Setup a new zone with the same dimension as the FE Line zone out_zn = dataset.add_ordered_zone(in_zn.name, in_zn.num_points) # Convert to ordered zone z = in_zn.values(z_var_number - 1).as_numpy_array() ii = numpy.argsort(z) for v in ds.variables(): out_zn.values(v.index)[:] = in_zn.values(v.index).as_numpy_array()[ii] return out_zn for fname in files: tp.new_layout() # Reset between each file. # Accepts .dat, .plt, .cgns and .szplt ds = load_by_extension(fname) # Ensure that plot type is 3D cartesian tp.active_frame().plot_type = tp.constant.PlotType.Cartesian3D plot = tp.active_frame().plot() extracted_zones = [] for locale in surface_points: # Extract to 2D slice from volume zn_2Dslice = tp.data.extract.extract_slice( origin=locale, normal=(1, 0, 0), # Slice along X direction
type=int, default=1024) parser.add_argument("-supersample", help="Supersample factor to use for image export", type=int, default=2) parser.add_argument("-imagebasename", help="Basename for exported PNG images", default="image") args = parser.parse_args() # Get the solution times over which to iterate. Stop PyTecplot in # the main process to free up the license for the workers. PyTecplot # cannot be restarted once stopped! tp.new_layout() tp.load_layout(args.layoutfile) solution_times = tp.active_frame().dataset.solution_times tp.session.stop() # !!! IMPORTANT !!! # On Linux systems, Python's multiprocessing start method # defaults to "fork" which is incompatible with PyTecplot # and must be set to "spawn" multiprocessing.set_start_method('spawn') # Set up the pool with initializing function and associated arguments pool = multiprocessing.Pool(processes=args.numprocs, initializer=initialize_process, initargs=(args.layoutfile, ))
def raytrace(filename): RMercury = 2440000 # connect to Tecplot tp.session.connect() # read in data tp.new_layout() dataset = tp.data.load_tecplot(filename) frame = tp.active_frame() # creating spherical zone shape = (32,32) # used for debugging # shape = (128,128) r = 1.05 phi = np.linspace(0, pi, shape[0]) theta = np.linspace(0, 2*pi, shape[1]) ttheta, pphi = np.meshgrid(theta, phi, indexing='ij') xx = r * sin(pphi) * cos(ttheta) yy = r * sin(pphi) * sin(ttheta) zz = r * cos(pphi) sphere_zone = dataset.add_ordered_zone('R = {}'.format(r),shape) sphere_zone.values('X*')[:] = xx.ravel() sphere_zone.values('Y*')[:] = yy.ravel() sphere_zone.values('Z*')[:] = zz.ravel() X_seed = sphere_zone.values('X*') Y_seed = sphere_zone.values('Y*') Z_seed = sphere_zone.values('Z*') # interpolate magnetic field to spherical zone tp.data.operate.interpolate_linear(sphere_zone, dataset.zone('3D*'), dataset.variable('B_x*')) tp.data.operate.interpolate_linear(sphere_zone, dataset.zone('3D*'), dataset.variable('B_y*')) tp.data.operate.interpolate_linear(sphere_zone, dataset.zone('3D*'), dataset.variable('B_z*')) # set up vectors and background contour plot = frame.plot() plot.vector.u_variable = dataset.variable('B_x*') plot.vector.v_variable = dataset.variable('B_y*') plot.vector.w_variable = dataset.variable('B_z*') plot.show_streamtraces = False streamtraces = plot.streamtraces streamtraces.step_size = .25 streamtraces.max_steps = 10000 # add status variable dataset.add_variable('Status') # initialize polar cap area and open flux Area = {} Flux = {} Area['North'] = 0.0 Area['South'] = 0.0 Flux['North'] = 0.0 Flux['South'] = 0.0 # Pre-allocate theta value for each node Phi = pphi.ravel() # suspend the session tp.session.suspend_enter() # loop over nodes on 2D sphere_zone for i in range(len(X_seed)): if np.mod(i+1,1000) == 0: print('Iteration {}'.format(i)) streamtraces.add([X_seed[i], Y_seed[i], Z_seed[i]],tp.constant.Streamtrace.VolumeLine) slice_zone = streamtraces.extract() # slice_zone is a one-element generator, use a for loop to get its value for streamline in slice_zone: pass X = streamline.values('X*') Y = streamline.values('Y*') Z = streamline.values('Z*') X_max = np.fmax(np.abs(X.min()),np.abs(X.max())) Y_max = np.fmax(np.abs(Y.min()),np.abs(Y.max())) Z_max = np.fmax(np.abs(Z.min()),np.abs(Z.max())) if X_max < 3.0 and Y_max < 3.0 and Z_max < 3.0: status = 3 # close field line elif Z_seed[i] > 0.0: status = 2 else: status = 1 sphere_zone.values('Status')[i] = status # clear slice_zone and streamtraces dataset.delete_zones(dataset.zone('Streamtrace')) streamtraces.delete_all() # calculating open flux and area if status == 2: Area['North'] += r*r*sin(Phi[i])*(pi/shape[0])*(2*pi/shape[1]) Bfield = np.array([sphere_zone.values('B_x*')[i], sphere_zone.values('B_y*')[i], sphere_zone.values('B_z*')[i]]) normal = np.array([X_seed[i], Y_seed[i], Z_seed[i]]) Flux['North'] += np.abs(np.dot(Bfield, normal))*r*sin(Phi[i])*(pi/shape[0])*(2*pi/shape[1]) elif status == 1: Area['South'] += r*r*sin(Phi[i])*(pi/shape[0])*(2*pi/shape[1]) Bfield = np.array([sphere_zone.values('B_x*')[i], sphere_zone.values('B_y*')[i], sphere_zone.values('B_z*')[i]]) normal = np.array([X_seed[i], Y_seed[i], Z_seed[i]]) Flux['South'] += np.abs(np.dot(Bfield, normal))*r*sin(Phi[i])*(pi/shape[0])*(2*pi/shape[1]) tp.session.suspend_exit() # disconnect from Tecplot tp.session.disconnect() # units conversion Area['North'] *= RMercury*RMercury Area['South'] *= RMercury*RMercury Flux['North'] *= RMercury*RMercury*1e-9 Flux['South'] *= RMercury*RMercury*1e-9 # output results to stdout or another function # print('Northern polar cap area is {} m*m'.format(Area['North'])) # print('Southern polar cap area is {} m*m'.format(Area['South'])) # print('Northern open flux is {} Wb'.format(Flux['North'])) # print('Southern open flux is {} Wb'.format(Flux['South'])) return Area, Flux