Skip to content

Tolvera

Example

This example demonstrates the basic usage of Tölvera. It will display a window with a black background.

from tolvera import Tolvera, run

def main(**kwargs):
    tv = Tolvera(**kwargs)

    @tv.render
    def _():
        return tv.px

if __name__ == '__main__':
    run(main)
Example

Here's an annotated version of the above example:

# First, we import Tolvera and run() from tolvera.
from tolvera import Tolvera, run

# Then, we define a main function which takes in keyword arguments 
# (kwargs) from the command line.
def main(**kwargs):
    # Inside the main function, we initialise a Tolvera instance 
    # with the given keyword arguments.
    tv = Tolvera(**kwargs)

    # We use the render() decorator to render the pixels.
    # This function can be named anything. 
    # It will run in a loop until the user exits the program.
    @tv.render
    def _():
        # render() must return Pixels. Often, these pixels will be 
        # the pixels of the Tolvera instance, accessed with tv.px.
        return tv.px

# Finally, we call run() with the main function as the argument.
if __name__ == '__main__':
    run(main)

When Tolvera is run, messages will be printed to the console. These messages inform the user of the status of Tolvera, during initialisation, setup, and running.

CONSTS

Dict of CONSTS that can be used in Taichi scope

Source code in src/tolvera/utils.py
class CONSTS:
    """
    Dict of CONSTS that can be used in Taichi scope
    """

    def __init__(self, dict: dict[str, (DataType, Any)]):
        self.struct = ti.types.struct(**{k: v[0] for k, v in dict.items()})
        self.consts = self.struct(**{k: v[1] for k, v in dict.items()})

    def __getattr__(self, name):
        try:
            return self.consts[name]
        except:
            raise AttributeError(f"CONSTS has no attribute {name}")

    def __getitem__(self, name):
        try:
            return self.consts[name]
        except:
            raise AttributeError(f"CONSTS has no attribute {name}")

Particle

Particle data structure and methods.

Source code in src/tolvera/particles.py
@ti.dataclass
class Particle:
    """Particle data structure and methods."""
    species: ti.i32
    active: ti.f32
    pos: ti.math.vec2
    vel: ti.math.vec2
    ppos: ti.math.vec2
    pvel: ti.math.vec2
    mass: ti.f32
    size: ti.f32
    speed: ti.f32

    @ti.func
    def dist(self, other):
        """Distance between two particles.

        Args:
            other (Particle): Other particle.

        Returns:
            ti.math.vec2: Distance between the two particles.
        """
        return self.pos - other.pos

    @ti.func
    def dist_norm(self, other):
        """ti.math.norm() distance between two particles.

        Args:
            other (Particle): Other particle.

        Returns:
            ti.math.vec2: ti.math.norm() distance between the two particles.
        """
        return self.dist(self.pos - other.pos).norm()

    @ti.func
    def dist_normalized(self, other):
        """ti.math.normalized() distance between two particles.

        Args:
            other (Particle): Other particle.

        Returns:
            ti.math.vec2: ti.math.normalized() distance between the two particles.
        """
        return self.dist(self.pos - other.pos).normalized()

    @ti.func
    def dist_wrap(self, other, x, y):
        """Wrap around distance between two particles.

        Args:
            other (Particle): Other particle.
            x (float): Width.
            y (float): Height.

        Returns:
            ti.math.vec2: Wrap around distance between the two particles.
        """
        dx = self.pos[0] - other.pos[0]
        dy = self.pos[1] - other.pos[1]
        if abs(dx) > x / 2:  # x-axis
            dx = x - abs(dx)
            if self.pos[0] > other.pos[0]:
                dx = -dx
        if abs(dy) > y / 2:  # y-axis
            dy = y - abs(dy)
            if self.pos[1] > other.pos[1]:
                dy = -dy
        return ti.Vector([dx, dy])

    # @ti.func
    # def dist_wrap(self, other, x, y):
    #     dx = self.pos[0] - other.pos[0]
    #     dy = self.pos[1] - other.pos[1]
    #     # Wrap around for the x-axis
    #     if abs(dx) > x / 2:
    #         dx = x - abs(dx)
    #         if self.pos[0] < other.pos[0]:
    #             dx = -dx
    #     # Wrap around for the y-axis
    #     if abs(dy) > y / 2:
    #         dy = y - abs(dy)
    #         if self.pos[1] < other.pos[1]:
    #             dy = -dy
    #     return ti.Vector([dx, dy])
    # @ti.func
    # def dist_wrap(self, other, width, height):
    #     # Compute the element-wise absolute difference
    #     self_abs = ti.abs(self.pos)
    #     other_abs = ti.abs(other.pos)
    #     delta = self_abs - other_abs
    #     # Check if wrapping around is shorter for both the x and y components
    #     if delta[0] > width / 2:
    #         delta[0] = width - delta[0]
    #     if delta[1] > height / 2:
    #         delta[1] = height - delta[1]
    #     # Correct the signs if necessary
    #     if self.pos[0] > other.pos[0] and delta[0] > 0:
    #         delta[0] = -delta[0]
    #     if self.pos[1] > other.pos[1] and delta[1] > 0:
    #         delta[1] = -delta[1]
    #     return delta
    @ti.func
    def randomise(self, x, y):
        """Randomise the particle's position and velocity.

        Args:
            x (ti.f32): Width.
            y (ti.f32): Height.
        """
        self.randomise_pos(x, y)
        self.randomise_vel()

    @ti.func
    def randomise_pos(self, x, y):
        """Randomise the particle's position.

        Args:
            x (ti.f32): Width.
            y (ti.f32): Height.
        """
        self.pos = [x * ti.random(ti.f32), y * ti.random(ti.f32)]

    @ti.func
    def randomise_vel(self):
        """Randomise the particle's velocity."""
        self.vel = [2 * (ti.random(ti.f32) - 0.5), 2 * (ti.random(ti.f32) - 0.5)]

dist(other)

Distance between two particles.

Parameters:

Name Type Description Default
other Particle

Other particle.

required

Returns:

Type Description

ti.math.vec2: Distance between the two particles.

Source code in src/tolvera/particles.py
@ti.func
def dist(self, other):
    """Distance between two particles.

    Args:
        other (Particle): Other particle.

    Returns:
        ti.math.vec2: Distance between the two particles.
    """
    return self.pos - other.pos

dist_norm(other)

ti.math.norm() distance between two particles.

Parameters:

Name Type Description Default
other Particle

Other particle.

required

Returns:

Type Description

ti.math.vec2: ti.math.norm() distance between the two particles.

Source code in src/tolvera/particles.py
@ti.func
def dist_norm(self, other):
    """ti.math.norm() distance between two particles.

    Args:
        other (Particle): Other particle.

    Returns:
        ti.math.vec2: ti.math.norm() distance between the two particles.
    """
    return self.dist(self.pos - other.pos).norm()

dist_normalized(other)

ti.math.normalized() distance between two particles.

Parameters:

Name Type Description Default
other Particle

Other particle.

required

Returns:

Type Description

ti.math.vec2: ti.math.normalized() distance between the two particles.

Source code in src/tolvera/particles.py
@ti.func
def dist_normalized(self, other):
    """ti.math.normalized() distance between two particles.

    Args:
        other (Particle): Other particle.

    Returns:
        ti.math.vec2: ti.math.normalized() distance between the two particles.
    """
    return self.dist(self.pos - other.pos).normalized()

dist_wrap(other, x, y)

Wrap around distance between two particles.

Parameters:

Name Type Description Default
other Particle

Other particle.

required
x float

Width.

required
y float

Height.

required

Returns:

Type Description

ti.math.vec2: Wrap around distance between the two particles.

Source code in src/tolvera/particles.py
@ti.func
def dist_wrap(self, other, x, y):
    """Wrap around distance between two particles.

    Args:
        other (Particle): Other particle.
        x (float): Width.
        y (float): Height.

    Returns:
        ti.math.vec2: Wrap around distance between the two particles.
    """
    dx = self.pos[0] - other.pos[0]
    dy = self.pos[1] - other.pos[1]
    if abs(dx) > x / 2:  # x-axis
        dx = x - abs(dx)
        if self.pos[0] > other.pos[0]:
            dx = -dx
    if abs(dy) > y / 2:  # y-axis
        dy = y - abs(dy)
        if self.pos[1] > other.pos[1]:
            dy = -dy
    return ti.Vector([dx, dy])

randomise(x, y)

Randomise the particle's position and velocity.

Parameters:

Name Type Description Default
x f32

Width.

required
y f32

Height.

required
Source code in src/tolvera/particles.py
@ti.func
def randomise(self, x, y):
    """Randomise the particle's position and velocity.

    Args:
        x (ti.f32): Width.
        y (ti.f32): Height.
    """
    self.randomise_pos(x, y)
    self.randomise_vel()

randomise_pos(x, y)

Randomise the particle's position.

Parameters:

Name Type Description Default
x f32

Width.

required
y f32

Height.

required
Source code in src/tolvera/particles.py
@ti.func
def randomise_pos(self, x, y):
    """Randomise the particle's position.

    Args:
        x (ti.f32): Width.
        y (ti.f32): Height.
    """
    self.pos = [x * ti.random(ti.f32), y * ti.random(ti.f32)]

randomise_vel()

Randomise the particle's velocity.

Source code in src/tolvera/particles.py
@ti.func
def randomise_vel(self):
    """Randomise the particle's velocity."""
    self.vel = [2 * (ti.random(ti.f32) - 0.5), 2 * (ti.random(ti.f32) - 0.5)]

Particles

Particle system.

Source code in src/tolvera/particles.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
@ti.data_oriented
class Particles:
    """Particle system."""
    def __init__(self, tolvera, **kwargs):
        """Initialise the particle system.

        Args:
            tolvera (Tolvera): Tolvera instance.
            **kwargs: Keyword arguments (currently there are none).
        """
        self.tv = tolvera
        self.kwargs = kwargs
        self.n = self.tv.pn
        self.p_per_s = self.tv.p_per_s
        self._speed = ti.field(ti.f32, shape=())
        self._speed[None] = 1.0
        self.substep = self.tv.substep
        self.field = Particle.field(shape=(self.n))
        # TODO: These should be possible with State
        # self.pos = State(self.tv, {
        #     'x': (0., self.tv.x),
        #     'y': (0., self.tv.y),
        # }, shape=(self.n,), osc=('get'), name='particles_pos')
        self.C = CONSTS({"COLL_RAD": (ti.f32, 10.0)})
        self.tv.s.collisions_p = {
            'state': {
                'collision': (ti.i32, 0, 1),
                'dpos': (ti.math.vec2, 0., 1.),
                'dvel': (ti.math.vec2, 0., 1.),
            },
            'shape': self.n,
        }
        self.tmp_pos = ti.Vector.field(2, ti.f32, shape=(self.n))
        self.tmp_vel = ti.Vector.field(2, ti.f32, shape=(self.n))
        self.tmp_pos_species = ti.Vector.field(2, ti.f32, shape=(self.p_per_s))
        self.tmp_vel_species = ti.Vector.field(2, ti.f32, shape=(self.p_per_s))
        self.tmp_vel_stats = ti.Vector.field(1, ti.f32, shape=(7))
        self.active_indexes = ti.field(ti.i32, shape=(self.n))
        self.active_count = ti.field(ti.i32, shape=())
        self.init()

    def init(self):
        """Initialise the particle system."""
        self.assign_species()
        self.randomise()

    @ti.kernel
    def assign_species(self):
        """Assign species to particles."""
        for i in range(self.n):
            self.field[i].species = i % self.tv.species

    def _randomise(self):
        """Randomise the particle system (Python scope)."""
        self.randomise()

    @ti.kernel
    def randomise(self):
        """Randomise the particle system (Taichi scope)."""
        for i in range(self.n):
            si = self.field[i].species
            s = self.tv.s.species[si]
            # FIXME: ugly
            # c = self.tv.species_consts
            species = si
            active = 1.0
            pos = [self.tv.x * ti.random(ti.f32), self.tv.y * ti.random(ti.f32)]
            vel = [2 * (ti.random(ti.f32) - 0.5), 2 * (ti.random(ti.f32) - 0.5)]
            size = (
                ti.random(ti.f32) * s.size * self.tv.species_consts.MAX_SIZE
                + self.tv.species_consts.MIN_SIZE
            )
            speed = (
                ti.random(ti.f32) * s.speed * self.tv.species_consts.MAX_SPEED
                + self.tv.species_consts.MIN_SPEED
            )
            mass = ti.random(ti.f32) * s.mass * self.tv.species_consts.MAX_MASS
            self.field[i] = Particle(
                species=species,
                pos=pos,
                vel=vel,
                active=active,
                mass=mass,
                size=size,
                speed=speed,
            )

    @ti.kernel
    def update(self):
        """Update the particle system."""
        j = 0
        for i in range(self.n):
            if self.field[i] == 0.0: continue
            self.toroidal_wrap(i)
            self.limit_speed(i)
            # self.detect_collisions(i, self.C.COLL_RAD)
            # self.update_prev(i)
            self.active_indexes[j] = i
            j += 1
        self.active_count[None] = j

    @ti.func
    def toroidal_wrap(self, i: ti.i32):
        """Toroidal wrap a particle.

        Args:
            i (ti.i32): Particle index.
        """
        p = self.field[i]
        if p.pos[0] > self.tv.x:
            self.field[i].pos[0] = 0.0
        if p.pos[0] < 0.0:
            self.field[i].pos[0] = self.tv.x
        if p.pos[1] > self.tv.y:
            self.field[i].pos[1] = 0.0
        if p.pos[1] < 0.0:
            self.field[i].pos[1] = self.tv.y

    @ti.func
    def limit_speed(self, i: ti.i32):
        """Limit the speed of a particle.

        Args:
            i (ti.i32): Particle index.
        """
        p = self.field[i]
        s = self.tv.s.species[p.species]
        # FIXME: ugly
        sp = (
            s.speed * self.tv.species_consts.MAX_SPEED
            + self.tv.species_consts.MIN_SPEED
        )
        if p.vel.norm() > s.speed:
            self.field[i].vel = p.vel.normalized() * sp * self._speed[None]

    @ti.func
    def detect_collisions(self, i: ti.i32, radius: ti.f32):
        """Detect collisions between particles.

        TODO: Merge deltas into @ti.dataclass, or reimplement Particle.field as tv.s?
        TODO: Multiple collision states? Collided, Colliding, etc.
        TODO: Detect collisions between external objects.

        Args:
            i (ti.i32): Particle index.
            radius (ti.f32): Collision radius.
        """
        for j in range(self.n):
            p1, p2 = self.tv.p.field[i], self.tv.p.field[j]
            if p2.active == 0: continue
            dist = p1.pos - p2.pos
            if dist.norm() < radius:
                pdist = p1.ppos - p2.ppos
                dpos = ti.abs(pdist - dist)
                dvel = ti.abs((p1.pvel - p2.pvel) - (p1.vel - p2.vel))
                self.tv.s.collisions_p[i].dpos = dpos
                self.tv.s.collisions_p[i].dvel = dvel
                if pdist.norm() > radius:
                    self.tv.s.collisions_p[i].collision = 1
                else:
                    self.tv.s.collisions_p[i].collision = 0

    @ti.func
    def update_prev(self, i: ti.i32):
        """Update the previous position and velocity of a particle.

        Args:
            i (ti.i32): Particle index.
        """
        self.field[i].ppos = self.field[i].pos
        self.field[i].pvel = self.field[i].vel

    @ti.kernel
    def activity_decay(self):
        """Decay the activity of the particles."""
        for i in range(self.active_count[None]):
            idx = self.active_indexes[i]
            self.field[idx].active *= self.field[i].decay

    def process(self):
        """Process the particle system."""
        for i in range(self.substep):
            self.update()

    @ti.kernel
    def set_total_active(self, total: ti.i32):
        """Set the total number of active particles.

        Args:
            total (ti.i32): Total active particles.
        """
        for i in range(self.field.shape[0]):
            if i >= total:
                self.field[i].active = 0
            else:
                self.field[i].active = 1

    @ti.kernel
    def set_total_active_amount(self, total: ti.i32, amount: ti.f32):
        """Set the total number of active particles.

        Args:
            total (ti.i32): Total active particles.
            amount (ti.f32): Amount of activity.
        """
        for i in range(self.field.shape[0]):
            if i >= total:
                self.field[i].active = 0
            else:
                self.field[i].active = amount

    @ti.kernel
    def set_species_total_active(self, i: ti.i32, total: ti.i32):
        """Set the total number of active particles for a species.

        Args:
            i (ti.i32): Species index.
            total (ti.i32): Total active particles.
        """
        for j in range(self.field.shape[0]):
            if self.field[j].species == i:
                if j >= total:
                    self.field[j].active = 0
                else:
                    self.field[j].active = 1

    @ti.kernel
    def set_species_total_active_amount(self, i: ti.i32, total: ti.i32, amount: ti.f32):
        """Set particle activity amount of a species.

        Args:
            i (ti.i32): Species index.
            total: (ti.i32): Total number of active particles.
            amount (ti.i32): Amount of activity.
        """
        for j in range(self.field.shape[0]):
            if self.field[j].species == i:
                if j >= total:
                    self.field[j].active = 0
                else:
                    self.field[j].active = amount

    def set_pos(self, i, x, y):
        self.field[i].pos = [x, y]

    def set_vel(self, i, x, y):
        self.field[i].vel = [x, y]

    def set_speed(self, i, s):
        self.field[i].speed = s

    def set_size(self, i, s):
        self.field[i].size = s

    def get_pos(self, i):
        return self.field[i].pos.to_numpy().tolist()

    def get_vel(self, i):
        return self.field[i].vel.to_numpy().tolist()

    def get_pos_all_1d(self):
        self._get_pos_all()
        return self.tmp_pos.to_numpy().flatten().tolist()

    def get_pos_all_2d(self):
        self._get_pos_all()
        return self.tmp_pos.to_numpy().tolist()

    def get_vel_all_1d(self):
        self._get_vel_all()
        return self.tmp_vel.to_numpy().flatten().tolist()

    def get_vel_all_2d(self):
        self._get_vel_all()
        return self.tmp_vel.to_numpy().tolist()

    @ti.kernel
    def _get_pos_all(self):
        # for i in range(self.active_count[None]):
        #     idx = self.active_indexes[i]
        #     p = self.field[idx]
        #     self.tmp_pos[i] = p.pos / [self.tv.x, self.tv.y]
        # TODO: Only send active particle positions...? Or inactive=-1?
        for i in range(self.n):
            p = self.field[i]
            # if p.active > 0.0: # causes IML shape assertion error
            self.tmp_pos[i] = p.pos / [self.tv.x, self.tv.y]
            # else:
            #     self.tmp_pos[i] = [0.0,0.0] # ???

    @ti.kernel
    def _get_vel_all(self):
        for i in range(self.n):
            p = self.field[i]
            if p.active > 0.0:
                self.tmp_vel[i] = p.vel

    def get_pos_species_1d(self, species: int):
        self._get_pos_species()
        return self.tmp_pos_species.to_numpy().flatten().tolist()

    def get_pos_species_2d(self, species: int):
        if species > self.tv.species - 1:
            return
        self._get_pos_species(species)
        return self.tmp_pos_species.to_numpy().tolist()

    @ti.kernel
    def _get_pos_species(self, i: ti.i32):
        for j in range(self.n):
            si = j % self.tv.species
            p = self.field[j]
            if i == si and p.active > 0.0:
                species_index = (j - i) // self.tv.species
                pos = p.pos / [self.tv.x, self.tv.y]
                self.tmp_pos_species[species_index] = pos

    def get_vel_species_1d(self, species: int):
        self._get_vel_species(species)
        return self.tmp_vel_species.to_numpy().flatten().tolist()

    def get_vel_species_2d(self, species: int):
        self._get_vel_species(species)
        return self.tmp_vel_species.to_numpy().tolist()

    @ti.kernel
    def _get_vel_species(self, i: ti.i32):
        for j in range(self.n):
            si = j % self.tv.species
            p = self.field[j]
            if i == si and p.active > 0.0:
                species_index = (j - i) // self.tv.species
                vel = p.vel / [self.tv.x, self.tv.y]
                self.tmp_vel_species[species_index] = vel

    def get_vel_stats_species_1d(self, species):
        self._species_velocity_statistics(species)
        return self.tmp_vel_stats.to_numpy().flatten().tolist()

    @ti.kernel
    def _species_velocity_statistics(self, i: ti.i32):
        """
        Centre of Mass Velocity: This is the average velocity of all particles in the species.
        Relative Velocity: This is the average velocity of all particles in the species relative to the centre of mass velocity.
        Angular Momentum: This is the sum of the angular momentum of all particles, which is given by mass * velocity * radius for each particle.
        Kinetic Energy: This is the sum of the kinetic energy of all particles, which is given by 0.5 * mass * velocity^2 for each particle.
        Temperature: In statistical mechanics, the temperature of a system of particles is related to the average kinetic energy of the particles.
        """
        centre_of_mass_velocity = ti.Vector([0.0, 0.0])
        relative_velocity = ti.Vector([0.0, 0.0])
        angular_momentum = ti.Vector([0.0])
        kinetic_energy = ti.Vector([0.0])
        for j in range(self.n):
            if self.field[j].species == i:
                v = self.field[j].vel
                p = self.field[j].pos
                m = self.field[j].mass
                centre_of_mass_velocity += v
                relative_velocity += v  # - centre_of_mass_velocity
                angular_momentum += m * ti.math.cross(v, p)
                kinetic_energy += 0.5 * m * v.norm_sqr()
        centre_of_mass_velocity = centre_of_mass_velocity / self.n_per_species
        relative_velocity = (
            relative_velocity - centre_of_mass_velocity * self.n_per_species
        ) / self.n_per_species
        temperature = 2.0 * kinetic_energy / (self.particles_per_species * 1.380649e-23)
        self.tmp_vel_stats[0] = centre_of_mass_velocity[0]
        self.tmp_vel_stats[1] = centre_of_mass_velocity[1]
        self.tmp_vel_stats[2] = relative_velocity[0]
        self.tmp_vel_stats[3] = relative_velocity[1]
        self.tmp_vel_stats[4] = angular_momentum[0]
        self.tmp_vel_stats[5] = kinetic_energy[0]
        self.tmp_vel_stats[6] = temperature[0]

    def reset(self):
        """Reset the particle system."""
        self.init()

    def speed(self, speed: float = None):
        """Get or set the speed of the particle system.

        Args:
            speed (float, optional): Speed. Defaults to None.

        Returns:
            float: Speed.
        """
        if speed is not None:
            self._speed[None] = 1 / (speed + 0.0001)
        else:
            return self._speed[None]

    def __call__(self):
        """Call will process the particle system."""
        self.process()

