def isosurf(x,y,z,s, scale=[1.0, 1.0, 1.0, 1.0], norm=0, viewer=None, f_args=(), f_keyw={}): """iso-surface plot of s, a 3D array,""" if norm: x = (x-x.min())/(x.max()-x.min()) y = (y-y.min())/(y.max()-y.min()) z = (z-z.min())/(z.max()-z.min()) xs = x*scale[0] ys = y*scale[1] zs = z*scale[2] data = create_structured_points3D(xs, ys, zs, s) if not viewer: v = mayavi.mayavi() else: v = viewer v.open_vtk_data(data) m = v.load_module('IsoSurface') if not viewer: a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) if (min(scale) != max(scale)) or (scale[0] != 1.0): a.axes.UseRangesOn() a.axes.SetRanges(x[0], x[-1], y[0], y[-1], z[0], z[-1]) o = v.load_module('Outline', 0) v.Render() return v
def volume(x,y,z,s, scale=[1.0, 1.0, 1.0, 1.0], viewer=None, f_args=(), f_keyw={}): """volume render s, a 3D array. s gets rescaled as an "unsigned char" 0..127""" xs = x*scale[0] ys = y*scale[1] zs = z*scale[2] sscale = s.max() - s.min() sd = ((s-s.min())*127/sscale).astype('b') data = create_structured_points3D(xs, ys, zs, sd) if not viewer: v = mayavi.mayavi() else: v = viewer v.open_vtk_data(data) m = v.load_module('Volume') if not viewer: a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) if (min(scale) != max(scale)) or (scale[0] != 1.0): a.axes.UseRangesOn() a.axes.SetRanges(x[0], x[-1], y[0], y[-1], z[0], z[-1]) o = v.load_module('Outline', 0) v.Render() return v
def visualise_mesh(mesh): import mayavi sys.argv=["",""] mesh_info = mesh.tolists() # define a few globals, so that the interval function can use them globals()['v'] = mayavi.mayavi() globals()['intervals'] = Numeric.arange(0,1.05,0.05) globals()['call_counter'] = 0 # to visualise without writing to disk, uncomment this section vtkData, points, simplices, simplexIndicies, icradii, ccradii = nmesh.visual.mesh2vtk(mesh_info, VTKonly=False) in2circ = nmesh.visual.findRatios(icradii, ccradii, factor=2) #2D mesh vtkData = nmesh.visual.append2vtk(vtkData, in2circ, "2*inradius/circumradius") globals()['v'].close_all() globals()['v'] = nmesh.visual.mesh2mayavi(vtkData, myv=globals()['v'], lut_range=(0,1)) m2 = v.load_module('SurfaceMap',0) m2.actor.GetProperty().SetRepresentationToWireframe() m2.mapper.SetScalarVisibility(0) m2.renwin.Render() dvm = v.get_current_dvm() mm = dvm.get_current_module_mgr() luthandler = mm.get_scalar_lut_handler() luthandler.set_lut_red_blue() luthandler.sc_bar.SetVisibility(1) luthandler.sc_bar.GetTitleTextProperty().SetShadow(1) luthandler.sc_bar.GetLabelTextProperty().SetShadow(1) globals()['v'].renwin.z_plus_view() # this line will reduce fluidity v.Render() raw_input()
def surf(x,y,z,warp=1, scale=[1.0, 1.0, 1.0], norm=0, viewer=None, f_args=(), f_keyw={}): """3D surface plot of z, a 2D array""" if norm: x = (x-x.min())/(x.max()-x.min()) y = (y-y.min())/(y.max()-y.min()) z = (z-z.min())/(z.max()-z.min()) xs = x*scale[0] ys = y*scale[1] data = create_structured_points(xs, ys, z) if not viewer: v = mayavi.mayavi() else: v = viewer v.open_vtk_data(data) if warp: f = v.load_filter('WarpScalar', 0) f.fil.SetScaleFactor(scale[2]) n = v.load_filter('PolyDataNormals', 0) n.fil.SetFeatureAngle(45) m = v.load_module('SurfaceMap', 0) if not viewer: a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) if (min(scale) != max(scale)) or (scale[0] != 1.0): a.axes.UseRangesOn() a.axes.SetRanges(x[0], x[-1], y[0], y[-1], min(zval), max(zval)) o = v.load_module('Outline', 0) v.Render() return v
def visualise_mesh(mesh): import mayavi sys.argv = ["", ""] mesh_info = mesh.tolists() # define a few globals, so that the interval function can use them globals()['v'] = mayavi.mayavi() globals()['intervals'] = Numeric.arange(0, 1.05, 0.05) globals()['call_counter'] = 0 # to visualise without writing to disk, uncomment this section vtkData, points, simplices, simplexIndicies, icradii, ccradii = nmesh.visual.mesh2vtk( mesh_info, VTKonly=False) in2circ = nmesh.visual.findRatios(icradii, ccradii, factor=2) #2D mesh vtkData = nmesh.visual.append2vtk(vtkData, in2circ, "2*inradius/circumradius") globals()['v'].close_all() globals()['v'] = nmesh.visual.mesh2mayavi(vtkData, myv=globals()['v'], lut_range=(0, 1)) m2 = v.load_module('SurfaceMap', 0) m2.actor.GetProperty().SetRepresentationToWireframe() m2.mapper.SetScalarVisibility(0) m2.renwin.Render() dvm = v.get_current_dvm() mm = dvm.get_current_module_mgr() luthandler = mm.get_scalar_lut_handler() luthandler.set_lut_red_blue() luthandler.sc_bar.SetVisibility(1) luthandler.sc_bar.GetTitleTextProperty().SetShadow(1) luthandler.sc_bar.GetLabelTextProperty().SetShadow(1) globals()['v'].renwin.z_plus_view() # this line will reduce fluidity v.Render() raw_input()
def main(): global myv myv = mayavi.mayavi() # open mayavi outside of loop def driver_do(nr_piece, n,mesh): print "Iteration: %d" %(n) mesh_info = ocaml.mesh_plotinfo(mesh) myv.close_all() v = mesh2vtk(mesh_info) vd = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() ## mm.scalar_lut_h.load_lut_from_file("gauss.lut") ## mm.scalar_lut_h.range_on_var.set(1) ## mm.scalar_lut_h.range_var.set((0, 1)) ## mm.scalar_lut_h.set_range_var() md = myv.load_module('SurfaceMap',0) myv.renwin.z_plus_view() vd2 = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() ## mm.scalar_lut_h.load_lut_from_file("gauss.lut") ## mm.scalar_lut_h.range_on_var.set(1) ## mm.scalar_lut_h.range_var.set((0, 1)) ## mm.scalar_lut_h.set_range_var() md2 = myv.load_module('SurfaceMap',0) md2.mapper.ScalarVisibilityOff() md2.actor.GetProperty().SetRepresentationToWireframe() myv.renwin.z_plus_view() myv.Render() raw_input() rod_length=0.6 my_mdefaults=ocaml.mesher_defaults my_gendriver=ocaml.make_mg_gendriver(120,driver_do) # create a mesh # the cone is called with arguments in the order: # center1, radius1, center2, radius2 frustum = ocaml.body_box([-3.0,-3.0,-3.0],[3.0,3.0,3.0]) density=""" { density=1.0; } """ mesh = ocaml.mesh_bodies_raw(my_gendriver,my_mdefaults, [-6.0,-6.0,-6.0], [6.0,6.0,6.0], 1,[frustum], rod_length,density) mesh_info = ocaml.mesh_plotinfo(mesh) v = mesh2vtk(mesh_info)
def main(): global myv myv = mayavi.mayavi() # open mayavi outside of loop def driver_do(nr_piece, n,mesh): print "Iteration: %d" %(n) mesh_info = ocaml.mesh_plotinfo(mesh) myv.close_all() v = mesh2vtk(mesh_info,n) vd = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() # mm.scalar_lut_h.load_lut_from_file("gauss.lut") # mm.scalar_lut_h.range_on_var.set(1) # mm.scalar_lut_h.range_var.set((0, 1)) # mm.scalar_lut_h.set_range_var() md = myv.load_module('SurfaceMap',0) myv.renwin.z_plus_view() vd2 = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() # mm.scalar_lut_h.load_lut_from_file("gauss.lut") # mm.scalar_lut_h.range_on_var.set(1) # mm.scalar_lut_h.range_var.set((0, 1)) # mm.scalar_lut_h.set_range_var() md2 = myv.load_module('SurfaceMap',0) md2.mapper.ScalarVisibilityOff() md2.actor.GetProperty().SetRepresentationToWireframe() myv.renwin.z_plus_view() myv.Render() raw_input() rod_length=0.1 my_mdefaults=ocaml.mesher_defaults my_gendriver=ocaml.make_mg_gendriver(40,driver_do) # create a mesh ell = ocaml.body_ellipsoid([0.5,0.2,0.2]) density=""" { density = 1.0; } """ mesh = ocaml.mesh_bodies_raw(my_gendriver,my_mdefaults, [-0.6,-0.6,-0.6], [0.6,0.6,0.6], 1,[ell], rod_length,density) mesh_info = ocaml.mesh_plotinfo(mesh) v = mesh2vtk(mesh_info)
def main(): def driver_do(nr_piece, n,mesh): print "Iteration: %d" %(n) mesh_info = ocaml.mesh_plotinfo(mesh) v = mesh2vtk(mesh_info) rod_length=0.8 my_mdefaults=ocaml.mesher_defaults my_gendriver=ocaml.make_mg_gendriver(120,driver_do) # create a mesh # the cone is called with arguments in the order: # center1, radius1, center2, radius2 square = ocaml.body_box([-3.0,-3.0],[3.0,3.0]) density=""" { density=1.0; } """ mesh = ocaml.mesh_bodies_raw(my_gendriver,my_mdefaults, [-5.0,-5.0], [5.0,5.0], 1,[square], rod_length,density) ocaml.mesh_writefile("test_write.dat",mesh) # write & read mesh on file mesh2 = ocaml.mesh_readfile("test_write.dat") mesh_info2 = ocaml.mesh_plotinfo(mesh2) # extract data from the mesh v = mesh2vtk(mesh_info2) myv = mayavi.mayavi() # open mayavi vd = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() md = myv.load_module('SurfaceMap',0) myv.renwin.z_plus_view() vd2 = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() md2 = myv.load_module('SurfaceMap',0) md2.mapper.ScalarVisibilityOff() md2.actor.GetProperty().SetRepresentationToWireframe() myv.renwin.z_plus_view() myv.Render() raw_input()
def __init__(self, argv): shellscript.ShellScript.__init__(self, argv) self.d_window = mayavi.mayavi() self.d_tuples = []
import mayavi theMayavi = mayavi.mayavi() theMayavi.open_vtk("resultCouetteGrid0000002.vtk",0) theMayavi.load_module("GridPlane",0) theMayavi.open_vtk("resultCouette0000002.vtk",0) theMayavi.load_module("Glyph",0)
def main(): global myv myv = mayavi.mayavi() # open mayavi outside of loop def driver_do(nr_piece, n,mesh): print "Iteration: %d" %(n) mesh_info = ocaml.mesh_plotinfo(mesh) myv.close_all() v = mesh2vtk(mesh_info) vd = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() md = myv.load_module('SurfaceMap',0) myv.renwin.z_plus_view() vd2 = myv.open_vtk_data(v) dvm = myv.get_current_dvm() mm = dvm.get_current_module_mgr() md2 = myv.load_module('SurfaceMap',0) md2.mapper.ScalarVisibilityOff() md2.actor.GetProperty().SetRepresentationToWireframe() myv.renwin.z_plus_view() myv.Render() raw_input() rod_length=0.3 my_mdefaults=ocaml.mesher_defaults my_gendriver=ocaml.make_mg_gendriver(20,driver_do) # create a mesh box= ocaml.body_shifted_sc(ocaml.body_box([0.0,0.0,0.0],[2.2,2.2,2.2]),[0.0,0.0,0.0]) dot = [] for i in Numeric.arange(0.4,2.0,0.7): for j in Numeric.arange(0.4,2.0,0.7): for k in Numeric.arange(0.4,2.0,0.7): #print i,j,k dot.append(ocaml.body_shifted_sc(ocaml.body_ellipsoid([0.3,0.3,0.3]),[i,j,k])) density=""" { double antidot_radius = 0.3; double r = sqrt(x[0]*x[0]+x[1]*x[1]+x[2]*x[2]); int nr_antidots = 27; double p[27][3]; /* centres of antidots*/ double rad[27]; /* radii of antidots */ int flag; /* point in or outside antidots */ int n,i,j,k,a; /* loop variables */ /* fill centres and radii */ n = 0; while (n < nr_antidots) { for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ for(k = 0; k < 3; k++){ p[n][0] = i*0.7 + 0.4; p[n][1] = j*0.7 + 0.4; p[n][2] = k*0.7 + 0.4; rad[n] = sqrt((x[0]-p[n][0])*(x[0]-p[n][0])+(x[1]-p[n][1])*(x[1]-p[n][1])+(x[2]-p[n][2])*(x[2]-p[n][2])); n += 1; }}} } /* function to get the max of two floats */ float max_float (float x, float y) { if (x > y) return x; else return y; } /* check point in-outside antidots */ flag = 1; for(i = 0; i < nr_antidots; i++) { if ((flag = 0) || (rad[i] < antidot_radius)) {flag = 0;} } /* associate density with the point */ density = 0.0; if (flag = 0) {density = 0.0;} else { for(i = 0; i < nr_antidots; i++) { density = max_float(density, 1./rad[i]); } } } """ mesh = ocaml.mesh_bodies_raw(my_gendriver,my_mdefaults, [0.0,0.0,0.0], [2.2,2.2,2.2], 1,dot, rod_length,density) mesh_info = ocaml.mesh_plotinfo(mesh) v = mesh2vtk(mesh_info)
def mesh_it(self, rod_length = 0.5 , driver = [],mesher = [], bbox = [], density = "", visual = False, angles = False, save = []): """mesh_it(rod_length:float, driver, mesher, \ bbox:[float list,float list]), density, visual:bool, save:string list). Function to mesh the present object(s). The rod_length is the desired length of the connections between the mesh nodes, a value which is weighted with the C function density. The bbox defines the outer boundary box of the mesh. The flag visual consents to visualise the mesh during its relaxation process, and it can be saved specifying the file (with format) in the save list. Possible formats are postscript file(s) ("ps" extension) (2D only), vtk file(s) ("vtk" extension) (included the ones created at every visualization step) and "pyfem" format ("dat" extension). The function returns the mesh data in a python list of lists (the content is clear once they are inspected). """ self.rod = rod_length self.density = density if mesher == []: self.mesher = ocaml.mesher_defaults else: self.mesher = mesher.my_mesher self.__file_vtk = "" self.__file_ps = "" self.__file_dat = "" self.__file_png = "" globals()['fig_number']=0 globals()['angles_time']=[] globals()['default_iterations'] = 200 def check_save(): """Function to check if the mesh has to be saved in any format. """ # print "check_save" if len(save)>0: for filename in save: if filename[-3:]=="dat": self.__file_dat = filename elif filename[-3:]=="vtk": self.__file_vtk = filename elif filename[-3:]==".ps": self.__file_ps = filename elif filename[-3:]=="png": self.__file_png = filename else: ValueError ("wrong extension in save file name") # print self.__file_vtk, self.__file_ps, self.__file_dat, self.__file_png if visual: # Initialisation of mayavi if argument visual = True # print "load mayavi" import mayavi, pylab # Tk error without pylab self.myv = mayavi.mayavi() def check_vtk(nr_piece,n,mesh): # print "check_vtk -- 0" if visual or self.__file_vtk!="": # print "mesh_info" mesh_info = ocaml.mesh_plotinfo(mesh) # print "check_vtk -- 1" v = self._mesh2vtk(mesh_info,self.__file_vtk,"-"+str(nr_piece),"-"+str(n)) # print "check_vtk -- 2" if visual: # print "visual" # Function executed for argument visual = True self.myv.close_all() vd = self.myv.open_vtk_data(v) dvm = self.myv.get_current_dvm() mm = dvm.get_current_module_mgr() md = self.myv.load_module('SurfaceMap',0) # reverse LUT luthandler = mm.get_scalar_lut_handler() luthandler.set_lut_red_blue() # display legend, vertically with shadow effect luthandler.sc_bar.SetVisibility(1) luthandler.sc_bar.GetTitleTextProperty().SetShadow(1) luthandler.sc_bar.GetLabelTextProperty().SetShadow(1) luthandler.sc_bar.GetPositionCoordinate().SetValue(0.01,0.15) luthandler.sc_bar.SetOrientationToVertical() luthandler.sc_bar.SetWidth(0.14) luthandler.sc_bar.SetHeight(0.85) # luthandler.sc_bar.SetTitle('in2circ') self.myv.renwin.z_plus_view() vd2 = self.myv.open_vtk_data(v) dvm = self.myv.get_current_dvm() mm = dvm.get_current_module_mgr() md2 = self.myv.load_module('SurfaceMap',0) md2.mapper.ScalarVisibilityOff() md2.actor.GetProperty().SetRepresentationToWireframe() self.myv.renwin.z_plus_view() self.myv.Render() # if angles analysis has been requested plot histogram in pylab now if angles: angles_data = self._findAngles(mesh_info) n, bins, patches = pylab.hist(angles_data, range(0,180,5)) pylab.xlabel('Internal angle in degrees') pylab.ylabel('Number of occurrences') pylab.title('Histogram of internal angles of %d triangles' % (len(mesh_info[2][2]))) pylab.axvline(x=60, color='r') pylab.savefig(self.__file_png[:-4]+str(globals()['fig_number'])+'.png') globals()['fig_number'] = globals()['fig_number'] + 1 pylab.show() #(screws with Tk events) pylab.clf() # attempt to save time series of angles data for quality vs. time plot # this temporary hack saves the median angle for the highest count bin highest = 0 modal = 0 for i in range(len(n)): if n[i] > highest: highest = n[i] modal = i median = (bins[modal] + bins[modal-1])/2. globals()['angles_time'].append(median) raw_input('Hit Any Key to Continue') def no_driver(nr_piece,n,mesh): """Function executed for argument visual = False """ # print "no_driver" check_vtk(nr_piece,n,mesh) pass def fun_from_driver(nr_piece,n,mesh): """Function that glues together the user-defined function and the (possible) visualisation of the mesh during relaxation process. """ check_vtk(nr_piece,n,mesh) # print "*********************fun_from_driver" driver.driver_do(nr_piece,n,mesh) #user-defined function check_save() # check if the mesh has to be saved if driver == []: # no driver is given: use the default one self.driver = ocaml.make_mg_gendriver(globals()['default_iterations'], no_driver) else: # print self.__file_vtk self.driver = ocaml.make_mg_gendriver(driver.every_nr_steps,fun_from_driver) if bbox != []: # overwrite bbox defined at object initialisation self.bbox = bbox # print self.bbox # print self.obj obj_length = len(self.obj) # number of objects to mesh raw_mesh = ocaml.mesh_bodies_raw(self.driver,self.mesher,\ self.bbox[0],self.bbox[1],obj_length,\ self.obj,rod_length,self.density) if self.__file_ps != "": ocaml.mesh2d_ps(raw_mesh,self.__file_ps,[50.0,50.0,300.0,300.0]) if self.__file_dat != "": ocaml.mesh_writefile(self.__file_dat,raw_mesh) # to display final results in visual mode if visual: mesh_info = ocaml.mesh_plotinfo(raw_mesh) v = self._mesh2vtk(mesh_info,self.__file_vtk) self.myv.close_all() vd = self.myv.open_vtk_data(v) dvm = self.myv.get_current_dvm() mm = dvm.get_current_module_mgr() md = self.myv.load_module('SurfaceMap',0) # reverse LUT luthandler = mm.get_scalar_lut_handler() luthandler.set_lut_red_blue() # display legend, vertically with shadow effect luthandler.sc_bar.SetVisibility(1) luthandler.sc_bar.GetTitleTextProperty().SetShadow(1) luthandler.sc_bar.GetLabelTextProperty().SetShadow(1) luthandler.sc_bar.GetPositionCoordinate().SetValue(0.01,0.15) luthandler.sc_bar.SetOrientationToVertical() luthandler.sc_bar.SetWidth(0.14) luthandler.sc_bar.SetHeight(0.85) # luthandler.sc_bar.SetTitle('in2circ') self.myv.renwin.z_plus_view() vd2 = self.myv.open_vtk_data(v) dvm = self.myv.get_current_dvm() mm = dvm.get_current_module_mgr() md2 = self.myv.load_module('SurfaceMap',0) md2.mapper.ScalarVisibilityOff() md2.actor.GetProperty().SetRepresentationToWireframe() self.myv.renwin.z_plus_view() self.myv.Render() if self.__file_png: # if angles analysis has been requested plot histogram in pylab now if angles: angles_data = self._findAngles(mesh_info) n, bins, patches = pylab.hist(angles_data, range(0,180,5)) pylab.clf() pylab.xlabel('Internal angle in degrees') pylab.ylabel('Number of occurrences') pylab.title('Histogram of internal angles of mesh triangles') pylab.axvline(x=60, color='r') pylab.savefig(self.__file_png[:-4]+str(globals()['fig_number'])+'.png') globals()['fig_number'] = globals()['fig_number'] + 1 pylab.show() #(screws with Tk events) # also save time plot of angles pylab.clf() total_iterations = globals()['default_iterations']*len(globals()['angles_time']) xvalues = range(0,total_iterations,globals()['default_iterations']) pylab.plot(xvalues,globals()['angles_time'],'k+') pylab.hold(True) pylab.plot(xvalues,globals()['angles_time']) pylab.xlabel('Number of iterations') pylab.ylabel('Modal internal angle (2D) in degrees') pylab.title('Plot of mesh quality against time') pylab.savefig(self.__file_png[:-4]+'_time.png') raw_input('Hit Any Key to Exit.') else: mesh_info = ocaml.mesh_plotinfo(raw_mesh) raw_input('Hit Any Key to Exit.')
import mayavi, sys, Numeric, nmesh filename = sys.argv[1] if filename[-5:] != "nmesh" : raise ValueError("The file is not a nmesh file.") sys.argv=["",""] # define a few globals, so that the interval function can use them globals()['v'] = mayavi.mayavi() globals()['intervals'] = Numeric.arange(0,1.05,0.05) globals()['call_counter'] = 0 the_mesh = nmesh.load(filename) mesh_info = the_mesh.tolists() # to visualise without writing to disk, uncomment this section vtkData, points, simplices, simplexIndicies, icradii, ccradii = nmesh.visual.mesh2vtk(mesh_info, VTKonly=False,body_numbers=True) in2circ = nmesh.visual.findRatios(icradii, ccradii)#, factor=3) #2D mesh # order the mesh by this metric mesh_info= nmesh.visual.order_mesh(mesh_info, data=in2circ) globals()['v'].close_all() # display this information and open the ExtractUnstructuredGrid filter nmesh.visual.solid_in2circ(mesh_info, myv = globals()['v']) m2 = v.load_module('SurfaceMap',0) m2.actor.GetProperty().SetRepresentationToWireframe() m2.mapper.SetScalarVisibility(0) m2.renwin.Render() dvm = v.get_current_dvm() mm = dvm.get_current_module_mgr() luthandler = mm.get_scalar_lut_handler()
#!/usr/bin/env python import mayavi bighead = '../data/bighead.vtk' mv = mayavi.mayavi() mv.open_vtk(bighead) for mod in ['Outline', 'Axes', 'PolyData']: mv.load_module(mod, 0)
# create square box = nmesh.box([0.0, 0.0], [1.0, 1.0]) # create cone cone = nmesh.conic([3.0, 0.0], 1.0, [3.0, 4.0], 0.0) rod = 0.4 bbox = [[-1., -1.], [7., 6.]] # Set up a MayaVi window ready for use during mesher 'pauses'. # The sys.argv hack is only required when MayaVi is used in # a 'callback' function as below, it is not needed in static mode. import mayavi, sys sys.argv = ["", ""] # define a few globals, so that the interval function can use them globals()['v'] = mayavi.mayavi() globals()['intervals'] = Numeric.arange(0, 1.05, 0.05) globals()['call_counter'] = 0 # define the interval function def my_function(piece, timestep, mesh_info): """This function can be called to provide MayaVi and pylab visualisations of a mesh whilst it is growing. Author: James Kenny """ # to visualise without writing to disk, uncomment this section vtkData, points, simplices, simplexIndicies, icradii, ccradii = nmesh.visual.mesh2vtk( mesh_info, VTKonly=False) in2circ = nmesh.visual.findRatios(icradii, ccradii, factor=2) #2D mesh
def surf(x, y, z, warp=1, scale=[1.0, 1.0, 1.0], viewer=None, f_args=(), f_keyw=None): """Creates a surface given regularly spaced values of x, y and the corresponding z as arrays. Also works if z is a function. Currently works only for regular data - can be enhanced later. Input Arguments: x -- Array of x points (regularly spaced) y -- Array if y points (regularly spaced) z -- A 2D array for the x and y points with x varying fastest and y next. Also will work if z is a callable which supports x and y arrays as the arguments. warp -- If true, warp the data to show a 3D surface (default = 1). scale -- Scale the x, y and z axis as per passed values. Defaults to [1.0, 1.0, 1.0]. viewer -- An optional viewer (defaults to None). If provided it will use this viewer instead of creating a new MayaVi window each time. f_args -- a tuple of additional positional arguments for func() (default is empty) f_keyw -- a dict of additional keyword arguments for func() (default is empty) """ if f_keyw is None: f_keyw = {} if callable(z): zval = Numeric.ravel(sampler(x, y, z, f_args=f_args, f_keyw=f_keyw)) x, y = squeeze(x), squeeze(y) else: x, y = squeeze(x), squeeze(y) _check_sanity(x, y, z) zval = Numeric.ravel(z) assert len(zval) > 0, "z is empty - nothing to plot!" xs = x*scale[0] ys = y*scale[1] data = _create_structured_points_direct(xs, ys, zval) # do the mayavi stuff. if not viewer: v = mayavi.mayavi() else: v = viewer v.open_vtk_data(data) if warp: f = v.load_filter('WarpScalar', 0) f.fil.SetScaleFactor(scale[2]) n = v.load_filter('PolyDataNormals', 0) n.fil.SetFeatureAngle(45) m = v.load_module('SurfaceMap', 0) if not viewer: a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) if (min(scale) != max(scale)) or (scale[0] != 1.0): a.axes.UseRangesOn() a.axes.SetRanges(x[0], x[-1], y[0], y[-1], min(zval), max(zval)) o = v.load_module('Outline', 0) v.Render() return v
import mayavi v = mayavi.mayavi() # create a MayaVi window. d = v.open_vtk('/tmp/test.vtk', config=0) # open the data file. # The config option turns on/off showing a GUI control for the data/filter/module. # load the filters. f = v.load_filter('WarpScalar', config=0) n = v.load_filter('PolyDataNormals', 0) n.fil.SetFeatureAngle(45) # configure the normals. # Load the necessary modules. m = v.load_module('SurfaceMap', 0) a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) # configure the axes module. o = v.load_module('Outline', 0) v.Render() # Re-render the scene.
import mayavi theMayavi = mayavi.mayavi() theMayavi.open_vtk("resultCouetteGrid0000002.vtk", 0) theMayavi.load_module("GridPlane", 0) theMayavi.open_vtk("resultCouette0000002.vtk", 0) theMayavi.load_module("Glyph", 0)
def main (): try: opts, args = getopt.getopt(sys.argv[1:], "hf:z:rs:", ["help", "flfile", "vizfile=", "", "recycle", "gif", "avi", "fps", "png"]) except getopt.GetoptError: # print help information and exit: print "ERROR: Bad arguments!" print usage() sys.exit(2) # Collect options. recycle = 0 flfile = None mvfile = None movie = "gif" fps = 5 maximize = False for o, a in opts: if o in ("-h", "--help"): print usage() sys.exit() if o in ("-z", "--vizfile"): mvfile = a if o in ("-r", "--recycle"): recycle = 1 if o in ("-f", "--flfile"): flfile = a if o == "--avi": movie = "avi" if o == "--png": movie = "non" if o in ("-s", "--fps"): try: fps = float(a) assert(fps > 0.0) except: print "ERROR: Bad arguments!" print usage() sys.exit(2) # Check for fluidity file if not flfile: print "ERROR: No fluidity file given." print usage() sys.exit() # Check for MayaVi visualisation file if not mvfile: # Guess mvfile = flfile+".mv" if not os.path.isfile( mvfile ): print "ERROR: No MayaVi visualisation file found." print usage() sys.exit() try: start = string.atoi( args[0] ) except: print "ERROR: Bad starting id %s"%args[0] print usage() sys.exit() try: finish = string.atoi( args[1] ) except: print "ERROR: Bad last id %s"%args[1] print usage() sys.exit() # Movie file that we'll be writting to moviefile = flfile+"."+movie # instantiate a MayaVi v = mayavi.mayavi() # load the visualisation v.load_visualization(mvfile) # grab the DataVizManager list dvms = v.get_dvm_names() # list frames to be animated frames = "" for id in range(start, finish+1): # Get frame name frame='./'+flfile+'%04d.png'%id if (movie=="avi"): frames = frames+","+frame else: frames = frames+" "+frame # Are we recycling frames if recycle: if os.path.isfile(frame): continue # Make a vtk file datafile = get_file (flfile, id) # go through all the DVM's for i in dvms: # grab a handle to the DVM dvm = v.mayavi.data_viz_mgr[i] # follow the pipeline, and load in the new data file ds = dvm.get_data_source () rdr = ds.get_reader () rdr.SetFileName (datafile) ds.reread_file () v.Render () # write this image to the disk v.renwin.save_png (frame) # Bail out if no movie desired if (movie=="non"): return 0 # Now generate the avi file pid = os.getpid () tmpfile_name = os.environ['PWD']+"/.tmpmvfile%d"%pid tmpfile = open(tmpfile_name, 'w') tmpfile.write( "#!/bin/sh\n") if (movie=="avi"): tmpfile.write( "mencoder mf://"+flfile+"*.png -mf fps=" + str(fps) + ":type=png -ovc copy -o "+flfile+".avi\n") else: tmpfile.write( "convert -delay " + str(100.0 / fps) + " -loop 0 "+frames+" "+flfile+".gif\n" ) tmpfile.write( "rm -f %s\n"%tmpfile_name ) tmpfile.close() os.chmod(tmpfile_name, 0700) # Generate animation if os.fork() == 0: os.execl( tmpfile_name, "" ) else: os.wait() return 0
def __init__(self, distanceVar, surfactantVar=None, levelSetValue=0., title=None, smooth=0, zoomFactor=1., animate=False, limits={}, **kwlimits): """ Create a `MayaviSurfactantViewer`. >>> from fipy import * >>> dx = 1. >>> dy = 1. >>> nx = 11 >>> ny = 11 >>> Lx = ny * dy >>> Ly = nx * dx >>> mesh = Grid2D(dx = dx, dy = dy, nx = nx, ny = ny) >>> # from fipy.models.levelSet.distanceFunction.distanceVariable import DistanceVariable >>> var = DistanceVariable(mesh = mesh, value = -1) >>> x, y = mesh.cellCenters >>> var.setValue(1, where=(x - Lx / 2.)**2 + (y - Ly / 2.)**2 < (Lx / 4.)**2) >>> var.calcDistanceFunction() >>> viewer = MayaviSurfactantViewer(var, smooth = 2) >>> viewer.plot() >>> viewer._promptForOpinion() >>> del viewer >>> var = DistanceVariable(mesh = mesh, value = -1) >>> var.setValue(1, where=(y > 2. * Ly / 3.) | ((x > Lx / 2.) & (y > Ly / 3.)) | ((y < Ly / 6.) & (x > Lx / 2))) >>> var.calcDistanceFunction() >>> viewer = MayaviSurfactantViewer(var) >>> viewer.plot() >>> viewer._promptForOpinion() >>> del viewer >>> viewer = MayaviSurfactantViewer(var, smooth = 2) >>> viewer.plot() >>> viewer._promptForOpinion() >>> del viewer :Parameters: - `distanceVar`: a `DistanceVariable` object. - `levelSetValue`: the value of the contour to be displayed - `title`: displayed at the top of the `Viewer` window - `animate`: whether to show only the initial condition and the - `limits`: a dictionary with possible keys `xmin`, `xmax`, `ymin`, `ymax`, `zmin`, `zmax`, `datamin`, `datamax`. A 1D `Viewer` will only use `xmin` and `xmax`, a 2D viewer will also use `ymin` and `ymax`, and so on. All viewers will use `datamin` and `datamax`. Any limit set to a (default) value of `None` will autoscale. moving top boundary or to show all contours (Default) """ kwlimits.update(limits) AbstractViewer.__init__(self, vars=[], title=title, **kwlimits) import mayavi self._viewer = mayavi.mayavi() self.distanceVar = distanceVar if surfactantVar is None: self.surfactantVar = numerix.zeros(len(self.distanceVar), 'd') else: self.surfactantVar = surfactantVar self.smooth = smooth self.zoomFactor = zoomFactor self.animate = animate if animate: self._initialCondition = None if distanceVar.mesh.dim != 2: raise MeshDimensionError( 'The MayaviIsoViewer only works for 2D meshes.')
def view(arr, smooth=0, warp=0, scale=[1.0, 1.0, 1.0]): """Allows one to view a 2D Numeric array. Note that the view will be set to the way we normally think of matrices with with 0, 0 at the top left of the screen. Input Arguments: arr -- Array to be viewed. smooth -- If true, view the array as VTK point data i.e. the matrix entries will be treated as scalar data at the integral values along the axes and between these points the colours will be interpolated providing a smooth appearance for the data. If set to false the data is viewed as cells with no interpolation and each cell of the matrix is viewed in a separate color with no interpolation. Note that if smooth is set to true you will be able to do more fancy things with the visualization (like contouring the data, warping it to get a 3d surface etc.) than when smooth is off. If warp is set to true then this option is set to true. (default=false) warp -- If true, warp the data to show a 3D surface (default = 0). If set the smooth option has no effect. Note that this is an expensive operation so use it sparingly for large arrays. scale -- Scale the x, y and z axis as per passed values. Defaults to [1.0, 1.0, 1.0]. """ assert len(arr.shape) == 2, "Only 2D arrays can be viewed!" ny, nx = arr.shape if warp: smooth=1 if not smooth: nx += 1 ny += 1 dx, dy, junk = Numeric.array(scale)*1.0 xa = Numeric.arange(0, nx*scale[0] - 0.1*dx, dx, 'f') ya = Numeric.arange(0, ny*scale[1] - 0.1*dy, dy, 'f') if smooth: data = _create_structured_points_direct(xa, ya, arr) else: data = _create_structured_points_direct(xa, ya) sc = array2vtk(arr) data.GetCellData().SetScalars(sc) # do the mayavi stuff. v = mayavi.mayavi() v.open_vtk_data(data) if warp: f = v.load_filter('WarpScalar', 0) f.fil.SetScaleFactor(scale[2]) n = v.load_filter('PolyDataNormals', 0) n.fil.SetFeatureAngle(45) m = v.load_module('SurfaceMap', 0) a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) a.axes.YAxisVisibilityOff() a.axes.UseRangesOn() arr_flat = Numeric.ravel(arr) a.axes.SetRanges(0, nx, 0, ny, min(arr_flat), max(arr_flat)) o = v.load_module('Outline', 0) v.renwin.update_view(0, 0, -1, 0, -1, 0) v.Render() return v
def __init__(self, distanceVar, surfactantVar=None, levelSetValue=0., title=None, smooth=0, zoomFactor=1., animate=False, limits={}, **kwlimits): """ Create a `MayaviSurfactantViewer`. >>> from fipy import * >>> dx = 1. >>> dy = 1. >>> nx = 11 >>> ny = 11 >>> Lx = ny * dy >>> Ly = nx * dx >>> mesh = Grid2D(dx = dx, dy = dy, nx = nx, ny = ny) >>> # from fipy.models.levelSet.distanceFunction.distanceVariable import DistanceVariable >>> var = DistanceVariable(mesh = mesh, value = -1) >>> x, y = mesh.cellCenters >>> var.setValue(1, where=(x - Lx / 2.)**2 + (y - Ly / 2.)**2 < (Lx / 4.)**2) >>> var.calcDistanceFunction() >>> viewer = MayaviSurfactantViewer(var, smooth = 2) >>> viewer.plot() >>> viewer._promptForOpinion() >>> del viewer >>> var = DistanceVariable(mesh = mesh, value = -1) >>> var.setValue(1, where=(y > 2. * Ly / 3.) | ((x > Lx / 2.) & (y > Ly / 3.)) | ((y < Ly / 6.) & (x > Lx / 2))) >>> var.calcDistanceFunction() >>> viewer = MayaviSurfactantViewer(var) >>> viewer.plot() >>> viewer._promptForOpinion() >>> del viewer >>> viewer = MayaviSurfactantViewer(var, smooth = 2) >>> viewer.plot() >>> viewer._promptForOpinion() >>> del viewer :Parameters: - `distanceVar`: a `DistanceVariable` object. - `levelSetValue`: the value of the contour to be displayed - `title`: displayed at the top of the `Viewer` window - `animate`: whether to show only the initial condition and the - `limits`: a dictionary with possible keys `xmin`, `xmax`, `ymin`, `ymax`, `zmin`, `zmax`, `datamin`, `datamax`. A 1D `Viewer` will only use `xmin` and `xmax`, a 2D viewer will also use `ymin` and `ymax`, and so on. All viewers will use `datamin` and `datamax`. Any limit set to a (default) value of `None` will autoscale. moving top boundary or to show all contours (Default) """ kwlimits.update(limits) AbstractViewer.__init__(self, vars=[], title=title, **kwlimits) import mayavi self._viewer = mayavi.mayavi() self.distanceVar = distanceVar if surfactantVar is None: self.surfactantVar = numerix.zeros(len(self.distanceVar), 'd') else: self.surfactantVar = surfactantVar self.smooth = smooth self.zoomFactor = zoomFactor self.animate = animate if animate: self._initialCondition = None if distanceVar.mesh.dim != 2: raise MeshDimensionError('The MayaviIsoViewer only works for 2D meshes.')
def viewi(arr, smooth=0, lut='br', scale=[1.0, 1.0, 1.0]): """Allows one to view a 2D Numeric array as an image. This works best for very large arrays (like 1024x1024 arrays). The implementation of this function is a bit of a hack and many of MayaVi's features cannot be used. For instance you cannot change the lookup table color and expect the color of the image to change. Note that the view will be set to the way we normally think of matrices with with 0, 0 at the top left of the screen. Input Arguments: arr -- Array to be viewed. smooth -- If true, perform interpolation on the image. If false do not perform interpolation. (default=0) lut -- Specifies the lookuptable to map the data with. This should be on of ['br', 'rb', 'bw', 'wb'] 'br' refers to blue-to-red, 'rb' to red-to-blue, 'bw' to black-to-white and 'wb' to white-black. (default='br') scale -- Scale the x, y and z axis as per passed values. Defaults to [1.0, 1.0, 1.0]. """ valid_lut = {'br': 1, 'rb':2, 'bw':3, 'wb':4} assert len(arr.shape) == 2, "Only 2D arrays can be viewed!" assert lut in valid_lut.keys(), \ "lut must be one of %s!"%(valid_lut.keys()) ny, nx = arr.shape dx, dy, junk = Numeric.array(scale)*1.0 xa = Numeric.arange(0, nx*scale[0] - 0.1*dx, dx, 'f') ya = Numeric.arange(0, ny*scale[1] - 0.1*dy, dy, 'f') arr_flat = Numeric.ravel(arr) min_val = min(arr_flat) max_val = max(arr_flat) sp = _create_structured_points_direct(xa, ya) v = mayavi.mayavi() v.open_vtk_data(sp) mm = v.get_current_dvm().get_current_module_mgr() luth = mm.get_scalar_lut_handler() luth.lut_var.set(valid_lut[lut]) luth.change_lut() l = luth.get_lut() l.SetRange(min_val, max_val) za = array2vtk(arr_flat) a = l.MapScalars(za, 0, 0) sp.GetPointData().SetScalars(a) sp.SetScalarTypeToUnsignedChar() sp.SetNumberOfScalarComponents(4) luth.legend_on.set(1) luth.legend_on_off() luth.set_data_range([min_val, max_val]) luth.range_on_var.set(1) luth.set_range_on() ia = vtk.vtkImageActor() if smooth: ia.InterpolateOn() else: ia.InterpolateOff() ia.SetInput(sp) v.renwin.add_actors(ia) a = v.load_module('Axes', 0) a.axes.SetCornerOffset(0.0) a.axes.YAxisVisibilityOff() a.axes.UseRangesOn() a.axes.SetRanges(0, nx, 0, ny, min_val, max_val) o = v.load_module('Outline', 0) v.renwin.update_view(0, 0, -1, 0, -1, 0) t = v.renwin.tkwidget t.UpdateRenderer(0,0) t.Pan(0,-25) v.Render() return v
#!/usr/bin/env python import mayavi bighead = '../data/bighead.vtk' mv = mayavi.mayavi() mv.open_vtk(bighead) for mod in ['Outline','Axes','PolyData']: mv.load_module(mod,0)
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hf:z:rs:", [ "help", "flfile", "vizfile=", "", "recycle", "gif", "avi", "fps", "png" ]) except getopt.GetoptError: # print help information and exit: print "ERROR: Bad arguments!" print usage() sys.exit(2) # Collect options. recycle = 0 flfile = None mvfile = None movie = "gif" fps = 5 maximize = False for o, a in opts: if o in ("-h", "--help"): print usage() sys.exit() if o in ("-z", "--vizfile"): mvfile = a if o in ("-r", "--recycle"): recycle = 1 if o in ("-f", "--flfile"): flfile = a if o == "--avi": movie = "avi" if o == "--png": movie = "non" if o in ("-s", "--fps"): try: fps = float(a) assert (fps > 0.0) except: print "ERROR: Bad arguments!" print usage() sys.exit(2) # Check for fluidity file if not flfile: print "ERROR: No fluidity file given." print usage() sys.exit() # Check for MayaVi visualisation file if not mvfile: # Guess mvfile = flfile + ".mv" if not os.path.isfile(mvfile): print "ERROR: No MayaVi visualisation file found." print usage() sys.exit() try: start = string.atoi(args[0]) except: print "ERROR: Bad starting id %s" % args[0] print usage() sys.exit() try: finish = string.atoi(args[1]) except: print "ERROR: Bad last id %s" % args[1] print usage() sys.exit() # Movie file that we'll be writting to moviefile = flfile + "." + movie # instantiate a MayaVi v = mayavi.mayavi() # load the visualisation v.load_visualization(mvfile) # grab the DataVizManager list dvms = v.get_dvm_names() # list frames to be animated frames = "" for id in range(start, finish + 1): # Get frame name frame = './' + flfile + '%04d.png' % id if (movie == "avi"): frames = frames + "," + frame else: frames = frames + " " + frame # Are we recycling frames if recycle: if os.path.isfile(frame): continue # Make a vtk file datafile = get_file(flfile, id) # go through all the DVM's for i in dvms: # grab a handle to the DVM dvm = v.mayavi.data_viz_mgr[i] # follow the pipeline, and load in the new data file ds = dvm.get_data_source() rdr = ds.get_reader() rdr.SetFileName(datafile) ds.reread_file() v.Render() # write this image to the disk v.renwin.save_png(frame) # Bail out if no movie desired if (movie == "non"): return 0 # Now generate the avi file pid = os.getpid() tmpfile_name = os.environ['PWD'] + "/.tmpmvfile%d" % pid tmpfile = open(tmpfile_name, 'w') tmpfile.write("#!/bin/sh\n") if (movie == "avi"): tmpfile.write("mencoder mf://" + flfile + "*.png -mf fps=" + str(fps) + ":type=png -ovc copy -o " + flfile + ".avi\n") else: tmpfile.write("convert -delay " + str(100.0 / fps) + " -loop 0 " + frames + " " + flfile + ".gif\n") tmpfile.write("rm -f %s\n" % tmpfile_name) tmpfile.close() os.chmod(tmpfile_name, 0700) # Generate animation if os.fork() == 0: os.execl(tmpfile_name, "") else: os.wait() return 0