idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
2,800
def render ( self ) : self . set_current ( ) size = self . physical_size fbo = FrameBuffer ( color = RenderBuffer ( size [ : : - 1 ] ) , depth = RenderBuffer ( size [ : : - 1 ] ) ) try : fbo . activate ( ) self . events . draw ( ) return fbo . read ( ) finally : fbo . deactivate ( )
Render the canvas to an offscreen buffer and return the image array .
2,801
def drag_events ( self ) : if not self . is_dragging : return None event = self events = [ ] while True : if event is None or event . type == 'mouse_press' : break events . append ( event ) event = event . last_event return events [ : : - 1 ]
Return a list of all mouse events in the current drag operation .
2,802
def width_max ( self , width_max ) : if width_max is None : self . _width_limits [ 1 ] = None return width_max = float ( width_max ) assert ( self . width_min <= width_max ) self . _width_limits [ 1 ] = width_max self . _update_layout ( )
Set the maximum width of the widget .
2,803
def height_max ( self , height_max ) : if height_max is None : self . _height_limits [ 1 ] = None return height_max = float ( height_max ) assert ( 0 <= self . height_min <= height_max ) self . _height_limits [ 1 ] = height_max self . _update_layout ( )
Set the maximum height of the widget .
2,804
def inner_rect ( self ) : m = self . margin + self . _border_width + self . padding if not self . border_color . is_blank : m += 1 return Rect ( ( m , m ) , ( self . size [ 0 ] - 2 * m , self . size [ 1 ] - 2 * m ) )
The rectangular area inside the margin border and padding .
2,805
def _update_clipper ( self ) : if self . clip_children and self . _clipper is None : self . _clipper = Clipper ( ) elif not self . clip_children : self . _clipper = None if self . _clipper is None : return self . _clipper . rect = self . inner_rect self . _clipper . transform = self . get_transform ( 'framebuffer' , 'v...
Called whenever the clipper for this widget may need to be updated .
2,806
def _update_line ( self ) : w = self . _border_width m = self . margin l = b = m r = self . size [ 0 ] - m t = self . size [ 1 ] - m pos = np . array ( [ [ l , b ] , [ l + w , b + w ] , [ r , b ] , [ r - w , b + w ] , [ r , t ] , [ r - w , t - w ] , [ l , t ] , [ l + w , t - w ] , ] , dtype = np . float32 ) faces = np ...
Update border line to match new shape
2,807
def add_widget ( self , widget ) : self . _widgets . append ( widget ) widget . parent = self self . _update_child_widgets ( ) return widget
Add a Widget as a managed child of this Widget .
2,808
def remove_widget ( self , widget ) : self . _widgets . remove ( widget ) widget . parent = None self . _update_child_widgets ( )
Remove a Widget as a managed child of this Widget .
2,809
def pack_ieee ( value ) : return np . fromstring ( value . tostring ( ) , np . ubyte ) . reshape ( ( value . shape + ( 4 , ) ) )
Packs float ieee binary representation into 4 unsigned int8
2,810
def load_spatial_filters ( packed = True ) : names = ( "Bilinear" , "Hanning" , "Hamming" , "Hermite" , "Kaiser" , "Quadric" , "Bicubic" , "CatRom" , "Mitchell" , "Spline16" , "Spline36" , "Gaussian" , "Bessel" , "Sinc" , "Lanczos" , "Blackman" , "Nearest" ) kernel = np . load ( op . join ( DATA_DIR , 'spatial-filters....
Load spatial - filters kernel
2,811
def timeout ( limit , handler ) : def wrapper ( f ) : def wrapped_f ( * args , ** kwargs ) : old_handler = signal . getsignal ( signal . SIGALRM ) signal . signal ( signal . SIGALRM , timeout_handler ) signal . alarm ( limit ) try : res = f ( * args , ** kwargs ) except Timeout : handler ( limit , f , args , kwargs ) e...
A decorator ensuring that the decorated function tun time does not exceeds the argument limit .
2,812
def _process_backend_kwargs ( self , kwargs ) : app = self . _vispy_canvas . app capability = app . backend_module . capability if kwargs [ 'context' ] . shared . name : if not capability [ 'context' ] : raise RuntimeError ( 'Cannot share context with this backend' ) for key in [ key for ( key , val ) in capability . i...
Simple utility to retrieve kwargs in predetermined order . Also checks whether the values of the backend arguments do not violate the backend capabilities .
2,813
def viewbox_key_event ( self , event ) : PerspectiveCamera . viewbox_key_event ( self , event ) if event . handled or not self . interactive : return if not self . _timer . running : self . _timer . start ( ) if event . key in self . _keymap : val_dims = self . _keymap [ event . key ] val = val_dims [ 0 ] if val == 0 :...
ViewBox key event handler
2,814
def set_inputhook ( self , callback ) : ignore_CTRL_C ( ) self . _callback = callback self . _callback_pyfunctype = self . PYFUNC ( callback ) pyos_inputhook_ptr = self . get_pyos_inputhook ( ) original = self . get_pyos_inputhook_as_func ( ) pyos_inputhook_ptr . value = ctypes . cast ( self . _callback_pyfunctype , ct...
Set PyOS_InputHook to callback and return the previous one .
2,815
def clear_inputhook ( self , app = None ) : pyos_inputhook_ptr = self . get_pyos_inputhook ( ) original = self . get_pyos_inputhook_as_func ( ) pyos_inputhook_ptr . value = ctypes . c_void_p ( None ) . value allow_CTRL_C ( ) self . _reset ( ) return original
Set PyOS_InputHook to NULL and return the previous one .
2,816
def set_current_canvas ( canvas ) : canvas . context . _do_CURRENT_command = True if canvasses and canvasses [ - 1 ] ( ) is canvas : return cc = [ c ( ) for c in canvasses if c ( ) is not None ] while canvas in cc : cc . remove ( canvas ) cc . append ( canvas ) canvasses [ : ] = [ weakref . ref ( c ) for c in cc ]
Make a canvas active . Used primarily by the canvas itself .
2,817
def forget_canvas ( canvas ) : cc = [ c ( ) for c in canvasses if c ( ) is not None ] while canvas in cc : cc . remove ( canvas ) canvasses [ : ] = [ weakref . ref ( c ) for c in cc ]
Forget about the given canvas . Used by the canvas when closed .
2,818
def create_shared ( self , name , ref ) : if self . _shared is not None : raise RuntimeError ( 'Can only set_shared once.' ) self . _shared = GLShared ( name , ref )
For the app backends to create the GLShared object .
2,819
def add_ref ( self , name , ref ) : if self . _name is None : self . _name = name elif name != self . _name : raise RuntimeError ( 'Contexts can only share between backends of ' 'the same type' ) self . _refs . append ( weakref . ref ( ref ) )
Add a reference for the backend object that gives access to the low level context . Used in vispy . app . canvas . backends . The given name must match with that of previously added references .
2,820
def obj ( x ) : j = np . arange ( 1 , 6 ) tmp1 = np . dot ( j , np . cos ( ( j + 1 ) * x [ 0 ] + j ) ) tmp2 = np . dot ( j , np . cos ( ( j + 1 ) * x [ 1 ] + j ) ) return tmp1 * tmp2
Two Dimensional Shubert Function
2,821
def copy ( self ) : return Quaternion ( self . w , self . x , self . y , self . z , False )
Create an exact copy of this quaternion .
2,822
def _normalize ( self ) : L = self . norm ( ) if not L : raise ValueError ( 'Quaternion cannot have 0-length.' ) self . w /= L self . x /= L self . y /= L self . z /= L
Make the quaternion unit length .
2,823
def rotate_point ( self , p ) : p = Quaternion ( 0 , p [ 0 ] , p [ 1 ] , p [ 2 ] , False ) q1 = self . normalize ( ) q2 = self . inverse ( ) r = ( q1 * p ) * q2 return r . x , r . y , r . z
Rotate a Point instance using this quaternion .
2,824
def get_matrix ( self ) : a = np . zeros ( ( 4 , 4 ) , dtype = np . float32 ) w , x , y , z = self . w , self . x , self . y , self . z a [ 0 , 0 ] = - 2.0 * ( y * y + z * z ) + 1.0 a [ 1 , 0 ] = + 2.0 * ( x * y + z * w ) a [ 2 , 0 ] = + 2.0 * ( x * z - y * w ) a [ 3 , 0 ] = 0.0 a [ 0 , 1 ] = + 2.0 * ( x * y - z * w ) ...
Create a 4x4 homography matrix that represents the rotation of the quaternion .
2,825
def create_from_euler_angles ( cls , rx , ry , rz , degrees = False ) : if degrees : rx , ry , rz = np . radians ( [ rx , ry , rz ] ) qx = Quaternion ( np . cos ( rx / 2 ) , 0 , 0 , np . sin ( rx / 2 ) ) qy = Quaternion ( np . cos ( ry / 2 ) , 0 , np . sin ( ry / 2 ) , 0 ) qz = Quaternion ( np . cos ( rz / 2 ) , np . s...
Classmethod to create a quaternion given the euler angles .
2,826
def as_enum ( enum ) : if isinstance ( enum , string_types ) : try : enum = getattr ( gl , 'GL_' + enum . upper ( ) ) except AttributeError : try : enum = _internalformats [ 'GL_' + enum . upper ( ) ] except KeyError : raise ValueError ( 'Could not find int value for enum %r' % enum ) return enum
Turn a possibly string enum into an integer enum .
2,827
def convert_shaders ( convert , shaders ) : out = [ ] if convert == 'es2' : for isfragment , shader in enumerate ( shaders ) : has_version = False has_prec_float = False has_prec_int = False lines = [ ] for line in shader . lstrip ( ) . splitlines ( ) : if line . startswith ( '#version' ) : has_version = True continue ...
Modify shading code so that we can write code once and make it run everywhere .
2,828
def as_es2_command ( command ) : if command [ 0 ] == 'FUNC' : return ( command [ 0 ] , re . sub ( r'^gl([A-Z])' , lambda m : m . group ( 1 ) . lower ( ) , command [ 1 ] ) ) + command [ 2 : ] if command [ 0 ] == 'SHADERS' : return command [ : 2 ] + convert_shaders ( 'es2' , command [ 2 : ] ) if command [ 0 ] == 'UNIFORM...
Modify a desktop command so it works on es2 .
2,829
def show ( self , filter = None ) : for command in self . _commands : if command [ 0 ] is None : continue if filter and command [ 0 ] != filter : continue t = [ ] for e in command : if isinstance ( e , np . ndarray ) : t . append ( 'array %s' % str ( e . shape ) ) elif isinstance ( e , str ) : s = e . strip ( ) if len ...
Print the list of commands currently in the queue . If filter is given print only commands that match the filter .
2,830
def flush ( self , parser ) : if self . _verbose : show = self . _verbose if isinstance ( self . _verbose , str ) else None self . show ( show ) parser . parse ( self . _filter ( self . clear ( ) , parser ) )
Flush all current commands to the GLIR interpreter .
2,831
def associate ( self , queue ) : assert isinstance ( queue , GlirQueue ) if queue . _shared is self . _shared : return self . _shared . _commands . extend ( queue . clear ( ) ) self . _shared . _verbose |= queue . _shared . _verbose self . _shared . _associations [ queue ] = None for ch in queue . _shared . _associatio...
Merge this queue with another .
2,832
def _parse ( self , command ) : cmd , id_ , args = command [ 0 ] , command [ 1 ] , command [ 2 : ] if cmd == 'CURRENT' : self . env . clear ( ) self . _gl_initialize ( ) self . env [ 'fbo' ] = args [ 0 ] gl . glBindFramebuffer ( gl . GL_FRAMEBUFFER , args [ 0 ] ) elif cmd == 'FUNC' : args = [ as_enum ( a ) for a in arg...
Parse a single command .
2,833
def parse ( self , commands ) : to_delete = [ ] for id_ , val in self . _objects . items ( ) : if val == JUST_DELETED : to_delete . append ( id_ ) for id_ in to_delete : self . _objects . pop ( id_ ) for command in commands : self . _parse ( command )
Parse a list of commands .
2,834
def _gl_initialize ( self ) : if '.es' in gl . current_backend . __name__ : pass else : GL_VERTEX_PROGRAM_POINT_SIZE = 34370 GL_POINT_SPRITE = 34913 gl . glEnable ( GL_VERTEX_PROGRAM_POINT_SIZE ) gl . glEnable ( GL_POINT_SPRITE ) if self . capabilities [ 'max_texture_size' ] is None : self . capabilities [ 'gl_version'...
Deal with compatibility ; desktop does not have sprites enabled by default . ES has .
2,835
def set_shaders ( self , vert , frag ) : self . _linked = False vert_handle = gl . glCreateShader ( gl . GL_VERTEX_SHADER ) frag_handle = gl . glCreateShader ( gl . GL_FRAGMENT_SHADER ) for code , handle , type_ in [ ( vert , vert_handle , 'vertex' ) , ( frag , frag_handle , 'fragment' ) ] : gl . glShaderSource ( handl...
This function takes care of setting the shading code and compiling + linking it into a working program object that is ready to use .
2,836
def _parse_error ( self , error ) : error = str ( error ) m = re . match ( r'(\d+)\((\d+)\)\s*:\s(.*)' , error ) if m : return int ( m . group ( 2 ) ) , m . group ( 3 ) m = re . match ( r'ERROR:\s(\d+):(\d+):\s(.*)' , error ) if m : return int ( m . group ( 2 ) ) , m . group ( 3 ) m = re . match ( r'(\d+):(\d+)\((\d+)\...
Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this .
2,837
def _get_error ( self , code , errors , indentation = 0 ) : results = [ ] lines = None if code is not None : lines = [ line . strip ( ) for line in code . split ( '\n' ) ] for error in errors . split ( '\n' ) : error = error . strip ( ) if not error : continue linenr , error = self . _parse_error ( error ) if None in (...
Get error and show the faulty line + some context Other GLIR implementations may omit this .
2,838
def set_texture ( self , name , value ) : if not self . _linked : raise RuntimeError ( 'Cannot set uniform when program has no code' ) handle = self . _handles . get ( name , - 1 ) if handle < 0 : if name in self . _known_invalid : return handle = gl . glGetUniformLocation ( self . _handle , name ) self . _unset_variab...
Set a texture sampler . Value is the id of the texture to link .
2,839
def set_uniform ( self , name , type_ , value ) : if not self . _linked : raise RuntimeError ( 'Cannot set uniform when program has no code' ) handle = self . _handles . get ( name , - 1 ) count = 1 if handle < 0 : if name in self . _known_invalid : return handle = gl . glGetUniformLocation ( self . _handle , name ) se...
Set a uniform value . Value is assumed to have been checked .
2,840
def set_attribute ( self , name , type_ , value ) : if not self . _linked : raise RuntimeError ( 'Cannot set attribute when program has no code' ) handle = self . _handles . get ( name , - 1 ) if handle < 0 : if name in self . _known_invalid : return handle = gl . glGetAttribLocation ( self . _handle , name ) self . _u...
Set an attribute value . Value is assumed to have been checked .
2,841
def as_matrix_transform ( transform ) : if isinstance ( transform , ChainTransform ) : matrix = np . identity ( 4 ) for tr in transform . transforms : matrix = np . matmul ( as_matrix_transform ( tr ) . matrix , matrix ) return MatrixTransform ( matrix ) elif isinstance ( transform , InverseTransform ) : matrix = as_ma...
Simplify a transform to a single matrix transform which makes it a lot faster to compute transformations .
2,842
def circular ( adjacency_mat , directed = False ) : if issparse ( adjacency_mat ) : adjacency_mat = adjacency_mat . tocoo ( ) num_nodes = adjacency_mat . shape [ 0 ] t = np . linspace ( 0 , 2 * np . pi , num_nodes , endpoint = False , dtype = np . float32 ) node_coords = ( 0.5 * np . array ( [ np . cos ( t ) , np . sin...
Places all nodes on a single circle .
2,843
def set_data ( self , pos = None , symbol = 'o' , size = 10. , edge_width = 1. , edge_width_rel = None , edge_color = 'black' , face_color = 'white' , scaling = False ) : assert ( isinstance ( pos , np . ndarray ) and pos . ndim == 2 and pos . shape [ 1 ] in ( 2 , 3 ) ) if ( edge_width is not None ) + ( edge_width_rel ...
Set the data used to display this visual .
2,844
def hook_changed ( self , hook_name , widget , new_data ) : if hook_name == 'song' : self . song_changed ( widget , new_data ) elif hook_name == 'state' : self . state_changed ( widget , new_data ) elif hook_name == 'elapsed_and_total' : elapsed , total = new_data self . time_changed ( widget , elapsed , total )
Handle a hook upate .
2,845
def update ( self , func , ** kw ) : "Update the signature of func with the data in self" func . __name__ = self . name func . __doc__ = getattr ( self , 'doc' , None ) func . __dict__ = getattr ( self , 'dict' , { } ) func . __defaults__ = getattr ( self , 'defaults' , ( ) ) func . __kwdefaults__ = getattr ( self , 'k...
Update the signature of func with the data in self
2,846
def make ( self , src_templ , evaldict = None , addsource = False , ** attrs ) : "Make a new function from a given template and update the signature" src = src_templ % vars ( self ) evaldict = evaldict or { } mo = DEF . match ( src ) if mo is None : raise SyntaxError ( 'not a valid function template\n%s' % src ) name =...
Make a new function from a given template and update the signature
2,847
def get_scene_bounds ( self , dim = None ) : bounds = [ ( np . inf , - np . inf ) , ( np . inf , - np . inf ) , ( np . inf , - np . inf ) ] for ob in self . scene . children : if hasattr ( ob , 'bounds' ) : for axis in ( 0 , 1 , 2 ) : if ( dim is not None ) and dim != axis : continue b = ob . bounds ( axis ) if b is no...
Get the total bounds based on the visuals present in the scene
2,848
def _array_clip_val ( val ) : val = np . array ( val ) if val . max ( ) > 1 or val . min ( ) < 0 : logger . warning ( 'value will be clipped between 0 and 1' ) val [ ... ] = np . clip ( val , 0 , 1 ) return val
Helper to turn val into array and clip between 0 and 1
2,849
def extend ( self , colors ) : colors = ColorArray ( colors ) self . _rgba = np . vstack ( ( self . _rgba , colors . _rgba ) ) return self
Extend a ColorArray with new colors
2,850
def rgba ( self , val ) : rgba = _user_to_rgba ( val , expand = False ) if self . _rgba is None : self . _rgba = rgba else : self . _rgba [ : , : rgba . shape [ 1 ] ] = rgba
Set the color using an Nx4 array of RGBA floats
2,851
def RGBA ( self , val ) : val = np . atleast_1d ( val ) . astype ( np . float32 ) / 255 self . rgba = val
Set the color using an Nx4 array of RGBA uint8 values
2,852
def RGB ( self , val ) : val = np . atleast_1d ( val ) . astype ( np . float32 ) / 255. self . rgba = val
Set the color using an Nx3 array of RGB uint8 values
2,853
def viewbox_mouse_event ( self , event ) : BaseCamera . viewbox_mouse_event ( self , event ) if event . type == 'mouse_wheel' : s = 1.1 ** - event . delta [ 1 ] self . _scale_factor *= s if self . _distance is not None : self . _distance *= s self . view_changed ( )
The ViewBox received a mouse event ; update transform accordingly . Default implementation adjusts scale factor when scolling .
2,854
def _set_range ( self , init ) : if init and ( self . _scale_factor is not None ) : return w , h = self . _viewbox . size w , h = float ( w ) , float ( h ) x1 , y1 , z1 = self . _xlim [ 0 ] , self . _ylim [ 0 ] , self . _zlim [ 0 ] x2 , y2 , z2 = self . _xlim [ 1 ] , self . _ylim [ 1 ] , self . _zlim [ 1 ] rx , ry , rz...
Reset the camera view using the known limits .
2,855
def viewbox_mouse_event ( self , event ) : if event . handled or not self . interactive : return PerspectiveCamera . viewbox_mouse_event ( self , event ) if event . type == 'mouse_release' : self . _event_value = None elif event . type == 'mouse_press' : event . handled = True elif event . type == 'mouse_move' : if eve...
The viewbox received a mouse event ; update transform accordingly .
2,856
def _update_camera_pos ( self ) : ch_em = self . events . transform_change with ch_em . blocker ( self . _update_transform ) : tr = self . transform tr . reset ( ) up , forward , right = self . _get_dim_vectors ( ) pp1 = np . array ( [ ( 0 , 0 , 0 ) , ( 0 , 0 , - 1 ) , ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) ] ) pp2 = np . array...
Set the camera position and orientation
2,857
def is_interactive ( self ) : if sys . flags . interactive : return True if '__IPYTHON__' not in dir ( six . moves . builtins ) : return False try : from IPython . config . application import Application as App return App . initialized ( ) and App . instance ( ) . interact except ( ImportError , AttributeError ) : retu...
Determine if the user requested interactive mode .
2,858
def run ( self , allow_interactive = True ) : if allow_interactive and self . is_interactive ( ) : inputhook . set_interactive ( enabled = True , app = self ) else : return self . _backend . _vispy_run ( )
Enter the native GUI event loop .
2,859
def _use ( self , backend_name = None ) : test_name = os . getenv ( '_VISPY_TESTING_APP' , None ) if backend_name is not None : if backend_name . lower ( ) == 'default' : backend_name = None elif backend_name . lower ( ) not in BACKENDMAP : raise ValueError ( 'backend_name must be one of %s or None, not ' '%r' % ( BACK...
Select a backend by name . See class docstring for details .
2,860
def _get_mods ( evt ) : mods = [ ] mods += [ keys . CONTROL ] if evt . ControlDown ( ) else [ ] mods += [ keys . ALT ] if evt . AltDown ( ) else [ ] mods += [ keys . SHIFT ] if evt . ShiftDown ( ) else [ ] mods += [ keys . META ] if evt . MetaDown ( ) else [ ] return mods
Helper to extract list of mods from event
2,861
def _process_key ( evt ) : key = evt . GetKeyCode ( ) if key in KEYMAP : return KEYMAP [ key ] , '' if 97 <= key <= 122 : key -= 32 if key >= 32 and key <= 127 : return keys . Key ( chr ( key ) ) , chr ( key ) else : return None , None
Helper to convert from wx keycode to vispy keycode
2,862
def is_child ( self , node ) : if node in self . children : return True for c in self . children : if c . is_child ( node ) : return True return False
Check if a node is a child of the current node
2,863
def scene_node ( self ) : if self . _scene_node is None : from . subscene import SubScene p = self . parent while True : if isinstance ( p , SubScene ) or p is None : self . _scene_node = p break p = p . parent if self . _scene_node is None : self . _scene_node = self return self . _scene_node
The first ancestor of this node that is a SubScene instance or self if no such node exists .
2,864
def update ( self ) : self . events . update ( ) c = getattr ( self , 'canvas' , None ) if c is not None : c . update ( node = self )
Emit an event to inform listeners that properties of this Node have changed . Also request a canvas update .
2,865
def parent_chain ( self ) : chain = [ self ] while True : try : parent = chain [ - 1 ] . parent except Exception : break if parent is None : break chain . append ( parent ) return chain
Return the list of parents starting from this node . The chain ends at the first node with no parents .
2,866
def _describe_tree ( self , prefix , with_transform ) : extra = ': "%s"' % self . name if self . name is not None else '' if with_transform : extra += ( ' [%s]' % self . transform . __class__ . __name__ ) output = '' if len ( prefix ) > 0 : output += prefix [ : - 3 ] output += ' +--' output += '%s%s\n' % ( self . __cl...
Helper function to actuall construct the tree
2,867
def common_parent ( self , node ) : p1 = self . parent_chain ( ) p2 = node . parent_chain ( ) for p in p1 : if p in p2 : return p return None
Return the common parent of two entities
2,868
def node_path_to_child ( self , node ) : if node is self : return [ ] path1 = [ node ] child = node while child . parent is not None : child = child . parent path1 . append ( child ) if child is self : return list ( reversed ( path1 ) ) if path1 [ - 1 ] . parent is None : raise RuntimeError ( '%r is not a child of %r' ...
Return a list describing the path from this node to a child node
2,869
def node_path ( self , node ) : p1 = self . parent_chain ( ) p2 = node . parent_chain ( ) cp = None for p in p1 : if p in p2 : cp = p break if cp is None : raise RuntimeError ( "No single-path common parent between nodes %s " "and %s." % ( self , node ) ) p1 = p1 [ : p1 . index ( cp ) + 1 ] p2 = p2 [ : p2 . index ( cp ...
Return two lists describing the path from this node to another
2,870
def node_path_transforms ( self , node ) : a , b = self . node_path ( node ) return ( [ n . transform for n in a [ : - 1 ] ] + [ n . transform . inverse for n in b ] ) [ : : - 1 ]
Return the list of transforms along the path to another node . The transforms are listed in reverse order such that the last transform should be applied first when mapping from this node to the other .
2,871
def readLine ( self ) : line = self . _f . readline ( ) . decode ( 'ascii' , 'ignore' ) if not line : raise EOFError ( ) line = line . strip ( ) if line . startswith ( 'v ' ) : self . _v . append ( self . readTuple ( line ) ) elif line . startswith ( 'vt ' ) : self . _vt . append ( self . readTuple ( line , 3 ) ) elif ...
The method that reads a line and processes it .
2,872
def finish ( self ) : self . _vertices = np . array ( self . _vertices , 'float32' ) if self . _faces : self . _faces = np . array ( self . _faces , 'uint32' ) else : self . _vertices = np . array ( self . _v , 'float32' ) self . _faces = None if self . _normals : self . _normals = np . array ( self . _normals , 'float...
Converts gathere lists to numpy arrays and creates BaseMesh instance .
2,873
def write ( cls , fname , vertices , faces , normals , texcoords , name = '' , reshape_faces = True ) : fmt = op . splitext ( fname ) [ 1 ] . lower ( ) if fmt not in ( '.obj' , '.gz' ) : raise ValueError ( 'Filename must end with .obj or .gz, not "%s"' % ( fmt , ) ) opener = open if fmt == '.obj' else gzip_open f = ope...
This classmethod is the entry point for writing mesh data to OBJ .
2,874
def writeFace ( self , val , what = 'f' ) : val = [ v + 1 for v in val ] if self . _hasValues and self . _hasNormals : val = ' ' . join ( [ '%i/%i/%i' % ( v , v , v ) for v in val ] ) elif self . _hasNormals : val = ' ' . join ( [ '%i//%i' % ( v , v ) for v in val ] ) elif self . _hasValues : val = ' ' . join ( [ '%i/%...
Write the face info to the net line .
2,875
def writeMesh ( self , vertices , faces , normals , values , name = '' , reshape_faces = True ) : self . _hasNormals = normals is not None self . _hasValues = values is not None self . _hasFaces = faces is not None if faces is None : faces = np . arange ( len ( vertices ) ) reshape_faces = True if reshape_faces : Nface...
Write the given mesh instance .
2,876
def _fast_cross_3d ( x , y ) : assert x . ndim == 2 assert y . ndim == 2 assert x . shape [ 1 ] == 3 assert y . shape [ 1 ] == 3 assert ( x . shape [ 0 ] == 1 or y . shape [ 0 ] == 1 ) or x . shape [ 0 ] == y . shape [ 0 ] if max ( [ x . shape [ 0 ] , y . shape [ 0 ] ] ) >= 500 : return np . c_ [ x [ : , 1 ] * y [ : , ...
Compute cross product between list of 3D vectors
2,877
def _calculate_normals ( rr , tris ) : rr = rr . astype ( np . float64 ) r1 = rr [ tris [ : , 0 ] , : ] r2 = rr [ tris [ : , 1 ] , : ] r3 = rr [ tris [ : , 2 ] , : ] tri_nn = _fast_cross_3d ( ( r2 - r1 ) , ( r3 - r1 ) ) size = np . sqrt ( np . sum ( tri_nn * tri_nn , axis = 1 ) ) size [ size == 0 ] = 1.0 tri_nn /= size...
Efficiently compute vertex normals for triangulated surface
2,878
def parse ( self ) : for line in self . lines : field_defs = self . parse_line ( line ) fields = [ ] for ( kind , options ) in field_defs : logger . debug ( "Creating field %s(%r)" , kind , options ) fields . append ( self . field_registry . create ( kind , ** options ) ) self . line_fields . append ( fields ) for fiel...
Parse the lines and fill self . line_fields accordingly .
2,879
def compute_positions ( cls , screen_width , line ) : left = 1 right = screen_width + 1 flexible = None for field in line : if field . is_flexible ( ) : if flexible : raise FormatError ( 'There can be only one flexible field per line.' ) flexible = field elif not flexible : left += field . width else : right -= field ....
Compute the relative position of the fields on a given line .
2,880
def add_to_screen ( self , screen_width , screen ) : for lineno , fields in enumerate ( self . line_fields ) : for left , field in self . compute_positions ( screen_width , fields ) : logger . debug ( "Adding field %s to screen %s at x=%d->%d, y=%d" , field , screen . ref , left , left + field . width - 1 , 1 + lineno ...
Add the pattern to a screen .
2,881
def register_hooks ( self , field ) : for hook , subhooks in field . register_hooks ( ) : self . hooks [ hook ] . append ( field ) self . subhooks [ hook ] |= set ( subhooks )
Register a field on its target hooks .
2,882
def hook_changed ( self , hook , new_data ) : for field in self . hooks [ hook ] : widget = self . widgets [ field ] field . hook_changed ( hook , widget , new_data )
Called whenever the data for a hook changed .
2,883
def add ( self , pattern_txt ) : self . patterns [ len ( pattern_txt ) ] = pattern_txt low = 0 high = len ( pattern_txt ) - 1 while not pattern_txt [ low ] : low += 1 while not pattern_txt [ high ] : high -= 1 min_pattern = pattern_txt [ low : high + 1 ] self . min_patterns [ len ( min_pattern ) ] = min_pattern
Add a pattern to the list .
2,884
def _arcball ( xy , wh ) : x , y = xy w , h = wh r = ( w + h ) / 2. x , y = - ( 2. * x - w ) / r , ( 2. * y - h ) / r h = np . sqrt ( x * x + y * y ) return ( 0. , x / h , y / h , 0. ) if h > 1. else ( 0. , x , y , np . sqrt ( 1. - h * h ) )
Convert x y coordinates to w x y z Quaternion parameters
2,885
def arg_to_array ( func ) : def fn ( self , arg , * args , ** kwargs ) : return func ( self , np . array ( arg ) , * args , ** kwargs ) return fn
Decorator to convert argument to array .
2,886
def arg_to_vec4 ( func , self_ , arg , * args , ** kwargs ) : if isinstance ( arg , ( tuple , list , np . ndarray ) ) : arg = np . array ( arg ) flatten = arg . ndim == 1 arg = as_vec4 ( arg ) ret = func ( self_ , arg , * args , ** kwargs ) if flatten and ret is not None : return ret . flatten ( ) return ret elif hasat...
Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication .
2,887
def roll ( self ) : rem = [ ] for key , item in self . _cache . items ( ) : if item [ 0 ] > self . max_age : rem . append ( key ) item [ 0 ] += 1 for key in rem : logger . debug ( "TransformCache remove: %s" , key ) del self . _cache [ key ]
Increase the age of all items in the cache by 1 . Items whose age is greater than self . max_age will be removed from the cache .
2,888
def histogram ( self , data , bins = 10 , color = 'w' , orientation = 'h' ) : self . _configure_2d ( ) hist = scene . Histogram ( data , bins , color , orientation ) self . view . add ( hist ) self . view . camera . set_range ( ) return hist
Calculate and show a histogram of data
2,889
def image ( self , data , cmap = 'cubehelix' , clim = 'auto' , fg_color = None ) : self . _configure_2d ( fg_color ) image = scene . Image ( data , cmap = cmap , clim = clim ) self . view . add ( image ) self . view . camera . aspect = 1 self . view . camera . set_range ( ) return image
Show an image
2,890
def mesh ( self , vertices = None , faces = None , vertex_colors = None , face_colors = None , color = ( 0.5 , 0.5 , 1. ) , fname = None , meshdata = None ) : self . _configure_3d ( ) if fname is not None : if not all ( x is None for x in ( vertices , faces , meshdata ) ) : raise ValueError ( 'vertices, faces, and mesh...
Show a 3D mesh
2,891
def plot ( self , data , color = 'k' , symbol = None , line_kind = '-' , width = 1. , marker_size = 10. , edge_color = 'k' , face_color = 'b' , edge_width = 1. , title = None , xlabel = None , ylabel = None ) : self . _configure_2d ( ) line = scene . LinePlot ( data , connect = 'strip' , color = color , symbol = symbol...
Plot a series of data using lines and markers
2,892
def spectrogram ( self , x , n_fft = 256 , step = None , fs = 1. , window = 'hann' , color_scale = 'log' , cmap = 'cubehelix' , clim = 'auto' ) : self . _configure_2d ( ) spec = scene . Spectrogram ( x , n_fft , step , fs , window , color_scale , cmap , clim ) self . view . add ( spec ) self . view . camera . set_range...
Calculate and show a spectrogram
2,893
def volume ( self , vol , clim = None , method = 'mip' , threshold = None , cmap = 'grays' ) : self . _configure_3d ( ) volume = scene . Volume ( vol , clim , method , threshold , cmap = cmap ) self . view . add ( volume ) self . view . camera . set_range ( ) return volume
Show a 3D volume
2,894
def surface ( self , zdata , ** kwargs ) : self . _configure_3d ( ) surf = scene . SurfacePlot ( z = zdata , ** kwargs ) self . view . add ( surf ) self . view . camera . set_range ( ) return surf
Show a 3D surface plot .
2,895
def colorbar ( self , cmap , position = "right" , label = "" , clim = ( "" , "" ) , border_width = 0.0 , border_color = "black" , ** kwargs ) : self . _configure_2d ( ) cbar = scene . ColorBarWidget ( orientation = position , label_str = label , cmap = cmap , clim = clim , border_width = border_width , border_color = b...
Show a ColorBar
2,896
def redraw ( self ) : if self . _multiscat is not None : self . _multiscat . _update ( ) self . vispy_widget . canvas . update ( )
Redraw the Vispy canvas
2,897
def remove ( self ) : if self . _multiscat is None : return self . _multiscat . deallocate ( self . id ) self . _multiscat = None self . _viewer_state . remove_global_callback ( self . _update_scatter ) self . state . remove_global_callback ( self . _update_scatter )
Remove the layer artist from the visualization
2,898
def _check_valid ( key , val , valid ) : if val not in valid : raise ValueError ( '%s must be one of %s, not "%s"' % ( key , valid , val ) )
Helper to check valid options
2,899
def _to_args ( x ) : if not isinstance ( x , ( list , tuple , np . ndarray ) ) : x = [ x ] return x
Convert to args representation