INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Draw random emitted photons from Poisson ( emission_rates ).
def sim_timetrace(emission, max_rate, t_step): """Draw random emitted photons from Poisson(emission_rates). """ emission_rates = emission * max_rate * t_step return np.random.poisson(lam=emission_rates).astype(np.uint8)
Draw random emitted photons from r. v. ~ Poisson ( emission_rates ).
def sim_timetrace_bg(emission, max_rate, bg_rate, t_step, rs=None): """Draw random emitted photons from r.v. ~ Poisson(emission_rates). Arguments: emission (2D array): array of normalized emission rates. One row per particle (axis = 0). Columns are the different time steps. max_rate...
Draw random emitted photons from r. v. ~ Poisson ( emission_rates ).
def sim_timetrace_bg2(emission, max_rate, bg_rate, t_step, rs=None): """Draw random emitted photons from r.v. ~ Poisson(emission_rates). This is an alternative implementation of :func:`sim_timetrace_bg`. """ if rs is None: rs = np.random.RandomState() emiss_bin_rate = np.zeros((emission.sha...
Box volume in m^3.
def volume(self): """Box volume in m^3.""" return (self.x2 - self.x1) * (self.y2 - self.y1) * (self.z2 - self.z1)
Generate a list of Particle objects.
def _generate(num_particles, D, box, rs): """Generate a list of `Particle` objects.""" X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1 Y0 = rs.rand(num_particles) * (box.y2 - box.y1) + box.y1 Z0 = rs.rand(num_particles) * (box.z2 - box.z1) + box.z1 return [Particle(D=D, ...
Add particles with diffusion coefficient D at random positions.
def add(self, num_particles, D): """Add particles with diffusion coefficient `D` at random positions. """ self._plist += self._generate(num_particles, D, box=self.box, rs=self.rs)
Initial position for each particle. Shape ( N 3 1 ).
def positions(self): """Initial position for each particle. Shape (N, 3, 1).""" return np.vstack([p.r0 for p in self]).reshape(len(self), 3, 1)
List of tuples of ( diffusion coefficient counts ) pairs.
def diffusion_coeff_counts(self): """List of tuples of (diffusion coefficient, counts) pairs. The order of the diffusion coefficients is as in self.diffusion_coeff. """ return [(key, len(list(group))) for key, group in itertools.groupby(self.diffusion_coeff)]
Return pathlib. Path for a data - file with given hash and prefix.
def datafile_from_hash(hash_, prefix, path): """Return pathlib.Path for a data-file with given hash and prefix. """ pattern = '%s_%s*.h*' % (prefix, hash_) datafiles = list(path.glob(pattern)) if len(datafiles) == 0: raise NoMatchError('No matches for "%s"' % pattern)...
Load simulation from disk trajectories and ( when present ) timestamps.
def from_datafile(hash_, path='./', ignore_timestamps=False, mode='r'): """Load simulation from disk trajectories and (when present) timestamps. """ path = Path(path) assert path.exists() file_traj = ParticlesSimulation.datafile_from_hash( hash_, prefix=ParticlesSimu...
Return a RandomState equal to the input unless rs is None.
def _get_group_randomstate(rs, seed, group): """Return a RandomState, equal to the input unless rs is None. When rs is None, try to get the random state from the 'last_random_state' attribute in `group`. When not available, use `seed` to generate a random state. When seed is None the re...
Return an hash for the simulation parameters ( excluding ID and EID ) This can be used to generate unique file names for simulations that have the same parameters and just different ID or EID.
def hash(self): """Return an hash for the simulation parameters (excluding ID and EID) This can be used to generate unique file names for simulations that have the same parameters and just different ID or EID. """ hash_numeric = 't_step=%.3e, t_max=%.2f, np=%d, conc=%.2e' % \ ...
Compact representation of simulation params ( no ID EID and t_max )
def compact_name_core(self, hashsize=6, t_max=False): """Compact representation of simulation params (no ID, EID and t_max) """ Moles = self.concentration() name = "%s_%dpM_step%.1fus" % ( self.particles.short_repr(), Moles * 1e12, self.t_step * 1e6) if hashsize > 0: ...
Compact representation of all simulation parameters
def compact_name(self, hashsize=6): """Compact representation of all simulation parameters """ # this can be made more robust for ID > 9 (double digit) s = self.compact_name_core(hashsize, t_max=True) s += "_ID%d-%d" % (self.ID, self.EID) return s
A dict containing all the simulation numeric - parameters.
def numeric_params(self): """A dict containing all the simulation numeric-parameters. The values are 2-element tuples: first element is the value and second element is a string describing the parameter (metadata). """ nparams = dict( D = (self.diffusion_coeff.mean(),...
Print on - disk array sizes required for current set of parameters.
def print_sizes(self): """Print on-disk array sizes required for current set of parameters.""" float_size = 4 MB = 1024 * 1024 size_ = self.n_samples * float_size em_size = size_ * self.num_particles / MB pos_size = 3 * size_ * self.num_particles / MB print(" Num...
Return the concentration ( in Moles ) of the particles in the box.
def concentration(self, pM=False): """Return the concentration (in Moles) of the particles in the box. """ concentr = (self.num_particles / NA) / self.box.volume_L if pM: concentr *= 1e12 return concentr
Simulate ( in - memory ) time_size steps of trajectories.
def _sim_trajectories(self, time_size, start_pos, rs, total_emission=False, save_pos=False, radial=False, wrap_func=wrap_periodic): """Simulate (in-memory) `time_size` steps of trajectories. Simulate Brownian motion diffusion and emission of all the p...
Simulate Brownian motion trajectories and emission rates.
def simulate_diffusion(self, save_pos=False, total_emission=True, radial=False, rs=None, seed=1, path='./', wrap_func=wrap_periodic, chunksize=2**19, chunkslice='times', verbose=True): """Simulate Brownian motion trajectories and e...
Return matching ( timestamps particles ) pytables arrays.
def get_timestamps_part(self, name): """Return matching (timestamps, particles) pytables arrays. """ par_name = name + '_par' timestamps = self.ts_store.h5file.get_node('/timestamps', name) particles = self.ts_store.h5file.get_node('/timestamps', par_name) return timestam...
Simulate timestamps from emission trajectories.
def _sim_timestamps(self, max_rate, bg_rate, emission, i_start, rs, ip_start=0, scale=10, sort=True): """Simulate timestamps from emission trajectories. Uses attributes: `.t_step`. Returns: A tuple of two arrays: timestamps and particles. """ ...
Compute one timestamps array for a mixture of N populations.
def simulate_timestamps_mix(self, max_rates, populations, bg_rate, rs=None, seed=1, chunksize=2**16, comp_filter=None, overwrite=False, skip_existing=False, scale=10, path=None, t_chunksize=No...
Compute D and A timestamps arrays for a mixture of N populations.
def simulate_timestamps_mix_da(self, max_rates_d, max_rates_a, populations, bg_rate_d, bg_rate_a, rs=None, seed=1, chunksize=2**16, comp_filter=None, overwrite=False, skip_existing...
Merge donor and acceptor timestamps and particle arrays.
def merge_da(ts_d, ts_par_d, ts_a, ts_par_a): """Merge donor and acceptor timestamps and particle arrays. Parameters: ts_d (array): donor timestamp array ts_par_d (array): donor particles array ts_a (array): acceptor timestamp array ts_par_a (array): acceptor particles array ...
Donor and Acceptor emission rates from total emission rate and E ( FRET ).
def em_rates_from_E_DA(em_rate_tot, E_values): """Donor and Acceptor emission rates from total emission rate and E (FRET). """ E_values = np.asarray(E_values) em_rates_a = E_values * em_rate_tot em_rates_d = em_rate_tot - em_rates_a return em_rates_d, em_rates_a
Array of unique emission rates for given total emission and E ( FRET ).
def em_rates_from_E_unique(em_rate_tot, E_values): """Array of unique emission rates for given total emission and E (FRET). """ em_rates_d, em_rates_a = em_rates_from_E_DA(em_rate_tot, E_values) return np.unique(np.hstack([em_rates_d, em_rates_a]))
D and A emission rates for two populations.
def em_rates_from_E_DA_mix(em_rates_tot, E_values): """D and A emission rates for two populations. """ em_rates_d, em_rates_a = [], [] for em_rate_tot, E_value in zip(em_rates_tot, E_values): em_rate_di, em_rate_ai = em_rates_from_E_DA(em_rate_tot, E_value) em_rates_d.append(em_rate_di) ...
Diffusion coefficients of the two specified populations.
def populations_diff_coeff(particles, populations): """Diffusion coefficients of the two specified populations. """ D_counts = particles.diffusion_coeff_counts if len(D_counts) == 1: pop_sizes = [pop.stop - pop.start for pop in populations] assert D_counts[0][1] >= sum(pop_sizes) ...
2 - tuple of slices for selection of two populations.
def populations_slices(particles, num_pop_list): """2-tuple of slices for selection of two populations. """ slices = [] i_prev = 0 for num_pop in num_pop_list: slices.append(slice(i_prev, i_prev + num_pop)) i_prev += num_pop return slices
Compute hash of D and A timestamps for single - step D + A case.
def _calc_hash_da(self, rs): """Compute hash of D and A timestamps for single-step D+A case. """ self.hash_d = hash_(rs.get_state())[:6] self.hash_a = self.hash_d
Compute timestamps for current populations.
def run(self, rs, overwrite=True, skip_existing=False, path=None, chunksize=None): """Compute timestamps for current populations.""" if path is None: path = str(self.S.store.filepath.parent) kwargs = dict(rs=rs, overwrite=overwrite, path=path, timesl...
Compute timestamps for current populations.
def run_da(self, rs, overwrite=True, skip_existing=False, path=None, chunksize=None): """Compute timestamps for current populations.""" if path is None: path = str(self.S.store.filepath.parent) kwargs = dict(rs=rs, overwrite=overwrite, path=path, ...
Merge donor and acceptor timestamps computes ts a_ch part.
def merge_da(self): """Merge donor and acceptor timestamps, computes `ts`, `a_ch`, `part`. """ print(' - Merging D and A timestamps', flush=True) ts_d, ts_par_d = self.S.get_timestamps_part(self.name_timestamps_d) ts_a, ts_par_a = self.S.get_timestamps_part(self.name_timestamps_a...
Create a smFRET Photon - HDF5 file with current timestamps.
def save_photon_hdf5(self, identity=None, overwrite=True, path=None): """Create a smFRET Photon-HDF5 file with current timestamps.""" filepath = self.filepath if path is not None: filepath = Path(path, filepath.name) self.merge_da() data = self._make_photon_hdf5(ident...
Print the HDF5 attributes for node_name.
def print_attrs(data_file, node_name='/', which='user', compress=False): """Print the HDF5 attributes for `node_name`. Parameters: data_file (pytables HDF5 file object): the data file to print node_name (string): name of the path inside the file to be printed. Can be either a group ...
Print all the sub - groups in group and leaf - nodes children of group.
def print_children(data_file, group='/'): """Print all the sub-groups in `group` and leaf-nodes children of `group`. Parameters: data_file (pytables HDF5 file object): the data file to print group (string): path name of the group to be printed. Default: '/', the root node. """ ...
Train model on given training examples and return the list of costs after each minibatch is processed.
def fit(self, trX, trY, batch_size=64, n_epochs=1, len_filter=LenFilter(), snapshot_freq=1, path=None): """Train model on given training examples and return the list of costs after each minibatch is processed. Args: trX (list) -- Inputs trY (list) -- Outputs batch_size (in...
Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included.
def plane_xz(size=(10, 10), resolution=(10, 10)) -> VAO: """ Generates a plane on the xz axis of a specific size and resolution. Normals and texture coordinates are also included. Args: size: (x, y) tuple resolution: (x, y) tuple Returns: A :py:class:`demosys.opengl.vao.VAO...
Deferred loading of the scene
def load(self): """ Deferred loading of the scene :param scene: The scene object :param file: Resolved path if changed by finder """ self.path = self.find_scene(self.meta.path) if not self.path: raise ValueError("Scene '{}' not found".format(self.meta...
Loads a gltf json file
def load_gltf(self): """Loads a gltf json file""" with open(self.path) as fd: self.meta = GLTFMeta(self.path, json.load(fd))
Loads a binary gltf file
def load_glb(self): """Loads a binary gltf file""" with open(self.path, 'rb') as fd: # Check header magic = fd.read(4) if magic != GLTF_MAGIC_HEADER: raise ValueError("{} has incorrect header {} != {}".format(self.path, magic, GLTF_MAGIC_HEADER)) ...
Add references
def _link_data(self): """Add references""" # accessors -> buffer_views -> buffers for acc in self.accessors: acc.bufferView = self.buffer_views[acc.bufferViewId] for buffer_view in self.buffer_views: buffer_view.buffer = self.buffers[buffer_view.bufferId] ...
extensionsRequired: [ KHR_draco_mesh_compression ] extensionsUsed: [ KHR_draco_mesh_compression ]
def check_extensions(self, supported): """ "extensionsRequired": ["KHR_draco_mesh_compression"], "extensionsUsed": ["KHR_draco_mesh_compression"] """ if self.data.get('extensionsRequired'): for ext in self.data.get('extensionsRequired'): if ext not in ...
Checks if the bin files referenced exist
def buffers_exist(self): """Checks if the bin files referenced exist""" for buff in self.buffers: if not buff.is_separate_file: continue path = self.path.parent / buff.uri if not os.path.exists(path): raise FileNotFoundError("Buffer {}...
Loads the index buffer/ polygon list for a primitive
def load_indices(self, primitive): """Loads the index buffer / polygon list for a primitive""" if getattr(primitive, "indices") is None: return None, None _, component_type, buffer = primitive.indices.read() return component_type, buffer
Pre - parse buffer mappings for each VBO to detect interleaved data for a primitive
def prepare_attrib_mapping(self, primitive): """Pre-parse buffer mappings for each VBO to detect interleaved data for a primitive""" buffer_info = [] for name, accessor in primitive.attributes.items(): info = VBOInfo(*accessor.info()) info.attributes.append((name, info.co...
Get the bounding box for the mesh
def get_bbox(self, primitive): """Get the bounding box for the mesh""" accessor = primitive.attributes.get('POSITION') return accessor.min, accessor.max
Does the buffer interleave with this one?
def interleaves(self, info): """Does the buffer interleave with this one?""" return info.byte_offset == self.component_type.size * self.components
Create the VBO
def create(self): """Create the VBO""" dtype = NP_COMPONENT_DTYPE[self.component_type.value] data = numpy.frombuffer( self.buffer.read(byte_length=self.byte_length, byte_offset=self.byte_offset), count=self.count * self.components, dtype=dtype, ) ...
Reads buffer data: return: component count component type data
def read(self): """ Reads buffer data :return: component count, component type, data """ # ComponentType helps us determine the datatype dtype = NP_COMPONENT_DTYPE[self.componentType.value] return ACCESSOR_TYPE[self.type], self.componentType, self.bufferView.read(...
Get underlying buffer info for this accessor: return: buffer byte_length byte_offset component_type count
def info(self): """ Get underlying buffer info for this accessor :return: buffer, byte_length, byte_offset, component_type, count """ buffer, byte_length, byte_offset = self.bufferView.info(byte_offset=self.byteOffset) return buffer, self.bufferView, \ byte_le...
Get the underlying buffer info: param byte_offset: byte offset from accessor: return: buffer byte_length byte_offset
def info(self, byte_offset=0): """ Get the underlying buffer info :param byte_offset: byte offset from accessor :return: buffer, byte_length, byte_offset """ return self.buffer, self.byteLength, byte_offset + self.byteOffset
Set the 3D position of the camera
def set_position(self, x, y, z): """ Set the 3D position of the camera :param x: float :param y: float :param z: float """ self.position = Vector3([x, y, z])
: return: The current view matrix for the camera
def view_matrix(self): """ :return: The current view matrix for the camera """ self._update_yaw_and_pitch() return self._gl_look_at(self.position, self.position + self.dir, self._up)
Updates the camera vectors based on the current yaw and pitch
def _update_yaw_and_pitch(self): """ Updates the camera vectors based on the current yaw and pitch """ front = Vector3([0.0, 0.0, 0.0]) front.x = cos(radians(self.yaw)) * cos(radians(self.pitch)) front.y = sin(radians(self.pitch)) front.z = sin(radians(self.yaw)) ...
Look at a specific point
def look_at(self, vec=None, pos=None): """ Look at a specific point :param vec: Vector3 position :param pos: python list [x, y, x] :return: Camera matrix """ if pos is None: vec = Vector3(pos) if vec is None: raise ValueError("vec...
The standard lookAt method
def _gl_look_at(self, pos, target, up): """ The standard lookAt method :param pos: current position :param target: target position to look at :param up: direction up """ z = vector.normalise(pos - target) x = vector.normalise(vector3.cross(vector.normalis...
Set the camera position move state
def move_state(self, direction, activate): """ Set the camera position move state :param direction: What direction to update :param activate: Start or stop moving in the direction """ if direction == RIGHT: self._xdir = POSITIVE if activate else STILL ...
Set the rotation state of the camera
def rot_state(self, x, y): """ Set the rotation state of the camera :param x: viewport x pos :param y: viewport y pos """ if self.last_x is None: self.last_x = x if self.last_y is None: self.last_y = y x_offset = self.last_x - x ...
: return: The current view matrix for the camera
def view_matrix(self): """ :return: The current view matrix for the camera """ # Use separate time in camera so we can move it when the demo is paused now = time.time() # If the camera has been inactive for a while, a large time delta # can suddenly move the camer...
Translate string into character texture positions
def _translate_string(self, data, length): """Translate string into character texture positions""" for index, char in enumerate(data): if index == length: break yield self._meta.characters - 1 - self._ct[char]
Generate character translation map ( latin1 pos to texture pos )
def _generate_character_map(self): """Generate character translation map (latin1 pos to texture pos)""" self._ct = [-1] * 256 index = 0 for crange in self._meta.character_ranges: for cpos in range(crange['min'], crange['max'] + 1): self._ct[cpos] = index...
Look up info about a buffer format: param frmt: format string such as f i and u: return: BufferFormat instance
def buffer_format(frmt: str) -> BufferFormat: """ Look up info about a buffer format :param frmt: format string such as 'f', 'i' and 'u' :return: BufferFormat instance """ try: return BUFFER_FORMATS[frmt] except KeyError: raise ValueError("Buffer format '{}' unknown. Valid fo...
Look up info about an attribute format: param frmt: Format of an: return: BufferFormat instance
def attribute_format(frmt: str) -> BufferFormat: """ Look up info about an attribute format :param frmt: Format of an :return: BufferFormat instance """ try: return ATTRIBUTE_FORMATS[frmt] except KeyError: raise ValueError("Buffer format '{}' unknown. Valid formats: {}".forma...
Initialize load and run
def init(window=None, project=None, timeline=None): """ Initialize, load and run :param manager: The effect manager to use """ from demosys.effects.registry import Effect from demosys.scene import camera window.timeline = timeline # Inject attributes into the base Effect class set...
Draw all the nodes in the scene
def draw(self, projection_matrix=None, camera_matrix=None, time=0): """ Draw all the nodes in the scene :param projection_matrix: projection matrix (bytes) :param camera_matrix: camera_matrix (bytes) :param time: The current time """ projection_matrix = projectio...
Draw scene and mesh bounding boxes
def draw_bbox(self, projection_matrix=None, camera_matrix=None, all=True): """Draw scene and mesh bounding boxes""" projection_matrix = projection_matrix.astype('f4').tobytes() camera_matrix = camera_matrix.astype('f4').tobytes() # Scene bounding box self.bbox_program["m_proj"]....
Applies mesh programs to meshes
def apply_mesh_programs(self, mesh_programs=None): """Applies mesh programs to meshes""" if not mesh_programs: mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgram()] for mesh in self.meshes: for mp in mesh_programs: instance = mp.apply(mesh...
Calculate scene bbox
def calc_scene_bbox(self): """Calculate scene bbox""" bbox_min, bbox_max = None, None for node in self.root_nodes: bbox_min, bbox_max = node.calc_global_bbox( matrix44.create_identity(), bbox_min, bbox_max ) self.bb...
Generates random positions inside a confied box.
def points_random_3d(count, range_x=(-10.0, 10.0), range_y=(-10.0, 10.0), range_z=(-10.0, 10.0), seed=None) -> VAO: """ Generates random positions inside a confied box. Args: count (int): Number of points to generate Keyword Args: range_x (tuple): min-max range for x axis: Example (-10...
Play the music
def start(self): """Play the music""" if self.initialized: mixer.music.unpause() else: mixer.music.play() # FIXME: Calling play twice to ensure the music is actually playing mixer.music.play() self.initialized = True self.paused...
Pause the music
def pause(self): """Pause the music""" mixer.music.pause() self.pause_time = self.get_time() self.paused = True
Get the current position in the music in seconds
def get_time(self) -> float: """ Get the current position in the music in seconds """ if self.paused: return self.pause_time return mixer.music.get_pos() / 1000.0
Set the current time in the music in seconds causing the player to seek to this location in the file.
def set_time(self, value: float): """ Set the current time in the music in seconds causing the player to seek to this location in the file. """ if value < 0: value = 0 # mixer.music.play(start=value) mixer.music.set_pos(value)
Draw framebuffers for debug purposes. We need to supply near and far plane so the depth buffer can be linearized when visualizing.
def draw_buffers(self, near, far): """ Draw framebuffers for debug purposes. We need to supply near and far plane so the depth buffer can be linearized when visualizing. :param near: Projection near value :param far: Projection far value """ self.ctx.disable(mode...
Add point light
def add_point_light(self, position, radius): """Add point light""" self.point_lights.append(PointLight(position, radius))
Render light volumes
def render_lights(self, camera_matrix, projection): """Render light volumes""" # Draw light volumes from the inside self.ctx.front_face = 'cw' self.ctx.blend_func = moderngl.ONE, moderngl.ONE helper._depth_sampler.use(location=1) with self.lightbuffer_scope: ...
Render outlines of light volumes
def render_lights_debug(self, camera_matrix, projection): """Render outlines of light volumes""" self.ctx.enable(moderngl.BLEND) self.ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA for light in self.point_lights: m_mv = matrix44.multiply(light.matrix, came...
Combine diffuse and light buffer
def combine(self): """Combine diffuse and light buffer""" self.gbuffer.color_attachments[0].use(location=0) self.combine_shader["diffuse_buffer"].value = 0 self.lightbuffer.color_attachments[0].use(location=1) self.combine_shader["light_buffer"].value = 1 self.quad.render...
Load a single shader
def load_shader(self, shader_type: str, path: str): """Load a single shader""" if path: resolved_path = self.find_program(path) if not resolved_path: raise ValueError("Cannot find {} shader '{}'".format(shader_type, path)) print("Loading:", pat...
Load a texture array
def load(self): """Load a texture array""" self._open_image() width, height, depth = self.image.size[0], self.image.size[1] // self.layers, self.layers components, data = image_data(self.image) texture = self.ctx.texture_array( (width, height, depth), ...
Draw the mesh using the assigned mesh program
def draw(self, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0): """ Draw the mesh using the assigned mesh program :param projection_matrix: projection_matrix (bytes) :param view_matrix: view_matrix (bytes) :param camera_matrix: camera_matrix (bytes) ...
Add metadata about the mesh: param attr_type: POSITION NORMAL etc: param name: The attribute name used in the program: param components: Number of floats
def add_attribute(self, attr_type, name, components): """ Add metadata about the mesh :param attr_type: POSITION, NORMAL etc :param name: The attribute name used in the program :param components: Number of floats """ self.attributes[attr_type] = {"name": name, "co...
Set the current time jumping in the timeline.
def set_time(self, value: float): """ Set the current time jumping in the timeline. Args: value (float): The new time """ if value < 0: value = 0 self.controller.row = self.rps * value
Draw function called by the system every frame when the effect is active. This method raises NotImplementedError unless implemented.
def draw(self, time: float, frametime: float, target: moderngl.Framebuffer): """ Draw function called by the system every frame when the effect is active. This method raises ``NotImplementedError`` unless implemented. Args: time (float): The current time in seconds. ...
Get a program by its label
def get_program(self, label: str) -> moderngl.Program: """ Get a program by its label Args: label (str): The label for the program Returns: py:class:`moderngl.Program` instance """ return self._project.get_program(label)
Get a texture by its label
def get_texture(self, label: str) -> Union[moderngl.Texture, moderngl.TextureArray, moderngl.Texture3D, moderngl.TextureCube]: """ Get a texture by its label Args: label (str): The Label for the texture Returns: The...
Get an effect class by the class name
def get_effect_class(self, effect_name: str, package_name: str = None) -> Type['Effect']: """ Get an effect class by the class name Args: effect_name (str): Name of the effect class Keyword Args: package_name (str): The package the effect belongs to. This is opt...
Create a projection matrix with the following parameters. When aspect_ratio is not provided the configured aspect ratio for the window will be used.
def create_projection(self, fov: float = 75.0, near: float = 1.0, far: float = 100.0, aspect_ratio: float = None): """ Create a projection matrix with the following parameters. When ``aspect_ratio`` is not provided the configured aspect ratio for the window will be used. Args: ...
Creates a transformation matrix woth rotations and translation.
def create_transformation(self, rotation=None, translation=None): """ Creates a transformation matrix woth rotations and translation. Args: rotation: 3 component vector as a list, tuple, or :py:class:`pyrr.Vector3` translation: 3 component vector as a list, tuple, or :py...
Creates a normal matrix from modelview matrix
def create_normal_matrix(self, modelview): """ Creates a normal matrix from modelview matrix Args: modelview: The modelview matrix Returns: A 3x3 Normal matrix as a :py:class:`numpy.array` """ normal_m = Matrix33.from_matrix44(modelview) ...
Scan for available templates in effect_templates
def available_templates(value): """Scan for available templates in effect_templates""" templates = list_templates() if value not in templates: raise ArgumentTypeError("Effect template '{}' does not exist.\n Available templates: {} ".format( value, ", ".join(templates))) return valu...
Get the absolute path to the root of the demosys package
def root_path(): """Get the absolute path to the root of the demosys package""" module_dir = os.path.dirname(globals()['__file__']) return os.path.dirname(os.path.dirname(module_dir))
Load a file in text mode
def load(self): """Load a file in text mode""" self.meta.resolved_path = self.find_data(self.meta.path) if not self.meta.resolved_path: raise ImproperlyConfigured("Data file '{}' not found".format(self.meta.path)) print("Loading:", self.meta.path) with ope...
Get a finder class from an import path. Raises demosys. core. exceptions. ImproperlyConfigured if the finder is not found. This function uses an lru cache.
def get_finder(import_path): """ Get a finder class from an import path. Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found. This function uses an lru cache. :param import_path: string representing an import path :return: An instance of the finder """ Fin...
Find a file in the path. The file may exist in multiple paths. The last found file will be returned.
def find(self, path: Path): """ Find a file in the path. The file may exist in multiple paths. The last found file will be returned. :param path: The path to find :return: The absolute path to the file or None if not found """ # Update paths from settings to make...
Update the internal projection matrix based on current values or values passed in if specified.
def update(self, aspect_ratio=None, fov=None, near=None, far=None): """ Update the internal projection matrix based on current values or values passed in if specified. :param aspect_ratio: New aspect ratio :param fov: New field of view :param near: New near value ...
Returns the ( x y ) projection constants for the current projection.: return: x y tuple projection constants
def projection_constants(self): """ Returns the (x, y) projection constants for the current projection. :return: x, y tuple projection constants """ return self.far / (self.far - self.near), (self.far * self.near) / (self.near - self.far)
Draw node and children
def draw(self, projection_matrix=None, camera_matrix=None, time=0): """ Draw node and children :param projection_matrix: projection matrix (bytes) :param camera_matrix: camera_matrix (bytes) :param time: The current time """ if self.mesh: self.mesh.dr...
Recursive calculation of scene bbox
def calc_global_bbox(self, view_matrix, bbox_min, bbox_max): """Recursive calculation of scene bbox""" if self.matrix is not None: view_matrix = matrix44.multiply(self.matrix, view_matrix) if self.mesh: bbox_min, bbox_max = self.mesh.calc_global_bbox(view_matrix, bbox_mi...