__call__()

Call will process the particle system.

Source code in src/tolvera/particles.py
def __call__(self):
    """Call will process the particle system."""
    self.process()

__init__(tolvera, **kwargs)

Initialise the particle system.

Parameters:

Name Type Description Default
tolvera Tolvera

Tolvera instance.

required
**kwargs

Keyword arguments (currently there are none).

{}
Source code in src/tolvera/particles.py
def __init__(self, tolvera, **kwargs):
    """Initialise the particle system.

    Args:
        tolvera (Tolvera): Tolvera instance.
        **kwargs: Keyword arguments (currently there are none).
    """
    self.tv = tolvera
    self.kwargs = kwargs
    self.n = self.tv.pn
    self.p_per_s = self.tv.p_per_s
    self._speed = ti.field(ti.f32, shape=())
    self._speed[None] = 1.0
    self.substep = self.tv.substep
    self.field = Particle.field(shape=(self.n))
    # TODO: These should be possible with State
    # self.pos = State(self.tv, {
    #     'x': (0., self.tv.x),
    #     'y': (0., self.tv.y),
    # }, shape=(self.n,), osc=('get'), name='particles_pos')
    self.C = CONSTS({"COLL_RAD": (ti.f32, 10.0)})
    self.tv.s.collisions_p = {
        'state': {
            'collision': (ti.i32, 0, 1),
            'dpos': (ti.math.vec2, 0., 1.),
            'dvel': (ti.math.vec2, 0., 1.),
        },
        'shape': self.n,
    }
    self.tmp_pos = ti.Vector.field(2, ti.f32, shape=(self.n))
    self.tmp_vel = ti.Vector.field(2, ti.f32, shape=(self.n))
    self.tmp_pos_species = ti.Vector.field(2, ti.f32, shape=(self.p_per_s))
    self.tmp_vel_species = ti.Vector.field(2, ti.f32, shape=(self.p_per_s))
    self.tmp_vel_stats = ti.Vector.field(1, ti.f32, shape=(7))
    self.active_indexes = ti.field(ti.i32, shape=(self.n))
    self.active_count = ti.field(ti.i32, shape=())
    self.init()

_randomise()

Randomise the particle system (Python scope).

Source code in src/tolvera/particles.py
def _randomise(self):
    """Randomise the particle system (Python scope)."""
    self.randomise()

_species_velocity_statistics(i)

Centre of Mass Velocity: This is the average velocity of all particles in the species. Relative Velocity: This is the average velocity of all particles in the species relative to the centre of mass velocity. Angular Momentum: This is the sum of the angular momentum of all particles, which is given by mass * velocity * radius for each particle. Kinetic Energy: This is the sum of the kinetic energy of all particles, which is given by 0.5 * mass * velocity^2 for each particle. Temperature: In statistical mechanics, the temperature of a system of particles is related to the average kinetic energy of the particles.

Source code in src/tolvera/particles.py
@ti.kernel
def _species_velocity_statistics(self, i: ti.i32):
    """
    Centre of Mass Velocity: This is the average velocity of all particles in the species.
    Relative Velocity: This is the average velocity of all particles in the species relative to the centre of mass velocity.
    Angular Momentum: This is the sum of the angular momentum of all particles, which is given by mass * velocity * radius for each particle.
    Kinetic Energy: This is the sum of the kinetic energy of all particles, which is given by 0.5 * mass * velocity^2 for each particle.
    Temperature: In statistical mechanics, the temperature of a system of particles is related to the average kinetic energy of the particles.
    """
    centre_of_mass_velocity = ti.Vector([0.0, 0.0])
    relative_velocity = ti.Vector([0.0, 0.0])
    angular_momentum = ti.Vector([0.0])
    kinetic_energy = ti.Vector([0.0])
    for j in range(self.n):
        if self.field[j].species == i:
            v = self.field[j].vel
            p = self.field[j].pos
            m = self.field[j].mass
            centre_of_mass_velocity += v
            relative_velocity += v  # - centre_of_mass_velocity
            angular_momentum += m * ti.math.cross(v, p)
            kinetic_energy += 0.5 * m * v.norm_sqr()
    centre_of_mass_velocity = centre_of_mass_velocity / self.n_per_species
    relative_velocity = (
        relative_velocity - centre_of_mass_velocity * self.n_per_species
    ) / self.n_per_species
    temperature = 2.0 * kinetic_energy / (self.particles_per_species * 1.380649e-23)
    self.tmp_vel_stats[0] = centre_of_mass_velocity[0]
    self.tmp_vel_stats[1] = centre_of_mass_velocity[1]
    self.tmp_vel_stats[2] = relative_velocity[0]
    self.tmp_vel_stats[3] = relative_velocity[1]
    self.tmp_vel_stats[4] = angular_momentum[0]
    self.tmp_vel_stats[5] = kinetic_energy[0]
    self.tmp_vel_stats[6] = temperature[0]

activity_decay()

Decay the activity of the particles.

Source code in src/tolvera/particles.py
@ti.kernel
def activity_decay(self):
    """Decay the activity of the particles."""
    for i in range(self.active_count[None]):
        idx = self.active_indexes[i]
        self.field[idx].active *= self.field[i].decay

assign_species()

Assign species to particles.

Source code in src/tolvera/particles.py
@ti.kernel
def assign_species(self):
    """Assign species to particles."""
    for i in range(self.n):
        self.field[i].species = i % self.tv.species

detect_collisions(i, radius)

Detect collisions between particles.

TODO: Merge deltas into @ti.dataclass, or reimplement Particle.field as tv.s? TODO: Multiple collision states? Collided, Colliding, etc. TODO: Detect collisions between external objects.

Parameters:

Name Type Description Default
i i32

Particle index.

required
radius f32

Collision radius.

required
Source code in src/tolvera/particles.py
@ti.func
def detect_collisions(self, i: ti.i32, radius: ti.f32):
    """Detect collisions between particles.

    TODO: Merge deltas into @ti.dataclass, or reimplement Particle.field as tv.s?
    TODO: Multiple collision states? Collided, Colliding, etc.
    TODO: Detect collisions between external objects.

    Args:
        i (ti.i32): Particle index.
        radius (ti.f32): Collision radius.
    """
    for j in range(self.n):
        p1, p2 = self.tv.p.field[i], self.tv.p.field[j]
        if p2.active == 0: continue
        dist = p1.pos - p2.pos
        if dist.norm() < radius:
            pdist = p1.ppos - p2.ppos
            dpos = ti.abs(pdist - dist)
            dvel = ti.abs((p1.pvel - p2.pvel) - (p1.vel - p2.vel))
            self.tv.s.collisions_p[i].dpos = dpos
            self.tv.s.collisions_p[i].dvel = dvel
            if pdist.norm() > radius:
                self.tv.s.collisions_p[i].collision = 1
            else:
                self.tv.s.collisions_p[i].collision = 0

init()

Initialise the particle system.

Source code in src/tolvera/particles.py
def init(self):
    """Initialise the particle system."""
    self.assign_species()
    self.randomise()

limit_speed(i)

Limit the speed of a particle.

Parameters:

Name Type Description Default
i i32

Particle index.

required
Source code in src/tolvera/particles.py
@ti.func
def limit_speed(self, i: ti.i32):
    """Limit the speed of a particle.

    Args:
        i (ti.i32): Particle index.
    """
    p = self.field[i]
    s = self.tv.s.species[p.species]
    # FIXME: ugly
    sp = (
        s.speed * self.tv.species_consts.MAX_SPEED
        + self.tv.species_consts.MIN_SPEED
    )
    if p.vel.norm() > s.speed:
        self.field[i].vel = p.vel.normalized() * sp * self._speed[None]

process()

Process the particle system.

Source code in src/tolvera/particles.py
def process(self):
    """Process the particle system."""
    for i in range(self.substep):
        self.update()

randomise()

Randomise the particle system (Taichi scope).

Source code in src/tolvera/particles.py
@ti.kernel
def randomise(self):
    """Randomise the particle system (Taichi scope)."""
    for i in range(self.n):
        si = self.field[i].species
        s = self.tv.s.species[si]
        # FIXME: ugly
        # c = self.tv.species_consts
        species = si
        active = 1.0
        pos = [self.tv.x * ti.random(ti.f32), self.tv.y * ti.random(ti.f32)]
        vel = [2 * (ti.random(ti.f32) - 0.5), 2 * (ti.random(ti.f32) - 0.5)]
        size = (
            ti.random(ti.f32) * s.size * self.tv.species_consts.MAX_SIZE
            + self.tv.species_consts.MIN_SIZE
        )
        speed = (
            ti.random(ti.f32) * s.speed * self.tv.species_consts.MAX_SPEED
            + self.tv.species_consts.MIN_SPEED
        )
        mass = ti.random(ti.f32) * s.mass * self.tv.species_consts.MAX_MASS
        self.field[i] = Particle(
            species=species,
            pos=pos,
            vel=vel,
            active=active,
            mass=mass,
            size=size,
            speed=speed,
        )

reset()

Reset the particle system.

Source code in src/tolvera/particles.py
def reset(self):
    """Reset the particle system."""
    self.init()

set_species_total_active(i, total)

Set the total number of active particles for a species.

Parameters:

Name Type Description Default
i i32

Species index.

required
total i32

Total active particles.

required
Source code in src/tolvera/particles.py
@ti.kernel
def set_species_total_active(self, i: ti.i32, total: ti.i32):
    """Set the total number of active particles for a species.

    Args:
        i (ti.i32): Species index.
        total (ti.i32): Total active particles.
    """
    for j in range(self.field.shape[0]):
        if self.field[j].species == i:
            if j >= total:
                self.field[j].active = 0
            else:
                self.field[j].active = 1

set_species_total_active_amount(i, total, amount)

Set particle activity amount of a species.

Parameters:

Name Type Description Default
i i32

Species index.

required
total i32

(ti.i32): Total number of active particles.

required
amount i32

Amount of activity.

required
Source code in src/tolvera/particles.py
@ti.kernel
def set_species_total_active_amount(self, i: ti.i32, total: ti.i32, amount: ti.f32):
    """Set particle activity amount of a species.

    Args:
        i (ti.i32): Species index.
        total: (ti.i32): Total number of active particles.
        amount (ti.i32): Amount of activity.
    """
    for j in range(self.field.shape[0]):
        if self.field[j].species == i:
            if j >= total:
                self.field[j].active = 0
            else:
                self.field[j].active = amount

set_total_active(total)

Set the total number of active particles.

Parameters:

Name Type Description Default
total i32

Total active particles.

required
Source code in src/tolvera/particles.py
@ti.kernel
def set_total_active(self, total: ti.i32):
    """Set the total number of active particles.

    Args:
        total (ti.i32): Total active particles.
    """
    for i in range(self.field.shape[0]):
        if i >= total:
            self.field[i].active = 0
        else:
            self.field[i].active = 1

set_total_active_amount(total, amount)

Set the total number of active particles.

Parameters:

Name Type Description Default
total i32

Total active particles.

required
amount f32

Amount of activity.

required
Source code in src/tolvera/particles.py
@ti.kernel
def set_total_active_amount(self, total: ti.i32, amount: ti.f32):
    """Set the total number of active particles.

    Args:
        total (ti.i32): Total active particles.
        amount (ti.f32): Amount of activity.
    """
    for i in range(self.field.shape[0]):
        if i >= total:
            self.field[i].active = 0
        else:
            self.field[i].active = amount

speed(speed=None)

Get or set the speed of the particle system.

Parameters:

Name Type Description Default
speed float

Speed. Defaults to None.

None

Returns:

Name Type Description
float

Speed.

