idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
21,500 | def backspace ( self ) : if self . _cx + self . _cw >= 0 : self . erase ( ) self . _cx -= self . _cw self . flush ( ) | Moves the cursor one place to the left erasing the character at the current position . Cannot move beyond column zero nor onto the previous line . |
21,501 | def erase ( self ) : bounds = ( self . _cx , self . _cy , self . _cx + self . _cw , self . _cy + self . _ch ) self . _canvas . rectangle ( bounds , fill = self . _bgcolor ) | Erase the contents of the cursor s current position without moving the cursor s position . |
21,502 | def reset ( self ) : self . _fgcolor = self . default_fgcolor self . _bgcolor = self . default_bgcolor | Resets the foreground and background color value back to the original when initialised . |
21,503 | def reverse_colors ( self ) : self . _bgcolor , self . _fgcolor = self . _fgcolor , self . _bgcolor | Flips the foreground and background colors . |
21,504 | def savepoint ( self ) : if self . _last_image : self . _savepoints . append ( self . _last_image ) self . _last_image = None | Copies the last displayed image . |
21,505 | def restore ( self , drop = 0 ) : assert ( drop >= 0 ) while drop > 0 : self . _savepoints . pop ( ) drop -= 1 img = self . _savepoints . pop ( ) self . display ( img ) | Restores the last savepoint . If drop is supplied and greater than zero then that many savepoints are dropped and the next savepoint is restored . |
21,506 | def text ( self , value ) : self . _text_buffer = observable ( mutable_string ( value ) , observer = self . _flush ) | Updates the seven - segment display with the given value . If there is not enough space to show the full text an OverflowException is raised . |
21,507 | def add_task ( self , func , * args , ** kargs ) : self . tasks . put ( ( func , args , kargs ) ) | Add a task to the queue . |
21,508 | def capabilities ( self , width , height , rotate , mode = "1" ) : assert mode in ( "1" , "RGB" , "RGBA" ) assert rotate in ( 0 , 1 , 2 , 3 ) self . _w = width self . _h = height self . width = width if rotate % 2 == 0 else height self . height = height if rotate % 2 == 0 else width self . size = ( self . width , self . height ) self . bounding_box = ( 0 , 0 , self . width - 1 , self . height - 1 ) self . rotate = rotate self . mode = mode self . persist = False | Assigns attributes such as width height size and bounding_box correctly oriented from the supplied parameters . |
21,509 | def show_message ( device , msg , y_offset = 0 , fill = None , font = None , scroll_delay = 0.03 ) : fps = 0 if scroll_delay == 0 else 1.0 / scroll_delay regulator = framerate_regulator ( fps ) font = font or DEFAULT_FONT with canvas ( device ) as draw : w , h = textsize ( msg , font ) x = device . width virtual = viewport ( device , width = w + x + x , height = device . height ) with canvas ( virtual ) as draw : text ( draw , ( x , y_offset ) , msg , font = font , fill = fill ) i = 0 while i <= w + x : with regulator : virtual . set_position ( ( i , 0 ) ) i += 1 | Scrolls a message right - to - left across the devices display . |
21,510 | def parse_str ( text ) : prog = re . compile ( r'^\033\[(\d+(;\d+)*)m' , re . UNICODE ) while text != "" : result = prog . match ( text ) if result : for code in result . group ( 1 ) . split ( ";" ) : directive = valid_attributes . get ( int ( code ) , None ) if directive : yield directive n = len ( result . group ( 0 ) ) text = text [ n : ] else : yield [ "putch" , text [ 0 ] ] text = text [ 1 : ] | Given a string of characters for each normal ASCII character yields a directive consisting of a putch instruction followed by the character itself . |
21,511 | def find_directives ( text , klass ) : directives = [ ] for directive in parse_str ( text ) : method = klass . __getattribute__ ( directive [ 0 ] ) args = directive [ 1 : ] directives . append ( ( method , args ) ) return directives | Find directives on class klass in string text . |
21,512 | def get_display_types ( ) : display_types = OrderedDict ( ) for namespace in get_supported_libraries ( ) : display_types [ namespace ] = get_choices ( 'luma.{0}.device' . format ( namespace ) ) return display_types | Get ordered dict containing available display types from available luma sub - projects . |
21,513 | def load_config ( path ) : args = [ ] with open ( path , 'r' ) as fp : for line in fp . readlines ( ) : if line . strip ( ) and not line . startswith ( "#" ) : args . append ( line . replace ( "\n" , "" ) ) return args | Load device configuration from file path and return list with parsed lines . |
21,514 | def create_device ( args , display_types = None ) : device = None if display_types is None : display_types = get_display_types ( ) if args . display in display_types . get ( 'oled' ) : import luma . oled . device Device = getattr ( luma . oled . device , args . display ) Serial = getattr ( make_serial ( args ) , args . interface ) device = Device ( Serial ( ) , ** vars ( args ) ) elif args . display in display_types . get ( 'lcd' ) : import luma . lcd . device import luma . lcd . aux Device = getattr ( luma . lcd . device , args . display ) spi = make_serial ( args ) . spi ( ) device = Device ( spi , ** vars ( args ) ) luma . lcd . aux . backlight ( gpio = spi . _gpio , gpio_LIGHT = args . gpio_backlight , active_low = args . backlight_active == "low" ) . enable ( True ) elif args . display in display_types . get ( 'led_matrix' ) : import luma . led_matrix . device from luma . core . interface . serial import noop Device = getattr ( luma . led_matrix . device , args . display ) spi = make_serial ( args , gpio = noop ( ) ) . spi ( ) device = Device ( serial_interface = spi , ** vars ( args ) ) elif args . display in display_types . get ( 'emulator' ) : import luma . emulator . device Device = getattr ( luma . emulator . device , args . display ) device = Device ( ** vars ( args ) ) return device | Create and return device . |
21,515 | def check_output ( * popenargs , ** kwargs ) : r if 'stdout' in kwargs : raise ValueError ( 'stdout argument not allowed, it will be overridden.' ) process = Popen ( stdout = PIPE , * popenargs , ** kwargs ) output , unused_err = process . communicate ( ) retcode = process . poll ( ) if retcode : cmd = kwargs . get ( "args" ) if cmd is None : cmd = popenargs [ 0 ] raise CalledProcessError ( retcode , cmd , output = output ) return output | r Run command with arguments and return its output as a byte string . |
21,516 | def simulate ( self ) : for i in range ( self . iterations ) : for a in self . particles : if a . fixed : continue ftot = vector ( 0 , 0 , 0 ) for b in self . particles : if a . negligible and b . negligible or a == b : continue ab = a . pos - b . pos ftot += ( ( K_COULOMB * a . charge * b . charge ) / mag2 ( ab ) ) * versor ( ab ) a . vel += ftot / a . mass * self . dt a . pos += a . vel * self . dt a . vtk_actor . pos ( a . pos ) if vp : vp . show ( zoom = 1.2 ) vp . camera . Azimuth ( 0.1 ) | Runs the particle simulation . Simulates one time step dt of the particle motion . Calculates the force between each pair of particles and updates particles motion accordingly |
21,517 | def addCutterTool ( actor ) : if isinstance ( actor , vtk . vtkVolume ) : return _addVolumeCutterTool ( actor ) elif isinstance ( actor , vtk . vtkImageData ) : from vtkplotter import Volume return _addVolumeCutterTool ( Volume ( actor ) ) vp = settings . plotter_instance if not vp . renderer : save_int = vp . interactive vp . show ( interactive = 0 ) vp . interactive = save_int vp . clickedActor = actor if hasattr ( actor , "polydata" ) : apd = actor . polydata ( ) else : apd = actor . GetMapper ( ) . GetInput ( ) planes = vtk . vtkPlanes ( ) planes . SetBounds ( apd . GetBounds ( ) ) clipper = vtk . vtkClipPolyData ( ) clipper . GenerateClipScalarsOff ( ) clipper . SetInputData ( apd ) clipper . SetClipFunction ( planes ) clipper . InsideOutOn ( ) clipper . GenerateClippedOutputOn ( ) act0Mapper = vtk . vtkPolyDataMapper ( ) act0Mapper . SetInputConnection ( clipper . GetOutputPort ( ) ) act0 = Actor ( ) act0 . SetMapper ( act0Mapper ) act0 . GetProperty ( ) . SetColor ( actor . GetProperty ( ) . GetColor ( ) ) act0 . GetProperty ( ) . SetOpacity ( 1 ) act1Mapper = vtk . vtkPolyDataMapper ( ) act1Mapper . SetInputConnection ( clipper . GetClippedOutputPort ( ) ) act1 = vtk . vtkActor ( ) act1 . SetMapper ( act1Mapper ) act1 . GetProperty ( ) . SetOpacity ( 0.02 ) act1 . GetProperty ( ) . SetRepresentationToWireframe ( ) act1 . VisibilityOn ( ) vp . renderer . AddActor ( act0 ) vp . renderer . AddActor ( act1 ) vp . renderer . RemoveActor ( actor ) def SelectPolygons ( vobj , event ) : vobj . GetPlanes ( planes ) boxWidget = vtk . vtkBoxWidget ( ) boxWidget . OutlineCursorWiresOn ( ) boxWidget . GetSelectedOutlineProperty ( ) . SetColor ( 1 , 0 , 1 ) boxWidget . GetOutlineProperty ( ) . SetColor ( 0.1 , 0.1 , 0.1 ) boxWidget . GetOutlineProperty ( ) . SetOpacity ( 0.8 ) boxWidget . SetPlaceFactor ( 1.05 ) boxWidget . SetInteractor ( vp . interactor ) boxWidget . SetInputData ( apd ) boxWidget . PlaceWidget ( ) boxWidget . AddObserver ( "InteractionEvent" , SelectPolygons ) boxWidget . On ( ) vp . cutterWidget = boxWidget vp . clickedActor = act0 ia = vp . actors . index ( actor ) vp . actors [ ia ] = act0 colors . printc ( "Mesh Cutter Tool:" , c = "m" , invert = 1 ) colors . printc ( " Move gray handles to cut away parts of the mesh" , c = "m" ) colors . printc ( " Press X to save file to: clipped.vtk" , c = "m" ) vp . interactor . Start ( ) boxWidget . Off ( ) vp . widgets . append ( boxWidget ) vp . interactor . Start ( ) return act0 | Create handles to cut away parts of a mesh . |
21,518 | def isSequence ( arg ) : if hasattr ( arg , "strip" ) : return False if hasattr ( arg , "__getslice__" ) : return True if hasattr ( arg , "__iter__" ) : return True return False | Check if input is iterable . |
21,519 | def flatten ( list_to_flatten ) : def genflatten ( lst ) : for elem in lst : if isinstance ( elem , ( list , tuple ) ) : for x in flatten ( elem ) : yield x else : yield elem return list ( genflatten ( list_to_flatten ) ) | Flatten out a list . |
21,520 | def humansort ( l ) : import re def alphanum_key ( s ) : def tryint ( s ) : if s . isdigit ( ) : return int ( s ) return s return [ tryint ( c ) for c in re . split ( "([0-9]+)" , s ) ] l . sort ( key = alphanum_key ) return None | Sort in place a given list the way humans expect . |
21,521 | def lin_interp ( x , rangeX , rangeY ) : s = ( x - rangeX [ 0 ] ) / mag ( rangeX [ 1 ] - rangeX [ 0 ] ) y = rangeY [ 0 ] * ( 1 - s ) + rangeY [ 1 ] * s return y | Interpolate linearly variable x in rangeX onto rangeY . |
21,522 | def versor ( v ) : if isinstance ( v [ 0 ] , np . ndarray ) : return np . divide ( v , mag ( v ) [ : , None ] ) else : return v / mag ( v ) | Return the unit vector . Input can be a list of vectors . |
21,523 | def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z ) | Get the magnitude of a vector . |
21,524 | def precision ( x , p ) : import math x = float ( x ) if x == 0.0 : return "0." + "0" * ( p - 1 ) out = [ ] if x < 0 : out . append ( "-" ) x = - x e = int ( math . log10 ( x ) ) tens = math . pow ( 10 , e - p + 1 ) n = math . floor ( x / tens ) if n < math . pow ( 10 , p - 1 ) : e = e - 1 tens = math . pow ( 10 , e - p + 1 ) n = math . floor ( x / tens ) if abs ( ( n + 1.0 ) * tens - x ) <= abs ( n * tens - x ) : n = n + 1 if n >= math . pow ( 10 , p ) : n = n / 10.0 e = e + 1 m = "%.*g" % ( p , n ) if e < - 2 or e >= p : out . append ( m [ 0 ] ) if p > 1 : out . append ( "." ) out . extend ( m [ 1 : p ] ) out . append ( "e" ) if e > 0 : out . append ( "+" ) out . append ( str ( e ) ) elif e == ( p - 1 ) : out . append ( m ) elif e >= 0 : out . append ( m [ : e + 1 ] ) if e + 1 < len ( m ) : out . append ( "." ) out . extend ( m [ e + 1 : ] ) else : out . append ( "0." ) out . extend ( [ "0" ] * - ( e + 1 ) ) out . append ( m ) return "" . join ( out ) | Returns a string representation of x formatted with precision p . |
21,525 | def spher2cart ( rho , theta , phi ) : st = np . sin ( theta ) sp = np . sin ( phi ) ct = np . cos ( theta ) cp = np . cos ( phi ) rhost = rho * st x = rhost * cp y = rhost * sp z = rho * ct return np . array ( [ x , y , z ] ) | Spherical to Cartesian coordinate conversion . |
21,526 | def cart2spher ( x , y , z ) : hxy = np . hypot ( x , y ) r = np . hypot ( hxy , z ) theta = np . arctan2 ( z , hxy ) phi = np . arctan2 ( y , x ) return r , theta , phi | Cartesian to Spherical coordinate conversion . |
21,527 | def cart2pol ( x , y ) : theta = np . arctan2 ( y , x ) rho = np . hypot ( x , y ) return theta , rho | Cartesian to Polar coordinates conversion . |
21,528 | def pol2cart ( theta , rho ) : x = rho * np . cos ( theta ) y = rho * np . sin ( theta ) return x , y | Polar to Cartesian coordinates conversion . |
21,529 | def isIdentity ( M , tol = 1e-06 ) : for i in [ 0 , 1 , 2 , 3 ] : for j in [ 0 , 1 , 2 , 3 ] : e = M . GetElement ( i , j ) if i == j : if np . abs ( e - 1 ) > tol : return False elif np . abs ( e ) > tol : return False return True | Check if vtkMatrix4x4 is Identity . |
21,530 | def grep ( filename , tag , firstOccurrence = False ) : import re try : afile = open ( filename , "r" ) except : print ( "Error in utils.grep(): cannot open file" , filename ) exit ( ) content = None for line in afile : if re . search ( tag , line ) : content = line . split ( ) if firstOccurrence : break if content : if len ( content ) == 2 : content = content [ 1 ] else : content = content [ 1 : ] afile . close ( ) return content | Greps the line that starts with a specific tag string from inside a file . |
21,531 | def makeBands ( inputlist , numberOfBands ) : if numberOfBands < 2 : return inputlist vmin = np . min ( inputlist ) vmax = np . max ( inputlist ) bb = np . linspace ( vmin , vmax , numberOfBands , endpoint = 0 ) dr = bb [ 1 ] - bb [ 0 ] bb += dr / 2 tol = dr / 2 * 1.001 newlist = [ ] for s in inputlist : for b in bb : if abs ( s - b ) < tol : newlist . append ( b ) break return np . array ( newlist ) | Group values of a list into bands of equal value . |
21,532 | def clear ( actor = ( ) ) : if not settings . plotter_instance : return settings . plotter_instance . clear ( actor ) return settings . plotter_instance | Clear specific actor or list of actors from the current rendering window . |
21,533 | def getVolumes ( self , obj = None , renderer = None ) : if renderer is None : renderer = self . renderer elif isinstance ( renderer , int ) : renderer = self . renderers . index ( renderer ) else : return [ ] if obj is None or isinstance ( obj , int ) : if obj is None : acs = renderer . GetVolumes ( ) elif obj >= len ( self . renderers ) : colors . printc ( "~timesError in getVolumes: non existing renderer" , obj , c = 1 ) return [ ] else : acs = self . renderers [ obj ] . GetVolumes ( ) vols = [ ] acs . InitTraversal ( ) for i in range ( acs . GetNumberOfItems ( ) ) : a = acs . GetNextItem ( ) if a . GetPickable ( ) : r = self . renderers . index ( renderer ) if a == self . axes_exist [ r ] : continue vols . append ( a ) return vols | Return the list of the rendered Volumes . |
21,534 | def getActors ( self , obj = None , renderer = None ) : if renderer is None : renderer = self . renderer elif isinstance ( renderer , int ) : renderer = self . renderers . index ( renderer ) else : return [ ] if obj is None or isinstance ( obj , int ) : if obj is None : acs = renderer . GetActors ( ) elif obj >= len ( self . renderers ) : colors . printc ( "~timesError in getActors: non existing renderer" , obj , c = 1 ) return [ ] else : acs = self . renderers [ obj ] . GetActors ( ) actors = [ ] acs . InitTraversal ( ) for i in range ( acs . GetNumberOfItems ( ) ) : a = acs . GetNextItem ( ) if a . GetPickable ( ) : r = self . renderers . index ( renderer ) if a == self . axes_exist [ r ] : continue actors . append ( a ) return actors elif isinstance ( obj , vtk . vtkAssembly ) : cl = vtk . vtkPropCollection ( ) obj . GetActors ( cl ) actors = [ ] cl . InitTraversal ( ) for i in range ( obj . GetNumberOfPaths ( ) ) : act = vtk . vtkActor . SafeDownCast ( cl . GetNextProp ( ) ) if act . GetPickable ( ) : actors . append ( act ) return actors elif isinstance ( obj , str ) : actors = [ ] for a in self . actors : if hasattr ( a , "_legend" ) and obj in a . _legend : actors . append ( a ) return actors elif isinstance ( obj , vtk . vtkActor ) : return [ obj ] if self . verbose : colors . printc ( "~lightning Warning in getActors: unexpected input type" , obj , c = 1 ) return [ ] | Return an actors list . |
21,535 | def add ( self , actors ) : if utils . isSequence ( actors ) : for a in actors : if a not in self . actors : self . actors . append ( a ) return None else : self . actors . append ( actors ) return actors | Append input object to the internal list of actors to be shown . |
21,536 | def light ( self , pos = ( 1 , 1 , 1 ) , fp = ( 0 , 0 , 0 ) , deg = 25 , diffuse = "y" , ambient = "r" , specular = "b" , showsource = False , ) : if isinstance ( fp , vtk . vtkActor ) : fp = fp . GetPosition ( ) light = vtk . vtkLight ( ) light . SetLightTypeToSceneLight ( ) light . SetPosition ( pos ) light . SetPositional ( 1 ) light . SetConeAngle ( deg ) light . SetFocalPoint ( fp ) light . SetDiffuseColor ( colors . getColor ( diffuse ) ) light . SetAmbientColor ( colors . getColor ( ambient ) ) light . SetSpecularColor ( colors . getColor ( specular ) ) save_int = self . interactive self . show ( interactive = 0 ) self . interactive = save_int if showsource : lightActor = vtk . vtkLightActor ( ) lightActor . SetLight ( light ) self . renderer . AddViewProp ( lightActor ) self . renderer . AddLight ( light ) return light | Generate a source of light placed at pos directed to focal point fp . |
21,537 | def removeActor ( self , a ) : if not self . initializedPlotter : save_int = self . interactive self . show ( interactive = 0 ) self . interactive = save_int return if self . renderer : self . renderer . RemoveActor ( a ) if hasattr ( a , 'renderedAt' ) : ir = self . renderers . index ( self . renderer ) a . renderedAt . discard ( ir ) if a in self . actors : i = self . actors . index ( a ) del self . actors [ i ] | Remove vtkActor or actor index from current renderer . |
21,538 | def clear ( self , actors = ( ) ) : if not utils . isSequence ( actors ) : actors = [ actors ] if len ( actors ) : for a in actors : self . removeActor ( a ) else : for a in settings . collectable_actors : self . removeActor ( a ) settings . collectable_actors = [ ] self . actors = [ ] for a in self . getActors ( ) : self . renderer . RemoveActor ( a ) for a in self . getVolumes ( ) : self . renderer . RemoveVolume ( a ) for s in self . sliders : s . EnabledOff ( ) for b in self . buttons : self . renderer . RemoveActor ( b ) for w in self . widgets : w . EnabledOff ( ) for c in self . scalarbars : self . renderer . RemoveActor ( c ) | Delete specified list of actors by default delete all . |
21,539 | def morph ( clm1 , clm2 , t , lmax ) : clm = ( 1 - t ) * clm1 + t * clm2 grid_reco = clm . expand ( lmax = lmax ) agrid_reco = grid_reco . to_array ( ) pts = [ ] for i , longs in enumerate ( agrid_reco ) : ilat = grid_reco . lats ( ) [ i ] for j , value in enumerate ( longs ) : ilong = grid_reco . lons ( ) [ j ] th = ( 90 - ilat ) / 57.3 ph = ilong / 57.3 r = value + rbias p = np . array ( [ sin ( th ) * cos ( ph ) , sin ( th ) * sin ( ph ) , cos ( th ) ] ) * r pts . append ( p ) return pts | Interpolate linearly the two sets of sph harm . coeeficients . |
21,540 | def mergeActors ( actors , tol = 0 ) : polylns = vtk . vtkAppendPolyData ( ) for a in actors : polylns . AddInputData ( a . polydata ( ) ) polylns . Update ( ) pd = polylns . GetOutput ( ) return Actor ( pd ) | Build a new actor formed by the fusion of the polydatas of input objects . Similar to Assembly but in this case the input objects become a single mesh . |
21,541 | def isosurface ( image , smoothing = 0 , threshold = None , connectivity = False ) : if smoothing : smImg = vtk . vtkImageGaussianSmooth ( ) smImg . SetDimensionality ( 3 ) smImg . SetInputData ( image ) smImg . SetStandardDeviations ( smoothing , smoothing , smoothing ) smImg . Update ( ) image = smImg . GetOutput ( ) scrange = image . GetScalarRange ( ) if scrange [ 1 ] > 1e10 : print ( "Warning, high scalar range detected:" , scrange ) cf = vtk . vtkContourFilter ( ) cf . SetInputData ( image ) cf . UseScalarTreeOn ( ) cf . ComputeScalarsOn ( ) if utils . isSequence ( threshold ) : cf . SetNumberOfContours ( len ( threshold ) ) for i , t in enumerate ( threshold ) : cf . SetValue ( i , t ) cf . Update ( ) else : if not threshold : threshold = ( 2 * scrange [ 0 ] + scrange [ 1 ] ) / 3.0 cf . SetValue ( 0 , threshold ) cf . Update ( ) clp = vtk . vtkCleanPolyData ( ) clp . SetInputConnection ( cf . GetOutputPort ( ) ) clp . Update ( ) poly = clp . GetOutput ( ) if connectivity : conn = vtk . vtkPolyDataConnectivityFilter ( ) conn . SetExtractionModeToLargestRegion ( ) conn . SetInputData ( poly ) conn . Update ( ) poly = conn . GetOutput ( ) a = Actor ( poly , c = None ) . phong ( ) a . mapper . SetScalarRange ( scrange [ 0 ] , scrange [ 1 ] ) return a | Return a vtkActor isosurface extracted from a vtkImageData object . |
21,542 | def show ( self , at = None , shape = ( 1 , 1 ) , N = None , pos = ( 0 , 0 ) , size = "auto" , screensize = "auto" , title = "" , bg = "blackboard" , bg2 = None , axes = 4 , infinity = False , verbose = True , interactive = None , offscreen = False , resetcam = True , zoom = None , viewup = "" , azimuth = 0 , elevation = 0 , roll = 0 , interactorStyle = 0 , newPlotter = False , depthpeeling = False , q = False , ) : from vtkplotter . plotter import show return show ( self , at = at , shape = shape , N = N , pos = pos , size = size , screensize = screensize , title = title , bg = bg , bg2 = bg2 , axes = axes , infinity = infinity , verbose = verbose , interactive = interactive , offscreen = offscreen , resetcam = resetcam , zoom = zoom , viewup = viewup , azimuth = azimuth , elevation = elevation , roll = roll , interactorStyle = interactorStyle , newPlotter = newPlotter , depthpeeling = depthpeeling , q = q , ) | Create on the fly an instance of class Plotter or use the last existing one to show one single object . |
21,543 | def addPos ( self , dp_x = None , dy = None , dz = None ) : p = np . array ( self . GetPosition ( ) ) if dz is None : self . SetPosition ( p + dp_x ) else : self . SetPosition ( p + [ dp_x , dy , dz ] ) if self . trail : self . updateTrail ( ) return self | Add vector to current actor position . |
21,544 | def rotate ( self , angle , axis = ( 1 , 0 , 0 ) , axis_point = ( 0 , 0 , 0 ) , rad = False ) : if rad : anglerad = angle else : anglerad = angle / 57.29578 axis = utils . versor ( axis ) a = np . cos ( anglerad / 2 ) b , c , d = - axis * np . sin ( anglerad / 2 ) aa , bb , cc , dd = a * a , b * b , c * c , d * d bc , ad , ac , ab , bd , cd = b * c , a * d , a * c , a * b , b * d , c * d R = np . array ( [ [ aa + bb - cc - dd , 2 * ( bc + ad ) , 2 * ( bd - ac ) ] , [ 2 * ( bc - ad ) , aa + cc - bb - dd , 2 * ( cd + ab ) ] , [ 2 * ( bd + ac ) , 2 * ( cd - ab ) , aa + dd - bb - cc ] , ] ) rv = np . dot ( R , self . GetPosition ( ) - np . array ( axis_point ) ) + axis_point if rad : angle *= 57.29578 self . RotateWXYZ ( angle , axis [ 0 ] , axis [ 1 ] , axis [ 2 ] ) self . SetPosition ( rv ) if self . trail : self . updateTrail ( ) return self | Rotate Actor around an arbitrary axis passing through axis_point . |
21,545 | def rotateX ( self , angle , axis_point = ( 0 , 0 , 0 ) , rad = False ) : if rad : angle *= 57.29578 self . RotateX ( angle ) if self . trail : self . updateTrail ( ) return self | Rotate around x - axis . If angle is in radians set rad = True . |
21,546 | def rotateY ( self , angle , axis_point = ( 0 , 0 , 0 ) , rad = False ) : if rad : angle *= 57.29578 self . RotateY ( angle ) if self . trail : self . updateTrail ( ) return self | Rotate around y - axis . If angle is in radians set rad = True . |
21,547 | def rotateZ ( self , angle , axis_point = ( 0 , 0 , 0 ) , rad = False ) : if rad : angle *= 57.29578 self . RotateZ ( angle ) if self . trail : self . updateTrail ( ) return self | Rotate around z - axis . If angle is in radians set rad = True . |
21,548 | def addTrail ( self , offset = None , maxlength = None , n = 25 , c = None , alpha = None , lw = 1 ) : if maxlength is None : maxlength = self . diagonalSize ( ) * 20 if maxlength == 0 : maxlength = 1 if self . trail is None : pos = self . GetPosition ( ) self . trailPoints = [ None ] * n self . trailSegmentSize = maxlength / n self . trailOffset = offset ppoints = vtk . vtkPoints ( ) poly = vtk . vtkPolyData ( ) ppoints . SetData ( numpy_to_vtk ( [ pos ] * n ) ) poly . SetPoints ( ppoints ) lines = vtk . vtkCellArray ( ) lines . InsertNextCell ( n ) for i in range ( n ) : lines . InsertCellPoint ( i ) poly . SetPoints ( ppoints ) poly . SetLines ( lines ) mapper = vtk . vtkPolyDataMapper ( ) if c is None : if hasattr ( self , "GetProperty" ) : col = self . GetProperty ( ) . GetColor ( ) else : col = ( 0.1 , 0.1 , 0.1 ) else : col = colors . getColor ( c ) if alpha is None : alpha = 1 if hasattr ( self , "GetProperty" ) : alpha = self . GetProperty ( ) . GetOpacity ( ) mapper . SetInputData ( poly ) tline = Actor ( ) tline . SetMapper ( mapper ) tline . GetProperty ( ) . SetColor ( col ) tline . GetProperty ( ) . SetOpacity ( alpha ) tline . GetProperty ( ) . SetLineWidth ( lw ) self . trail = tline return self | Add a trailing line to actor . |
21,549 | def updateMesh ( self , polydata ) : self . poly = polydata self . mapper . SetInputData ( polydata ) self . mapper . Modified ( ) return self | Overwrite the polygonal mesh of the actor with a new one . |
21,550 | def addScalarBar ( self , c = None , title = "" , horizontal = False , vmin = None , vmax = None ) : self . scalarbar = [ c , title , horizontal , vmin , vmax ] return self | Add a 2D scalar bar to actor . |
21,551 | def addScalarBar3D ( self , pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , sx = 0.1 , sy = 2 , nlabels = 9 , ncols = 256 , cmap = None , c = "k" , alpha = 1 , ) : self . scalarbar = [ pos , normal , sx , sy , nlabels , ncols , cmap , c , alpha ] return self | Draw a 3D scalar bar to actor . |
21,552 | def texture ( self , name , scale = 1 , falsecolors = False , mapTo = 1 ) : import os if mapTo == 1 : tmapper = vtk . vtkTextureMapToCylinder ( ) elif mapTo == 2 : tmapper = vtk . vtkTextureMapToSphere ( ) elif mapTo == 3 : tmapper = vtk . vtkTextureMapToPlane ( ) tmapper . SetInputData ( self . polydata ( False ) ) if mapTo == 1 : tmapper . PreventSeamOn ( ) xform = vtk . vtkTransformTextureCoords ( ) xform . SetInputConnection ( tmapper . GetOutputPort ( ) ) xform . SetScale ( scale , scale , scale ) if mapTo == 1 : xform . FlipSOn ( ) xform . Update ( ) mapper = vtk . vtkDataSetMapper ( ) mapper . SetInputConnection ( xform . GetOutputPort ( ) ) mapper . ScalarVisibilityOff ( ) fn = settings . textures_path + name + ".jpg" if os . path . exists ( name ) : fn = name elif not os . path . exists ( fn ) : colors . printc ( "~sad Texture" , name , "not found in" , settings . textures_path , c = "r" ) colors . printc ( "~target Available textures:" , c = "m" , end = " " ) for ff in os . listdir ( settings . textures_path ) : colors . printc ( ff . split ( "." ) [ 0 ] , end = " " , c = "m" ) print ( ) return jpgReader = vtk . vtkJPEGReader ( ) jpgReader . SetFileName ( fn ) atext = vtk . vtkTexture ( ) atext . RepeatOn ( ) atext . EdgeClampOff ( ) atext . InterpolateOn ( ) if falsecolors : atext . MapColorScalarsThroughLookupTableOn ( ) atext . SetInputConnection ( jpgReader . GetOutputPort ( ) ) self . GetProperty ( ) . SetColor ( 1 , 1 , 1 ) self . SetMapper ( mapper ) self . SetTexture ( atext ) self . Modified ( ) return self | Assign a texture to actor from image file or predefined texture name . |
21,553 | def computeNormals ( self ) : poly = self . polydata ( False ) pnormals = poly . GetPointData ( ) . GetNormals ( ) cnormals = poly . GetCellData ( ) . GetNormals ( ) if pnormals and cnormals : return self pdnorm = vtk . vtkPolyDataNormals ( ) pdnorm . SetInputData ( poly ) pdnorm . ComputePointNormalsOn ( ) pdnorm . ComputeCellNormalsOn ( ) pdnorm . FlipNormalsOff ( ) pdnorm . ConsistencyOn ( ) pdnorm . Update ( ) return self . updateMesh ( pdnorm . GetOutput ( ) ) | Compute cell and vertex normals for the actor s mesh . |
21,554 | def clean ( self , tol = None ) : poly = self . polydata ( False ) cleanPolyData = vtk . vtkCleanPolyData ( ) cleanPolyData . PointMergingOn ( ) cleanPolyData . ConvertLinesToPointsOn ( ) cleanPolyData . ConvertPolysToLinesOn ( ) cleanPolyData . SetInputData ( poly ) if tol : cleanPolyData . SetTolerance ( tol ) cleanPolyData . Update ( ) return self . updateMesh ( cleanPolyData . GetOutput ( ) ) | Clean actor s polydata . Can also be used to decimate a mesh if tol is large . If tol = None only removes coincident points . |
21,555 | def averageSize ( self ) : cm = self . centerOfMass ( ) coords = self . coordinates ( copy = False ) if not len ( coords ) : return 0 s , c = 0.0 , 0.0 n = len ( coords ) step = int ( n / 10000.0 ) + 1 for i in np . arange ( 0 , n , step ) : s += utils . mag ( coords [ i ] - cm ) c += 1 return s / c | Calculate the average size of a mesh . This is the mean of the vertex distances from the center of mass . |
21,556 | def diagonalSize ( self ) : b = self . polydata ( ) . GetBounds ( ) return np . sqrt ( ( b [ 1 ] - b [ 0 ] ) ** 2 + ( b [ 3 ] - b [ 2 ] ) ** 2 + ( b [ 5 ] - b [ 4 ] ) ** 2 ) | Get the length of the diagonal of actor bounding box . |
21,557 | def maxBoundSize ( self ) : b = self . polydata ( True ) . GetBounds ( ) return max ( abs ( b [ 1 ] - b [ 0 ] ) , abs ( b [ 3 ] - b [ 2 ] ) , abs ( b [ 5 ] - b [ 4 ] ) ) | Get the maximum dimension in x y or z of the actor bounding box . |
21,558 | def centerOfMass ( self ) : cmf = vtk . vtkCenterOfMass ( ) cmf . SetInputData ( self . polydata ( True ) ) cmf . Update ( ) c = cmf . GetCenter ( ) return np . array ( c ) | Get the center of mass of actor . |
21,559 | def closestPoint ( self , pt , N = 1 , radius = None , returnIds = False ) : poly = self . polydata ( True ) if N > 1 or radius : plocexists = self . point_locator if not plocexists or ( plocexists and self . point_locator is None ) : point_locator = vtk . vtkPointLocator ( ) point_locator . SetDataSet ( poly ) point_locator . BuildLocator ( ) self . point_locator = point_locator vtklist = vtk . vtkIdList ( ) if N > 1 : self . point_locator . FindClosestNPoints ( N , pt , vtklist ) else : self . point_locator . FindPointsWithinRadius ( radius , pt , vtklist ) if returnIds : return [ int ( vtklist . GetId ( k ) ) for k in range ( vtklist . GetNumberOfIds ( ) ) ] else : trgp = [ ] for i in range ( vtklist . GetNumberOfIds ( ) ) : trgp_ = [ 0 , 0 , 0 ] vi = vtklist . GetId ( i ) poly . GetPoints ( ) . GetPoint ( vi , trgp_ ) trgp . append ( trgp_ ) return np . array ( trgp ) clocexists = self . cell_locator if not clocexists or ( clocexists and self . cell_locator is None ) : cell_locator = vtk . vtkCellLocator ( ) cell_locator . SetDataSet ( poly ) cell_locator . BuildLocator ( ) self . cell_locator = cell_locator trgp = [ 0 , 0 , 0 ] cid = vtk . mutable ( 0 ) dist2 = vtk . mutable ( 0 ) subid = vtk . mutable ( 0 ) self . cell_locator . FindClosestPoint ( pt , trgp , cid , subid , dist2 ) if returnIds : return int ( cid ) else : return np . array ( trgp ) | Find the closest point on a mesh given from the input point pt . |
21,560 | def transformMesh ( self , transformation ) : if isinstance ( transformation , vtk . vtkMatrix4x4 ) : tr = vtk . vtkTransform ( ) tr . SetMatrix ( transformation ) transformation = tr tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetTransform ( transformation ) tf . SetInputData ( self . polydata ( ) ) tf . Update ( ) self . PokeMatrix ( vtk . vtkMatrix4x4 ( ) ) return self . updateMesh ( tf . GetOutput ( ) ) | Apply this transformation to the polygonal mesh not to the actor s transformation which is reset . |
21,561 | def normalize ( self ) : cm = self . centerOfMass ( ) coords = self . coordinates ( ) if not len ( coords ) : return pts = coords - cm xyz2 = np . sum ( pts * pts , axis = 0 ) scale = 1 / np . sqrt ( np . sum ( xyz2 ) / len ( pts ) ) t = vtk . vtkTransform ( ) t . Scale ( scale , scale , scale ) t . Translate ( - cm ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( self . poly ) tf . SetTransform ( t ) tf . Update ( ) return self . updateMesh ( tf . GetOutput ( ) ) | Shift actor s center of mass at origin and scale its average size to unit . |
21,562 | def mirror ( self , axis = "x" ) : poly = self . polydata ( transformed = True ) polyCopy = vtk . vtkPolyData ( ) polyCopy . DeepCopy ( poly ) sx , sy , sz = 1 , 1 , 1 dx , dy , dz = self . GetPosition ( ) if axis . lower ( ) == "x" : sx = - 1 elif axis . lower ( ) == "y" : sy = - 1 elif axis . lower ( ) == "z" : sz = - 1 elif axis . lower ( ) == "n" : pass else : colors . printc ( "~times Error in mirror(): mirror must be set to x, y, z or n." , c = 1 ) raise RuntimeError ( ) if axis != "n" : for j in range ( polyCopy . GetNumberOfPoints ( ) ) : p = [ 0 , 0 , 0 ] polyCopy . GetPoint ( j , p ) polyCopy . GetPoints ( ) . SetPoint ( j , p [ 0 ] * sx - dx * ( sx - 1 ) , p [ 1 ] * sy - dy * ( sy - 1 ) , p [ 2 ] * sz - dz * ( sz - 1 ) , ) rs = vtk . vtkReverseSense ( ) rs . SetInputData ( polyCopy ) rs . ReverseNormalsOn ( ) rs . Update ( ) polyCopy = rs . GetOutput ( ) pdnorm = vtk . vtkPolyDataNormals ( ) pdnorm . SetInputData ( polyCopy ) pdnorm . ComputePointNormalsOn ( ) pdnorm . ComputeCellNormalsOn ( ) pdnorm . FlipNormalsOff ( ) pdnorm . ConsistencyOn ( ) pdnorm . Update ( ) return self . updateMesh ( pdnorm . GetOutput ( ) ) | Mirror the actor polydata along one of the cartesian axes . |
21,563 | def shrink ( self , fraction = 0.85 ) : poly = self . polydata ( True ) shrink = vtk . vtkShrinkPolyData ( ) shrink . SetInputData ( poly ) shrink . SetShrinkFactor ( fraction ) shrink . Update ( ) return self . updateMesh ( shrink . GetOutput ( ) ) | Shrink the triangle polydata in the representation of the input mesh . |
21,564 | def stretch ( self , q1 , q2 ) : if self . base is None : colors . printc ( '~times Error in stretch(): Please define vectors \ actor.base and actor.top at creation. Exit.' , c = 'r' ) exit ( 0 ) p1 , p2 = self . base , self . top q1 , q2 , z = np . array ( q1 ) , np . array ( q2 ) , np . array ( [ 0 , 0 , 1 ] ) plength = np . linalg . norm ( p2 - p1 ) qlength = np . linalg . norm ( q2 - q1 ) T = vtk . vtkTransform ( ) T . PostMultiply ( ) T . Translate ( - p1 ) cosa = np . dot ( p2 - p1 , z ) / plength n = np . cross ( p2 - p1 , z ) T . RotateWXYZ ( np . arccos ( cosa ) * 57.3 , n ) T . Scale ( 1 , 1 , qlength / plength ) cosa = np . dot ( q2 - q1 , z ) / qlength n = np . cross ( q2 - q1 , z ) T . RotateWXYZ ( - np . arccos ( cosa ) * 57.3 , n ) T . Translate ( q1 ) self . SetUserMatrix ( T . GetMatrix ( ) ) if self . trail : self . updateTrail ( ) return self | Stretch actor between points q1 and q2 . Mesh is not affected . |
21,565 | def cutWithPlane ( self , origin = ( 0 , 0 , 0 ) , normal = ( 1 , 0 , 0 ) , showcut = False ) : if normal is "x" : normal = ( 1 , 0 , 0 ) elif normal is "y" : normal = ( 0 , 1 , 0 ) elif normal is "z" : normal = ( 0 , 0 , 1 ) plane = vtk . vtkPlane ( ) plane . SetOrigin ( origin ) plane . SetNormal ( normal ) self . computeNormals ( ) poly = self . polydata ( ) clipper = vtk . vtkClipPolyData ( ) clipper . SetInputData ( poly ) clipper . SetClipFunction ( plane ) if showcut : clipper . GenerateClippedOutputOn ( ) else : clipper . GenerateClippedOutputOff ( ) clipper . GenerateClipScalarsOff ( ) clipper . SetValue ( 0 ) clipper . Update ( ) self . updateMesh ( clipper . GetOutput ( ) ) if showcut : c = self . GetProperty ( ) . GetColor ( ) cpoly = clipper . GetClippedOutput ( ) restActor = Actor ( cpoly , c = c , alpha = 0.05 , wire = 1 ) restActor . SetUserMatrix ( self . GetMatrix ( ) ) asse = Assembly ( [ self , restActor ] ) self = asse return asse else : return self | Takes a vtkActor and cuts it with the plane defined by a point and a normal . |
21,566 | def cutWithMesh ( self , mesh , invert = False ) : if isinstance ( mesh , vtk . vtkPolyData ) : polymesh = mesh if isinstance ( mesh , Actor ) : polymesh = mesh . polydata ( ) else : polymesh = mesh . GetMapper ( ) . GetInput ( ) poly = self . polydata ( ) signedDistances = vtk . vtkFloatArray ( ) signedDistances . SetNumberOfComponents ( 1 ) signedDistances . SetName ( "SignedDistances" ) ippd = vtk . vtkImplicitPolyDataDistance ( ) ippd . SetInput ( polymesh ) for pointId in range ( poly . GetNumberOfPoints ( ) ) : p = poly . GetPoint ( pointId ) signedDistance = ippd . EvaluateFunction ( p ) signedDistances . InsertNextValue ( signedDistance ) poly . GetPointData ( ) . SetScalars ( signedDistances ) clipper = vtk . vtkClipPolyData ( ) clipper . SetInputData ( poly ) if invert : clipper . InsideOutOff ( ) else : clipper . InsideOutOn ( ) clipper . SetValue ( 0.0 ) clipper . Update ( ) return self . updateMesh ( clipper . GetOutput ( ) ) | Cut an Actor mesh with another vtkPolyData or Actor . |
21,567 | def cap ( self , returnCap = False ) : poly = self . polydata ( True ) fe = vtk . vtkFeatureEdges ( ) fe . SetInputData ( poly ) fe . BoundaryEdgesOn ( ) fe . FeatureEdgesOff ( ) fe . NonManifoldEdgesOff ( ) fe . ManifoldEdgesOff ( ) fe . Update ( ) stripper = vtk . vtkStripper ( ) stripper . SetInputData ( fe . GetOutput ( ) ) stripper . Update ( ) boundaryPoly = vtk . vtkPolyData ( ) boundaryPoly . SetPoints ( stripper . GetOutput ( ) . GetPoints ( ) ) boundaryPoly . SetPolys ( stripper . GetOutput ( ) . GetLines ( ) ) tf = vtk . vtkTriangleFilter ( ) tf . SetInputData ( boundaryPoly ) tf . Update ( ) if returnCap : return Actor ( tf . GetOutput ( ) ) else : polyapp = vtk . vtkAppendPolyData ( ) polyapp . AddInputData ( poly ) polyapp . AddInputData ( tf . GetOutput ( ) ) polyapp . Update ( ) return self . updateMesh ( polyapp . GetOutput ( ) ) . clean ( ) | Generate a cap on a clipped actor or caps sharp edges . |
21,568 | def threshold ( self , scalars , vmin = None , vmax = None , useCells = False ) : if utils . isSequence ( scalars ) : self . addPointScalars ( scalars , "threshold" ) scalars = "threshold" elif self . scalars ( scalars ) is None : colors . printc ( "~times No scalars found with name" , scalars , c = 1 ) exit ( ) thres = vtk . vtkThreshold ( ) thres . SetInputData ( self . poly ) if useCells : asso = vtk . vtkDataObject . FIELD_ASSOCIATION_CELLS else : asso = vtk . vtkDataObject . FIELD_ASSOCIATION_POINTS thres . SetInputArrayToProcess ( 0 , 0 , 0 , asso , scalars ) if vmin is None and vmax is not None : thres . ThresholdByLower ( vmax ) elif vmax is None and vmin is not None : thres . ThresholdByUpper ( vmin ) else : thres . ThresholdBetween ( vmin , vmax ) thres . Update ( ) gf = vtk . vtkGeometryFilter ( ) gf . SetInputData ( thres . GetOutput ( ) ) gf . Update ( ) return self . updateMesh ( gf . GetOutput ( ) ) | Extracts cells where scalar value satisfies threshold criterion . |
21,569 | def triangle ( self , verts = True , lines = True ) : tf = vtk . vtkTriangleFilter ( ) tf . SetPassLines ( lines ) tf . SetPassVerts ( verts ) tf . SetInputData ( self . poly ) tf . Update ( ) return self . updateMesh ( tf . GetOutput ( ) ) | Converts actor polygons and strips to triangles . |
21,570 | def pointColors ( self , scalars , cmap = "jet" , alpha = 1 , bands = None , vmin = None , vmax = None ) : poly = self . polydata ( False ) if isinstance ( scalars , str ) : scalars = vtk_to_numpy ( poly . GetPointData ( ) . GetArray ( scalars ) ) n = len ( scalars ) useAlpha = False if n != poly . GetNumberOfPoints ( ) : colors . printc ( '~times pointColors Error: nr. of scalars != nr. of points' , n , poly . GetNumberOfPoints ( ) , c = 1 ) if utils . isSequence ( alpha ) : useAlpha = True if len ( alpha ) > n : colors . printc ( '~times pointColors Error: nr. of scalars < nr. of alpha values' , n , len ( alpha ) , c = 1 ) exit ( ) if bands : scalars = utils . makeBands ( scalars , bands ) if vmin is None : vmin = np . min ( scalars ) if vmax is None : vmax = np . max ( scalars ) lut = vtk . vtkLookupTable ( ) if utils . isSequence ( cmap ) : sname = "pointColors_custom" lut . SetNumberOfTableValues ( len ( cmap ) ) lut . Build ( ) for i , c in enumerate ( cmap ) : col = colors . getColor ( c ) r , g , b = col if useAlpha : lut . SetTableValue ( i , r , g , b , alpha [ i ] ) else : lut . SetTableValue ( i , r , g , b , alpha ) elif isinstance ( cmap , vtk . vtkLookupTable ) : sname = "pointColors_lut" lut = cmap else : if isinstance ( cmap , str ) : sname = "pointColors_" + cmap else : sname = "pointColors" lut . SetNumberOfTableValues ( 512 ) lut . Build ( ) for i in range ( 512 ) : r , g , b = colors . colorMap ( i , cmap , 0 , 512 ) if useAlpha : idx = int ( i / 512 * len ( alpha ) ) lut . SetTableValue ( i , r , g , b , alpha [ idx ] ) else : lut . SetTableValue ( i , r , g , b , alpha ) arr = numpy_to_vtk ( np . ascontiguousarray ( scalars ) , deep = True ) arr . SetName ( sname ) self . mapper . SetScalarRange ( vmin , vmax ) self . mapper . SetLookupTable ( lut ) self . mapper . ScalarVisibilityOn ( ) poly . GetPointData ( ) . SetScalars ( arr ) poly . GetPointData ( ) . SetActiveScalars ( sname ) return self | Set individual point colors by providing a list of scalar values and a color map . scalars can be a string name of the vtkArray . |
21,571 | def addPointScalars ( self , scalars , name ) : poly = self . polydata ( False ) if len ( scalars ) != poly . GetNumberOfPoints ( ) : colors . printc ( '~times pointScalars Error: Number of scalars != nr. of points' , len ( scalars ) , poly . GetNumberOfPoints ( ) , c = 1 ) exit ( ) arr = numpy_to_vtk ( np . ascontiguousarray ( scalars ) , deep = True ) arr . SetName ( name ) poly . GetPointData ( ) . AddArray ( arr ) poly . GetPointData ( ) . SetActiveScalars ( name ) self . mapper . SetScalarRange ( np . min ( scalars ) , np . max ( scalars ) ) self . mapper . ScalarVisibilityOn ( ) return self | Add point scalars to the actor s polydata assigning it a name . |
21,572 | def addCellScalars ( self , scalars , name ) : poly = self . polydata ( False ) if isinstance ( scalars , str ) : scalars = vtk_to_numpy ( poly . GetPointData ( ) . GetArray ( scalars ) ) if len ( scalars ) != poly . GetNumberOfCells ( ) : colors . printc ( "~times Number of scalars != nr. of cells" , c = 1 ) exit ( ) arr = numpy_to_vtk ( np . ascontiguousarray ( scalars ) , deep = True ) arr . SetName ( name ) poly . GetCellData ( ) . AddArray ( arr ) poly . GetCellData ( ) . SetActiveScalars ( name ) self . mapper . SetScalarRange ( np . min ( scalars ) , np . max ( scalars ) ) self . mapper . ScalarVisibilityOn ( ) return self | Add cell scalars to the actor s polydata assigning it a name . |
21,573 | def addPointVectors ( self , vectors , name ) : poly = self . polydata ( False ) if len ( vectors ) != poly . GetNumberOfPoints ( ) : colors . printc ( '~times addPointVectors Error: Number of vectors != nr. of points' , len ( vectors ) , poly . GetNumberOfPoints ( ) , c = 1 ) exit ( ) arr = vtk . vtkDoubleArray ( ) arr . SetNumberOfComponents ( 3 ) arr . SetName ( name ) for v in vectors : arr . InsertNextTuple ( v ) poly . GetPointData ( ) . AddArray ( arr ) poly . GetPointData ( ) . SetActiveVectors ( name ) return self | Add a point vector field to the actor s polydata assigning it a name . |
21,574 | def addIDs ( self , asfield = False ) : ids = vtk . vtkIdFilter ( ) ids . SetInputData ( self . poly ) ids . PointIdsOn ( ) ids . CellIdsOn ( ) if asfield : ids . FieldDataOn ( ) else : ids . FieldDataOff ( ) ids . Update ( ) return self . updateMesh ( ids . GetOutput ( ) ) | Generate point and cell ids . |
21,575 | def addCurvatureScalars ( self , method = 0 , lut = None ) : curve = vtk . vtkCurvatures ( ) curve . SetInputData ( self . poly ) curve . SetCurvatureType ( method ) curve . Update ( ) self . poly = curve . GetOutput ( ) scls = self . poly . GetPointData ( ) . GetScalars ( ) . GetRange ( ) print ( "curvature(): scalar range is" , scls ) self . mapper . SetInputData ( self . poly ) if lut : self . mapper . SetLookupTable ( lut ) self . mapper . SetUseLookupTableScalarRange ( 1 ) self . mapper . Update ( ) self . Modified ( ) self . mapper . ScalarVisibilityOn ( ) return self | Build an Actor that contains the color coded surface curvature calculated in three different ways . |
21,576 | def scalars ( self , name_or_idx = None , datatype = "point" ) : poly = self . polydata ( False ) if name_or_idx is None : ncd = poly . GetCellData ( ) . GetNumberOfArrays ( ) npd = poly . GetPointData ( ) . GetNumberOfArrays ( ) nfd = poly . GetFieldData ( ) . GetNumberOfArrays ( ) arrs = [ ] for i in range ( npd ) : print ( i , "PointData" , poly . GetPointData ( ) . GetArrayName ( i ) ) arrs . append ( [ "PointData" , poly . GetPointData ( ) . GetArrayName ( i ) ] ) for i in range ( ncd ) : print ( i , "CellData" , poly . GetCellData ( ) . GetArrayName ( i ) ) arrs . append ( [ "CellData" , poly . GetCellData ( ) . GetArrayName ( i ) ] ) for i in range ( nfd ) : print ( i , "FieldData" , poly . GetFieldData ( ) . GetArrayName ( i ) ) arrs . append ( [ "FieldData" , poly . GetFieldData ( ) . GetArrayName ( i ) ] ) return arrs else : if "point" in datatype . lower ( ) : data = poly . GetPointData ( ) elif "cell" in datatype . lower ( ) : data = poly . GetCellData ( ) elif "field" in datatype . lower ( ) : data = poly . GetFieldData ( ) else : colors . printc ( "~times Error in scalars(): unknown datatype" , datatype , c = 1 ) exit ( ) if isinstance ( name_or_idx , int ) : name = data . GetArrayName ( name_or_idx ) if name is None : return None data . SetActiveScalars ( name ) return vtk_to_numpy ( data . GetArray ( name ) ) elif isinstance ( name_or_idx , str ) : arr = data . GetArray ( name_or_idx ) if arr is None : return None data . SetActiveScalars ( name_or_idx ) return vtk_to_numpy ( arr ) return None | Retrieve point or cell scalars using array name or index number . If no name is given return the list of names of existing arrays . |
21,577 | def subdivide ( self , N = 1 , method = 0 ) : triangles = vtk . vtkTriangleFilter ( ) triangles . SetInputData ( self . polydata ( ) ) triangles . Update ( ) originalMesh = triangles . GetOutput ( ) if method == 0 : sdf = vtk . vtkLoopSubdivisionFilter ( ) elif method == 1 : sdf = vtk . vtkLinearSubdivisionFilter ( ) elif method == 2 : sdf = vtk . vtkAdaptiveSubdivisionFilter ( ) elif method == 3 : sdf = vtk . vtkButterflySubdivisionFilter ( ) else : colors . printc ( "~times Error in subdivide: unknown method." , c = "r" ) exit ( ) if method != 2 : sdf . SetNumberOfSubdivisions ( N ) sdf . SetInputData ( originalMesh ) sdf . Update ( ) return self . updateMesh ( sdf . GetOutput ( ) ) | Increase the number of vertices of a surface mesh . |
21,578 | def decimate ( self , fraction = 0.5 , N = None , boundaries = False , verbose = True ) : poly = self . polydata ( True ) if N : Np = poly . GetNumberOfPoints ( ) fraction = float ( N ) / Np if fraction >= 1 : return self decimate = vtk . vtkDecimatePro ( ) decimate . SetInputData ( poly ) decimate . SetTargetReduction ( 1 - fraction ) decimate . PreserveTopologyOff ( ) if boundaries : decimate . BoundaryVertexDeletionOff ( ) else : decimate . BoundaryVertexDeletionOn ( ) decimate . Update ( ) if verbose : print ( "Nr. of pts, input:" , poly . GetNumberOfPoints ( ) , end = "" ) print ( " output:" , decimate . GetOutput ( ) . GetNumberOfPoints ( ) ) return self . updateMesh ( decimate . GetOutput ( ) ) | Downsample the number of vertices in a mesh . |
21,579 | def addGaussNoise ( self , sigma ) : sz = self . diagonalSize ( ) pts = self . coordinates ( ) n = len ( pts ) ns = np . random . randn ( n , 3 ) * sigma * sz / 100 vpts = vtk . vtkPoints ( ) vpts . SetNumberOfPoints ( n ) vpts . SetData ( numpy_to_vtk ( pts + ns , deep = True ) ) self . poly . SetPoints ( vpts ) self . poly . GetPoints ( ) . Modified ( ) return self | Add gaussian noise . |
21,580 | def smoothLaplacian ( self , niter = 15 , relaxfact = 0.1 , edgeAngle = 15 , featureAngle = 60 ) : poly = self . poly cl = vtk . vtkCleanPolyData ( ) cl . SetInputData ( poly ) cl . Update ( ) smoothFilter = vtk . vtkSmoothPolyDataFilter ( ) smoothFilter . SetInputData ( cl . GetOutput ( ) ) smoothFilter . SetNumberOfIterations ( niter ) smoothFilter . SetRelaxationFactor ( relaxfact ) smoothFilter . SetEdgeAngle ( edgeAngle ) smoothFilter . SetFeatureAngle ( featureAngle ) smoothFilter . BoundarySmoothingOn ( ) smoothFilter . FeatureEdgeSmoothingOn ( ) smoothFilter . GenerateErrorScalarsOn ( ) smoothFilter . Update ( ) return self . updateMesh ( smoothFilter . GetOutput ( ) ) | Adjust mesh point positions using Laplacian smoothing . |
21,581 | def smoothWSinc ( self , niter = 15 , passBand = 0.1 , edgeAngle = 15 , featureAngle = 60 ) : poly = self . poly cl = vtk . vtkCleanPolyData ( ) cl . SetInputData ( poly ) cl . Update ( ) smoothFilter = vtk . vtkWindowedSincPolyDataFilter ( ) smoothFilter . SetInputData ( cl . GetOutput ( ) ) smoothFilter . SetNumberOfIterations ( niter ) smoothFilter . SetEdgeAngle ( edgeAngle ) smoothFilter . SetFeatureAngle ( featureAngle ) smoothFilter . SetPassBand ( passBand ) smoothFilter . NormalizeCoordinatesOn ( ) smoothFilter . NonManifoldSmoothingOn ( ) smoothFilter . FeatureEdgeSmoothingOn ( ) smoothFilter . BoundarySmoothingOn ( ) smoothFilter . Update ( ) return self . updateMesh ( smoothFilter . GetOutput ( ) ) | Adjust mesh point positions using the Windowed Sinc function interpolation kernel . |
21,582 | def fillHoles ( self , size = None ) : fh = vtk . vtkFillHolesFilter ( ) if not size : mb = self . maxBoundSize ( ) size = mb / 10 fh . SetHoleSize ( size ) fh . SetInputData ( self . poly ) fh . Update ( ) return self . updateMesh ( fh . GetOutput ( ) ) | Identifies and fills holes in input mesh . Holes are identified by locating boundary edges linking them together into loops and then triangulating the resulting loops . |
21,583 | def write ( self , filename = "mesh.vtk" , binary = True ) : import vtkplotter . vtkio as vtkio return vtkio . write ( self , filename , binary ) | Write actor s polydata in its current transformation to file . |
21,584 | def normalAt ( self , i ) : normals = self . polydata ( True ) . GetPointData ( ) . GetNormals ( ) return np . array ( normals . GetTuple ( i ) ) | Return the normal vector at vertex point i . |
21,585 | def normals ( self , cells = False ) : if cells : vtknormals = self . polydata ( True ) . GetCellData ( ) . GetNormals ( ) else : vtknormals = self . polydata ( True ) . GetPointData ( ) . GetNormals ( ) return vtk_to_numpy ( vtknormals ) | Retrieve vertex normals as a numpy array . |
21,586 | def polydata ( self , transformed = True ) : if not transformed : if not self . poly : self . poly = self . GetMapper ( ) . GetInput ( ) return self . poly M = self . GetMatrix ( ) if utils . isIdentity ( M ) : if not self . poly : self . poly = self . GetMapper ( ) . GetInput ( ) return self . poly transform = vtk . vtkTransform ( ) transform . SetMatrix ( M ) tp = vtk . vtkTransformPolyDataFilter ( ) tp . SetTransform ( transform ) tp . SetInputData ( self . poly ) tp . Update ( ) return tp . GetOutput ( ) | Returns the vtkPolyData of an Actor . |
21,587 | def move ( self , u_function ) : if self . mesh : self . u = u_function delta = [ u_function ( p ) for p in self . mesh . coordinates ( ) ] movedpts = self . mesh . coordinates ( ) + delta self . polydata ( False ) . GetPoints ( ) . SetData ( numpy_to_vtk ( movedpts ) ) self . poly . GetPoints ( ) . Modified ( ) self . u_values = delta else : colors . printc ( "Warning: calling move() but actor.mesh is" , self . mesh , c = 3 ) return self | Move a mesh by using an external function which prescribes the displacement at any point in space . Useful for manipulating dolfin meshes . |
21,588 | def setTransform ( self , T ) : if isinstance ( T , vtk . vtkMatrix4x4 ) : self . SetUserMatrix ( T ) else : try : self . SetUserTransform ( T ) except TypeError : colors . printc ( '~time Error in setTransform(): consider transformPolydata() instead.' , c = 1 ) return self | Transform actor position and orientation wrt to its polygonal mesh which remains unmodified . |
21,589 | def isInside ( self , point , tol = 0.0001 ) : poly = self . polydata ( True ) points = vtk . vtkPoints ( ) points . InsertNextPoint ( point ) pointsPolydata = vtk . vtkPolyData ( ) pointsPolydata . SetPoints ( points ) sep = vtk . vtkSelectEnclosedPoints ( ) sep . SetTolerance ( tol ) sep . CheckSurfaceOff ( ) sep . SetInputData ( pointsPolydata ) sep . SetSurfaceData ( poly ) sep . Update ( ) return sep . IsInside ( 0 ) | Return True if point is inside a polydata closed surface . |
21,590 | def cellCenters ( self ) : vcen = vtk . vtkCellCenters ( ) vcen . SetInputData ( self . polydata ( True ) ) vcen . Update ( ) return vtk_to_numpy ( vcen . GetOutput ( ) . GetPoints ( ) . GetData ( ) ) | Get the list of cell centers of the mesh surface . |
21,591 | def connectedVertices ( self , index , returnIds = False ) : mesh = self . polydata ( ) cellIdList = vtk . vtkIdList ( ) mesh . GetPointCells ( index , cellIdList ) idxs = [ ] for i in range ( cellIdList . GetNumberOfIds ( ) ) : pointIdList = vtk . vtkIdList ( ) mesh . GetCellPoints ( cellIdList . GetId ( i ) , pointIdList ) for j in range ( pointIdList . GetNumberOfIds ( ) ) : idj = pointIdList . GetId ( j ) if idj == index : continue if idj in idxs : continue idxs . append ( idj ) if returnIds : return idxs else : trgp = [ ] for i in idxs : p = [ 0 , 0 , 0 ] mesh . GetPoints ( ) . GetPoint ( i , p ) trgp . append ( p ) return np . array ( trgp ) | Find all vertices connected to an input vertex specified by its index . |
21,592 | def connectedCells ( self , index , returnIds = False ) : dpoly = self . polydata ( ) cellPointIds = vtk . vtkIdList ( ) dpoly . GetPointCells ( index , cellPointIds ) ids = vtk . vtkIdTypeArray ( ) ids . SetNumberOfComponents ( 1 ) rids = [ ] for k in range ( cellPointIds . GetNumberOfIds ( ) ) : cid = cellPointIds . GetId ( k ) ids . InsertNextValue ( cid ) rids . append ( int ( cid ) ) if returnIds : return rids selectionNode = vtk . vtkSelectionNode ( ) selectionNode . SetFieldType ( vtk . vtkSelectionNode . CELL ) selectionNode . SetContentType ( vtk . vtkSelectionNode . INDICES ) selectionNode . SetSelectionList ( ids ) selection = vtk . vtkSelection ( ) selection . AddNode ( selectionNode ) extractSelection = vtk . vtkExtractSelection ( ) extractSelection . SetInputData ( 0 , dpoly ) extractSelection . SetInputData ( 1 , selection ) extractSelection . Update ( ) gf = vtk . vtkGeometryFilter ( ) gf . SetInputData ( extractSelection . GetOutput ( ) ) gf . Update ( ) return Actor ( gf . GetOutput ( ) ) . lw ( 1 ) | Find all cellls connected to an input vertex specified by its index . |
21,593 | def intersectWithLine ( self , p0 , p1 ) : if not self . line_locator : line_locator = vtk . vtkOBBTree ( ) line_locator . SetDataSet ( self . polydata ( True ) ) line_locator . BuildLocator ( ) self . line_locator = line_locator intersectPoints = vtk . vtkPoints ( ) intersection = [ 0 , 0 , 0 ] self . line_locator . IntersectWithLine ( p0 , p1 , intersectPoints , None ) pts = [ ] for i in range ( intersectPoints . GetNumberOfPoints ( ) ) : intersectPoints . GetPoint ( i , intersection ) pts . append ( list ( intersection ) ) return pts | Return the list of points intersecting the actor along the segment defined by two points p0 and p1 . |
21,594 | def getActors ( self ) : cl = vtk . vtkPropCollection ( ) self . GetActors ( cl ) self . actors = [ ] cl . InitTraversal ( ) for i in range ( self . GetNumberOfPaths ( ) ) : act = vtk . vtkActor . SafeDownCast ( cl . GetNextProp ( ) ) if act . GetPickable ( ) : self . actors . append ( act ) return self . actors | Unpack a list of vtkActor objects from a vtkAssembly . |
21,595 | def diagonalSize ( self ) : szs = [ a . diagonalSize ( ) for a in self . actors ] return np . max ( szs ) | Return the maximum diagonal size of the Actors of the Assembly . |
21,596 | def threshold ( self , vmin = None , vmax = None , replaceWith = None ) : th = vtk . vtkImageThreshold ( ) th . SetInputData ( self . image ) if vmin is not None and vmax is not None : th . ThresholdBetween ( vmin , vmax ) elif vmin is not None : th . ThresholdByUpper ( vmin ) elif vmax is not None : th . ThresholdByLower ( vmax ) if replaceWith : th . ReplaceOutOn ( ) th . SetOutValue ( replaceWith ) th . Update ( ) self . image = th . GetOutput ( ) self . mapper . SetInputData ( self . image ) self . mapper . Modified ( ) return self | Binary or continuous volume thresholding . |
21,597 | def loadOFF ( filename , c = "gold" , alpha = 1 , wire = False , bc = None ) : if not os . path . exists ( filename ) : colors . printc ( "~noentry Error in loadOFF: Cannot find" , filename , c = 1 ) return None f = open ( filename , "r" ) lines = f . readlines ( ) f . close ( ) vertices = [ ] faces = [ ] NumberOfVertices = None i = - 1 for text in lines : if len ( text ) == 0 : continue if text == '\n' : continue if "#" in text : continue if "OFF" in text : continue ts = text . split ( ) n = len ( ts ) if not NumberOfVertices and n > 1 : NumberOfVertices , NumberOfFaces = int ( ts [ 0 ] ) , int ( ts [ 1 ] ) continue i += 1 if i < NumberOfVertices and n == 3 : x , y , z = float ( ts [ 0 ] ) , float ( ts [ 1 ] ) , float ( ts [ 2 ] ) vertices . append ( [ x , y , z ] ) ids = [ ] if NumberOfVertices <= i < ( NumberOfVertices + NumberOfFaces + 1 ) and n > 2 : ids += [ int ( x ) for x in ts [ 1 : ] ] faces . append ( ids ) return Actor ( buildPolyData ( vertices , faces ) , c , alpha , wire , bc ) | Read OFF file format . |
21,598 | def loadImageData ( filename , spacing = ( ) ) : if not os . path . isfile ( filename ) : colors . printc ( "~noentry File not found:" , filename , c = 1 ) return None if ".tif" in filename . lower ( ) : reader = vtk . vtkTIFFReader ( ) elif ".slc" in filename . lower ( ) : reader = vtk . vtkSLCReader ( ) if not reader . CanReadFile ( filename ) : colors . printc ( "~prohibited Sorry bad slc file " + filename , c = 1 ) exit ( 1 ) elif ".vti" in filename . lower ( ) : reader = vtk . vtkXMLImageDataReader ( ) elif ".mhd" in filename . lower ( ) : reader = vtk . vtkMetaImageReader ( ) reader . SetFileName ( filename ) reader . Update ( ) image = reader . GetOutput ( ) if len ( spacing ) == 3 : image . SetSpacing ( spacing [ 0 ] , spacing [ 1 ] , spacing [ 2 ] ) return image | Read and return a vtkImageData object from file . |
21,599 | def write ( objct , fileoutput , binary = True ) : obj = objct if isinstance ( obj , Actor ) : obj = objct . polydata ( True ) elif isinstance ( obj , vtk . vtkActor ) : obj = objct . GetMapper ( ) . GetInput ( ) fr = fileoutput . lower ( ) if ".vtk" in fr : w = vtk . vtkPolyDataWriter ( ) elif ".ply" in fr : w = vtk . vtkPLYWriter ( ) elif ".stl" in fr : w = vtk . vtkSTLWriter ( ) elif ".vtp" in fr : w = vtk . vtkXMLPolyDataWriter ( ) elif ".vtm" in fr : g = vtk . vtkMultiBlockDataGroupFilter ( ) for ob in objct : g . AddInputData ( ob ) g . Update ( ) mb = g . GetOutputDataObject ( 0 ) wri = vtk . vtkXMLMultiBlockDataWriter ( ) wri . SetInputData ( mb ) wri . SetFileName ( fileoutput ) wri . Write ( ) return mb elif ".xyz" in fr : w = vtk . vtkSimplePointsWriter ( ) elif ".byu" in fr or fr . endswith ( ".g" ) : w = vtk . vtkBYUWriter ( ) elif ".obj" in fr : w = vtk . vtkOBJExporter ( ) w . SetFilePrefix ( fileoutput . replace ( ".obj" , "" ) ) colors . printc ( "~target Please use write(vp.window)" , c = 3 ) w . SetInputData ( obj ) w . Update ( ) colors . printc ( "~save Saved file: " + fileoutput , c = "g" ) return objct elif ".tif" in fr : w = vtk . vtkTIFFWriter ( ) w . SetFileDimensionality ( len ( obj . GetDimensions ( ) ) ) elif ".vti" in fr : w = vtk . vtkXMLImageDataWriter ( ) elif ".png" in fr : w = vtk . vtkPNGWriter ( ) elif ".jpg" in fr : w = vtk . vtkJPEGWriter ( ) elif ".bmp" in fr : w = vtk . vtkBMPWriter ( ) else : colors . printc ( "~noentry Unknown format" , fileoutput , "file not saved." , c = "r" ) return objct try : if not ".tif" in fr and not ".vti" in fr : if binary and not ".tif" in fr and not ".vti" in fr : w . SetFileTypeToBinary ( ) else : w . SetFileTypeToASCII ( ) w . SetInputData ( obj ) w . SetFileName ( fileoutput ) w . Write ( ) colors . printc ( "~save Saved file: " + fileoutput , c = "g" ) except Exception as e : colors . printc ( "~noentry Error saving: " + fileoutput , "\n" , e , c = "r" ) return objct | Write 3D object to file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.