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 ... | 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 = view... | 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 ... | 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 .... | 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 ( "... | 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 ) ) * ... | 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 . interact... | 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 - ... | 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 : i... | 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 : ... | 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 ... | 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 ( ... | 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 . SetPosi... | 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... | 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 ( ) : s... | 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 = (... | 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 ( )... | 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... | 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 , ... | 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 = maxl... | 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... | 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 . Co... | 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 ) cleanP... | 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_l... | 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 ( )... | 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 ) ... | 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 = ... | 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... | 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 . co... | 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 . Set... | 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 . GetOut... | 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 ... | 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 ( ... | 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 . ascontiguo... | 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 ( ) ... | 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 ( ) ar... | 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 ... | 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 ) : ... | 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 ( ) e... | 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... | 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 ... | 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 . SetNumberOfI... | 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 . SetNumberOf... | 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 . v... | 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 .... | 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 . S... | 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 ) , pointId... | 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 . ... | 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 . I... | 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 . ThresholdByLo... | 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 = [ ] NumberOfVerti... | 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... | 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 .... | 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.