Source code in src/tolvera/particles.py
def speed(self, speed: float = None):
    """Get or set the speed of the particle system.

    Args:
        speed (float, optional): Speed. Defaults to None.

    Returns:
        float: Speed.
    """
    if speed is not None:
        self._speed[None] = 1 / (speed + 0.0001)
    else:
        return self._speed[None]

toroidal_wrap(i)

Toroidal wrap a particle.

Parameters:

Name Type Description Default
i i32

Particle index.

required
Source code in src/tolvera/particles.py
@ti.func
def toroidal_wrap(self, i: ti.i32):
    """Toroidal wrap a particle.

    Args:
        i (ti.i32): Particle index.
    """
    p = self.field[i]
    if p.pos[0] > self.tv.x:
        self.field[i].pos[0] = 0.0
    if p.pos[0] < 0.0:
        self.field[i].pos[0] = self.tv.x
    if p.pos[1] > self.tv.y:
        self.field[i].pos[1] = 0.0
    if p.pos[1] < 0.0:
        self.field[i].pos[1] = self.tv.y

update()

Update the particle system.

Source code in src/tolvera/particles.py
@ti.kernel
def update(self):
    """Update the particle system."""
    j = 0
    for i in range(self.n):
        if self.field[i] == 0.0: continue
        self.toroidal_wrap(i)
        self.limit_speed(i)
        # self.detect_collisions(i, self.C.COLL_RAD)
        # self.update_prev(i)
        self.active_indexes[j] = i
        j += 1
    self.active_count[None] = j

update_prev(i)

Update the previous position and velocity of a particle.

Parameters:

Name Type Description Default
i i32

Particle index.

required
Source code in src/tolvera/particles.py
@ti.func
def update_prev(self, i: ti.i32):
    """Update the previous position and velocity of a particle.

    Args:
        i (ti.i32): Particle index.
    """
    self.field[i].ppos = self.field[i].pos
    self.field[i].pvel = self.field[i].vel

Pixels

Pixels class for drawing pixels to the screen.

This class is used to draw pixels to the screen. It contains methods for drawing points, lines, rectangles, circles, triangles, and polygons. It also contains methods for blending pixels together, flipping pixels, inverting pixels, and diffusing, decaying and clearing pixels.

It tries to follow a similar API to the Processing library.

