idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
21,600 | def convertNeutral2Xml ( infile , outfile = None ) : f = open ( infile , "r" ) lines = f . readlines ( ) f . close ( ) ncoords = int ( lines [ 0 ] ) fdolf_coords = [ ] for i in range ( 1 , ncoords + 1 ) : x , y , z = lines [ i ] . split ( ) fdolf_coords . append ( [ float ( x ) , float ( y ) , float ( z ) ] ) ntets = int ( lines [ ncoords + 1 ] ) idolf_tets = [ ] for i in range ( ncoords + 2 , ncoords + ntets + 2 ) : text = lines [ i ] . split ( ) v0 , v1 , v2 , v3 = text [ 1 ] , text [ 2 ] , text [ 3 ] , text [ 4 ] idolf_tets . append ( [ int ( v0 ) - 1 , int ( v1 ) - 1 , int ( v2 ) - 1 , int ( v3 ) - 1 ] ) if outfile : outF = open ( outfile , "w" ) outF . write ( '<?xml version="1.0" encoding="UTF-8"?>\n' ) outF . write ( '<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n' ) outF . write ( ' <mesh celltype="tetrahedron" dim="3">\n' ) outF . write ( ' <vertices size="' + str ( ncoords ) + '">\n' ) for i in range ( ncoords ) : x , y , z = fdolf_coords [ i ] outF . write ( ' <vertex index="' + str ( i ) + '" x="' + str ( x ) + '" y="' + str ( y ) + '" z="' + str ( z ) + '"/>\n' ) outF . write ( ' </vertices>\n' ) outF . write ( ' <cells size="' + str ( ntets ) + '">\n' ) for i in range ( ntets ) : v0 , v1 , v2 , v3 = idolf_tets [ i ] outF . write ( ' <tetrahedron index="' + str ( i ) + '" v0="' + str ( v0 ) + '" v1="' + str ( v1 ) + '" v2="' + str ( v2 ) + '" v3="' + str ( v3 ) + '"/>\n' ) outF . write ( ' </cells>\n' ) outF . write ( " </mesh>\n" ) outF . write ( "</dolfin>\n" ) outF . close ( ) return fdolf_coords , idolf_tets | Convert Neutral file format to Dolfin XML . |
21,601 | def screenshot ( filename = "screenshot.png" ) : if not settings . plotter_instance . window : colors . printc ( '~bomb screenshot(): Rendering window is not present, skip.' , c = 1 ) return w2if = vtk . vtkWindowToImageFilter ( ) w2if . ShouldRerenderOff ( ) w2if . SetInput ( settings . plotter_instance . window ) w2if . ReadFrontBufferOff ( ) w2if . Update ( ) pngwriter = vtk . vtkPNGWriter ( ) pngwriter . SetFileName ( filename ) pngwriter . SetInputConnection ( w2if . GetOutputPort ( ) ) pngwriter . Write ( ) | Save a screenshot of the current rendering window . |
21,602 | def addFrame ( self ) : fr = "/tmp/vpvid/" + str ( len ( self . frames ) ) + ".png" screenshot ( fr ) self . frames . append ( fr ) | Add frame to current video . |
21,603 | def pause ( self , pause = 0 ) : fr = self . frames [ - 1 ] n = int ( self . fps * pause ) for i in range ( n ) : fr2 = "/tmp/vpvid/" + str ( len ( self . frames ) ) + ".png" self . frames . append ( fr2 ) os . system ( "cp -f %s %s" % ( fr , fr2 ) ) | Insert a pause in seconds . |
21,604 | def close ( self ) : if self . duration : _fps = len ( self . frames ) / float ( self . duration ) colors . printc ( "Recalculated video FPS to" , round ( _fps , 3 ) , c = "yellow" ) else : _fps = int ( _fps ) self . name = self . name . split ( '.' ) [ 0 ] + '.mp4' out = os . system ( "ffmpeg -loglevel panic -y -r " + str ( _fps ) + " -i /tmp/vpvid/%01d.png " + self . name ) if out : colors . printc ( "ffmpeg returning error" , c = 1 ) colors . printc ( "~save Video saved as" , self . name , c = "green" ) return | Render the video and write to file . |
21,605 | def update_fields ( u , u_old , v_old , a_old ) : u_vec , u0_vec = u . vector ( ) , u_old . vector ( ) v0_vec , a0_vec = v_old . vector ( ) , a_old . vector ( ) a_vec = update_a ( u_vec , u0_vec , v0_vec , a0_vec , ufl = False ) v_vec = update_v ( a_vec , u0_vec , v0_vec , a0_vec , ufl = False ) v_old . vector ( ) [ : ] , a_old . vector ( ) [ : ] = v_vec , a_vec u_old . vector ( ) [ : ] = u . vector ( ) | Update fields at the end of each time step . |
21,606 | def local_project ( v , V , u = None ) : dv = TrialFunction ( V ) v_ = TestFunction ( V ) a_proj = inner ( dv , v_ ) * dx b_proj = inner ( v , v_ ) * dx solver = LocalSolver ( a_proj , b_proj ) solver . factorize ( ) if u is None : u = Function ( V ) solver . solve_local_rhs ( u ) return u else : solver . solve_local_rhs ( u ) return | Element - wise projection using LocalSolver |
21,607 | def Point ( pos = ( 0 , 0 , 0 ) , r = 12 , c = "red" , alpha = 1 ) : if len ( pos ) == 2 : pos = ( pos [ 0 ] , pos [ 1 ] , 0 ) actor = Points ( [ pos ] , r , c , alpha ) return actor | Create a simple point actor . |
21,608 | def Tube ( points , r = 1 , c = "r" , alpha = 1 , res = 12 ) : ppoints = vtk . vtkPoints ( ) ppoints . SetData ( numpy_to_vtk ( points , deep = True ) ) lines = vtk . vtkCellArray ( ) lines . InsertNextCell ( len ( points ) ) for i in range ( len ( points ) ) : lines . InsertCellPoint ( i ) polyln = vtk . vtkPolyData ( ) polyln . SetPoints ( ppoints ) polyln . SetLines ( lines ) tuf = vtk . vtkTubeFilter ( ) tuf . CappingOn ( ) tuf . SetNumberOfSides ( res ) tuf . SetInputData ( polyln ) if utils . isSequence ( r ) : arr = numpy_to_vtk ( np . ascontiguousarray ( r ) , deep = True ) arr . SetName ( "TubeRadius" ) polyln . GetPointData ( ) . AddArray ( arr ) polyln . GetPointData ( ) . SetActiveScalars ( "TubeRadius" ) tuf . SetVaryRadiusToVaryRadiusByAbsoluteScalar ( ) else : tuf . SetRadius ( r ) usingColScals = False if utils . isSequence ( c ) and len ( c ) != 3 : usingColScals = True cc = vtk . vtkUnsignedCharArray ( ) cc . SetName ( "TubeColors" ) cc . SetNumberOfComponents ( 3 ) cc . SetNumberOfTuples ( len ( c ) ) for i , ic in enumerate ( c ) : r , g , b = colors . getColor ( ic ) cc . InsertTuple3 ( i , int ( 255 * r ) , int ( 255 * g ) , int ( 255 * b ) ) polyln . GetPointData ( ) . AddArray ( cc ) c = None tuf . Update ( ) polytu = tuf . GetOutput ( ) actor = Actor ( polytu , c = c , alpha = alpha , computeNormals = 0 ) actor . phong ( ) if usingColScals : actor . mapper . SetScalarModeToUsePointFieldData ( ) actor . mapper . ScalarVisibilityOn ( ) actor . mapper . SelectColorArray ( "TubeColors" ) actor . mapper . Modified ( ) actor . base = np . array ( points [ 0 ] ) actor . top = np . array ( points [ - 1 ] ) settings . collectable_actors . append ( actor ) return actor | Build a tube along the line defined by a set of points . |
21,609 | def Ribbon ( line1 , line2 , c = "m" , alpha = 1 , res = ( 200 , 5 ) ) : if isinstance ( line1 , Actor ) : line1 = line1 . coordinates ( ) if isinstance ( line2 , Actor ) : line2 = line2 . coordinates ( ) ppoints1 = vtk . vtkPoints ( ) ppoints1 . SetData ( numpy_to_vtk ( line1 , deep = True ) ) lines1 = vtk . vtkCellArray ( ) lines1 . InsertNextCell ( len ( line1 ) ) for i in range ( len ( line1 ) ) : lines1 . InsertCellPoint ( i ) poly1 = vtk . vtkPolyData ( ) poly1 . SetPoints ( ppoints1 ) poly1 . SetLines ( lines1 ) ppoints2 = vtk . vtkPoints ( ) ppoints2 . SetData ( numpy_to_vtk ( line2 , deep = True ) ) lines2 = vtk . vtkCellArray ( ) lines2 . InsertNextCell ( len ( line2 ) ) for i in range ( len ( line2 ) ) : lines2 . InsertCellPoint ( i ) poly2 = vtk . vtkPolyData ( ) poly2 . SetPoints ( ppoints2 ) poly2 . SetLines ( lines2 ) lines1 = vtk . vtkCellArray ( ) lines1 . InsertNextCell ( poly1 . GetNumberOfPoints ( ) ) for i in range ( poly1 . GetNumberOfPoints ( ) ) : lines1 . InsertCellPoint ( i ) polygon1 = vtk . vtkPolyData ( ) polygon1 . SetPoints ( ppoints1 ) polygon1 . SetLines ( lines1 ) lines2 = vtk . vtkCellArray ( ) lines2 . InsertNextCell ( poly2 . GetNumberOfPoints ( ) ) for i in range ( poly2 . GetNumberOfPoints ( ) ) : lines2 . InsertCellPoint ( i ) polygon2 = vtk . vtkPolyData ( ) polygon2 . SetPoints ( ppoints2 ) polygon2 . SetLines ( lines2 ) mergedPolyData = vtk . vtkAppendPolyData ( ) mergedPolyData . AddInputData ( polygon1 ) mergedPolyData . AddInputData ( polygon2 ) mergedPolyData . Update ( ) rsf = vtk . vtkRuledSurfaceFilter ( ) rsf . CloseSurfaceOff ( ) rsf . SetRuledModeToResample ( ) rsf . SetResolution ( res [ 0 ] , res [ 1 ] ) rsf . SetInputData ( mergedPolyData . GetOutput ( ) ) rsf . Update ( ) actor = Actor ( rsf . GetOutput ( ) , c = c , alpha = alpha ) settings . collectable_actors . append ( actor ) return actor | Connect two lines to generate the surface inbetween . |
21,610 | def FlatArrow ( line1 , line2 , c = "m" , alpha = 1 , tipSize = 1 , tipWidth = 1 ) : if isinstance ( line1 , Actor ) : line1 = line1 . coordinates ( ) if isinstance ( line2 , Actor ) : line2 = line2 . coordinates ( ) sm1 , sm2 = np . array ( line1 [ - 1 ] ) , np . array ( line2 [ - 1 ] ) v = ( sm1 - sm2 ) / 3 * tipWidth p1 = sm1 + v p2 = sm2 - v pm1 = ( sm1 + sm2 ) / 2 pm2 = ( np . array ( line1 [ - 2 ] ) + np . array ( line2 [ - 2 ] ) ) / 2 pm12 = pm1 - pm2 tip = pm12 / np . linalg . norm ( pm12 ) * np . linalg . norm ( v ) * 3 * tipSize / tipWidth + pm1 line1 . append ( p1 ) line1 . append ( tip ) line2 . append ( p2 ) line2 . append ( tip ) resm = max ( 100 , len ( line1 ) ) actor = Ribbon ( line1 , line2 , alpha = alpha , c = c , res = ( resm , 1 ) ) . phong ( ) settings . collectable_actors . pop ( ) settings . collectable_actors . append ( actor ) return actor | Build a 2D arrow in 3D space by joining two close lines . |
21,611 | def Polygon ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , nsides = 6 , r = 1 , c = "coral" , bc = "darkgreen" , lw = 1 , alpha = 1 , followcam = False ) : ps = vtk . vtkRegularPolygonSource ( ) ps . SetNumberOfSides ( nsides ) ps . SetRadius ( r ) ps . SetNormal ( - np . array ( normal ) ) ps . Update ( ) tf = vtk . vtkTriangleFilter ( ) tf . SetInputConnection ( ps . GetOutputPort ( ) ) tf . Update ( ) mapper = vtk . vtkPolyDataMapper ( ) mapper . SetInputConnection ( tf . GetOutputPort ( ) ) if followcam : actor = vtk . vtkFollower ( ) if isinstance ( followcam , vtk . vtkCamera ) : actor . SetCamera ( followcam ) else : actor . SetCamera ( settings . plotter_instance . camera ) else : actor = Actor ( ) actor . SetMapper ( mapper ) actor . GetProperty ( ) . SetColor ( colors . getColor ( c ) ) actor . GetProperty ( ) . SetOpacity ( alpha ) actor . GetProperty ( ) . SetLineWidth ( lw ) actor . GetProperty ( ) . SetInterpolationToFlat ( ) if bc : backProp = vtk . vtkProperty ( ) backProp . SetDiffuseColor ( colors . getColor ( bc ) ) backProp . SetOpacity ( alpha ) actor . SetBackfaceProperty ( backProp ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Build a 2D polygon of nsides of radius r oriented as normal . |
21,612 | def Rectangle ( p1 = ( 0 , 0 , 0 ) , p2 = ( 2 , 1 , 0 ) , c = "k" , bc = "dg" , lw = 1 , alpha = 1 , texture = None ) : p1 = np . array ( p1 ) p2 = np . array ( p2 ) pos = ( p1 + p2 ) / 2 length = abs ( p2 [ 0 ] - p1 [ 0 ] ) height = abs ( p2 [ 1 ] - p1 [ 1 ] ) return Plane ( pos , [ 0 , 0 , - 1 ] , length , height , c , bc , alpha , texture ) | Build a rectangle in the xy plane identified by two corner points . |
21,613 | def Disc ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , r1 = 0.5 , r2 = 1 , c = "coral" , bc = "darkgreen" , lw = 1 , alpha = 1 , res = 12 , resphi = None , ) : ps = vtk . vtkDiskSource ( ) ps . SetInnerRadius ( r1 ) ps . SetOuterRadius ( r2 ) ps . SetRadialResolution ( res ) if not resphi : resphi = 6 * res ps . SetCircumferentialResolution ( resphi ) ps . Update ( ) axis = np . array ( normal ) / np . linalg . norm ( normal ) theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransform ( ) t . PostMultiply ( ) t . RotateY ( theta * 57.3 ) t . RotateZ ( phi * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( ps . GetOutput ( ) ) tf . SetTransform ( t ) tf . Update ( ) pd = tf . GetOutput ( ) mapper = vtk . vtkPolyDataMapper ( ) mapper . SetInputData ( pd ) actor = Actor ( ) actor . SetMapper ( mapper ) actor . GetProperty ( ) . SetColor ( colors . getColor ( c ) ) actor . GetProperty ( ) . SetOpacity ( alpha ) actor . GetProperty ( ) . SetLineWidth ( lw ) actor . GetProperty ( ) . SetInterpolationToFlat ( ) if bc : backProp = vtk . vtkProperty ( ) backProp . SetDiffuseColor ( colors . getColor ( bc ) ) backProp . SetOpacity ( alpha ) actor . SetBackfaceProperty ( backProp ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Build a 2D disc of internal radius r1 and outer radius r2 oriented perpendicular to normal . |Disk| |
21,614 | def Sphere ( pos = ( 0 , 0 , 0 ) , r = 1 , c = "r" , alpha = 1 , res = 24 ) : ss = vtk . vtkSphereSource ( ) ss . SetRadius ( r ) ss . SetThetaResolution ( 2 * res ) ss . SetPhiResolution ( res ) ss . Update ( ) pd = ss . GetOutput ( ) actor = Actor ( pd , c , alpha ) actor . GetProperty ( ) . SetInterpolationToPhong ( ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Build a sphere at position pos of radius r . |Sphere| |
21,615 | def Earth ( pos = ( 0 , 0 , 0 ) , r = 1 , lw = 1 ) : import os tss = vtk . vtkTexturedSphereSource ( ) tss . SetRadius ( r ) tss . SetThetaResolution ( 72 ) tss . SetPhiResolution ( 36 ) earthMapper = vtk . vtkPolyDataMapper ( ) earthMapper . SetInputConnection ( tss . GetOutputPort ( ) ) earthActor = Actor ( c = "w" ) earthActor . SetMapper ( earthMapper ) atext = vtk . vtkTexture ( ) pnmReader = vtk . vtkPNMReader ( ) cdir = os . path . dirname ( __file__ ) if cdir == "" : cdir = "." fn = settings . textures_path + "earth.ppm" pnmReader . SetFileName ( fn ) atext . SetInputConnection ( pnmReader . GetOutputPort ( ) ) atext . InterpolateOn ( ) earthActor . SetTexture ( atext ) if not lw : earthActor . SetPosition ( pos ) return earthActor es = vtk . vtkEarthSource ( ) es . SetRadius ( r / 0.995 ) earth2Mapper = vtk . vtkPolyDataMapper ( ) earth2Mapper . SetInputConnection ( es . GetOutputPort ( ) ) earth2Actor = Actor ( ) earth2Actor . SetMapper ( earth2Mapper ) earth2Mapper . ScalarVisibilityOff ( ) earth2Actor . GetProperty ( ) . SetLineWidth ( lw ) ass = Assembly ( [ earthActor , earth2Actor ] ) ass . SetPosition ( pos ) settings . collectable_actors . append ( ass ) return ass | Build a textured actor representing the Earth . |
21,616 | def Grid ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , sx = 1 , sy = 1 , c = "g" , bc = "darkgreen" , lw = 1 , alpha = 1 , resx = 10 , resy = 10 , ) : ps = vtk . vtkPlaneSource ( ) ps . SetResolution ( resx , resy ) ps . Update ( ) poly0 = ps . GetOutput ( ) t0 = vtk . vtkTransform ( ) t0 . Scale ( sx , sy , 1 ) tf0 = vtk . vtkTransformPolyDataFilter ( ) tf0 . SetInputData ( poly0 ) tf0 . SetTransform ( t0 ) tf0 . Update ( ) poly = tf0 . GetOutput ( ) axis = np . array ( normal ) / np . linalg . norm ( normal ) theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransform ( ) t . PostMultiply ( ) t . RotateY ( theta * 57.3 ) t . RotateZ ( phi * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( poly ) tf . SetTransform ( t ) tf . Update ( ) pd = tf . GetOutput ( ) actor = Actor ( pd , c = c , bc = bc , alpha = alpha ) actor . GetProperty ( ) . SetRepresentationToWireframe ( ) actor . GetProperty ( ) . SetLineWidth ( lw ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Return a grid plane . |
21,617 | def Plane ( pos = ( 0 , 0 , 0 ) , normal = ( 0 , 0 , 1 ) , sx = 1 , sy = None , c = "g" , bc = "darkgreen" , alpha = 1 , texture = None ) : if sy is None : sy = sx ps = vtk . vtkPlaneSource ( ) ps . SetResolution ( 1 , 1 ) tri = vtk . vtkTriangleFilter ( ) tri . SetInputConnection ( ps . GetOutputPort ( ) ) tri . Update ( ) poly = tri . GetOutput ( ) axis = np . array ( normal ) / np . linalg . norm ( normal ) theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransform ( ) t . PostMultiply ( ) t . Scale ( sx , sy , 1 ) t . RotateY ( theta * 57.3 ) t . RotateZ ( phi * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( poly ) tf . SetTransform ( t ) tf . Update ( ) pd = tf . GetOutput ( ) actor = Actor ( pd , c = c , bc = bc , alpha = alpha , texture = texture ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Draw a plane of size sx and sy oriented perpendicular to vector normal and so that it passes through point pos . |
21,618 | def Box ( pos = ( 0 , 0 , 0 ) , length = 1 , width = 2 , height = 3 , normal = ( 0 , 0 , 1 ) , c = "g" , alpha = 1 , texture = None ) : src = vtk . vtkCubeSource ( ) src . SetXLength ( length ) src . SetYLength ( width ) src . SetZLength ( height ) src . Update ( ) poly = src . GetOutput ( ) axis = np . array ( normal ) / np . linalg . norm ( normal ) theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransform ( ) t . PostMultiply ( ) t . RotateY ( theta * 57.3 ) t . RotateZ ( phi * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( poly ) tf . SetTransform ( t ) tf . Update ( ) pd = tf . GetOutput ( ) actor = Actor ( pd , c , alpha , texture = texture ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Build a box of dimensions x = length y = width and z = height oriented along vector normal . |
21,619 | def Cube ( pos = ( 0 , 0 , 0 ) , side = 1 , normal = ( 0 , 0 , 1 ) , c = "g" , alpha = 1 , texture = None ) : return Box ( pos , side , side , side , normal , c , alpha , texture ) | Build a cube of size side oriented along vector normal . |
21,620 | def Spring ( startPoint = ( 0 , 0 , 0 ) , endPoint = ( 1 , 0 , 0 ) , coils = 20 , r = 0.1 , r2 = None , thickness = None , c = "grey" , alpha = 1 , ) : diff = endPoint - np . array ( startPoint ) length = np . linalg . norm ( diff ) if not length : return None if not r : r = length / 20 trange = np . linspace ( 0 , length , num = 50 * coils ) om = 6.283 * ( coils - 0.5 ) / length if not r2 : r2 = r pts = [ ] for t in trange : f = ( length - t ) / length rd = r * f + r2 * ( 1 - f ) pts . append ( [ rd * np . cos ( om * t ) , rd * np . sin ( om * t ) , t ] ) pts = [ [ 0 , 0 , 0 ] ] + pts + [ [ 0 , 0 , length ] ] diff = diff / length theta = np . arccos ( diff [ 2 ] ) phi = np . arctan2 ( diff [ 1 ] , diff [ 0 ] ) sp = Line ( pts ) . polydata ( False ) t = vtk . vtkTransform ( ) t . RotateZ ( phi * 57.3 ) t . RotateY ( theta * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( sp ) tf . SetTransform ( t ) tf . Update ( ) tuf = vtk . vtkTubeFilter ( ) tuf . SetNumberOfSides ( 12 ) tuf . CappingOn ( ) tuf . SetInputData ( tf . GetOutput ( ) ) if not thickness : thickness = r / 10 tuf . SetRadius ( thickness ) tuf . Update ( ) poly = tuf . GetOutput ( ) actor = Actor ( poly , c , alpha ) actor . GetProperty ( ) . SetInterpolationToPhong ( ) actor . SetPosition ( startPoint ) actor . base = np . array ( startPoint ) actor . top = np . array ( endPoint ) settings . collectable_actors . append ( actor ) return actor | Build a spring of specified nr of coils between startPoint and endPoint . |
21,621 | def Cylinder ( pos = ( 0 , 0 , 0 ) , r = 1 , height = 1 , axis = ( 0 , 0 , 1 ) , c = "teal" , alpha = 1 , res = 24 ) : if utils . isSequence ( pos [ 0 ] ) : base = np . array ( pos [ 0 ] ) top = np . array ( pos [ 1 ] ) pos = ( base + top ) / 2 height = np . linalg . norm ( top - base ) axis = top - base axis = utils . versor ( axis ) else : axis = utils . versor ( axis ) base = pos - axis * height / 2 top = pos + axis * height / 2 cyl = vtk . vtkCylinderSource ( ) cyl . SetResolution ( res ) cyl . SetRadius ( r ) cyl . SetHeight ( height ) cyl . Update ( ) theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransform ( ) t . PostMultiply ( ) t . RotateX ( 90 ) t . RotateY ( theta * 57.3 ) t . RotateZ ( phi * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( cyl . GetOutput ( ) ) tf . SetTransform ( t ) tf . Update ( ) pd = tf . GetOutput ( ) actor = Actor ( pd , c , alpha ) actor . GetProperty ( ) . SetInterpolationToPhong ( ) actor . SetPosition ( pos ) actor . base = base + pos actor . top = top + pos settings . collectable_actors . append ( actor ) return actor | Build a cylinder of specified height and radius r centered at pos . |
21,622 | def Cone ( pos = ( 0 , 0 , 0 ) , r = 1 , height = 3 , axis = ( 0 , 0 , 1 ) , c = "dg" , alpha = 1 , res = 48 ) : con = vtk . vtkConeSource ( ) con . SetResolution ( res ) con . SetRadius ( r ) con . SetHeight ( height ) con . SetDirection ( axis ) con . Update ( ) actor = Actor ( con . GetOutput ( ) , c , alpha ) actor . GetProperty ( ) . SetInterpolationToPhong ( ) actor . SetPosition ( pos ) v = utils . versor ( axis ) * height / 2 actor . base = pos - v actor . top = pos + v settings . collectable_actors . append ( actor ) return actor | Build a cone of specified radius r and height centered at pos . |Cone| |
21,623 | def Pyramid ( pos = ( 0 , 0 , 0 ) , s = 1 , height = 1 , axis = ( 0 , 0 , 1 ) , c = "dg" , alpha = 1 ) : return Cone ( pos , s , height , axis , c , alpha , 4 ) | Build a pyramid of specified base size s and height centered at pos . |
21,624 | def Torus ( pos = ( 0 , 0 , 0 ) , r = 1 , thickness = 0.1 , axis = ( 0 , 0 , 1 ) , c = "khaki" , alpha = 1 , res = 30 ) : rs = vtk . vtkParametricTorus ( ) rs . SetRingRadius ( r ) rs . SetCrossSectionRadius ( thickness ) pfs = vtk . vtkParametricFunctionSource ( ) pfs . SetParametricFunction ( rs ) pfs . SetUResolution ( res * 3 ) pfs . SetVResolution ( res ) pfs . Update ( ) nax = np . linalg . norm ( axis ) if nax : axis = np . array ( axis ) / nax theta = np . arccos ( axis [ 2 ] ) phi = np . arctan2 ( axis [ 1 ] , axis [ 0 ] ) t = vtk . vtkTransform ( ) t . PostMultiply ( ) t . RotateY ( theta * 57.3 ) t . RotateZ ( phi * 57.3 ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( pfs . GetOutput ( ) ) tf . SetTransform ( t ) tf . Update ( ) pd = tf . GetOutput ( ) actor = Actor ( pd , c , alpha ) actor . GetProperty ( ) . SetInterpolationToPhong ( ) actor . SetPosition ( pos ) settings . collectable_actors . append ( actor ) return actor | Build a torus of specified outer radius r internal radius thickness centered at pos . |
21,625 | def getColorName ( c ) : c = np . array ( getColor ( c ) ) mdist = 99.0 kclosest = "" for key in colors . keys ( ) : ci = np . array ( getColor ( key ) ) d = np . linalg . norm ( c - ci ) if d < mdist : mdist = d kclosest = str ( key ) return kclosest | Find the name of a color . |
21,626 | def makePalette ( color1 , color2 , N , hsv = True ) : if hsv : color1 = rgb2hsv ( color1 ) color2 = rgb2hsv ( color2 ) c1 = np . array ( getColor ( color1 ) ) c2 = np . array ( getColor ( color2 ) ) cols = [ ] for f in np . linspace ( 0 , 1 , N - 1 , endpoint = True ) : c = c1 * ( 1 - f ) + c2 * f if hsv : c = np . array ( hsv2rgb ( c ) ) cols . append ( c ) return cols | Generate N colors starting from color1 to color2 by linear interpolation HSV in or RGB spaces . |
21,627 | def kelvin2rgb ( temperature ) : if temperature < 1000 : temperature = 1000 elif temperature > 40000 : temperature = 40000 tmp_internal = temperature / 100.0 if tmp_internal <= 66 : red = 255 else : tmp_red = 329.698727446 * np . power ( tmp_internal - 60 , - 0.1332047592 ) if tmp_red < 0 : red = 0 elif tmp_red > 255 : red = 255 else : red = tmp_red if tmp_internal <= 66 : tmp_green = 99.4708025861 * np . log ( tmp_internal ) - 161.1195681661 if tmp_green < 0 : green = 0 elif tmp_green > 255 : green = 255 else : green = tmp_green else : tmp_green = 288.1221695283 * np . power ( tmp_internal - 60 , - 0.0755148492 ) if tmp_green < 0 : green = 0 elif tmp_green > 255 : green = 255 else : green = tmp_green if tmp_internal >= 66 : blue = 255 elif tmp_internal <= 19 : blue = 0 else : tmp_blue = 138.5177312231 * np . log ( tmp_internal - 10 ) - 305.0447927307 if tmp_blue < 0 : blue = 0 elif tmp_blue > 255 : blue = 255 else : blue = tmp_blue return [ red / 255 , green / 255 , blue / 255 ] | Converts from Kelvin temperature to an RGB color . |
21,628 | def geometry ( obj ) : gf = vtk . vtkGeometryFilter ( ) gf . SetInputData ( obj ) gf . Update ( ) return gf . GetOutput ( ) | Apply vtkGeometryFilter . |
21,629 | def spline ( points , smooth = 0.5 , degree = 2 , s = 2 , c = "b" , alpha = 1.0 , nodes = False , res = 20 ) : from scipy . interpolate import splprep , splev Nout = len ( points ) * res points = np . array ( points ) minx , miny , minz = np . min ( points , axis = 0 ) maxx , maxy , maxz = np . max ( points , axis = 0 ) maxb = max ( maxx - minx , maxy - miny , maxz - minz ) smooth *= maxb / 2 x , y , z = points [ : , 0 ] , points [ : , 1 ] , points [ : , 2 ] tckp , _ = splprep ( [ x , y , z ] , task = 0 , s = smooth , k = degree ) xnew , ynew , znew = splev ( np . linspace ( 0 , 1 , Nout ) , tckp ) ppoints = vtk . vtkPoints ( ) profileData = vtk . vtkPolyData ( ) ppoints . SetData ( numpy_to_vtk ( list ( zip ( xnew , ynew , znew ) ) , deep = True ) ) lines = vtk . vtkCellArray ( ) lines . InsertNextCell ( Nout ) for i in range ( Nout ) : lines . InsertCellPoint ( i ) profileData . SetPoints ( ppoints ) profileData . SetLines ( lines ) actline = Actor ( profileData , c = c , alpha = alpha ) actline . GetProperty ( ) . SetLineWidth ( s ) if nodes : actnodes = vs . Points ( points , r = 5 , c = c , alpha = alpha ) ass = Assembly ( [ actline , actnodes ] ) return ass else : return actline | Return an Actor for a spline so that it does not necessarly pass exactly throught all points . |
21,630 | def histogram ( values , bins = 10 , vrange = None , title = "" , c = "g" , corner = 1 , lines = True ) : fs , edges = np . histogram ( values , bins = bins , range = vrange ) pts = [ ] for i in range ( len ( fs ) ) : pts . append ( [ ( edges [ i ] + edges [ i + 1 ] ) / 2 , fs [ i ] ] ) return xyplot ( pts , title , c , corner , lines ) | Build a 2D histogram from a list of values in n bins . |
21,631 | def delaunay2D ( plist , mode = 'xy' , tol = None ) : pd = vtk . vtkPolyData ( ) vpts = vtk . vtkPoints ( ) vpts . SetData ( numpy_to_vtk ( plist , deep = True ) ) pd . SetPoints ( vpts ) delny = vtk . vtkDelaunay2D ( ) delny . SetInputData ( pd ) if tol : delny . SetTolerance ( tol ) if mode == 'fit' : delny . SetProjectionPlaneMode ( vtk . VTK_BEST_FITTING_PLANE ) delny . Update ( ) return Actor ( delny . GetOutput ( ) ) | Create a mesh from points in the XY plane . If mode = fit then the filter computes a best fitting plane and projects the points onto it . |
21,632 | def delaunay3D ( dataset , alpha = 0 , tol = None , boundary = True ) : deln = vtk . vtkDelaunay3D ( ) deln . SetInputData ( dataset ) deln . SetAlpha ( alpha ) if tol : deln . SetTolerance ( tol ) deln . SetBoundingTriangulation ( boundary ) deln . Update ( ) return deln . GetOutput ( ) | Create 3D Delaunay triangulation of input points . |
21,633 | def normalLines ( actor , ratio = 1 , c = ( 0.6 , 0.6 , 0.6 ) , alpha = 0.8 ) : maskPts = vtk . vtkMaskPoints ( ) maskPts . SetOnRatio ( ratio ) maskPts . RandomModeOff ( ) actor = actor . computeNormals ( ) src = actor . polydata ( ) maskPts . SetInputData ( src ) arrow = vtk . vtkLineSource ( ) arrow . SetPoint1 ( 0 , 0 , 0 ) arrow . SetPoint2 ( 0.75 , 0 , 0 ) glyph = vtk . vtkGlyph3D ( ) glyph . SetSourceConnection ( arrow . GetOutputPort ( ) ) glyph . SetInputConnection ( maskPts . GetOutputPort ( ) ) glyph . SetVectorModeToUseNormal ( ) b = src . GetBounds ( ) sc = max ( [ b [ 1 ] - b [ 0 ] , b [ 3 ] - b [ 2 ] , b [ 5 ] - b [ 4 ] ] ) / 20.0 glyph . SetScaleFactor ( sc ) glyph . OrientOn ( ) glyph . Update ( ) glyphActor = Actor ( glyph . GetOutput ( ) , c = vc . getColor ( c ) , alpha = alpha ) glyphActor . mapper . SetScalarModeToUsePointFieldData ( ) glyphActor . PickableOff ( ) prop = vtk . vtkProperty ( ) prop . DeepCopy ( actor . GetProperty ( ) ) glyphActor . SetProperty ( prop ) return glyphActor | Build an vtkActor made of the normals at vertices shown as lines . |
21,634 | def extractLargestRegion ( actor ) : conn = vtk . vtkConnectivityFilter ( ) conn . SetExtractionModeToLargestRegion ( ) conn . ScalarConnectivityOff ( ) poly = actor . GetMapper ( ) . GetInput ( ) conn . SetInputData ( poly ) conn . Update ( ) epoly = conn . GetOutput ( ) eact = Actor ( epoly ) pr = vtk . vtkProperty ( ) pr . DeepCopy ( actor . GetProperty ( ) ) eact . SetProperty ( pr ) return eact | Keep only the largest connected part of a mesh and discard all the smaller pieces . |
21,635 | def alignLandmarks ( source , target , rigid = False ) : lmt = vtk . vtkLandmarkTransform ( ) ss = source . polydata ( ) . GetPoints ( ) st = target . polydata ( ) . GetPoints ( ) if source . N ( ) != target . N ( ) : vc . printc ( '~times Error in alignLandmarks(): Source and Target with != nr of points!' , source . N ( ) , target . N ( ) , c = 1 ) exit ( ) lmt . SetSourceLandmarks ( ss ) lmt . SetTargetLandmarks ( st ) if rigid : lmt . SetModeToRigidBody ( ) lmt . Update ( ) tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetInputData ( source . polydata ( ) ) tf . SetTransform ( lmt ) tf . Update ( ) actor = Actor ( tf . GetOutput ( ) ) actor . info [ "transform" ] = lmt pr = vtk . vtkProperty ( ) pr . DeepCopy ( source . GetProperty ( ) ) actor . SetProperty ( pr ) return actor | Find best matching of source points towards target in the mean least square sense in one single step . |
21,636 | def alignICP ( source , target , iters = 100 , rigid = False ) : if isinstance ( source , Actor ) : source = source . polydata ( ) if isinstance ( target , Actor ) : target = target . polydata ( ) icp = vtk . vtkIterativeClosestPointTransform ( ) icp . SetSource ( source ) icp . SetTarget ( target ) icp . SetMaximumNumberOfIterations ( iters ) if rigid : icp . GetLandmarkTransform ( ) . SetModeToRigidBody ( ) icp . StartByMatchingCentroidsOn ( ) icp . Update ( ) icpTransformFilter = vtk . vtkTransformPolyDataFilter ( ) icpTransformFilter . SetInputData ( source ) icpTransformFilter . SetTransform ( icp ) icpTransformFilter . Update ( ) poly = icpTransformFilter . GetOutput ( ) actor = Actor ( poly ) sourcePoints = vtk . vtkPoints ( ) targetPoints = vtk . vtkPoints ( ) for i in range ( 10 ) : p1 = [ 0 , 0 , 0 ] source . GetPoints ( ) . GetPoint ( i , p1 ) sourcePoints . InsertNextPoint ( p1 ) p2 = [ 0 , 0 , 0 ] poly . GetPoints ( ) . GetPoint ( i , p2 ) targetPoints . InsertNextPoint ( p2 ) landmarkTransform = vtk . vtkLandmarkTransform ( ) landmarkTransform . SetSourceLandmarks ( sourcePoints ) landmarkTransform . SetTargetLandmarks ( targetPoints ) if rigid : landmarkTransform . SetModeToRigidBody ( ) actor . info [ "transform" ] = landmarkTransform return actor | Return a copy of source actor which is aligned to target actor through the Iterative Closest Point algorithm . |
21,637 | def alignProcrustes ( sources , rigid = False ) : group = vtk . vtkMultiBlockDataGroupFilter ( ) for source in sources : if sources [ 0 ] . N ( ) != source . N ( ) : vc . printc ( "~times Procrustes error in align():" , c = 1 ) vc . printc ( " sources have different nr of points" , c = 1 ) exit ( 0 ) group . AddInputData ( source . polydata ( ) ) procrustes = vtk . vtkProcrustesAlignmentFilter ( ) procrustes . StartFromCentroidOn ( ) procrustes . SetInputConnection ( group . GetOutputPort ( ) ) if rigid : procrustes . GetLandmarkTransform ( ) . SetModeToRigidBody ( ) procrustes . Update ( ) acts = [ ] for i , s in enumerate ( sources ) : poly = procrustes . GetOutput ( ) . GetBlock ( i ) actor = Actor ( poly ) actor . SetProperty ( s . GetProperty ( ) ) acts . append ( actor ) assem = Assembly ( acts ) assem . info [ "transform" ] = procrustes . GetLandmarkTransform ( ) return assem | Return an Assembly of aligned source actors with the Procrustes algorithm . The output Assembly is normalized in size . |
21,638 | def fitLine ( points , c = "orange" , lw = 1 ) : data = np . array ( points ) datamean = data . mean ( axis = 0 ) uu , dd , vv = np . linalg . svd ( data - datamean ) vv = vv [ 0 ] / np . linalg . norm ( vv [ 0 ] ) xyz_min = points . min ( axis = 0 ) xyz_max = points . max ( axis = 0 ) a = np . linalg . norm ( xyz_min - datamean ) b = np . linalg . norm ( xyz_max - datamean ) p1 = datamean - a * vv p2 = datamean + b * vv l = vs . Line ( p1 , p2 , c = c , lw = lw , alpha = 1 ) l . info [ "slope" ] = vv l . info [ "center" ] = datamean l . info [ "variances" ] = dd return l | Fits a line through points . |
21,639 | def fitPlane ( points , c = "g" , bc = "darkgreen" ) : data = np . array ( points ) datamean = data . mean ( axis = 0 ) res = np . linalg . svd ( data - datamean ) dd , vv = res [ 1 ] , res [ 2 ] xyz_min = points . min ( axis = 0 ) xyz_max = points . max ( axis = 0 ) s = np . linalg . norm ( xyz_max - xyz_min ) n = np . cross ( vv [ 0 ] , vv [ 1 ] ) pla = vs . Plane ( datamean , n , s , s , c , bc ) pla . info [ "normal" ] = n pla . info [ "center" ] = datamean pla . info [ "variance" ] = dd [ 2 ] return pla | Fits a plane to a set of points . |
21,640 | def fitSphere ( coords ) : coords = np . array ( coords ) n = len ( coords ) A = np . zeros ( ( n , 4 ) ) A [ : , : - 1 ] = coords * 2 A [ : , 3 ] = 1 f = np . zeros ( ( n , 1 ) ) x = coords [ : , 0 ] y = coords [ : , 1 ] z = coords [ : , 2 ] f [ : , 0 ] = x * x + y * y + z * z C , residue , rank , sv = np . linalg . lstsq ( A , f ) if rank < 4 : return None t = ( C [ 0 ] * C [ 0 ] ) + ( C [ 1 ] * C [ 1 ] ) + ( C [ 2 ] * C [ 2 ] ) + C [ 3 ] radius = np . sqrt ( t ) [ 0 ] center = np . array ( [ C [ 0 ] [ 0 ] , C [ 1 ] [ 0 ] , C [ 2 ] [ 0 ] ] ) if len ( residue ) : residue = np . sqrt ( residue [ 0 ] ) / n else : residue = 0 s = vs . Sphere ( center , radius , c = "r" , alpha = 1 ) . wire ( 1 ) s . info [ "radius" ] = radius s . info [ "center" ] = center s . info [ "residue" ] = residue return s | Fits a sphere to a set of points . |
21,641 | def booleanOperation ( actor1 , operation , actor2 , c = None , alpha = 1 , wire = False , bc = None , texture = None ) : bf = vtk . vtkBooleanOperationPolyDataFilter ( ) poly1 = actor1 . computeNormals ( ) . polydata ( ) poly2 = actor2 . computeNormals ( ) . polydata ( ) if operation . lower ( ) == "plus" or operation . lower ( ) == "+" : bf . SetOperationToUnion ( ) elif operation . lower ( ) == "intersect" : bf . SetOperationToIntersection ( ) elif operation . lower ( ) == "minus" or operation . lower ( ) == "-" : bf . SetOperationToDifference ( ) bf . ReorientDifferenceCellsOn ( ) bf . SetInputData ( 0 , poly1 ) bf . SetInputData ( 1 , poly2 ) bf . Update ( ) actor = Actor ( bf . GetOutput ( ) , c , alpha , wire , bc , texture ) return actor | Volumetric union intersection and subtraction of surfaces . |
21,642 | def surfaceIntersection ( actor1 , actor2 , tol = 1e-06 , lw = 3 ) : bf = vtk . vtkIntersectionPolyDataFilter ( ) poly1 = actor1 . GetMapper ( ) . GetInput ( ) poly2 = actor2 . GetMapper ( ) . GetInput ( ) bf . SetInputData ( 0 , poly1 ) bf . SetInputData ( 1 , poly2 ) bf . Update ( ) actor = Actor ( bf . GetOutput ( ) , "k" , 1 ) actor . GetProperty ( ) . SetLineWidth ( lw ) return actor | Intersect 2 surfaces and return a line actor . |
21,643 | def probePoints ( img , pts ) : src = vtk . vtkProgrammableSource ( ) def readPoints ( ) : output = src . GetPolyDataOutput ( ) points = vtk . vtkPoints ( ) for p in pts : x , y , z = p points . InsertNextPoint ( x , y , z ) output . SetPoints ( points ) cells = vtk . vtkCellArray ( ) cells . InsertNextCell ( len ( pts ) ) for i in range ( len ( pts ) ) : cells . InsertCellPoint ( i ) output . SetVerts ( cells ) src . SetExecuteMethod ( readPoints ) src . Update ( ) probeFilter = vtk . vtkProbeFilter ( ) probeFilter . SetSourceData ( img ) probeFilter . SetInputConnection ( src . GetOutputPort ( ) ) probeFilter . Update ( ) pact = Actor ( probeFilter . GetOutput ( ) , c = None ) pact . mapper . SetScalarRange ( img . GetScalarRange ( ) ) return pact | Takes a vtkImageData and probes its scalars at the specified points in space . |
21,644 | def probeLine ( img , p1 , p2 , res = 100 ) : line = vtk . vtkLineSource ( ) line . SetResolution ( res ) line . SetPoint1 ( p1 ) line . SetPoint2 ( p2 ) probeFilter = vtk . vtkProbeFilter ( ) probeFilter . SetSourceData ( img ) probeFilter . SetInputConnection ( line . GetOutputPort ( ) ) probeFilter . Update ( ) lact = Actor ( probeFilter . GetOutput ( ) , c = None ) lact . mapper . SetScalarRange ( img . GetScalarRange ( ) ) return lact | Takes a vtkImageData and probes its scalars along a line defined by 2 points p1 and p2 . |
21,645 | def probePlane ( img , origin = ( 0 , 0 , 0 ) , normal = ( 1 , 0 , 0 ) ) : plane = vtk . vtkPlane ( ) plane . SetOrigin ( origin ) plane . SetNormal ( normal ) planeCut = vtk . vtkCutter ( ) planeCut . SetInputData ( img ) planeCut . SetCutFunction ( plane ) planeCut . Update ( ) cutActor = Actor ( planeCut . GetOutput ( ) , c = None ) cutActor . mapper . SetScalarRange ( img . GetPointData ( ) . GetScalars ( ) . GetRange ( ) ) return cutActor | Takes a vtkImageData and probes its scalars on a plane . |
21,646 | def recoSurface ( points , bins = 256 ) : if isinstance ( points , vtk . vtkActor ) : points = points . coordinates ( ) N = len ( points ) if N < 50 : print ( "recoSurface: Use at least 50 points." ) return None points = np . array ( points ) ptsSource = vtk . vtkPointSource ( ) ptsSource . SetNumberOfPoints ( N ) ptsSource . Update ( ) vpts = ptsSource . GetOutput ( ) . GetPoints ( ) for i , p in enumerate ( points ) : vpts . SetPoint ( i , p ) polyData = ptsSource . GetOutput ( ) distance = vtk . vtkSignedDistance ( ) f = 0.1 x0 , x1 , y0 , y1 , z0 , z1 = polyData . GetBounds ( ) distance . SetBounds ( x0 - ( x1 - x0 ) * f , x1 + ( x1 - x0 ) * f , y0 - ( y1 - y0 ) * f , y1 + ( y1 - y0 ) * f , z0 - ( z1 - z0 ) * f , z1 + ( z1 - z0 ) * f ) if polyData . GetPointData ( ) . GetNormals ( ) : distance . SetInputData ( polyData ) else : normals = vtk . vtkPCANormalEstimation ( ) normals . SetInputData ( polyData ) normals . SetSampleSize ( int ( N / 50 ) ) normals . SetNormalOrientationToGraphTraversal ( ) distance . SetInputConnection ( normals . GetOutputPort ( ) ) print ( "Recalculating normals for" , N , "Points, sample size=" , int ( N / 50 ) ) b = polyData . GetBounds ( ) diagsize = np . sqrt ( ( b [ 1 ] - b [ 0 ] ) ** 2 + ( b [ 3 ] - b [ 2 ] ) ** 2 + ( b [ 5 ] - b [ 4 ] ) ** 2 ) radius = diagsize / bins * 5 distance . SetRadius ( radius ) distance . SetDimensions ( bins , bins , bins ) distance . Update ( ) print ( "Calculating mesh from points with R =" , radius ) surface = vtk . vtkExtractSurface ( ) surface . SetRadius ( radius * 0.99 ) surface . HoleFillingOn ( ) surface . ComputeNormalsOff ( ) surface . ComputeGradientsOff ( ) surface . SetInputConnection ( distance . GetOutputPort ( ) ) surface . Update ( ) return Actor ( surface . GetOutput ( ) , "gold" , 1 , 0 , "tomato" ) | Surface reconstruction from a scattered cloud of points . |
21,647 | def cluster ( points , radius ) : if isinstance ( points , vtk . vtkActor ) : poly = points . GetMapper ( ) . GetInput ( ) else : src = vtk . vtkPointSource ( ) src . SetNumberOfPoints ( len ( points ) ) src . Update ( ) vpts = src . GetOutput ( ) . GetPoints ( ) for i , p in enumerate ( points ) : vpts . SetPoint ( i , p ) poly = src . GetOutput ( ) cluster = vtk . vtkEuclideanClusterExtraction ( ) cluster . SetInputData ( poly ) cluster . SetExtractionModeToAllClusters ( ) cluster . SetRadius ( radius ) cluster . ColorClustersOn ( ) cluster . Update ( ) idsarr = cluster . GetOutput ( ) . GetPointData ( ) . GetArray ( "ClusterId" ) Nc = cluster . GetNumberOfExtractedClusters ( ) sets = [ [ ] for i in range ( Nc ) ] for i , p in enumerate ( points ) : sets [ idsarr . GetValue ( i ) ] . append ( p ) acts = [ ] for i , aset in enumerate ( sets ) : acts . append ( vs . Points ( aset , c = i ) ) actor = Assembly ( acts ) actor . info [ "clusters" ] = sets print ( "Nr. of extracted clusters" , Nc ) if Nc > 10 : print ( "First ten:" ) for i in range ( Nc ) : if i > 9 : print ( "..." ) break print ( "Cluster #" + str ( i ) + ", N =" , len ( sets [ i ] ) ) print ( "Access individual clusters through attribute: actor.cluster" ) return actor | Clustering of points in space . |
21,648 | def removeOutliers ( points , radius ) : isactor = False if isinstance ( points , vtk . vtkActor ) : isactor = True poly = points . GetMapper ( ) . GetInput ( ) else : src = vtk . vtkPointSource ( ) src . SetNumberOfPoints ( len ( points ) ) src . Update ( ) vpts = src . GetOutput ( ) . GetPoints ( ) for i , p in enumerate ( points ) : vpts . SetPoint ( i , p ) poly = src . GetOutput ( ) removal = vtk . vtkRadiusOutlierRemoval ( ) removal . SetInputData ( poly ) removal . SetRadius ( radius ) removal . SetNumberOfNeighbors ( 5 ) removal . GenerateOutliersOff ( ) removal . Update ( ) rpoly = removal . GetOutput ( ) print ( "# of removed outlier points: " , removal . GetNumberOfPointsRemoved ( ) , '/' , poly . GetNumberOfPoints ( ) ) outpts = [ ] for i in range ( rpoly . GetNumberOfPoints ( ) ) : outpts . append ( list ( rpoly . GetPoint ( i ) ) ) outpts = np . array ( outpts ) if not isactor : return outpts actor = vs . Points ( outpts ) return actor | Remove outliers from a cloud of points within the specified radius search . |
21,649 | def thinPlateSpline ( actor , sourcePts , targetPts , userFunctions = ( None , None ) ) : ns = len ( sourcePts ) ptsou = vtk . vtkPoints ( ) ptsou . SetNumberOfPoints ( ns ) for i in range ( ns ) : ptsou . SetPoint ( i , sourcePts [ i ] ) nt = len ( sourcePts ) if ns != nt : vc . printc ( "~times thinPlateSpline Error: #source != #target points" , ns , nt , c = 1 ) exit ( ) pttar = vtk . vtkPoints ( ) pttar . SetNumberOfPoints ( nt ) for i in range ( ns ) : pttar . SetPoint ( i , targetPts [ i ] ) transform = vtk . vtkThinPlateSplineTransform ( ) transform . SetBasisToR ( ) if userFunctions [ 0 ] : transform . SetBasisFunction ( userFunctions [ 0 ] ) transform . SetBasisDerivative ( userFunctions [ 1 ] ) transform . SetSigma ( 1 ) transform . SetSourceLandmarks ( ptsou ) transform . SetTargetLandmarks ( pttar ) tfa = transformFilter ( actor . polydata ( ) , transform ) tfa . info [ "transform" ] = transform return tfa | Thin Plate Spline transformations describe a nonlinear warp transform defined by a set of source and target landmarks . Any point on the mesh close to a source landmark will be moved to a place close to the corresponding target landmark . The points in between are interpolated smoothly using Bookstein s Thin Plate Spline algorithm . |
21,650 | def transformFilter ( actor , transformation ) : tf = vtk . vtkTransformPolyDataFilter ( ) tf . SetTransform ( transformation ) prop = None if isinstance ( actor , vtk . vtkPolyData ) : tf . SetInputData ( actor ) else : tf . SetInputData ( actor . polydata ( ) ) prop = vtk . vtkProperty ( ) prop . DeepCopy ( actor . GetProperty ( ) ) tf . Update ( ) tfa = Actor ( tf . GetOutput ( ) ) if prop : tfa . SetProperty ( prop ) return tfa | Transform a vtkActor and return a new object . |
21,651 | def splitByConnectivity ( actor , maxdepth = 100 ) : actor . addIDs ( ) pd = actor . polydata ( ) cf = vtk . vtkConnectivityFilter ( ) cf . SetInputData ( pd ) cf . SetExtractionModeToAllRegions ( ) cf . ColorRegionsOn ( ) cf . Update ( ) cpd = cf . GetOutput ( ) a = Actor ( cpd ) alist = [ ] for t in range ( max ( a . scalars ( "RegionId" ) ) - 1 ) : if t == maxdepth : break suba = a . clone ( ) . threshold ( "RegionId" , t - 0.1 , t + 0.1 ) area = suba . area ( ) alist . append ( [ suba , area ] ) alist . sort ( key = lambda x : x [ 1 ] ) alist . reverse ( ) blist = [ ] for i , l in enumerate ( alist ) : l [ 0 ] . color ( i + 1 ) l [ 0 ] . mapper . ScalarVisibilityOff ( ) blist . append ( l [ 0 ] ) return blist | Split a mesh by connectivity and order the pieces by increasing area . |
21,652 | def pointSampler ( actor , distance = None ) : poly = actor . polydata ( True ) pointSampler = vtk . vtkPolyDataPointSampler ( ) if not distance : distance = actor . diagonalSize ( ) / 100.0 pointSampler . SetDistance ( distance ) pointSampler . SetInputData ( poly ) pointSampler . Update ( ) uactor = Actor ( pointSampler . GetOutput ( ) ) prop = vtk . vtkProperty ( ) prop . DeepCopy ( actor . GetProperty ( ) ) uactor . SetProperty ( prop ) return uactor | Algorithm to generate points the specified distance apart . |
21,653 | def geodesic ( actor , start , end ) : dijkstra = vtk . vtkDijkstraGraphGeodesicPath ( ) if vu . isSequence ( start ) : cc = actor . coordinates ( ) pa = vs . Points ( cc ) start = pa . closestPoint ( start , returnIds = True ) end = pa . closestPoint ( end , returnIds = True ) dijkstra . SetInputData ( pa . polydata ( ) ) else : dijkstra . SetInputData ( actor . polydata ( ) ) dijkstra . SetStartVertex ( start ) dijkstra . SetEndVertex ( end ) dijkstra . Update ( ) weights = vtk . vtkDoubleArray ( ) dijkstra . GetCumulativeWeights ( weights ) length = weights . GetMaxId ( ) + 1 arr = np . zeros ( length ) for i in range ( length ) : arr [ i ] = weights . GetTuple ( i ) [ 0 ] dactor = Actor ( dijkstra . GetOutput ( ) ) prop = vtk . vtkProperty ( ) prop . DeepCopy ( actor . GetProperty ( ) ) prop . SetLineWidth ( 3 ) prop . SetOpacity ( 1 ) dactor . SetProperty ( prop ) dactor . info [ "CumulativeWeights" ] = arr return dactor | Dijkstra algorithm to compute the graph geodesic . Takes as input a polygonal mesh and performs a single source shortest path calculation . |
21,654 | def convexHull ( actor_or_list , alphaConstant = 0 ) : if vu . isSequence ( actor_or_list ) : actor = vs . Points ( actor_or_list ) else : actor = actor_or_list apoly = actor . clean ( ) . polydata ( ) triangleFilter = vtk . vtkTriangleFilter ( ) triangleFilter . SetInputData ( apoly ) triangleFilter . Update ( ) poly = triangleFilter . GetOutput ( ) delaunay = vtk . vtkDelaunay3D ( ) if alphaConstant : delaunay . SetAlpha ( alphaConstant ) delaunay . SetInputData ( poly ) delaunay . Update ( ) surfaceFilter = vtk . vtkDataSetSurfaceFilter ( ) surfaceFilter . SetInputConnection ( delaunay . GetOutputPort ( ) ) surfaceFilter . Update ( ) chuact = Actor ( surfaceFilter . GetOutput ( ) ) return chuact | Create a 3D Delaunay triangulation of input points . |
21,655 | def extractSurface ( image , radius = 0.5 ) : fe = vtk . vtkExtractSurface ( ) fe . SetInputData ( image ) fe . SetRadius ( radius ) fe . Update ( ) return Actor ( fe . GetOutput ( ) ) | vtkExtractSurface filter . Input is a vtkImageData . Generate zero - crossing isosurface from truncated signed distance volume . |
21,656 | def projectSphereFilter ( actor ) : poly = actor . polydata ( ) psf = vtk . vtkProjectSphereFilter ( ) psf . SetInputData ( poly ) psf . Update ( ) a = Actor ( psf . GetOutput ( ) ) return a | Project a spherical - like object onto a plane . |
21,657 | def wait ( self , timeout = None ) : try : if timeout : gevent . sleep ( timeout ) else : while True : gevent . sleep ( 1000 ) except ( KeyboardInterrupt , SystemExit , Exception ) : pass | Wait for events . |
21,658 | def discover ( self , seconds = 2 ) : log . info ( "Discovering devices" ) with gevent . Timeout ( seconds , StopBroadcasting ) as timeout : try : try : while True : self . upnp . broadcast ( ) gevent . sleep ( 1 ) except Exception as e : raise StopBroadcasting ( e ) except StopBroadcasting : return | Discover devices in the environment . |
21,659 | def send ( self , sender , ** named ) : responses = [ ] if not self . receivers or self . sender_receivers_cache . get ( sender ) is NO_RECEIVERS : return responses for receiver in self . _live_receivers ( sender ) : response = receiver ( signal = self , sender = sender , ** named ) responses . append ( ( receiver , response ) ) return responses | Send signal from sender to all connected receivers . |
21,660 | def send_robust ( self , sender , ** named ) : responses = [ ] if not self . receivers or self . sender_receivers_cache . get ( sender ) is NO_RECEIVERS : return responses for receiver in self . _live_receivers ( sender ) : try : response = receiver ( signal = self , sender = sender , ** named ) except Exception as err : if not hasattr ( err , '__traceback__' ) : err . __traceback__ = sys . exc_info ( ) [ 2 ] responses . append ( ( receiver , err ) ) else : responses . append ( ( receiver , response ) ) return responses | Send signal from sender to all connected receivers catching errors . |
21,661 | def _live_receivers ( self , sender ) : receivers = None if self . use_caching and not self . _dead_receivers : receivers = self . sender_receivers_cache . get ( sender ) if receivers is NO_RECEIVERS : return [ ] if receivers is None : with self . lock : self . _clear_dead_receivers ( ) senderkey = _make_id ( sender ) receivers = [ ] for ( receiverkey , r_senderkey ) , receiver in self . receivers : if r_senderkey == NONE_ID or r_senderkey == senderkey : receivers . append ( receiver ) if self . use_caching : if not receivers : self . sender_receivers_cache [ sender ] = NO_RECEIVERS else : self . sender_receivers_cache [ sender ] = receivers non_weak_receivers = [ ] for receiver in receivers : if isinstance ( receiver , weakref . ReferenceType ) : receiver = receiver ( ) if receiver is not None : non_weak_receivers . append ( receiver ) else : non_weak_receivers . append ( receiver ) return non_weak_receivers | Filter sequence of receivers to get resolved live receivers . |
21,662 | def set_state ( self , state ) : self . basicevent . SetBinaryState ( BinaryState = int ( state ) ) self . _state = int ( state ) | Set the state of this device to on or off . |
21,663 | def broadcast ( self ) : log . debug ( "Broadcasting M-SEARCH to %s:%s" , self . mcast_ip , self . mcast_port ) request = '\r\n' . join ( ( "M-SEARCH * HTTP/1.1" , "HOST:{mcast_ip}:{mcast_port}" , "ST:upnp:rootdevice" , "MX:2" , 'MAN:"ssdp:discover"' , "" , "" ) ) . format ( ** self . __dict__ ) self . server . sendto ( request . encode ( ) , ( self . mcast_ip , self . mcast_port ) ) | Send a multicast M - SEARCH request asking for devices to report in . |
21,664 | def retry_with_delay ( f , delay = 60 ) : @ wraps ( f ) def inner ( * args , ** kwargs ) : kwargs [ 'timeout' ] = 5 remaining = get_retries ( ) + 1 while remaining : remaining -= 1 try : return f ( * args , ** kwargs ) except ( requests . ConnectionError , requests . Timeout ) : if not remaining : raise gevent . sleep ( delay ) return inner | Retry the wrapped requests . request function in case of ConnectionError . Optionally limit the number of retries or set the delay between retries . |
21,665 | def searchType ( libtype ) : libtype = compat . ustr ( libtype ) if libtype in [ compat . ustr ( v ) for v in SEARCHTYPES . values ( ) ] : return libtype if SEARCHTYPES . get ( libtype ) is not None : return SEARCHTYPES [ libtype ] raise NotFound ( 'Unknown libtype: %s' % libtype ) | Returns the integer value of the library string type . |
21,666 | def toDatetime ( value , format = None ) : if value and value is not None : if format : value = datetime . strptime ( value , format ) else : if int ( value ) == 0 : value = 86400 value = datetime . fromtimestamp ( int ( value ) ) return value | Returns a datetime object from the specified value . |
21,667 | def toList ( value , itemcast = None , delim = ',' ) : value = value or '' itemcast = itemcast or str return [ itemcast ( item ) for item in value . split ( delim ) if item != '' ] | Returns a list of strings from the specified value . |
21,668 | def downloadSessionImages ( server , filename = None , height = 150 , width = 150 , opacity = 100 , saturation = 100 ) : info = { } for media in server . sessions ( ) : url = None for part in media . iterParts ( ) : if media . thumb : url = media . thumb if part . indexes : url = '/library/parts/%s/indexes/%s/%s' % ( part . id , part . indexes . lower ( ) , media . viewOffset ) if url : if filename is None : prettyname = media . _prettyfilename ( ) filename = 'session_transcode_%s_%s_%s' % ( media . usernames [ 0 ] , prettyname , int ( time . time ( ) ) ) url = server . transcodeImage ( url , height , width , opacity , saturation ) filepath = download ( url , filename = filename ) info [ 'username' ] = { 'filepath' : filepath , 'url' : url } return info | Helper to download a bif image or thumb . url from plex . server . sessions . |
21,669 | def download ( url , token , filename = None , savepath = None , session = None , chunksize = 4024 , unpack = False , mocked = False , showstatus = False ) : from plexapi import log session = session or requests . Session ( ) headers = { 'X-Plex-Token' : token } response = session . get ( url , headers = headers , stream = True ) savepath = savepath or os . getcwd ( ) compat . makedirs ( savepath , exist_ok = True ) if not filename and response . headers . get ( 'Content-Disposition' ) : filename = re . findall ( r'filename=\"(.+)\"' , response . headers . get ( 'Content-Disposition' ) ) filename = filename [ 0 ] if filename [ 0 ] else None filename = os . path . basename ( filename ) fullpath = os . path . join ( savepath , filename ) extension = os . path . splitext ( fullpath ) [ - 1 ] if not extension : contenttype = response . headers . get ( 'content-type' ) if contenttype and 'image' in contenttype : fullpath += contenttype . split ( '/' ) [ 1 ] if mocked : log . debug ( 'Mocked download %s' , fullpath ) return fullpath log . info ( 'Downloading: %s' , fullpath ) if showstatus : total = int ( response . headers . get ( 'content-length' , 0 ) ) bar = tqdm ( unit = 'B' , unit_scale = True , total = total , desc = filename ) with open ( fullpath , 'wb' ) as handle : for chunk in response . iter_content ( chunk_size = chunksize ) : handle . write ( chunk ) if showstatus : bar . update ( len ( chunk ) ) if showstatus : bar . close ( ) if fullpath . endswith ( 'zip' ) and unpack : with zipfile . ZipFile ( fullpath , 'r' ) as handle : handle . extractall ( savepath ) return fullpath | Helper to download a thumb videofile or other media item . Returns the local path to the downloaded file . |
21,670 | def tag_helper ( tag , items , locked = True , remove = False ) : if not isinstance ( items , list ) : items = [ items ] data = { } if not remove : for i , item in enumerate ( items ) : tagname = '%s[%s].tag.tag' % ( tag , i ) data [ tagname ] = item if remove : tagname = '%s[].tag.tag-' % tag data [ tagname ] = ',' . join ( items ) data [ '%s.locked' % tag ] = 1 if locked else 0 return data | Simple tag helper for editing a object . |
21,671 | def choose ( msg , items , attr ) : if len ( items ) == 1 : return items [ 0 ] print ( ) for index , i in enumerate ( items ) : name = attr ( i ) if callable ( attr ) else getattr ( i , attr ) print ( ' %s: %s' % ( index , name ) ) print ( ) while True : try : inp = input ( '%s: ' % msg ) if any ( s in inp for s in ( ':' , '::' , '-' ) ) : idx = slice ( * map ( lambda x : int ( x . strip ( ) ) if x . strip ( ) else None , inp . split ( ':' ) ) ) return items [ idx ] else : return items [ int ( inp ) ] except ( ValueError , IndexError ) : pass | Command line helper to display a list of choices asking the user to choose one of the options . |
21,672 | def _find_server ( account , servername = None ) : servers = servers = [ s for s in account . resources ( ) if 'server' in s . provides ] if servername is not None : for server in servers : if server . name == servername : return server . connect ( ) raise SystemExit ( 'Unknown server name: %s' % servername ) return utils . choose ( 'Choose a Server' , servers , 'name' ) . connect ( ) | Find and return a PlexServer object . |
21,673 | def backup_watched ( plex , opts ) : data = defaultdict ( lambda : dict ( ) ) for section in _iter_sections ( plex , opts ) : print ( 'Fetching watched status for %s..' % section . title ) skey = section . title . lower ( ) for item in _iter_items ( section ) : if not opts . watchedonly or item . isWatched : ikey = _item_key ( item ) data [ skey ] [ ikey ] = item . isWatched import pprint pprint . pprint ( item . __dict__ ) break print ( 'Writing backup file to %s' % opts . filepath ) with open ( opts . filepath , 'w' ) as handle : json . dump ( dict ( data ) , handle , sort_keys = True , indent = 2 ) | Backup watched status to the specified filepath . |
21,674 | def restore_watched ( plex , opts ) : with open ( opts . filepath , 'r' ) as handle : source = json . load ( handle ) differences = defaultdict ( lambda : dict ( ) ) for section in _iter_sections ( plex , opts ) : print ( 'Finding differences in %s..' % section . title ) skey = section . title . lower ( ) for item in _iter_items ( section ) : ikey = _item_key ( item ) sval = source . get ( skey , { } ) . get ( ikey ) if sval is None : raise SystemExit ( '%s not found' % ikey ) if ( sval is not None and item . isWatched != sval ) and ( not opts . watchedonly or sval ) : differences [ skey ] [ ikey ] = { 'isWatched' : sval , 'item' : item } print ( 'Applying %s differences to destination' % len ( differences ) ) import pprint pprint . pprint ( differences ) | Restore watched status from the specified filepath . |
21,675 | def _onMessage ( self , ws , message ) : try : data = json . loads ( message ) [ 'NotificationContainer' ] log . debug ( 'Alert: %s %s %s' , * data ) if self . _callback : self . _callback ( data ) except Exception as err : log . error ( 'AlertListener Msg Error: %s' , err ) | Called when websocket message is recieved . |
21,676 | def _cast ( self , value ) : if self . type != 'text' : value = utils . cast ( self . TYPES . get ( self . type ) [ 'cast' ] , value ) return value | Cast the specifief value to the type of this setting . |
21,677 | def _getEnumValues ( self , data ) : enumstr = data . attrib . get ( 'enumValues' ) if not enumstr : return None if ':' in enumstr : return { self . _cast ( k ) : v for k , v in [ kv . split ( ':' ) for kv in enumstr . split ( '|' ) ] } return enumstr . split ( '|' ) | Returns a list of dictionary of valis value for this setting . |
21,678 | def _headers ( self , ** kwargs ) : headers = BASE_HEADERS . copy ( ) if self . _token : headers [ 'X-Plex-Token' ] = self . _token headers . update ( kwargs ) return headers | Returns dict containing base headers for all requests to the server . |
21,679 | def library ( self ) : if not self . _library : try : data = self . query ( Library . key ) self . _library = Library ( self , data ) except BadRequest : data = self . query ( '/library/sections/' ) return Library ( self , data ) return self . _library | Library to browse or search your media . |
21,680 | def settings ( self ) : if not self . _settings : data = self . query ( Settings . key ) self . _settings = Settings ( self , data ) return self . _settings | Returns a list of all server settings . |
21,681 | def downloadDatabases ( self , savepath = None , unpack = False ) : url = self . url ( '/diagnostics/databases' ) filepath = utils . download ( url , self . _token , None , savepath , self . _session , unpack = unpack ) return filepath | Download databases . |
21,682 | def installUpdate ( self ) : part = '/updater/apply' release = self . check_for_update ( force = True , download = True ) if release and release . version != self . version : return self . query ( part , method = self . _session . put ) | Install the newest version of Plex Media Server . |
21,683 | def startAlertListener ( self , callback = None ) : notifier = AlertListener ( self , callback ) notifier . start ( ) return notifier | Creates a websocket connection to the Plex Server to optionally recieve notifications . These often include messages from Plex about media scans as well as updates to currently running Transcode Sessions . |
21,684 | def url ( self , key , includeToken = None ) : if self . _token and ( includeToken or self . _showSecrets ) : delim = '&' if '?' in key else '?' return '%s%s%sX-Plex-Token=%s' % ( self . _baseurl , key , delim , self . _token ) return '%s%s' % ( self . _baseurl , key ) | Build a URL string with proper token argument . Token will be appended to the URL if either includeToken is True or CONFIG . log . show_secrets is true . |
21,685 | def thumbUrl ( self ) : thumb = self . firstAttr ( 'thumb' , 'parentThumb' , 'granparentThumb' ) return self . _server . url ( thumb , includeToken = True ) if thumb else None | Return the first first thumbnail url starting on the most specific thumbnail for that item . |
21,686 | def artUrl ( self ) : art = self . firstAttr ( 'art' , 'grandparentArt' ) return self . _server . url ( art , includeToken = True ) if art else None | Return the first first art url starting on the most specific for that item . |
21,687 | def url ( self , part ) : return self . _server . url ( part , includeToken = True ) if part else None | Returns the full url for something . Typically used for getting a specific image . |
21,688 | def markWatched ( self ) : key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self . ratingKey self . _server . query ( key ) self . reload ( ) | Mark video as watched . |
21,689 | def markUnwatched ( self ) : key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self . ratingKey self . _server . query ( key ) self . reload ( ) | Mark video unwatched . |
21,690 | def _asDict ( self ) : config = defaultdict ( dict ) for section in self . _sections : for name , value in self . _sections [ section ] . items ( ) : if name != '__name__' : config [ section . lower ( ) ] [ name . lower ( ) ] = value return dict ( config ) | Returns all configuration values as a dictionary . |
21,691 | def parse ( server , data , initpath ) : STREAMCLS = { 1 : VideoStream , 2 : AudioStream , 3 : SubtitleStream } stype = cast ( int , data . attrib . get ( 'streamType' ) ) cls = STREAMCLS . get ( stype , MediaPartStream ) return cls ( server , data , initpath ) | Factory method returns a new MediaPartStream from xml data . |
21,692 | def delete ( self ) : url = SyncList . key . format ( clientId = self . clientIdentifier ) url += '/' + str ( self . id ) self . _server . query ( url , self . _server . _session . delete ) | Removes current SyncItem |
21,693 | def _buildItem ( self , elem , cls = None , initpath = None ) : initpath = initpath or self . _initpath if cls is not None : return cls ( self . _server , elem , initpath ) etype = elem . attrib . get ( 'type' , elem . attrib . get ( 'streamType' ) ) ehash = '%s.%s' % ( elem . tag , etype ) if etype else elem . tag ecls = utils . PLEXOBJECTS . get ( ehash , utils . PLEXOBJECTS . get ( elem . tag ) ) if ecls is not None : return ecls ( self . _server , elem , initpath ) raise UnknownType ( "Unknown library type <%s type='%s'../>" % ( elem . tag , etype ) ) | Factory function to build objects based on registered PLEXOBJECTS . |
21,694 | def fetchItem ( self , ekey , cls = None , ** kwargs ) : if isinstance ( ekey , int ) : ekey = '/library/metadata/%s' % ekey for elem in self . _server . query ( ekey ) : if self . _checkAttrs ( elem , ** kwargs ) : return self . _buildItem ( elem , cls , ekey ) clsname = cls . __name__ if cls else 'None' raise NotFound ( 'Unable to find elem: cls=%s, attrs=%s' % ( clsname , kwargs ) ) | Load the specified key to find and build the first item with the specified tag and attrs . If no tag or attrs are specified then the first item in the result set is returned . |
21,695 | def firstAttr ( self , * attrs ) : for attr in attrs : value = self . __dict__ . get ( attr ) if value is not None : return value | Return the first attribute in attrs that is not None . |
21,696 | def reload ( self , key = None ) : key = key or self . _details_key or self . key if not key : raise Unsupported ( 'Cannot reload an object not built from a URL.' ) self . _initpath = key data = self . _server . query ( key ) self . _loadData ( data [ 0 ] ) return self | Reload the data for this object from self . key . |
21,697 | def edit ( self , ** kwargs ) : if 'id' not in kwargs : kwargs [ 'id' ] = self . ratingKey if 'type' not in kwargs : kwargs [ 'type' ] = utils . searchType ( self . type ) part = '/library/sections/%s/all?%s' % ( self . librarySectionID , urlencode ( kwargs ) ) self . _server . query ( part , method = self . _server . _session . put ) | Edit an object . |
21,698 | def _edit_tags ( self , tag , items , locked = True , remove = False ) : if not isinstance ( items , list ) : items = [ items ] value = getattr ( self , tag + 's' ) existing_cols = [ t . tag for t in value if t and remove is False ] d = tag_helper ( tag , existing_cols + items , locked , remove ) self . edit ( ** d ) self . refresh ( ) | Helper to edit and refresh a tags . |
21,699 | def getStreamURL ( self , ** params ) : if self . TYPE not in ( 'movie' , 'episode' , 'track' ) : raise Unsupported ( 'Fetching stream URL for %s is unsupported.' % self . TYPE ) mvb = params . get ( 'maxVideoBitrate' ) vr = params . get ( 'videoResolution' , '' ) params = { 'path' : self . key , 'offset' : params . get ( 'offset' , 0 ) , 'copyts' : params . get ( 'copyts' , 1 ) , 'protocol' : params . get ( 'protocol' ) , 'mediaIndex' : params . get ( 'mediaIndex' , 0 ) , 'X-Plex-Platform' : params . get ( 'platform' , 'Chrome' ) , 'maxVideoBitrate' : max ( mvb , 64 ) if mvb else None , 'videoResolution' : vr if re . match ( '^\d+x\d+$' , vr ) else None } params = { k : v for k , v in params . items ( ) if v is not None } streamtype = 'audio' if self . TYPE in ( 'track' , 'album' ) else 'video' sorted_params = sorted ( params . items ( ) , key = lambda val : val [ 0 ] ) return self . _server . url ( '/%s/:/transcode/universal/start.m3u8?%s' % ( streamtype , urlencode ( sorted_params ) ) , includeToken = True ) | Returns a stream url that may be used by external applications such as VLC . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.