Source code in src/tolvera/pixels.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
@ti.data_oriented
class Pixels:
    """Pixels class for drawing pixels to the screen.

    This class is used to draw pixels to the screen. It contains methods for drawing
    points, lines, rectangles, circles, triangles, and polygons. It also contains
    methods for blending pixels together, flipping pixels, inverting pixels, and
    diffusing, decaying and clearing pixels.

    It tries to follow a similar API to the Processing library.
    """
    def __init__(self, tolvera, **kwargs):
        """Initialise Pixels

        Args:
            tolvera (Tolvera): Tölvera instance.
            **kwargs: Keyword arguments.
                polygon_mode (str): Polygon mode. Defaults to "crossing".
                brightness (float): Brightness. Defaults to 1.0. 
        """
        self.tv = tolvera
        self.kwargs = kwargs
        self.polygon_mode = kwargs.get("polygon_mode", "crossing")
        self.x = kwargs.get("x", self.tv.x)
        self.y = kwargs.get("y", self.tv.y)
        self.px = Pixel.field(shape=(self.x, self.y))
        brightness = kwargs.get("brightness", 1.0)
        self.CONSTS = CONSTS(
            {
                "BRIGHTNESS": (ti.f32, brightness),
            }
        )
        self.shape_enum = {
            "point": 0,
            "line": 1,
            "rect": 2,
            "circle": 3,
            "triangle": 4,
            "polygon": 5,
        }


    def set(self, px: Any):
        """Set pixels.

        Args:
            px (Any): Pixels to set. Can be Pixels, StructField, MatrixField, etc (see rgba_from_px).
        """
        self.px.rgba = self.rgba_from_px(px)

    @ti.kernel
    def k_set(self, px: ti.template()):
        for x, y in ti.ndrange(self.x, self.y):
            self.px.rgba[x, y] = px.px.rgba[x, y]

    @ti.kernel
    def f_set(self, px: ti.template()):
        for x, y in ti.ndrange(self.x, self.y):
            self.px.rgba[x, y] = px.px.rgba[x, y]

    @ti.func
    def stamp(self, x: ti.i32, y: ti.i32, px: ti.template()):
        """Stamp pixels.

        Args:
            x (ti.i32): X position.
            y (ti.i32): Y position.
            px (ti.template): Pixels to stamp.
        """
        for i, j in ti.ndrange(px.px.shape[0], px.px.shape[1]):
            p = px.px.rgba[i, j]
            if p[0]+p[1]+p[2] > 0: # transparency
                self.px.rgba[x + i, y + j] = p

    @ti.kernel
    def from_numpy(self, img: ti.template()):
        for x, y in ti.ndrange(self.x, self.y):
            if img[x, y, 0]+img[x, y, 1]+img[x, y, 2] > 0.:
                self.px.rgba[x, y] = ti.Vector([
                    img[x, y, 0]/255.,
                    img[x, y, 1]/255.,
                    img[x, y, 2]/255.,
                    img[x, y, 3]/255.])

    def from_img(self, path: str):
        img = ti.tools.imread(path)
        img_fld = ti.field(dtype=ti.f32, shape=img.shape)
        img_fld.from_numpy(img)
        self.from_numpy(img_fld)
        return img_fld

    def get(self):
        """Get pixels."""
        return self.px

    @ti.kernel
    def clear(self):
        """Clear pixels."""
        self.px.rgba.fill(0)

    @ti.kernel
    def diffuse(self, evaporate: ti.f32):
        """Diffuse pixels.

        Args:
            evaporate (float): Evaporation rate.
        """
        for i, j in ti.ndrange(self.x, self.y):
            d = ti.Vector([0.0, 0.0, 0.0, 0.0])
            for di in ti.static(range(-1, 2)):
                for dj in ti.static(range(-1, 2)):
                    dx = (i + di) % self.x
                    dy = (j + dj) % self.y
                    d += self.px.rgba[dx, dy]
            d *= 0.99 / 9.0
            self.px.rgba[i, j] = d

    @ti.func
    def background(self, r: ti.f32, g: ti.f32, b: ti.f32):
        """Set background colour.

        Args:
            r (ti.f32): Red.
            g (ti.f32): Green.
            b (ti.f32): Blue.
        """
        bg = ti.Vector([r, g, b, 1.0])
        self.rect(0, 0, self.x, self.y, bg)

    @ti.func
    def point(self, x: ti.i32, y: ti.i32, rgba: vec4):
        """Draw point.

        Args:
            x (ti.i32): X position.
            y (ti.i32): Y position.
            rgba (vec4): Colour.
        """
        self.px.rgba[x, y] = rgba

    @ti.func
    def points(self, x: ti.template(), y: ti.template(), rgba: vec4):
        """Draw points with the same colour.

        Args:
            x (ti.template): X positions.
            y (ti.template): Y positions.
            rgba (vec4): Colour.
        """
        for i in ti.static(range(len(x))):
            self.point(x[i], y[i], rgba)

    @ti.func
    def rect(self, x: ti.i32, y: ti.i32, w: ti.i32, h: ti.i32, rgba: vec4):
        """Draw a filled rectangle.

        Args:
            x (ti.i32): X position.
            y (ti.i32): Y position.
            w (ti.i32): Width.
            h (ti.i32): Height.
            rgba (vec4): Colour.
        """
        # TODO: fill arg
        # TODO: gradients, lerp with ti.math.mix(x, y, a)
        for i, j in ti.ndrange(w, h):
            self.px.rgba[x + i, y + j] = rgba

    @ti.kernel
    def stamp(self, x: ti.i32, y: ti.i32, px: ti.template()):
        """Stamp pixels.

        Args:
            x (ti.i32): X position.
            y (ti.i32): Y position.
            px (ti.template): Pixels to stamp.
        """
        self.stamp_f(x, y, px)

    @ti.func
    def stamp_f(self, x: ti.i32, y: ti.i32, px: ti.template()):
        """Stamp pixels.

        Args:
            x (ti.i32): X position.
            y (ti.i32): Y position.
            px (ti.template): Pixels to stamp.
        """
        for i, j in ti.ndrange(px.px.shape[0], px.px.shape[1]):
            p = px.px.rgba[i, j]
            if p[0]+p[1]+p[2] > 0: # transparency
                self.px.rgba[x + i, y + j] = p

    @ti.func
    def plot(self, x, y, c, rgba):
        """Set the pixel color with blending."""
        self.px.rgba[x, y] = self.px.rgba[x, y] * (1 - c) + rgba * c

    @ti.func
    def ipart(self, x):
        return ti.math.floor(x)

    @ti.func
    def round(self, x):
        return self.ipart(x + 0.5)

    @ti.func
    def fpart(self, x):
        return x - ti.math.floor(x)

    @ti.func
    def rfpart(self, x):
        return 1 - self.fpart(x)

    @ti.func
    def line(self, x0: ti.f32, y0: ti.f32, x1: ti.f32, y1: ti.f32, rgba: vec4):
        """Draw an anti-aliased line using Xiaolin Wu's algorithm."""
        steep = ti.abs(y1 - y0) > ti.abs(x1 - x0)
        if steep:
            x0, y0 = y0, x0
            x1, y1 = y1, x1

        if x0 > x1:
            x0, x1 = x1, x0
            y0, y1 = y1, y0

        dx = x1 - x0
        dy = y1 - y0
        gradient = dy / dx if dx != 0 else 1.0

        xend = ti.math.round(x0)
        yend = y0 + gradient * (xend - x0)
        xgap = self.rfpart(x0 + 0.5)
        xpxl1 = int(xend)
        ypxl1 = int(self.ipart(yend))
        if steep:
            self.plot(ypxl1, xpxl1, self.rfpart(yend) * xgap, rgba)
            self.plot(ypxl1 + 1, xpxl1, self.fpart(yend) * xgap, rgba)
        else:
            self.plot(xpxl1, ypxl1, self.rfpart(yend) * xgap, rgba)
            self.plot(xpxl1, ypxl1 + 1, self.fpart(yend) * xgap, rgba)

        intery = yend + gradient

        xend = ti.math.round(x1)
        yend = y1 + gradient * (xend - x1)
        xgap = self.fpart(x1 + 0.5)
        xpxl2 = int(xend)
        ypxl2 = int(self.ipart(yend))
        if steep:
            self.plot(ypxl2, xpxl2, self.rfpart(yend) * xgap, rgba)
            self.plot(ypxl2 + 1, xpxl2, self.fpart(yend) * xgap, rgba)
        else:
            self.plot(xpxl2, ypxl2, self.rfpart(yend) * xgap, rgba)
            self.plot(xpxl2, ypxl2 + 1, self.fpart(yend) * xgap, rgba)

        if steep:
            for x in range(xpxl1 + 1, xpxl2):
                self.plot(int(self.ipart(intery)), x, self.rfpart(intery), rgba)
                self.plot(int(self.ipart(intery)) + 1, x, self.fpart(intery), rgba)
                intery += gradient
        else:
            for x in range(xpxl1 + 1, xpxl2):
                self.plot(x, int(self.ipart(intery)), self.rfpart(intery), rgba)
                self.plot(x, int(self.ipart(intery)) + 1, self.fpart(intery), rgba)
                intery += gradient

    # @ti.func
    # def line(self, x0: ti.i32, y0: ti.i32, x1: ti.i32, y1: ti.i32, rgba: vec4):
    #     """Draw a line using Bresenham's algorithm.

    #     Args:
    #         x0 (ti.i32): X start position.
    #         y0 (ti.i32): Y start position.
    #         x1 (ti.i32): X end position.
    #         y1 (ti.i32): Y end position.
    #         rgba (vec4): Colour.

    #     TODO: thickness
    #     TODO: anti-aliasing
    #     TODO: should lines wrap around (as two lines)?
    #     """
    #     dx = ti.abs(x1 - x0)
    #     dy = ti.abs(y1 - y0)
    #     x, y = x0, y0
    #     sx = -1 if x0 > x1 else 1
    #     sy = -1 if y0 > y1 else 1
    #     if dx > dy:
    #         err = dx / 2.0
    #         while x != x1:
    #             self.px.rgba[x, y] = rgba
    #             err -= dy
    #             if err < 0:
    #                 y += sy
    #                 err += dx
    #             x += sx
    #     else:
    #         err = dy / 2.0
    #         while y != y1:
    #             self.px.rgba[x, y] = rgba
    #             err -= dx
    #             if err < 0:
    #                 x += sx
    #                 err += dy
    #             y += sy
    #     self.px.rgba[x, y] = rgba

    @ti.func
    def lines(self, points: ti.template(), rgba: vec4):
        """Draw lines with the same colour.

        Args:
            points (ti.template): Points.
            rgba (vec4): Colour.
        """
        for i in range(points.shape[0] - 1):
            self.line(points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], rgba)

    @ti.func
    def circle(self, x: ti.i32, y: ti.i32, r: ti.i32, rgba: vec4):
        """Draw a filled circle.

        Args:
            x (ti.i32): X position.
            y (ti.i32): Y position.
            r (ti.i32): Radius.
            rgba (vec4): Colour.
        """
        for i in range(r + 1):
            d = ti.sqrt(r**2 - i**2)
            d_int = ti.cast(d, ti.i32)
            # TODO: parallelise ?
            for j in range(d_int):
                self.px.rgba[x + i, y + j] = rgba
                self.px.rgba[x + i, y - j] = rgba
                self.px.rgba[x - i, y - j] = rgba
                self.px.rgba[x - i, y + j] = rgba

    @ti.func
    def circles(self, x: ti.template(), y: ti.template(), r: ti.template(), rgba: vec4):
        """Draw circles with the same colour.

        Args:
            x (ti.template): X positions.
            y (ti.template): Y positions.
            r (ti.template): Radii.
            rgba (vec4): Colour.
        """
        for i in ti.static(range(len(x))):
            self.circle(x[i], y[i], r[i], rgba)

    @ti.func
    def triangle(self, a, b, c, rgba: vec4):
        """Draw a filled triangle.

        Args:
            a (vec2): Point A.
            b (vec2): Point B.
            c (vec2): Point C.
            rgba (vec4): Colour.
        """
        # TODO: fill arg
        x = ti.Vector([a[0], b[0], c[0]])
        y = ti.Vector([a[1], b[1], c[1]])
        self.polygon(x, y, rgba)

    @ti.func
    def polygon(self, x: ti.template(), y: ti.template(), rgba: vec4):
        """Draw a filled polygon.

        Polygons are drawn according to the polygon mode, which can be "crossing" 
        (default) or "winding". First, the bounding box of the polygon is calculated.
        Then, we check if each pixel in the bounding box is inside the polygon. If it
        is, we draw it (along with each neighbour pixel).

        Reference for point in polygon inclusion testing:
        http://www.dgp.toronto.edu/~mac/e-stuff/point_in_polygon.py

        Args:
            x (ti.template): X positions.
            y (ti.template): Y positions.
            rgba (vec4): Colour.

        TODO: fill arg
        """
        x_min, x_max = ti.cast(x.min(), ti.i32), ti.cast(x.max(), ti.i32)
        y_min, y_max = ti.cast(y.min(), ti.i32), ti.cast(y.max(), ti.i32)
        l = len(x)
        for i, j in ti.ndrange(x_max - x_min, y_max - y_min):
            p = ti.Vector([x_min + i, y_min + j])
            if self._is_inside(p, x, y, l) != 0:
                # TODO: abstract out, weight?
                """
                x-1,y-1  x,y-1  x+1,y-1
                x-1,y    x,y    x+1,y
                x-1,y+1  x,y+1  x+1,y+1
                """
                _x, _y = p[0], p[1]
                self.px.rgba[_x - 1, _y - 1] = rgba
                self.px.rgba[_x - 1, _y] = rgba
                self.px.rgba[_x - 1, _y + 1] = rgba

                self.px.rgba[_x, _y - 1] = rgba
                self.px.rgba[_x, _y] = rgba
                self.px.rgba[_x, _y + 1] = rgba

                self.px.rgba[_x + 1, _y - 1] = rgba
                self.px.rgba[_x + 1, _y] = rgba
                self.px.rgba[_x + 1, _y + 1] = rgba

    @ti.func
    def _is_inside(self, p: vec2, x: ti.template(), y: ti.template(), l: ti.i32):
        """Check if point is inside polygon.

        Args:
            p (vec2): Point.
            x (ti.template): X positions.
            y (ti.template): Y positions.
            l (ti.i32): Number of points.

        Returns:
            int: 1 if inside, 0 if outside.
        """
        is_inside = 0
        if self.polygon_mode == "crossing":
            is_inside = self._is_inside_crossing(p, x, y, l)
        elif self.polygon_mode == "winding":
            is_inside = self._is_inside_winding(p, x, y, l)
        return is_inside

    @ti.func
    def _is_inside_crossing(self, p: vec2, x: ti.template(), y: ti.template(), l: ti.i32):
        """Check if point is inside polygon using crossing number algorithm.

        Args:
            p (vec2): Point.
            x (ti.template): X positions.
            y (ti.template): Y positions.
            l (ti.i32): Number of points.

        Returns:
            int: 1 if inside, 0 if outside.
        """
        n = 0
        v0, v1 = ti.Vector([0.0, 0.0]), ti.Vector([0.0, 0.0])
        for i in range(l):
            i1 = i + 1 if i < l - 1 else 0
            v0, v1 = [x[i], y[i]], [x[i1], y[i1]]
            if (v0[1] <= p[1] and v1[1] > p[1]) or (v0[1] > p[1] and v1[1] <= p[1]):
                vt = (p[1] - v0[1]) / (v1[1] - v0[1])
                if p[0] < v0[0] + vt * (v1[0] - v0[0]):
                    n += 1
        return n % 2

    @ti.func
    def _is_inside_winding(self, p: vec2, x: ti.template(), y: ti.template(), l: ti.i32):
        """Check if point is inside polygon using winding number algorithm.

        Args:
            p (vec2): Point.
            x (ti.template): X positions.
            y (ti.template): Y positions.
            l (ti.i32): Number of points.

        Returns:
            int: 1 if inside, 0 if outside.
        """
        n = 0
        v0, v1 = ti.Vector([0.0, 0.0]), ti.Vector([0.0, 0.0])
        for i in range(l):
            i1 = i + 1 if i < l - 1 else 0
            v0, v1 = [x[i], y[i]], [x[i1], y[i1]]
            if v0[1] <= p[1] and v1[1] > p[1] and (v0 - v1).cross(p - v1) > 0:
                n += 1
            elif v1[1] <= p[1] and (v0 - v1).cross(p - v1) < 0:
                n -= 1
        return n

    @ti.kernel
    def flip_x(self):
        """Flip image in x-axis."""
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = self.px.rgba[self.x - 1 - i, j]

    @ti.kernel
    def flip_y(self):
        """Flip image in y-axis."""
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = self.px.rgba[i, self.y - 1 - j]

    @ti.kernel
    def invert(self):
        """Invert image."""
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = 1.0 - self.px.rgba[i, j]

    @ti.kernel
    def decay(self, rate: ti.f32):
        """Decay pixels.

        Args:
            rate (ti.f32): decay rate.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] *= rate

    def blend_add(self, px: ti.template()):
        """Blend by adding pixels together (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_add(self.rgba_from_px(px))

    @ti.kernel
    def _blend_add(self, rgba: ti.template()):
        """Blend by adding pixels together (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] += rgba[i, j]

    def blend_sub(self, px: ti.template()):
        """Blend by subtracting pixels (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_sub(self.rgba_from_px(px))

    @ti.kernel
    def _blend_sub(self, rgba: ti.template()):
        """Blend by subtracting pixels (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] -= rgba[i, j]

    def blend_mul(self, px: ti.template()):
        """Blend by multiplying pixels (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_mul(self.rgba_from_px(px))

    @ti.kernel
    def _blend_mul(self, rgba: ti.template()):
        """Blend by multiplying pixels (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] *= rgba[i, j]

    def blend_div(self, px: ti.template()):
        """Blend by dividing pixels (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_div(self.rgba_from_px(px))

    @ti.kernel
    def _blend_div(self, rgba: ti.template()):
        """Blend by dividing pixels (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] /= rgba[i, j]

    def blend_min(self, px: ti.template()):
        """Blend by taking the minimum of each pixel (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_min(self.rgba_from_px(px))

    @ti.kernel
    def _blend_min(self, rgba: ti.template()):
        """Blend by taking the minimum of each pixel (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = ti.min(self.px.rgba[i, j], rgba[i, j])

    def blend_max(self, px: ti.template()):
        """Blend by taking the maximum of each pixel (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_max(self.rgba_from_px(px))

    @ti.kernel
    def _blend_max(self, rgba: ti.template()):
        """Blend by taking the maximum of each pixel (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = ti.max(self.px.rgba[i, j], rgba[i, j])

    def blend_diff(self, px: ti.template()):
        """Blend by taking the difference of each pixel (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_diff(self.rgba_from_px(px))

    @ti.kernel
    def _blend_diff(self, rgba: ti.template()):
        """Blend by taking the difference of each pixel (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = ti.abs(self.px.rgba[i, j] - rgba[i, j])

    def blend_diff_inv(self, px: ti.template()):
        """Blend by taking the inverse difference of each pixel (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
        """
        self._blend_diff_inv(self.rgba_from_px(px))

    @ti.kernel
    def _blend_diff_inv(self, rgba: ti.template()):
        """Blend by taking the inverse difference of each pixel (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = ti.abs(rgba[i, j] - self.px.rgba[i, j])

    def blend_mix(self, px: ti.template(), amount: ti.f32):
        """Blend by mixing pixels (Python scope).

        Args:
            px (ti.template): Pixels to blend with.
            amount (ti.f32): Amount to mix.
        """
        self._blend_mix(self.rgba_from_px(px), amount)

    @ti.kernel
    def _blend_mix(self, rgba: ti.template(), amount: ti.f32):
        """Blend by mixing pixels (Taichi scope).

        Args:
            rgba (ti.template): Pixels to blend with.
            amount (ti.f32): Amount to mix.
        """
        for i, j in ti.ndrange(self.x, self.y):
            self.px.rgba[i, j] = ti.math.mix(self.px.rgba[i, j], rgba[i, j], amount)

    @ti.kernel
    def blur(self, radius: ti.i32):
        """Blur pixels.

        Args:
            radius (ti.i32): Blur radius.
        """
        for i, j in ti.ndrange(self.x, self.y):
            d = ti.Vector([0.0, 0.0, 0.0, 0.0])
            for di in range(-radius, radius + 1):
                for dj in range(-radius, radius + 1):
                    dx = (i + di) % self.x
                    dy = (j + dj) % self.y
                    d += self.px.rgba[dx, dy]
            d /= (radius * 2 + 1) ** 2
            self.px.rgba[i, j] = d

    def particles(
        self, particles: ti.template(), species: ti.template(), shape="circle"
    ):
        """Draw particles.

        Args:
            particles (ti.template): Particles.
            species (ti.template): Species.
            shape (str, optional): Shape. Defaults to "circle".
        """
        shape = self.shape_enum[shape]
        self._particles(particles, species, shape)

    @ti.kernel
    def _particles(self, particles: ti.template(), species: ti.template(), shape: int):
        """Draw particles.

        Args:
            particles (ti.template): Particles.
            species (ti.template): Species.
            shape (int): Shape enum value.
        """
        for i in range(self.tv.p.n):
            p = particles.field[i]
            s = species[p.species]
            if p.active == 0.0:
                continue
            px = ti.cast(p.pos[0], ti.i32)
            py = ti.cast(p.pos[1], ti.i32)
            vx = ti.cast(p.pos[0] + p.vel[0] * 20, ti.i32)
            vy = ti.cast(p.pos[1] + p.vel[1] * 20, ti.i32)
            rgba = s.rgba * self.CONSTS.BRIGHTNESS
            if shape == 0:
                self.point(px, py, rgba)
            elif shape == 1:
                self.line(px, py, vx, vy, rgba)
            elif shape == 2:
                side = int(s.size) * 2
                self.rect(px, py, side, side, rgba)
            elif shape == 3:
                self.circle(px, py, p.size, rgba)
            elif shape == 4:
                a = p.pos
                b = p.pos + 1
                c = a + b
                self.triangle(a, b, c, rgba)
            # elif shape == 5:
            #     self.polygon(px, py, rgba)

    def rgba_from_px(self, px):
        """Get rgba from pixels.

        Args:
            px (Any): Pixels to get rgba from.

        Raises:
            TypeError: If pixel field cannot be found.

        Returns:
            MatrixField: RGBA matrix field.
        """
        if isinstance(px, Pixels):
            return px.px.rgba
        elif isinstance(px, StructField):
            return px.rgba
        elif isinstance(px, MatrixField):
            return px
        elif isinstance(px, ScalarField):
            return px
        else:
            try:
                return px.px.px.rgba
            except:
                raise TypeError(f"Cannot find pixel field in {type(px)}")

    def __call__(self):
        """Call returns pixels."""
        return self.get()

__call__()

Call returns pixels.

Source code in src/tolvera/pixels.py
def __call__(self):
    """Call returns pixels."""
    return self.get()

__init__(tolvera, **kwargs)

Initialise Pixels

Parameters:

Name Type Description Default
tolvera Tolvera

Tölvera instance.

required
**kwargs

Keyword arguments. polygon_mode (str): Polygon mode. Defaults to "crossing". brightness (float): Brightness. Defaults to 1.0.

{}
Source code in src/tolvera/pixels.py
def __init__(self, tolvera, **kwargs):
    """Initialise Pixels

    Args:
        tolvera (Tolvera): Tölvera instance.
        **kwargs: Keyword arguments.
            polygon_mode (str): Polygon mode. Defaults to "crossing".
            brightness (float): Brightness. Defaults to 1.0. 
    """
    self.tv = tolvera
    self.kwargs = kwargs
    self.polygon_mode = kwargs.get("polygon_mode", "crossing")
    self.x = kwargs.get("x", self.tv.x)
    self.y = kwargs.get("y", self.tv.y)
    self.px = Pixel.field(shape=(self.x, self.y))
    brightness = kwargs.get("brightness", 1.0)
    self.CONSTS = CONSTS(
        {
            "BRIGHTNESS": (ti.f32, brightness),
        }
    )
    self.shape_enum = {
        "point": 0,
        "line": 1,
        "rect": 2,
        "circle": 3,
        "triangle": 4,
        "polygon": 5,
    }

_blend_add(rgba)

Blend by adding pixels together (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_add(self, rgba: ti.template()):
    """Blend by adding pixels together (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] += rgba[i, j]

_blend_diff(rgba)

Blend by taking the difference of each pixel (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_diff(self, rgba: ti.template()):
    """Blend by taking the difference of each pixel (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = ti.abs(self.px.rgba[i, j] - rgba[i, j])

_blend_diff_inv(rgba)

Blend by taking the inverse difference of each pixel (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_diff_inv(self, rgba: ti.template()):
    """Blend by taking the inverse difference of each pixel (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = ti.abs(rgba[i, j] - self.px.rgba[i, j])

_blend_div(rgba)

Blend by dividing pixels (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_div(self, rgba: ti.template()):
    """Blend by dividing pixels (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] /= rgba[i, j]

_blend_max(rgba)

Blend by taking the maximum of each pixel (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_max(self, rgba: ti.template()):
    """Blend by taking the maximum of each pixel (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = ti.max(self.px.rgba[i, j], rgba[i, j])

_blend_min(rgba)

Blend by taking the minimum of each pixel (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_min(self, rgba: ti.template()):
    """Blend by taking the minimum of each pixel (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = ti.min(self.px.rgba[i, j], rgba[i, j])

_blend_mix(rgba, amount)

Blend by mixing pixels (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
amount f32

Amount to mix.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_mix(self, rgba: ti.template(), amount: ti.f32):
    """Blend by mixing pixels (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
        amount (ti.f32): Amount to mix.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = ti.math.mix(self.px.rgba[i, j], rgba[i, j], amount)

_blend_mul(rgba)

Blend by multiplying pixels (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_mul(self, rgba: ti.template()):
    """Blend by multiplying pixels (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] *= rgba[i, j]

_blend_sub(rgba)

Blend by subtracting pixels (Taichi scope).

Parameters:

Name Type Description Default
rgba template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _blend_sub(self, rgba: ti.template()):
    """Blend by subtracting pixels (Taichi scope).

    Args:
        rgba (ti.template): Pixels to blend with.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] -= rgba[i, j]

_is_inside(p, x, y, l)

Check if point is inside polygon.

Parameters:

Name Type Description Default
p vec2

Point.

required
x template

X positions.

required
y template

Y positions.

required
l i32

Number of points.

required

Returns:

Name Type Description
int

1 if inside, 0 if outside.

Source code in src/tolvera/pixels.py
@ti.func
def _is_inside(self, p: vec2, x: ti.template(), y: ti.template(), l: ti.i32):
    """Check if point is inside polygon.

    Args:
        p (vec2): Point.
        x (ti.template): X positions.
        y (ti.template): Y positions.
        l (ti.i32): Number of points.

    Returns:
        int: 1 if inside, 0 if outside.
    """
    is_inside = 0
    if self.polygon_mode == "crossing":
        is_inside = self._is_inside_crossing(p, x, y, l)
    elif self.polygon_mode == "winding":
        is_inside = self._is_inside_winding(p, x, y, l)
    return is_inside

_is_inside_crossing(p, x, y, l)

Check if point is inside polygon using crossing number algorithm.

Parameters:

Name Type Description Default
p vec2

Point.

required
x template

X positions.

required
y template

Y positions.

required
l i32

Number of points.

required

Returns:

Name Type Description
int

1 if inside, 0 if outside.

Source code in src/tolvera/pixels.py
@ti.func
def _is_inside_crossing(self, p: vec2, x: ti.template(), y: ti.template(), l: ti.i32):
    """Check if point is inside polygon using crossing number algorithm.

    Args:
        p (vec2): Point.
        x (ti.template): X positions.
        y (ti.template): Y positions.
        l (ti.i32): Number of points.

    Returns:
        int: 1 if inside, 0 if outside.
    """
    n = 0
    v0, v1 = ti.Vector([0.0, 0.0]), ti.Vector([0.0, 0.0])
    for i in range(l):
        i1 = i + 1 if i < l - 1 else 0
        v0, v1 = [x[i], y[i]], [x[i1], y[i1]]
        if (v0[1] <= p[1] and v1[1] > p[1]) or (v0[1] > p[1] and v1[1] <= p[1]):
            vt = (p[1] - v0[1]) / (v1[1] - v0[1])
            if p[0] < v0[0] + vt * (v1[0] - v0[0]):
                n += 1
    return n % 2

_is_inside_winding(p, x, y, l)

Check if point is inside polygon using winding number algorithm.

Parameters:

Name Type Description Default
p vec2

Point.

required
x template

X positions.

required
y template

Y positions.

required
l i32

Number of points.

required

Returns:

Name Type Description
int

1 if inside, 0 if outside.

Source code in src/tolvera/pixels.py
@ti.func
def _is_inside_winding(self, p: vec2, x: ti.template(), y: ti.template(), l: ti.i32):
    """Check if point is inside polygon using winding number algorithm.

    Args:
        p (vec2): Point.
        x (ti.template): X positions.
        y (ti.template): Y positions.
        l (ti.i32): Number of points.

    Returns:
        int: 1 if inside, 0 if outside.
    """
    n = 0
    v0, v1 = ti.Vector([0.0, 0.0]), ti.Vector([0.0, 0.0])
    for i in range(l):
        i1 = i + 1 if i < l - 1 else 0
        v0, v1 = [x[i], y[i]], [x[i1], y[i1]]
        if v0[1] <= p[1] and v1[1] > p[1] and (v0 - v1).cross(p - v1) > 0:
            n += 1
        elif v1[1] <= p[1] and (v0 - v1).cross(p - v1) < 0:
            n -= 1
    return n

_particles(particles, species, shape)

Draw particles.

Parameters:

Name Type Description Default
particles template

Particles.

required
species template

Species.

required
shape int

Shape enum value.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def _particles(self, particles: ti.template(), species: ti.template(), shape: int):
    """Draw particles.

    Args:
        particles (ti.template): Particles.
        species (ti.template): Species.
        shape (int): Shape enum value.
    """
    for i in range(self.tv.p.n):
        p = particles.field[i]
        s = species[p.species]
        if p.active == 0.0:
            continue
        px = ti.cast(p.pos[0], ti.i32)
        py = ti.cast(p.pos[1], ti.i32)
        vx = ti.cast(p.pos[0] + p.vel[0] * 20, ti.i32)
        vy = ti.cast(p.pos[1] + p.vel[1] * 20, ti.i32)
        rgba = s.rgba * self.CONSTS.BRIGHTNESS
        if shape == 0:
            self.point(px, py, rgba)
        elif shape == 1:
            self.line(px, py, vx, vy, rgba)
        elif shape == 2:
            side = int(s.size) * 2
            self.rect(px, py, side, side, rgba)
        elif shape == 3:
            self.circle(px, py, p.size, rgba)
        elif shape == 4:
            a = p.pos
            b = p.pos + 1
            c = a + b
            self.triangle(a, b, c, rgba)

background(r, g, b)

Set background colour.

Parameters:

Name Type Description Default
r f32

Red.

required
g f32

Green.

required
b f32

Blue.

required
Source code in src/tolvera/pixels.py
@ti.func
def background(self, r: ti.f32, g: ti.f32, b: ti.f32):
    """Set background colour.

    Args:
        r (ti.f32): Red.
        g (ti.f32): Green.
        b (ti.f32): Blue.
    """
    bg = ti.Vector([r, g, b, 1.0])
    self.rect(0, 0, self.x, self.y, bg)

blend_add(px)

Blend by adding pixels together (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_add(self, px: ti.template()):
    """Blend by adding pixels together (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_add(self.rgba_from_px(px))

blend_diff(px)

Blend by taking the difference of each pixel (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_diff(self, px: ti.template()):
    """Blend by taking the difference of each pixel (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_diff(self.rgba_from_px(px))

blend_diff_inv(px)

Blend by taking the inverse difference of each pixel (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_diff_inv(self, px: ti.template()):
    """Blend by taking the inverse difference of each pixel (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_diff_inv(self.rgba_from_px(px))

blend_div(px)

Blend by dividing pixels (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_div(self, px: ti.template()):
    """Blend by dividing pixels (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_div(self.rgba_from_px(px))

blend_max(px)

Blend by taking the maximum of each pixel (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_max(self, px: ti.template()):
    """Blend by taking the maximum of each pixel (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_max(self.rgba_from_px(px))

blend_min(px)

Blend by taking the minimum of each pixel (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_min(self, px: ti.template()):
    """Blend by taking the minimum of each pixel (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_min(self.rgba_from_px(px))

blend_mix(px, amount)

Blend by mixing pixels (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
amount f32

Amount to mix.

required
Source code in src/tolvera/pixels.py
def blend_mix(self, px: ti.template(), amount: ti.f32):
    """Blend by mixing pixels (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
        amount (ti.f32): Amount to mix.
    """
    self._blend_mix(self.rgba_from_px(px), amount)

blend_mul(px)

Blend by multiplying pixels (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_mul(self, px: ti.template()):
    """Blend by multiplying pixels (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_mul(self.rgba_from_px(px))

blend_sub(px)

Blend by subtracting pixels (Python scope).

Parameters:

Name Type Description Default
px template

Pixels to blend with.

required
Source code in src/tolvera/pixels.py
def blend_sub(self, px: ti.template()):
    """Blend by subtracting pixels (Python scope).

    Args:
        px (ti.template): Pixels to blend with.
    """
    self._blend_sub(self.rgba_from_px(px))

blur(radius)

Blur pixels.

Parameters:

Name Type Description Default
radius i32

Blur radius.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def blur(self, radius: ti.i32):
    """Blur pixels.

    Args:
        radius (ti.i32): Blur radius.
    """
    for i, j in ti.ndrange(self.x, self.y):
        d = ti.Vector([0.0, 0.0, 0.0, 0.0])
        for di in range(-radius, radius + 1):
            for dj in range(-radius, radius + 1):
                dx = (i + di) % self.x
                dy = (j + dj) % self.y
                d += self.px.rgba[dx, dy]
        d /= (radius * 2 + 1) ** 2
        self.px.rgba[i, j] = d

circle(x, y, r, rgba)

Draw a filled circle.

Parameters:

Name Type Description Default
x i32

X position.

required
y i32

Y position.

required
r i32

Radius.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def circle(self, x: ti.i32, y: ti.i32, r: ti.i32, rgba: vec4):
    """Draw a filled circle.

    Args:
        x (ti.i32): X position.
        y (ti.i32): Y position.
        r (ti.i32): Radius.
        rgba (vec4): Colour.
    """
    for i in range(r + 1):
        d = ti.sqrt(r**2 - i**2)
        d_int = ti.cast(d, ti.i32)
        # TODO: parallelise ?
        for j in range(d_int):
            self.px.rgba[x + i, y + j] = rgba
            self.px.rgba[x + i, y - j] = rgba
            self.px.rgba[x - i, y - j] = rgba
            self.px.rgba[x - i, y + j] = rgba

circles(x, y, r, rgba)

Draw circles with the same colour.

Parameters:

Name Type Description Default
x template

X positions.

required
y template

Y positions.

required
r template

Radii.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def circles(self, x: ti.template(), y: ti.template(), r: ti.template(), rgba: vec4):
    """Draw circles with the same colour.

    Args:
        x (ti.template): X positions.
        y (ti.template): Y positions.
        r (ti.template): Radii.
        rgba (vec4): Colour.
    """
    for i in ti.static(range(len(x))):
        self.circle(x[i], y[i], r[i], rgba)

clear()

Clear pixels.

Source code in src/tolvera/pixels.py
@ti.kernel
def clear(self):
    """Clear pixels."""
    self.px.rgba.fill(0)

decay(rate)

Decay pixels.

Parameters:

Name Type Description Default
rate f32

decay rate.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def decay(self, rate: ti.f32):
    """Decay pixels.

    Args:
        rate (ti.f32): decay rate.
    """
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] *= rate

diffuse(evaporate)

Diffuse pixels.

Parameters:

Name Type Description Default
evaporate float

Evaporation rate.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def diffuse(self, evaporate: ti.f32):
    """Diffuse pixels.

    Args:
        evaporate (float): Evaporation rate.
    """
    for i, j in ti.ndrange(self.x, self.y):
        d = ti.Vector([0.0, 0.0, 0.0, 0.0])
        for di in ti.static(range(-1, 2)):
            for dj in ti.static(range(-1, 2)):
                dx = (i + di) % self.x
                dy = (j + dj) % self.y
                d += self.px.rgba[dx, dy]
        d *= 0.99 / 9.0
        self.px.rgba[i, j] = d

flip_x()

Flip image in x-axis.

Source code in src/tolvera/pixels.py
@ti.kernel
def flip_x(self):
    """Flip image in x-axis."""
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = self.px.rgba[self.x - 1 - i, j]

flip_y()

Flip image in y-axis.

Source code in src/tolvera/pixels.py
@ti.kernel
def flip_y(self):
    """Flip image in y-axis."""
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = self.px.rgba[i, self.y - 1 - j]

get()

Get pixels.

Source code in src/tolvera/pixels.py
def get(self):
    """Get pixels."""
    return self.px

invert()

Invert image.

Source code in src/tolvera/pixels.py
@ti.kernel
def invert(self):
    """Invert image."""
    for i, j in ti.ndrange(self.x, self.y):
        self.px.rgba[i, j] = 1.0 - self.px.rgba[i, j]

line(x0, y0, x1, y1, rgba)

Draw an anti-aliased line using Xiaolin Wu's algorithm.

Source code in src/tolvera/pixels.py
@ti.func
def line(self, x0: ti.f32, y0: ti.f32, x1: ti.f32, y1: ti.f32, rgba: vec4):
    """Draw an anti-aliased line using Xiaolin Wu's algorithm."""
    steep = ti.abs(y1 - y0) > ti.abs(x1 - x0)
    if steep:
        x0, y0 = y0, x0
        x1, y1 = y1, x1

    if x0 > x1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0

    dx = x1 - x0
    dy = y1 - y0
    gradient = dy / dx if dx != 0 else 1.0

    xend = ti.math.round(x0)
    yend = y0 + gradient * (xend - x0)
    xgap = self.rfpart(x0 + 0.5)
    xpxl1 = int(xend)
    ypxl1 = int(self.ipart(yend))
    if steep:
        self.plot(ypxl1, xpxl1, self.rfpart(yend) * xgap, rgba)
        self.plot(ypxl1 + 1, xpxl1, self.fpart(yend) * xgap, rgba)
    else:
        self.plot(xpxl1, ypxl1, self.rfpart(yend) * xgap, rgba)
        self.plot(xpxl1, ypxl1 + 1, self.fpart(yend) * xgap, rgba)

    intery = yend + gradient

    xend = ti.math.round(x1)
    yend = y1 + gradient * (xend - x1)
    xgap = self.fpart(x1 + 0.5)
    xpxl2 = int(xend)
    ypxl2 = int(self.ipart(yend))
    if steep:
        self.plot(ypxl2, xpxl2, self.rfpart(yend) * xgap, rgba)
        self.plot(ypxl2 + 1, xpxl2, self.fpart(yend) * xgap, rgba)
    else:
        self.plot(xpxl2, ypxl2, self.rfpart(yend) * xgap, rgba)
        self.plot(xpxl2, ypxl2 + 1, self.fpart(yend) * xgap, rgba)

    if steep:
        for x in range(xpxl1 + 1, xpxl2):
            self.plot(int(self.ipart(intery)), x, self.rfpart(intery), rgba)
            self.plot(int(self.ipart(intery)) + 1, x, self.fpart(intery), rgba)
            intery += gradient
    else:
        for x in range(xpxl1 + 1, xpxl2):
            self.plot(x, int(self.ipart(intery)), self.rfpart(intery), rgba)
            self.plot(x, int(self.ipart(intery)) + 1, self.fpart(intery), rgba)
            intery += gradient

lines(points, rgba)

Draw lines with the same colour.

Parameters:

Name Type Description Default
points template

Points.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def lines(self, points: ti.template(), rgba: vec4):
    """Draw lines with the same colour.

    Args:
        points (ti.template): Points.
        rgba (vec4): Colour.
    """
    for i in range(points.shape[0] - 1):
        self.line(points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], rgba)

particles(particles, species, shape='circle')

Draw particles.

Parameters:

Name Type Description Default
particles template

Particles.

required
species template

Species.

required
shape str

Shape. Defaults to "circle".

'circle'
Source code in src/tolvera/pixels.py
def particles(
    self, particles: ti.template(), species: ti.template(), shape="circle"
):
    """Draw particles.

    Args:
        particles (ti.template): Particles.
        species (ti.template): Species.
        shape (str, optional): Shape. Defaults to "circle".
    """
    shape = self.shape_enum[shape]
    self._particles(particles, species, shape)

plot(x, y, c, rgba)

Set the pixel color with blending.

Source code in src/tolvera/pixels.py
@ti.func
def plot(self, x, y, c, rgba):
    """Set the pixel color with blending."""
    self.px.rgba[x, y] = self.px.rgba[x, y] * (1 - c) + rgba * c

point(x, y, rgba)

Draw point.

Parameters:

Name Type Description Default
x i32

X position.

required
y i32

Y position.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def point(self, x: ti.i32, y: ti.i32, rgba: vec4):
    """Draw point.

    Args:
        x (ti.i32): X position.
        y (ti.i32): Y position.
        rgba (vec4): Colour.
    """
    self.px.rgba[x, y] = rgba

points(x, y, rgba)

Draw points with the same colour.

Parameters:

Name Type Description Default
x template

X positions.

required
y template

Y positions.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def points(self, x: ti.template(), y: ti.template(), rgba: vec4):
    """Draw points with the same colour.

    Args:
        x (ti.template): X positions.
        y (ti.template): Y positions.
        rgba (vec4): Colour.
    """
    for i in ti.static(range(len(x))):
        self.point(x[i], y[i], rgba)

polygon(x, y, rgba)

Draw a filled polygon.

Polygons are drawn according to the polygon mode, which can be "crossing" (default) or "winding". First, the bounding box of the polygon is calculated. Then, we check if each pixel in the bounding box is inside the polygon. If it is, we draw it (along with each neighbour pixel).

Reference for point in polygon inclusion testing: http://www.dgp.toronto.edu/~mac/e-stuff/point_in_polygon.py

Parameters:

Name Type Description Default
x template

X positions.

required
y template

Y positions.

required
rgba vec4

Colour.

required

TODO: fill arg

Source code in src/tolvera/pixels.py
@ti.func
def polygon(self, x: ti.template(), y: ti.template(), rgba: vec4):
    """Draw a filled polygon.

    Polygons are drawn according to the polygon mode, which can be "crossing" 
    (default) or "winding". First, the bounding box of the polygon is calculated.
    Then, we check if each pixel in the bounding box is inside the polygon. If it
    is, we draw it (along with each neighbour pixel).

    Reference for point in polygon inclusion testing:
    http://www.dgp.toronto.edu/~mac/e-stuff/point_in_polygon.py

    Args:
        x (ti.template): X positions.
        y (ti.template): Y positions.
        rgba (vec4): Colour.

    TODO: fill arg
    """
    x_min, x_max = ti.cast(x.min(), ti.i32), ti.cast(x.max(), ti.i32)
    y_min, y_max = ti.cast(y.min(), ti.i32), ti.cast(y.max(), ti.i32)
    l = len(x)
    for i, j in ti.ndrange(x_max - x_min, y_max - y_min):
        p = ti.Vector([x_min + i, y_min + j])
        if self._is_inside(p, x, y, l) != 0:
            # TODO: abstract out, weight?
            """
            x-1,y-1  x,y-1  x+1,y-1
            x-1,y    x,y    x+1,y
            x-1,y+1  x,y+1  x+1,y+1
            """
            _x, _y = p[0], p[1]
            self.px.rgba[_x - 1, _y - 1] = rgba
            self.px.rgba[_x - 1, _y] = rgba
            self.px.rgba[_x - 1, _y + 1] = rgba

            self.px.rgba[_x, _y - 1] = rgba
            self.px.rgba[_x, _y] = rgba
            self.px.rgba[_x, _y + 1] = rgba

            self.px.rgba[_x + 1, _y - 1] = rgba
            self.px.rgba[_x + 1, _y] = rgba
            self.px.rgba[_x + 1, _y + 1] = rgba

rect(x, y, w, h, rgba)

Draw a filled rectangle.

Parameters:

Name Type Description Default
x i32

X position.

required
y i32

Y position.

required
w i32

Width.

required
h i32

Height.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def rect(self, x: ti.i32, y: ti.i32, w: ti.i32, h: ti.i32, rgba: vec4):
    """Draw a filled rectangle.

    Args:
        x (ti.i32): X position.
        y (ti.i32): Y position.
        w (ti.i32): Width.
        h (ti.i32): Height.
        rgba (vec4): Colour.
    """
    # TODO: fill arg
    # TODO: gradients, lerp with ti.math.mix(x, y, a)
    for i, j in ti.ndrange(w, h):
        self.px.rgba[x + i, y + j] = rgba

rgba_from_px(px)

Get rgba from pixels.

Parameters:

Name Type Description Default
px Any

Pixels to get rgba from.

required

Raises:

Type Description
TypeError

If pixel field cannot be found.

Returns:

Name Type Description
MatrixField

RGBA matrix field.

Source code in src/tolvera/pixels.py
def rgba_from_px(self, px):
    """Get rgba from pixels.

    Args:
        px (Any): Pixels to get rgba from.

    Raises:
        TypeError: If pixel field cannot be found.

    Returns:
        MatrixField: RGBA matrix field.
    """
    if isinstance(px, Pixels):
        return px.px.rgba
    elif isinstance(px, StructField):
        return px.rgba
    elif isinstance(px, MatrixField):
        return px
    elif isinstance(px, ScalarField):
        return px
    else:
        try:
            return px.px.px.rgba
        except:
            raise TypeError(f"Cannot find pixel field in {type(px)}")

set(px)

Set pixels.

Parameters:

Name Type Description Default
px Any

Pixels to set. Can be Pixels, StructField, MatrixField, etc (see rgba_from_px).

required
Source code in src/tolvera/pixels.py
def set(self, px: Any):
    """Set pixels.

    Args:
        px (Any): Pixels to set. Can be Pixels, StructField, MatrixField, etc (see rgba_from_px).
    """
    self.px.rgba = self.rgba_from_px(px)

stamp(x, y, px)

Stamp pixels.

Parameters:

Name Type Description Default
x i32

X position.

required
y i32

Y position.

required
px template

Pixels to stamp.

required
Source code in src/tolvera/pixels.py
@ti.kernel
def stamp(self, x: ti.i32, y: ti.i32, px: ti.template()):
    """Stamp pixels.

    Args:
        x (ti.i32): X position.
        y (ti.i32): Y position.
        px (ti.template): Pixels to stamp.
    """
    self.stamp_f(x, y, px)

stamp_f(x, y, px)

Stamp pixels.

Parameters:

Name Type Description Default
x i32

X position.

required
y i32

Y position.

required
px template

Pixels to stamp.

required
Source code in src/tolvera/pixels.py
@ti.func
def stamp_f(self, x: ti.i32, y: ti.i32, px: ti.template()):
    """Stamp pixels.

    Args:
        x (ti.i32): X position.
        y (ti.i32): Y position.
        px (ti.template): Pixels to stamp.
    """
    for i, j in ti.ndrange(px.px.shape[0], px.px.shape[1]):
        p = px.px.rgba[i, j]
        if p[0]+p[1]+p[2] > 0: # transparency
            self.px.rgba[x + i, y + j] = p

triangle(a, b, c, rgba)

Draw a filled triangle.

Parameters:

Name Type Description Default
a vec2

Point A.

required
b vec2

Point B.

required
c vec2

Point C.

required
rgba vec4

Colour.

required
Source code in src/tolvera/pixels.py
@ti.func
def triangle(self, a, b, c, rgba: vec4):
    """Draw a filled triangle.

    Args:
        a (vec2): Point A.
        b (vec2): Point B.
        c (vec2): Point C.
        rgba (vec4): Colour.
    """
    # TODO: fill arg
    x = ti.Vector([a[0], b[0], c[0]])
    y = ti.Vector([a[1], b[1], c[1]])
    self.polygon(x, y, rgba)

Species

Species in Tölvera.

Species are implemented as a State with attributes for size, speed, mass and colour (rgba), and with a length determined by the number of species in the Tölvera instance (tv.sn). The attributes are normalised and scaled by species the species_consts attribute. They are initialised with random values.

Rather than accessing this class directly, access is typically via the State attributes via the Tölvera instance, via e.g. tv.s.species.field[i].size.

Source code in src/tolvera/species.py
class Species:
    """Species in Tölvera.

    Species are implemented as a State with attributes for `size`, `speed`, `mass` and
    `colour` (rgba), and with a length determined by the number of species in the
    Tölvera instance (`tv.sn`). The attributes are normalised and scaled by species the 
    `species_consts` attribute. They are initialised with random values.

    Rather than accessing this class directly, access is typically via the State
    attributes via the Tölvera instance, via e.g. `tv.s.species.field[i].size`.
    """
    def __init__(self, tolvera, **kwargs) -> None:
        """Initialise Species

        Args:
            tolvera (Tolvera): Tolvera instance.
            **kwargs: Keyword arguments. 
        """
        self.tv = tolvera
        self.kwargs = kwargs
        self.n = self.tv.sn
        self.tv.species_consts = CONSTS(
            {
                "MIN_SIZE": (ti.f32, 2.0),
                "MAX_SIZE": (ti.f32, 5.0),
                "MIN_SPEED": (ti.f32, 0.2),
                "MAX_SPEED": (ti.f32, 2.0),
                "MAX_MASS": (ti.f32, 1.0),
            }
        )
        self.tv.s.species = (
            {
                "size": (ti.f32, 0.0, 1.0),
                "speed": (ti.f32, 0.0, 1.0),
                "mass": (ti.f32, 0.0, 1.0),
                "rgba": (ti.math.vec4, 0.0, 1.0),
            },
            self.n,
            "set",
            "set",
        )

    def randomise(self):
        """Randomise species."""
        self.tv.s.species.randomise()

__init__(tolvera, **kwargs)

Initialise Species

Parameters:

Name Type Description Default
tolvera Tolvera

Tolvera instance.

required
**kwargs

Keyword arguments.

{}
Source code in src/tolvera/species.py
def __init__(self, tolvera, **kwargs) -> None:
    """Initialise Species

    Args:
        tolvera (Tolvera): Tolvera instance.
        **kwargs: Keyword arguments. 
    """
    self.tv = tolvera
    self.kwargs = kwargs
    self.n = self.tv.sn
    self.tv.species_consts = CONSTS(
        {
            "MIN_SIZE": (ti.f32, 2.0),
            "MAX_SIZE": (ti.f32, 5.0),
            "MIN_SPEED": (ti.f32, 0.2),
            "MAX_SPEED": (ti.f32, 2.0),
            "MAX_MASS": (ti.f32, 1.0),
        }
    )
    self.tv.s.species = (
        {
            "size": (ti.f32, 0.0, 1.0),
            "speed": (ti.f32, 0.0, 1.0),
            "mass": (ti.f32, 0.0, 1.0),
            "rgba": (ti.math.vec4, 0.0, 1.0),
        },
        self.n,
        "set",
        "set",
    )

randomise()

Randomise species.

Source code in src/tolvera/species.py
def randomise(self):
    """Randomise species."""
    self.tv.s.species.randomise()

State

State class for Tölvera.

This class takes a name, dictionary of state attributes, and a shape, and creates a Taichi struct field and a corresponding dictionary of NumPy arrays (NpNdarrayDict) for a state.

The Taichi struct field can be used in Taichi scope, and the NpNdarrayDict can be used in Python scope, and the two are kept in sync by the from_nddict() and to_nddict() methods.

The State class also handles OSC accessors for the state, which use the NpNdarrayDict to get and set data. A Tölvera instance is therefore required to initialise a State instance.

State attributes are defined as a dictionary of attribute names and tuples of (Taichi type, min value, max value). The domain of the attribute is used when randomising the data in the state, and by OSCMap endpoints and client patches.

The state is n-dimensional based on the shape argument, and the NpNdarrayDict provides methods for accessing the data in the state in n-dimensional slices.

Example
tv.s.flock_p = {
    "state": {
        "separate": (ti.math.vec2, 0.0, 1.0),
        "align": (ti.math.vec2, 0.0, 1.0),
        "cohere": (ti.math.vec2, 0.0, 1.0),
        "nearby": (ti.i32, 0, self.tv.p.n - 1),
    },
    "shape": self.tv.pn, # particle count
    "osc": ("get"),
    "randomise": False,
}
Source code in src/tolvera/state.py
@ti.data_oriented
class State:
    """State class for Tölvera.

    This class takes a name, dictionary of state attributes, and a shape, and
    creates a Taichi struct field and a corresponding dictionary of NumPy arrays 
    (NpNdarrayDict) for a state.

    The Taichi struct field can be used in Taichi scope, and the NpNdarrayDict
    can be used in Python scope, and the two are kept in sync by the from_nddict()
    and to_nddict() methods.

    The State class also handles OSC accessors for the state, which use the
    NpNdarrayDict to get and set data. A Tölvera instance is therefore required
    to initialise a State instance.

    State attributes are defined as a dictionary of attribute names and tuples of
    (Taichi type, min value, max value). The domain of the attribute is used when
    randomising the data in the state, and by OSCMap endpoints and client patches.

    The state is n-dimensional based on the shape argument, and the NpNdarrayDict
    provides methods for accessing the data in the state in n-dimensional slices.

    Example:
        ```py
        tv.s.flock_p = {
            "state": {
                "separate": (ti.math.vec2, 0.0, 1.0),
                "align": (ti.math.vec2, 0.0, 1.0),
                "cohere": (ti.math.vec2, 0.0, 1.0),
                "nearby": (ti.i32, 0, self.tv.p.n - 1),
            },
            "shape": self.tv.pn, # particle count
            "osc": ("get"),
            "randomise": False,
        }
        ```
    """
    def __init__(
        self,
        tolvera,
        name: str,
        state: dict[str, tuple[DataType, Any, Any]],
        shape: int | tuple[int] = None,
        osc: str | tuple = None,  # ('get', 'set', 'stream')
        randomise: bool = True,
        methods: dict[str, Any] = None,
    ):
        """Initialise a state for Tölvera.

        Args:
            tolvera (Tolvera): Tolvera instance to which this state belongs.
            name (str): Name of this state.
            state (dict[str, tuple[DataType, Any, Any]]): Dict of state attributes.
            shape (int | tuple[int], optional): Shape of the state. Defaults to 1.
            methods (dict[str, Any], optional): Flag for OSC via iipyper. Defaults to False.
        """
        self.tv = tolvera
        assert name is not None, "State must have a name."
        self.name = name
        shape = 1 if shape is None else shape
        self.setup_data(state, shape, randomise, methods)
        self.setup_osc(osc)

    def setup_data(
        self,
        dict: dict[str, tuple[DataType, Any, Any]],
        shape: int | tuple[int],
        randomise: bool = True,
        methods: dict[str, Any] = None,
    ):
        """Setup data structures and data for this state.

        Args:
            dict (dict[str, tuple[DataType, Any, Any]]): Dict of state attributes.
            shape (int | tuple[int]): Shape of the state.
            randomise (bool, optional): Flag to randomise the data on creation. Defaults to True.
            methods (dict[str, Any], optional): Dict of Taichi field struct methods. Defaults to None.
        """
        self.create_struct_field(dict, shape, methods)
        self.create_npndarray_dict()
        if randomise:
            self.randomise()

    def create_struct_field(
        self,
        dict: dict[str, tuple[DataType, Any, Any]],
        shape: int | tuple[int],
        methods: dict[str, Any] = None,
    ):
        """Create a Taichi struct field for this state.

        Args:
            dict (dict[str, tuple[DataType, Any, Any]]): Dict of state attributes.
            shape (int | tuple[int]): Shape of the state.
            methods (dict[str, Any], optional): Dict of Taichi field struct methods. Defaults to None.
        """
        self.dict = dict
        self.shape = (shape,) if isinstance(shape, int) else shape
        if methods is None:
            self.struct = ti.types.struct(**{k: v[0] for k, v in self.dict.items()})
        else:
            self.methods = methods if methods is not None else {}
            self.struct = ti.types.struct(
                **{k: v[0] for k, v in self.dict.items()}, methods=self.methods
            )
        self.field = self.struct.field(shape=self.shape)

    def create_npndarray_dict(self):
        """Create a NpNdarrayDict for this state.

        Raises:
            NotImplementedError: If no Numpy type is found for a Taichi type.
        """
        nddict = {}
        for k, v in self.dict.items():
            titype, min_val, max_val = v
            nptype = TiNpTypeMap.get(titype)
            if nptype is None:
                raise NotImplementedError(f"no nptype for {titype}")
            nddict[k] = (nptype, min_val, max_val)
        self.nddict = NpNdarrayDict(nddict, self.shape)
        self.size = self.nddict.size

    def randomise(self):
        """Randomise the data in this state."""
        self.nddict.randomise()
        self.from_nddict()

    def randomise_attr(self, attr: str):
        """Randomise an attribute in this state.

        Args:
            attr (str): Attribute name.
        """
        self.nddict.randomise_attr(attr)
        self.from_nddict()

    def setup_osc(self, osc: tuple|str = None):
        """Setup OSC for this state.

        Args:
            osc (tuple | str, optional): ("get", "set", "stream"). Defaults to None.
        """
        self.osc = osc is not None
        if not self.osc: return
        if isinstance(osc, str): osc = (osc,)
        self.osc_set = "set" in osc if self.osc else False
        self.osc_get = "get" in osc if self.osc else False
        self.osc_stream = "stream" in osc if self.osc else False
        self.setter_name = f"{self.tv.name_clean}_set_{self.name}"
        self.getter_name = f"{self.tv.name_clean}_get_{self.name}"
        self.stream_name = f"{self.tv.name_clean}_stream_{self.name}"
        if self.tv.osc is not False and self.osc:
            self.osc = self.tv.osc
            if self.osc_set: self.add_osc_setters()
            # if self.osc_get: self.add_osc_getters()
            # if self.osc_stream: self.add_osc_streams()

    def add_osc_setters(self):
        name = self.setter_name
        self.osc.map.receive_args_inline(name + "_randomise", self.randomise)

    def add_osc_getters(self):
        name = self.getter_name
        for k, v in self.dict.items():
            ranges = (int(v[0]), int(v[0]), int(v[1]))
            kwargs = {"i": ranges, "j": ranges, "attr": (k, k, k)}
            self.osc.map.receive_args_inline(f"{name}", self.osc_getter, **kwargs)

    # def osc_getter(self, i: int, j: int, attribute: str):
    #     ret = self.get((i, j), attribute)
    #     if ret is not None:
    #         route = self.osc.map.pascal_to_path(self.getter_name)  # +'/'+attribute
    #         self.osc.host.return_to_sender_by_name(
    #             (route, attribute, ret), self.osc.client_name
    #         )
    #     return ret

    # def add_osc_streams(self):
    #     # add send in broadcast mode
    #     raise NotImplementedError("add_osc_streams not implemented")

    def serialize(self) -> str:
        return ti_serialize(self.field)

    def deserialize(self, json_str: str):
        ti_deserialize(self.field, json_str)

    def save(self, path: str):
        # TODO: path validation, save to path, etc.
        json_str = self.serialize()
        raise NotImplementedError("save not implemented")

    def load(self, path: str):
        # TODO: path validation, file ext., etc.
        # TODO: data validation (pydantic?)
        json_str = jsons.load(path)
        self.deserialize(json_str)
        raise NotImplementedError("load not implemented")

    def from_nddict(self):
        """Copy data from NpNdarrayDict to Taichi field.

        Raises:
            Exception: If data cannot be copied.
        """
        try:
            data = self.nddict.get_data()
            self.field.from_numpy(data)
        except Exception as e:
            raise Exception(f"[tolvera.state.from_nddict] {e}") from e

    def to_nddict(self):
        """Copy data from Taichi field to NpNdarrayDict.

        Raises:
            Exception: If data cannot be copied.
        """
        try:
            data = self.field.to_numpy()
            self.nddict.set_data(data)
        except Exception as e:
            raise Exception(f"[tolvera.state.to_nddict] {e}") from e

    def set_from_nddict(self, data: dict):
        """Copy data from NumPy array dict to Taichi field.

        Args:
            data (dict): NumPy array dict to copy.

        Raises:
            Exception: If data cannot be copied.
        """
        try:
            self.field.from_numpy(data)
        except Exception as e:
            raise Exception(f"[tolvera.state.from_numpy] {e}") from e

    """
    npndarray_dict wrappers
    """

    def from_vec(self, vec: list):
        """Wrapper for NpNdarrayDict.from_vec()."""
        self.to_nddict()
        self.nddict.from_vec(vec)
        self.from_nddict()

    def to_vec(self) -> list:
        """Wrapper for NpNdarrayDict.to_vec()."""
        self.to_nddict()
        return self.nddict.to_vec()

    def attr_from_vec(self, attr: str, vec: list):
        """Wrapper for NpNdarrayDict.attr_from_vec()."""
        self.to_nddict()
        self.nddict.attr_from_vec(attr, vec)
        self.from_nddict()

    def attr_to_vec(self, attr: str) -> list:
        """Wrapper for NpNdarrayDict.attr_to_vec()."""
        self.to_nddict()
        return self.nddict.attr_to_vec(attr)

    def slice_from_vec(self, slice_args: list, slice_vec: list):
        """Wrapper for NpNdarrayDict.slice_from_vec()."""
        self.to_nddict()
        self.nddict.slice_from_vec(slice_args, slice_vec)
        self.from_nddict()

    def slice_to_vec(self, slice_args: list) -> list:
        """Wrapper for NpNdarrayDict.slice_to_vec()."""
        self.to_nddict()
        return self.nddict.slice_to_vec(slice_args)

    def attr_slice_from_vec(self, attr: str, slice_args: list, slice_vec: list):
        """Wrapper for NpNdarrayDict.attr_slice_from_vec()."""
        self.to_nddict()
        self.nddict.attr_slice_from_vec(attr, slice_args, slice_vec)
        self.from_nddict()

    def attr_slice_to_vec(self, attr: str, slice_args: list) -> list:
        """Wrapper for NpNdarrayDict.attr_slice_to_vec()."""
        self.to_nddict()
        return self.nddict.attr_slice_to_vec(attr, slice_args)

    def attr_size(self, attr: str) -> int:
        """Return the size of the attribute."""
        return self.nddict.data[attr].size

    """
    misc
    """

    def fill(self, value: ti.f32):
        """Fill the Taichi field with a value."""
        self.field.fill(value)

    @ti.func
    def __getitem__(self, index: ti.i32):
        """Return the Taichi field attribute.

        Args:
            index (ti.i32): Attribute index.
        """
        return self.field[index]

    def __call__(self, *args: Any, **kwds: Any) -> Any:
        """Return the Taichi field."""
        return self.field

__call__(*args, **kwds)

Return the Taichi field.

Source code in src/tolvera/state.py
def __call__(self, *args: Any, **kwds: Any) -> Any:
    """Return the Taichi field."""
    return self.field

__getitem__(index)

Return the Taichi field attribute.

Parameters:

Name Type Description Default
index i32

Attribute index.

required
Source code in src/tolvera/state.py
@ti.func
def __getitem__(self, index: ti.i32):
    """Return the Taichi field attribute.

    Args:
        index (ti.i32): Attribute index.
    """
    return self.field[index]

__init__(tolvera, name, state, shape=None, osc=None, randomise=True, methods=None)

Initialise a state for Tölvera.

Parameters:

Name Type Description Default
tolvera Tolvera

Tolvera instance to which this state belongs.

required
name str

Name of this state.

required
state dict[str, tuple[DataType, Any, Any]]

Dict of state attributes.

required
shape int | tuple[int]

Shape of the state. Defaults to 1.

None
methods dict[str, Any]

Flag for OSC via iipyper. Defaults to False.

None
Source code in src/tolvera/state.py
def __init__(
    self,
    tolvera,
    name: str,
    state: dict[str, tuple[DataType, Any, Any]],
    shape: int | tuple[int] = None,
    osc: str | tuple = None,  # ('get', 'set', 'stream')
    randomise: bool = True,
    methods: dict[str, Any] = None,
):
    """Initialise a state for Tölvera.

    Args:
        tolvera (Tolvera): Tolvera instance to which this state belongs.
        name (str): Name of this state.
        state (dict[str, tuple[DataType, Any, Any]]): Dict of state attributes.
        shape (int | tuple[int], optional): Shape of the state. Defaults to 1.
        methods (dict[str, Any], optional): Flag for OSC via iipyper. Defaults to False.
    """
    self.tv = tolvera
    assert name is not None, "State must have a name."
    self.name = name
    shape = 1 if shape is None else shape
    self.setup_data(state, shape, randomise, methods)
    self.setup_osc(osc)

attr_from_vec(attr, vec)

Wrapper for NpNdarrayDict.attr_from_vec().

Source code in src/tolvera/state.py
def attr_from_vec(self, attr: str, vec: list):
    """Wrapper for NpNdarrayDict.attr_from_vec()."""
    self.to_nddict()
    self.nddict.attr_from_vec(attr, vec)
    self.from_nddict()

attr_size(attr)

Return the size of the attribute.

Source code in src/tolvera/state.py
def attr_size(self, attr: str) -> int:
    """Return the size of the attribute."""
    return self.nddict.data[attr].size

attr_slice_from_vec(attr, slice_args, slice_vec)

Wrapper for NpNdarrayDict.attr_slice_from_vec().

Source code in src/tolvera/state.py
def attr_slice_from_vec(self, attr: str, slice_args: list, slice_vec: list):
    """Wrapper for NpNdarrayDict.attr_slice_from_vec()."""
    self.to_nddict()
    self.nddict.attr_slice_from_vec(attr, slice_args, slice_vec)
    self.from_nddict()

attr_slice_to_vec(attr, slice_args)

Wrapper for NpNdarrayDict.attr_slice_to_vec().

Source code in src/tolvera/state.py
def attr_slice_to_vec(self, attr: str, slice_args: list) -> list:
    """Wrapper for NpNdarrayDict.attr_slice_to_vec()."""
    self.to_nddict()
    return self.nddict.attr_slice_to_vec(attr, slice_args)

attr_to_vec(attr)

Wrapper for NpNdarrayDict.attr_to_vec().

Source code in src/tolvera/state.py
def attr_to_vec(self, attr: str) -> list:
    """Wrapper for NpNdarrayDict.attr_to_vec()."""
    self.to_nddict()
    return self.nddict.attr_to_vec(attr)

create_npndarray_dict()

Create a NpNdarrayDict for this state.

Raises:

Type Description
NotImplementedError

If no Numpy type is found for a Taichi type.

Source code in src/tolvera/state.py
def create_npndarray_dict(self):
    """Create a NpNdarrayDict for this state.

    Raises:
        NotImplementedError: If no Numpy type is found for a Taichi type.
    """
    nddict = {}
    for k, v in self.dict.items():
        titype, min_val, max_val = v
        nptype = TiNpTypeMap.get(titype)
        if nptype is None:
            raise NotImplementedError(f"no nptype for {titype}")
        nddict[k] = (nptype, min_val, max_val)
    self.nddict = NpNdarrayDict(nddict, self.shape)
    self.size = self.nddict.size

create_struct_field(dict, shape, methods=None)

Create a Taichi struct field for this state.

Parameters:

Name Type Description Default
dict dict[str, tuple[DataType, Any, Any]]

Dict of state attributes.

required
shape int | tuple[int]

Shape of the state.

required
methods dict[str, Any]

Dict of Taichi field struct methods. Defaults to None.

None
Source code in src/tolvera/state.py
def create_struct_field(
    self,
    dict: dict[str, tuple[DataType, Any, Any]],
    shape: int | tuple[int],
    methods: dict[str, Any] = None,
):
    """Create a Taichi struct field for this state.

    Args:
        dict (dict[str, tuple[DataType, Any, Any]]): Dict of state attributes.
        shape (int | tuple[int]): Shape of the state.
        methods (dict[str, Any], optional): Dict of Taichi field struct methods. Defaults to None.
    """
    self.dict = dict
    self.shape = (shape,) if isinstance(shape, int) else shape
    if methods is None:
        self.struct = ti.types.struct(**{k: v[0] for k, v in self.dict.items()})
    else:
        self.methods = methods if methods is not None else {}
        self.struct = ti.types.struct(
            **{k: v[0] for k, v in self.dict.items()}, methods=self.methods
        )
    self.field = self.struct.field(shape=self.shape)

fill(value)

Fill the Taichi field with a value.

Source code in src/tolvera/state.py
def fill(self, value: ti.f32):
    """Fill the Taichi field with a value."""
    self.field.fill(value)

from_nddict()

Copy data from NpNdarrayDict to Taichi field.

Raises:

Type Description
Exception

If data cannot be copied.

Source code in src/tolvera/state.py
def from_nddict(self):
    """Copy data from NpNdarrayDict to Taichi field.

    Raises:
        Exception: If data cannot be copied.
    """
    try:
        data = self.nddict.get_data()
        self.field.from_numpy(data)
    except Exception as e:
        raise Exception(f"[tolvera.state.from_nddict] {e}") from e

from_vec(vec)

Wrapper for NpNdarrayDict.from_vec().

Source code in src/tolvera/state.py
def from_vec(self, vec: list):
    """Wrapper for NpNdarrayDict.from_vec()."""
    self.to_nddict()
    self.nddict.from_vec(vec)
    self.from_nddict()

randomise()

Randomise the data in this state.

Source code in src/tolvera/state.py
def randomise(self):
    """Randomise the data in this state."""
    self.nddict.randomise()
    self.from_nddict()

randomise_attr(attr)

Randomise an attribute in this state.

Parameters:

Name Type Description Default
attr str

Attribute name.

required
Source code in src/tolvera/state.py
def randomise_attr(self, attr: str):
    """Randomise an attribute in this state.

    Args:
        attr (str): Attribute name.
    """
    self.nddict.randomise_attr(attr)
    self.from_nddict()

set_from_nddict(data)

Copy data from NumPy array dict to Taichi field.

Parameters:

Name Type Description Default
data dict

NumPy array dict to copy.

required

Raises:

Type Description
Exception

If data cannot be copied.

Source code in src/tolvera/state.py
def set_from_nddict(self, data: dict):
    """Copy data from NumPy array dict to Taichi field.

    Args:
        data (dict): NumPy array dict to copy.

    Raises:
        Exception: If data cannot be copied.
    """
    try:
        self.field.from_numpy(data)
    except Exception as e:
        raise Exception(f"[tolvera.state.from_numpy] {e}") from e

setup_data(dict, shape, randomise=True, methods=None)

Setup data structures and data for this state.

Parameters:

Name Type Description Default
dict dict[str, tuple[DataType, Any, Any]]

Dict of state attributes.

required
shape int | tuple[int]

Shape of the state.

required
randomise bool

Flag to randomise the data on creation. Defaults to True.

True
methods dict[str, Any]

Dict of Taichi field struct methods. Defaults to None.

None
Source code in src/tolvera/state.py
def setup_data(
    self,
    dict: dict[str, tuple[DataType, Any, Any]],
    shape: int | tuple[int],
    randomise: bool = True,
    methods: dict[str, Any] = None,
):
    """Setup data structures and data for this state.

    Args:
        dict (dict[str, tuple[DataType, Any, Any]]): Dict of state attributes.
        shape (int | tuple[int]): Shape of the state.
        randomise (bool, optional): Flag to randomise the data on creation. Defaults to True.
        methods (dict[str, Any], optional): Dict of Taichi field struct methods. Defaults to None.
    """
    self.create_struct_field(dict, shape, methods)
    self.create_npndarray_dict()
    if randomise:
        self.randomise()

setup_osc(osc=None)

Setup OSC for this state.

Parameters:

Name Type Description Default
osc tuple | str

("get", "set", "stream"). Defaults to None.

None
Source code in src/tolvera/state.py
def setup_osc(self, osc: tuple|str = None):
    """Setup OSC for this state.

    Args:
        osc (tuple | str, optional): ("get", "set", "stream"). Defaults to None.
    """
    self.osc = osc is not None
    if not self.osc: return
    if isinstance(osc, str): osc = (osc,)
    self.osc_set = "set" in osc if self.osc else False
    self.osc_get = "get" in osc if self.osc else False
    self.osc_stream = "stream" in osc if self.osc else False
    self.setter_name = f"{self.tv.name_clean}_set_{self.name}"
    self.getter_name = f"{self.tv.name_clean}_get_{self.name}"
    self.stream_name = f"{self.tv.name_clean}_stream_{self.name}"
    if self.tv.osc is not False and self.osc:
        self.osc = self.tv.osc
        if self.osc_set: self.add_osc_setters()

slice_from_vec(slice_args, slice_vec)

Wrapper for NpNdarrayDict.slice_from_vec().

Source code in src/tolvera/state.py
def slice_from_vec(self, slice_args: list, slice_vec: list):
    """Wrapper for NpNdarrayDict.slice_from_vec()."""
    self.to_nddict()
    self.nddict.slice_from_vec(slice_args, slice_vec)
    self.from_nddict()

slice_to_vec(slice_args)

Wrapper for NpNdarrayDict.slice_to_vec().

Source code in src/tolvera/state.py
def slice_to_vec(self, slice_args: list) -> list:
    """Wrapper for NpNdarrayDict.slice_to_vec()."""
    self.to_nddict()
    return self.nddict.slice_to_vec(slice_args)

to_nddict()

Copy data from Taichi field to NpNdarrayDict.

Raises:

Type Description
Exception

If data cannot be copied.

Source code in src/tolvera/state.py
def to_nddict(self):
    """Copy data from Taichi field to NpNdarrayDict.

    Raises:
        Exception: If data cannot be copied.
    """
    try:
        data = self.field.to_numpy()
        self.nddict.set_data(data)
    except Exception as e:
        raise Exception(f"[tolvera.state.to_nddict] {e}") from e

to_vec()

Wrapper for NpNdarrayDict.to_vec().

Source code in src/tolvera/state.py
def to_vec(self) -> list:
    """Wrapper for NpNdarrayDict.to_vec()."""
    self.to_nddict()
    return self.nddict.to_vec()

Tolvera

Tolvera main class.

Attributes:

Name Type Description
`name` str

Name of Tölvera instance.

`ctx` TolveraContext

Shared TolveraContext.

`speed` float

Global timebase speed.

`pn` int

Number of particles.

`sn` int

Number of species.

`p_per_s` int

Number of particles per species.

`substep` int

Number of substeps per frame.

`iml` int

Dict of IML instances via anguilla.

`cv` int

computer vision integration via OpenCV.

`osc` int

OSC via iipyper.

`ti` int

Taichi (graphics backend).

Source code in src/tolvera/tolvera_.py
class Tolvera:
    """Tolvera main class.

    Attributes:
        `name` (str): Name of Tölvera instance. 
        `ctx` (TolveraContext): Shared TolveraContext.
        `speed` (float): Global timebase speed.
        `pn` (int): Number of particles.
        `sn` (int): Number of species.
        `p_per_s` (int): Number of particles per species.
        `substep` (int): Number of substeps per frame.
        `iml`: Dict of IML instances via anguilla.
        `cv`: computer vision integration via OpenCV.
        `osc`: OSC via iipyper.
        `ti`: Taichi (graphics backend).
    """

    def __init__(self, **kwargs):
        """
        Initialise and setup Tölvera with given keyword arguments.

        Args:
            name (str): Name of Tölvera instance. Defaults to "Tölvera".
            ctx (TolveraContext): TolveraContext to share. Defaults to None.
            see also kwargs for Tolvera.setup().
        """
        self.kwargs = kwargs
        self.name = kwargs.get("name", "Tölvera")
        self.name_clean = clean_name(self.name)
        if "ctx" not in kwargs:
            self.init_context(**kwargs)
        else:
            self.share_context(kwargs["ctx"])
        self.setup(**kwargs)
        print(f"[{self.name}] Initialisation and setup complete.")

    def init_context(self, **kwargs):
        """Initiliase TölveraContext with given keyword arguments.

        Args:
            **kwargs: Keyword arguments for TölveraContext.
        """
        context = TolveraContext(**kwargs)
        self.share_context(context)

    def share_context(self, context):
        """Share TölveraContext with another Tölvera instance.

        Args:
            context: TölveraContext to share.
        """
        if len(context.get_names()) == 0:
            print(f"[{self.name}] Sharing context '{context.name}'.")
        else:
            print(
                f"[{self.name}] Sharing context '{context.name}' with {context.get_names()}."
            )
        self.ctx = context
        self.x = context.x
        self.y = context.y
        self.ti = context.ti
        self.show = context.show
        self.canvas = context.canvas
        self.osc = context.osc
        self.s = context.s
        self.iml = context.iml
        self.render = context.render
        self.cleanup = context.cleanup
        self.cv = context.cv
        self.hands = context.hands
        self.pose = context.pose
        self.face = context.face
        self.face_mesh = context.face_mesh

    def setup(self, **kwargs):
        """
        Setup Tölvera with given keyword arguments.
        This can be called multiple throughout the lifetime of a Tölvera instance.

        Args:
            **kwargs: Keyword arguments for setup.
                speed (float): Global timebase speed. Defaults to 1.
                particles (int): Number of particles. Defaults to 1024.
                species (int): Number of species. Defaults to 4.
                substep (int): Number of substeps per frame. Defaults to 1.
            See also kwargs for Pixels, Species, Particles, and Vera.
        """
        self._speed = kwargs.get("speed", 1)  # global timebase
        self.particles = kwargs.get("particles", 1024)
        self.species = kwargs.get("species", 4)
        if self.particles < self.species:
            self.species = self.particles
        self.pn = self.particles
        self.sn = self.species
        self.p_per_s = self.particles // self.species
        self.substep = kwargs.get("substep", 1)
        self.px = Pixels(self, **kwargs)
        self._species = Species(self, **kwargs)
        self.p = Particles(self, **kwargs)
        self.speed(self._speed)
        self.v = Vera(self, **kwargs)
        if self.osc is not False:
            self.add_to_osc_map()
        if self.cv is not False:
            if self.hands:
                self.hands.px = self.px
            if self.pose:
                self.pose.px = self.px
            if self.face:
                self.face.px = self.px
            if self.face_mesh:
                self.face_mesh.px = self.px
        self.ctx.add(self)
        print(f"[{self.name}] Setup complete.")

    def randomise(self):
        """
        Randomise particles, species, and Vera.
        """
        self.p.randomise()
        self.s.species.randomise()
        self.v.randomise()

    def reset(self, **kwargs):
        """
        Reset Tölvera with given keyword arguments.
        This will call setup() with given keyword arguments, but not init().

        Args:
            **kwargs: Keyword arguments for reset.
        """
        print(f"[{self.name}] Resetting self with kwargs={kwargs}...")
        if kwargs is not None:
            self.kwargs = kwargs
        self.setup()

    def speed(self, speed: float = None):
        """Set or get global timebase speed."""
        if speed is not None:
            self._speed = speed
            self.p.speed(speed)
        return self._speed

    def add_to_osc_map(self):
        """
        Add top-level Tölvera functions to OSCMap.
        """
        setter_name = f"{self.name_clean}_set"
        getter_name = f"{self.name_clean}_get"
        self.osc.map.receive_args_inline(setter_name + "_randomise", self.randomise)
        # self.osc.map.receive_args_inline(setter_name+'_reset', self.reset) # TODO: kwargs?
        self.osc.map.receive_args_inline(
            setter_name + "_particles_randomise", self.p._randomise
        )  # TODO: move inside Particles

        @self.osc.map.receive_args(speed=(1, 0, 100), count=1)
        def tolvera_set_speed(speed: float):
            """Set global timebase speed."""
            self.speed(speed)

__init__(**kwargs)

Initialise and setup Tölvera with given keyword arguments.

Parameters:

Name Type Description Default
name str

Name of Tölvera instance. Defaults to "Tölvera".

required
ctx TolveraContext

TolveraContext to share. Defaults to None.

required
Source code in src/tolvera/tolvera_.py
def __init__(self, **kwargs):
    """
    Initialise and setup Tölvera with given keyword arguments.

    Args:
        name (str): Name of Tölvera instance. Defaults to "Tölvera".
        ctx (TolveraContext): TolveraContext to share. Defaults to None.
        see also kwargs for Tolvera.setup().
    """
    self.kwargs = kwargs
    self.name = kwargs.get("name", "Tölvera")
    self.name_clean = clean_name(self.name)
    if "ctx" not in kwargs:
        self.init_context(**kwargs)
    else:
        self.share_context(kwargs["ctx"])
    self.setup(**kwargs)
    print(f"[{self.name}] Initialisation and setup complete.")

add_to_osc_map()

Add top-level Tölvera functions to OSCMap.

Source code in src/tolvera/tolvera_.py
def add_to_osc_map(self):
    """
    Add top-level Tölvera functions to OSCMap.
    """
    setter_name = f"{self.name_clean}_set"
    getter_name = f"{self.name_clean}_get"
    self.osc.map.receive_args_inline(setter_name + "_randomise", self.randomise)
    # self.osc.map.receive_args_inline(setter_name+'_reset', self.reset) # TODO: kwargs?
    self.osc.map.receive_args_inline(
        setter_name + "_particles_randomise", self.p._randomise
    )  # TODO: move inside Particles

    @self.osc.map.receive_args(speed=(1, 0, 100), count=1)
    def tolvera_set_speed(speed: float):
        """Set global timebase speed."""
        self.speed(speed)

init_context(**kwargs)

Initiliase TölveraContext with given keyword arguments.

Parameters:

Name Type Description Default
**kwargs

Keyword arguments for TölveraContext.

{}
Source code in src/tolvera/tolvera_.py
def init_context(self, **kwargs):
    """Initiliase TölveraContext with given keyword arguments.

    Args:
        **kwargs: Keyword arguments for TölveraContext.
    """
    context = TolveraContext(**kwargs)
    self.share_context(context)

randomise()

Randomise particles, species, and Vera.

Source code in src/tolvera/tolvera_.py
def randomise(self):
    """
    Randomise particles, species, and Vera.
    """
    self.p.randomise()
    self.s.species.randomise()
    self.v.randomise()

reset(**kwargs)

Reset Tölvera with given keyword arguments. This will call setup() with given keyword arguments, but not init().

Parameters:

Name Type Description Default
**kwargs

Keyword arguments for reset.

{}
Source code in src/tolvera/tolvera_.py
def reset(self, **kwargs):
    """
    Reset Tölvera with given keyword arguments.
    This will call setup() with given keyword arguments, but not init().

    Args:
        **kwargs: Keyword arguments for reset.
    """
    print(f"[{self.name}] Resetting self with kwargs={kwargs}...")
    if kwargs is not None:
        self.kwargs = kwargs
    self.setup()

setup(**kwargs)

Setup Tölvera with given keyword arguments. This can be called multiple throughout the lifetime of a Tölvera instance.

Parameters:

Name Type Description Default
**kwargs

Keyword arguments for setup. speed (float): Global timebase speed. Defaults to 1. particles (int): Number of particles. Defaults to 1024. species (int): Number of species. Defaults to 4. substep (int): Number of substeps per frame. Defaults to 1.

{}
Source code in src/tolvera/tolvera_.py
def setup(self, **kwargs):
    """
    Setup Tölvera with given keyword arguments.
    This can be called multiple throughout the lifetime of a Tölvera instance.

    Args:
        **kwargs: Keyword arguments for setup.
            speed (float): Global timebase speed. Defaults to 1.
            particles (int): Number of particles. Defaults to 1024.
            species (int): Number of species. Defaults to 4.
            substep (int): Number of substeps per frame. Defaults to 1.
        See also kwargs for Pixels, Species, Particles, and Vera.
    """
    self._speed = kwargs.get("speed", 1)  # global timebase
    self.particles = kwargs.get("particles", 1024)
    self.species = kwargs.get("species", 4)
    if self.particles < self.species:
        self.species = self.particles
    self.pn = self.particles
    self.sn = self.species
    self.p_per_s = self.particles // self.species
    self.substep = kwargs.get("substep", 1)
    self.px = Pixels(self, **kwargs)
    self._species = Species(self, **kwargs)
    self.p = Particles(self, **kwargs)
    self.speed(self._speed)
    self.v = Vera(self, **kwargs)
    if self.osc is not False:
        self.add_to_osc_map()
    if self.cv is not False:
        if self.hands:
            self.hands.px = self.px
        if self.pose:
            self.pose.px = self.px
        if self.face:
            self.face.px = self.px
        if self.face_mesh:
            self.face_mesh.px = self.px
    self.ctx.add(self)
    print(f"[{self.name}] Setup complete.")

share_context(context)

Share TölveraContext with another Tölvera instance.

Parameters:

Name Type Description Default
context

TölveraContext to share.

required
Source code in src/tolvera/tolvera_.py
def share_context(self, context):
    """Share TölveraContext with another Tölvera instance.

    Args:
        context: TölveraContext to share.
    """
    if len(context.get_names()) == 0:
        print(f"[{self.name}] Sharing context '{context.name}'.")
    else:
        print(
            f"[{self.name}] Sharing context '{context.name}' with {context.get_names()}."
        )
    self.ctx = context
    self.x = context.x
    self.y = context.y
    self.ti = context.ti
    self.show = context.show
    self.canvas = context.canvas
    self.osc = context.osc
    self.s = context.s
    self.iml = context.iml
    self.render = context.render
    self.cleanup = context.cleanup
    self.cv = context.cv
    self.hands = context.hands
    self.pose = context.pose
    self.face = context.face
    self.face_mesh = context.face_mesh

speed(speed=None)

Set or get global timebase speed.

Source code in src/tolvera/tolvera_.py
def speed(self, speed: float = None):
    """Set or get global timebase speed."""
    if speed is not None:
        self._speed = speed
        self.p.speed(speed)
    return self._speed

dotdict

Bases: dict

dot.notation access to dictionary attributes

Source code in src/tolvera/utils.py
class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

create_and_validate_slice(arg, target_array)

Creates and validates a slice object based on the target array.

Source code in src/tolvera/utils.py
def create_and_validate_slice(
    arg: Union[int, tuple[int, ...], slice], target_array: np.ndarray
) -> slice:
    """
    Creates and validates a slice object based on the target array.
    """
    try:
        slice_obj = create_safe_slice(arg)
        if not validate_slice(slice_obj, target_array):
            raise ValueError(f"Invalid slice: {slice_obj}")
        return slice_obj
    except Exception as e:
        raise type(e)(f"Error creating slice: {e}")

create_ndslices(dims)

Create a multi-dimensional slice from a list of tuples.

Parameters:

Name Type Description Default
dims list[tuple]

A list of tuples containing the slice parameters for each dimension.

required

Returns:

Type Description
s_

np.s_: A multi-dimensional slice object.

Source code in src/tolvera/utils.py
def create_ndslices(dims: list[tuple]) -> np.s_:
    """
    Create a multi-dimensional slice from a list of tuples.

    Args:
        dims (list[tuple]): A list of tuples containing the slice parameters for each dimension.

    Returns:
        np.s_: A multi-dimensional slice object.
    """
    return np.s_[tuple(slice(*dim) if isinstance(dim, tuple) else dim for dim in dims)]

create_safe_slice(arg)

Creates a slice object based on the input argument.

Parameters:

Name Type Description Default
arg (int, tuple, slice)

The argument for creating the slice. It can be an integer, a tuple with slice parameters, or a slice object itself.

required

Returns:

Name Type Description
slice slice

A slice object created based on the provided argument.

Source code in src/tolvera/utils.py
def create_safe_slice(arg: Union[int, tuple[int, ...], slice]) -> slice:
    """
    Creates a slice object based on the input argument.

    Args:
        arg (int, tuple, slice): The argument for creating the slice. It can be an integer,
                                 a tuple with slice parameters, or a slice object itself.

    Returns:
        slice: A slice object created based on the provided argument.
    """
    try:
        if isinstance(arg, slice):
            return arg
        elif isinstance(arg, tuple):
            return slice(*arg)
        elif isinstance(arg, int):
            return slice(arg, arg + 1)
        else:
            raise TypeError(f"Invalid slice type: {type(arg)} {arg}")
    except Exception as e:
        raise type(e)(f"[create_safe_slice] Error creating slice: {e}")

findsource(object)

Return the entire source file and starting line number for an object. For interactively-defined objects, the 'file' is the interpreter's history.

The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved, while a TypeError is raised for objects where the source code is unavailable (e.g. builtins).

Source code in src/tolvera/patches.py
def findsource(object):
    # print(f"[dill.source.findsource] PATCHED")

    """Return the entire source file and starting line number for an object.
    For interactively-defined objects, the 'file' is the interpreter's history.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a list of all the lines
    in the file and the line number indexes a line in that list.  An IOError
    is raised if the source code cannot be retrieved, while a TypeError is
    raised for objects where the source code is unavailable (e.g. builtins)."""

    def patched_getfile(module):
        # set file = None when module.__package__ == 'asyncio'
        # print(f"[dill.source.patched_getfile] module={module}\nmodule.__package__={module.__package__}\nmodule.__name__={module.__name__}")
        if module.__package__ == "asyncio":
            raise TypeError
        # if module.__package__ == 'sardine':
        #     raise TypeError
        ret = getfile(module)
        return ret

    module = getmodule(object)
    # try: file = getfile(module)
    try:
        file = patched_getfile(module)
    except TypeError:
        file = None
    # correctly compute `is_module_main` when in asyncio
    is_module_main = module and module.__name__ == "__main__" and not file
    # is_module_main = (module and module.__name__ == '__main__' or module.__name__ == 'sardine' and not file)
    print(
        f"[dill.source.findsource] module: {module}, file: {file}, is_module_main: {is_module_main}"
    )
    if IS_IPYTHON and is_module_main:
        # FIXME: quick fix for functions and classes in IPython interpreter
        try:
            file = getfile(object)
            sourcefile = getsourcefile(object)
        except TypeError:
            if isclass(object):
                for object_method in filter(isfunction, object.__dict__.values()):
                    # look for a method of the class
                    file_candidate = getfile(object_method)
                    if not file_candidate.startswith("<ipython-input-"):
                        continue
                    file = file_candidate
                    sourcefile = getsourcefile(object_method)
                    break
        if file:
            lines = linecache.getlines(file)
        else:
            # fallback to use history
            history = "\n".join(get_ipython().history_manager.input_hist_parsed)
            lines = [line + "\n" for line in history.splitlines()]
    # use readline when working in interpreter (i.e. __main__ and not file)
    elif is_module_main:
        try:
            import readline

            err = ""
        except ImportError:
            import sys

            err = sys.exc_info()[1].args[0]
            if sys.platform[:3] == "win":
                err += ", please install 'pyreadline'"
        if err:
            raise IOError(err)
        lbuf = readline.get_current_history_length()
        lines = [readline.get_history_item(i) + "\n" for i in range(1, lbuf)]
    else:
        try:  # special handling for class instances
            if not isclass(object) and isclass(type(object)):  # __class__
                file = getfile(module)
                sourcefile = getsourcefile(module)
            else:  # builtins fail with a TypeError
                file = getfile(object)
                sourcefile = getsourcefile(object)
        except (TypeError, AttributeError):  # fail with better error
            file = getfile(object)
            sourcefile = getsourcefile(object)
        if not sourcefile and file[:1] + file[-1:] != "<>":
            raise IOError("source code not available")
        file = sourcefile if sourcefile else file

        module = getmodule(object, file)
        if module:
            lines = linecache.getlines(file, module.__dict__)
        else:
            lines = linecache.getlines(file)

    if not lines:
        raise IOError("could not extract source code")

    # FIXME: all below may fail if exec used (i.e. exec('f = lambda x:x') )
    if ismodule(object):
        return lines, 0

    # NOTE: beneficial if search goes from end to start of buffer history
    name = pat1 = obj = ""
    pat2 = r"^(\s*@)"
    #   pat1b = r'^(\s*%s\W*=)' % name #FIXME: finds 'f = decorate(f)', not exec
    if ismethod(object):
        name = object.__name__
        if name == "<lambda>":
            pat1 = r"(.*(?<!\w)lambda(:|\s))"
        else:
            pat1 = r"^(\s*def\s)"
        object = object.__func__
    if isfunction(object):
        name = object.__name__
        if name == "<lambda>":
            pat1 = r"(.*(?<!\w)lambda(:|\s))"
            obj = object  # XXX: better a copy?
        else:
            pat1 = r"^(\s*def\s)"
        object = object.__code__
    if istraceback(object):
        object = object.tb_frame
    if isframe(object):
        object = object.f_code
    if iscode(object):
        if not hasattr(object, "co_firstlineno"):
            raise IOError("could not find function definition")
        # stdin = object.co_filename == '<stdin>'
        stdin = object.co_filename in ("<console>", "<stdin>")
        # print(f"[dill.source.findsource] object.co_filename: {object.co_filename}, stdin: {stdin}")
        if stdin:
            lnum = len(lines) - 1  # can't get lnum easily, so leverage pat
            if not pat1:
                pat1 = r"^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)"
        else:
            lnum = object.co_firstlineno - 1
            pat1 = r"^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)"
        pat1 = re.compile(pat1)
        pat2 = re.compile(pat2)
        # XXX: candidate_lnum = [n for n in range(lnum) if pat1.match(lines[n])]
        while lnum > 0:  # XXX: won't find decorators in <stdin> ?
            line = lines[lnum]
            if pat1.match(line):
                if not stdin:
                    break  # co_firstlineno does the job
                if name == "<lambda>":  # hackery needed to confirm a match
                    if _matchlambda(obj, line):
                        break
                else:  # not a lambda, just look for the name
                    if name in line:  # need to check for decorator...
                        hats = 0
                        for _lnum in range(lnum - 1, -1, -1):
                            if pat2.match(lines[_lnum]):
                                hats += 1
                            else:
                                break
                        lnum = lnum - hats
                        break
            lnum = lnum - 1
        return lines, lnum

    try:  # turn instances into classes
        if not isclass(object) and isclass(type(object)):  # __class__
            object = object.__class__  # XXX: sometimes type(class) is better?
            # XXX: we don't find how the instance was built
    except AttributeError:
        pass
    if isclass(object):
        name = object.__name__
        pat = re.compile(r"^(\s*)class\s*" + name + r"\b")
        # make some effort to find the best matching class definition:
        # use the one with the least indentation, which is the one
        # that's most probably not inside a function definition.
        candidates = []
        for i in range(len(lines) - 1, -1, -1):
            match = pat.match(lines[i])
            if match:
                # if it's at toplevel, it's already the best one
                if lines[i][0] == "c":
                    return lines, i
                # else add whitespace to candidate list
                candidates.append((match.group(1), i))
        if candidates:
            # this will sort by whitespace, and by line number,
            # less whitespace first  #XXX: should sort high lnum before low
            candidates.sort()
            return lines, candidates[0][1]
        else:
            raise IOError("could not find class definition")
    raise IOError("could not find code object")

flatten(lst)

Flatten a nested list or return a non-nested list as is.

Source code in src/tolvera/utils.py
def flatten(lst):
    """Flatten a nested list or return a non-nested list as is."""
    if all(isinstance(el, list) for el in lst):
        return [item for sublist in lst for item in sublist]
    return lst

generic_slice(array, slice_params)

Slices a NumPy array based on a tuple of slice parameters for each dimension.

Parameters:

Name Type Description Default
array ndarray

The array to be sliced.

required
slice_params tuple

A tuple where each item is either an integer, a tuple with slice parameters, or a slice object.

required

Returns:

Name Type Description
ndarray ndarray

The sliced array.

Source code in src/tolvera/utils.py
def generic_slice(
    array: np.ndarray,
    slice_params: Union[
        tuple[Union[int, tuple[int, ...], slice], ...],
        Union[int, tuple[int, ...], slice],
    ],
) -> np.ndarray:
    """
    Slices a NumPy array based on a tuple of slice parameters for each dimension.

    Args:
        array (np.ndarray): The array to be sliced.
        slice_params (tuple): A tuple where each item is either an integer, a tuple with
                             slice parameters, or a slice object.

    Returns:
        ndarray: The sliced array.
    """
    if not isinstance(slice_params, tuple):
        slice_params = (slice_params,)
    slices = tuple(create_safe_slice(param) for param in slice_params)
    return array.__getitem__(slices)

time_function(func, *args, **kwargs)

Time how long it takes to run a function and print the result

Source code in src/tolvera/utils.py
def time_function(func, *args, **kwargs):
    """Time how long it takes to run a function and print the result"""
    start = time.time()
    ret = func(*args, **kwargs)
    end = time.time()
    print(f"[Tolvera.utils] {func.__name__}() ran in {end-start:.4f}s")
    if ret is not None:
        return (ret, end - start)
    return end - start

validate_json_path(path)

Validate a JSON file path. It uses validate_path for initial validation.

Parameters:

Name Type Description Default
path str

The JSON file path to be validated.

required

Returns:

Name Type Description
bool bool

True if the path is a valid JSON file path, raises an exception otherwise.

Raises:

Type Description
ValueError

If the path does not end with '.json'.

Source code in src/tolvera/utils.py
def validate_json_path(path: str) -> bool:
    """
    Validate a JSON file path. It uses validate_path for initial validation.

    Args:
        path (str): The JSON file path to be validated.

    Returns:
        bool: True if the path is a valid JSON file path, raises an exception otherwise.

    Raises:
        ValueError: If the path does not end with '.json'.
    """
    # Using validate_path for basic path validation
    validate_path(path)

    if not path.endswith(".json"):
        raise ValueError("Path should end with '.json'")

    return True

validate_path(path)

Validate a path using os.path and pathlib.

Parameters:

Name Type Description Default
path str

The path to be validated.

required

Returns:

Name Type Description
bool bool

True if the path is valid, raises an exception otherwise.

Raises:

Type Description
TypeError

If the input is not a string.

FileNotFoundError

If the path does not exist.

PermissionError

If the path is not accessible.

Source code in src/tolvera/utils.py
def validate_path(path: str) -> bool:
    """
    Validate a path using os.path and pathlib.

    Args:
        path (str): The path to be validated.

    Returns:
        bool: True if the path is valid, raises an exception otherwise.

    Raises:
        TypeError: If the input is not a string.
        FileNotFoundError: If the path does not exist.
        PermissionError: If the path is not accessible.
    """
    if not isinstance(path, str):
        raise TypeError(f"Expected a string for path, but received {type(path)}")

    path_obj = Path(path)
    if not path_obj.is_file():
        raise FileNotFoundError(f"The path {path} does not exist or is not a file")

    if not os.access(path, os.R_OK):
        raise PermissionError(f"The path {path} is not accessible")

    return True

validate_slice(slice_obj, target_array)

Validates if the given slice object is applicable to the target ndarray.

Parameters:

Name Type Description Default
slice_obj tuple[slice]

A tuple containing slice objects for each dimension.

required
target_array ndarray

The array to be sliced.

required

Returns:

Name Type Description
bool bool

True if the slice is valid for the given array, False otherwise.

Source code in src/tolvera/utils.py
def validate_slice(slice_obj: tuple[slice], target_array: np.ndarray) -> bool:
    """
    Validates if the given slice object is applicable to the target ndarray.

    Args:
        slice_obj (tuple[slice]): A tuple containing slice objects for each dimension.
        target_array (np.ndarray): The array to be sliced.

    Returns:
        bool: True if the slice is valid for the given array, False otherwise.
    """
    if len(slice_obj) != target_array.ndim:
        return False

    for sl, size in zip(slice_obj, target_array.shape):
        # Check if slice start and stop are within the dimension size
        start, stop, _ = sl.indices(size)
        if not (0 <= start < size and (0 <= stop <= size or stop == -1)):
            return False
    return True