pyviewfactor 0.1.6__tar.gz → 0.1.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyviewfactor
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: A python library to calculate numerically exact radiation view factors between planar faces.
5
5
  Home-page: https://gitlab.com/arep-dev/pyViewFactor/
6
6
  Author: Mateusz BOGDAN, Edouard WALTHER, Marc ALECIAN, Mina CHAPON
@@ -1,5 +1,5 @@
1
1
  """Version info for pyViewFactor"""
2
- version_info = 0, 1, 6
2
+ version_info = 0, 1, 7
3
3
 
4
4
  # Nice string for the version
5
5
  __version__ = '.'.join(map(str, version_info))
@@ -7,8 +7,12 @@ import numpy as np
7
7
  import pyvista as pv
8
8
  from joblib import Parallel, delayed
9
9
  from tqdm import tqdm
10
+ from numpy.polynomial.legendre import leggauss
11
+ import scipy.integrate
12
+ from functools import partial
10
13
 
11
14
 
15
+ # Utils
12
16
  def fc_unstruc2poly(mesh_unstruc):
13
17
  """Convenience conversion function from UnstructuredGrid to PolyData
14
18
 
@@ -82,6 +86,7 @@ def trunc(values, decs=0):
82
86
  return np.trunc(values * factor) / factor
83
87
 
84
88
 
89
+ # Visibility / Obstructions
85
90
  def get_visibility(c1, c2, strict=False, print_warning=False, rounding_decimal=6):
86
91
  """Facets visibility:
87
92
 
@@ -334,22 +339,20 @@ def get_obstruction(face1, face2, obstacle, strict=False, print_debug=False):
334
339
  # --- strict mode: test every vertex‐to‐vertex ray ---
335
340
  if strict:
336
341
  # build a (N_tri,3,3) array of triangles
337
- tri_array = np.array([
338
- obstacle.get_cell(i).points
339
- for i in range(obstacle.n_cells)
340
- ])
341
- # build all (m×n) start‐end pairs
342
- m = face1.points.shape[0]
343
- n = face2.points.shape[0]
344
- m = face1.points.shape[0]
345
- n = face2.points.shape[0]
346
- tri_array = np.array([obstacle.get_cell(i).points
347
- for i in range(obstacle.n_cells)])
348
- ray_starts = np.repeat(face1.points, n, axis=0)
349
- ray_ends = np.tile(face2.points, (m, 1))
342
+ # force everything to float64 so Numba's np.dot sees matching dtypes
343
+ tri_array = np.array(
344
+ [obstacle.get_cell(i).points for i in range(obstacle.n_cells)],
345
+ dtype=np.float64
346
+ )
347
+ pts1 = face1.points.astype(np.float64)
348
+ pts2 = face2.points.astype(np.float64)
349
+ # build all (m×n) start‐end pairs now in float64
350
+ m = pts1.shape[0]
351
+ n = pts2.shape[0]
352
+ ray_starts = np.repeat(pts1, n, axis=0)
353
+ ray_ends = np.tile(pts2, (m, 1))
350
354
  mask = batch_ray_obstruction(ray_starts, ray_ends, tri_array, eps=eps)
351
355
 
352
- print(mask)
353
356
  # if *all* rays clear → fully visible
354
357
  if mask.all():
355
358
  return True, ""
@@ -383,200 +386,243 @@ def get_obstruction(face1, face2, obstacle, strict=False, print_debug=False):
383
386
  return visible, ""
384
387
 
385
388
 
386
- @njit
387
- def fast_integrand(norm_q_carree, norm_p_carree, scal_qpq,
388
- scal_qpp, scal_pq, norm_qp_carree):
389
- """
390
- Compute the contour integral kernel for view factor between two edges.
389
+ # Computations
391
390
 
392
- Uses 10-point Gauss–Legendre quadrature over [0,1]^2.
393
391
 
394
- Parameters
395
- ----------
396
- norm_q_carree : float
397
- Squared length of edge vector q.
398
- norm_p_carree : float
399
- Squared length of edge vector p.
400
- scal_qpq : float
401
- Dot(q, p).
402
- scal_qpp : float
403
- Dot(q, p_next).
404
- scal_pq : float
405
- Dot(p, q).
406
- norm_qp_carree : float
407
- Squared distance between edge origins.
392
+ @njit # numba's just in time compilation offers a x2 speedup
393
+ def _integrand_dblquad(x, y, norm_q_carree, norm_p_carree, scal_qpq,
394
+ scal_qpp, scal_pq, norm_qp_carree):
395
+ """
396
+ Return the integrand for a pair of edges of two facets for the view factor
397
+ computation.
408
398
 
409
- Returns
410
- -------
411
- float
412
- The weighted sum of ln(expr)*scal_pq over quadrature points.
399
+ Used in the *compute_viewfactor* function.
413
400
 
414
- Examples
415
- --------
416
- >>> fast_integrand(1.0, 1.0, 0.5, 0.5, 0.25, 2.0)
417
- 0.0 # example output
418
401
  """
419
- nodes = np.array([
420
- -0.9739065285, -0.8650633667, -0.6794095682, -0.4333953941, -0.1488743390,
421
- 0.1488743390, 0.4333953941, 0.6794095682, 0.8650633667, 0.9739065285
422
- ])
423
- weights = np.array([
424
- 0.0666713443, 0.1494513491, 0.2190863625, 0.2692667193, 0.2955242247,
425
- 0.2955242247, 0.2692667193, 0.2190863625, 0.1494513491, 0.0666713443
426
- ])
427
- x = 0.5 * (nodes + 1.0)
428
- w = 0.5 * weights
429
- result = 0.0
430
- for i in range(10):
431
- xi = x[i]
432
- wi = w[i]
433
- for j in range(10):
434
- yj = x[j]
435
- wj = w[j]
436
- expr = (yj * yj * norm_q_carree + xi * xi * norm_p_carree
437
- - 2 * yj * scal_qpq + 2 * xi * scal_qpp
438
- - 2 * xi * yj * scal_pq + norm_qp_carree)
439
- if expr > 0.0:
440
- result += wi * wj * np.log(expr) * scal_pq
441
- return result
402
+ integrand_function = np.log(y**2 * norm_q_carree
403
+ + x**2 * norm_p_carree
404
+ - 2 * y * scal_qpq
405
+ + 2 * x * scal_qpp
406
+ - 2 * x * y * scal_pq
407
+ + norm_qp_carree
408
+ ) * scal_pq
409
+ return integrand_function
442
410
 
443
411
 
444
- @njit
445
- def compute_viewfactor_core(cell_1_points, cell_2_points,
446
- vect_intra_1, vect_intra_2,
447
- constante):
448
- """
449
- Core Numba kernel: sum contributions of all edge pairs between two facets.
412
+ def _compute_viewfactor_dblquad(pts1, pts2, constante):
413
+ total = 0.0
414
+ n1, n2 = len(pts1), len(pts2)
415
+ v1 = np.roll(pts1, -1, axis=0) - pts1
416
+ v2 = np.roll(pts2, -1, axis=0) - pts2
417
+ norm1 = np.sum(v1 * v1, axis=1)
418
+ norm2 = np.sum(v2 * v2, axis=1)
419
+ scal = v1 @ v2.T
450
420
 
451
- Parameters
452
- ----------
453
- cell_1_points : ndarray, shape (n1,3)
454
- Vertex coordinates of facet 1.
455
- cell_2_points : ndarray, shape (n2,3)
456
- Vertex coordinates of facet 2.
457
- vect_intra_1 : ndarray, shape (n1,3)
458
- Edge vectors of facet 1.
459
- vect_intra_2 : ndarray, shape (n2,3)
460
- Edge vectors of facet 2.
461
- constante : float
462
- Normalization constant = 4*pi*Area(facet2).
421
+ for i in range(n1):
422
+ nq = norm1[i]
423
+ e1 = v1[i]
424
+ for j in range(n2):
425
+ np_ = norm2[j]
426
+ e2 = v2[j]
427
+ d = pts2[j] - pts1[i]
428
+ nqp = np.dot(d, d)
429
+ sqpq = np.dot(d, e1)
430
+ sqpp = np.dot(d, e2)
431
+ spq = scal[i, j]
432
+ val, _ = scipy.integrate.dblquad(
433
+ _integrand_dblquad,
434
+ 0.0, 1.0,
435
+ lambda xx: 0.0, lambda xx: 1.0,
436
+ args=(nq, np_, sqpq, sqpp, spq, nqp)
437
+ )
438
+ total += val
439
+ vf = total / constante
440
+ if vf > 0:
441
+ return vf
442
+ else:
443
+ return 0.0
463
444
 
464
- Returns
465
- -------
466
- float
467
- View factor from facet 2 to facet 1.
468
445
 
469
- Examples
470
- --------
471
- >>> pts1 = np.array([[0,0,0],[1,0,0],[1,1,0]])
472
- >>> pts2 = pts1 + [0,0,1]
473
- >>> v1 = np.vstack([pts1[1:]-pts1[:-1], pts1[0]-pts1[-1]])
474
- >>> v2 = np.vstack([pts2[1:]-pts2[:-1], pts2[0]-pts2[-1]])
475
- >>> constant = 4*np.pi*1.0
476
- >>> compute_viewfactor_core(pts1, pts2, v1, v2, constant)
477
- 0.0
446
+ # Precompute 30×30 nodes & weights once
447
+ _GL_ORDER = 10
448
+ _nodes, _weights = leggauss(_GL_ORDER)
449
+ # map from [-1,1] → [0,1]
450
+ _GL_X = 0.5 * (_nodes + 1.0)
451
+ _GL_W = 0.5 * _weights
452
+
453
+
454
+ @njit
455
+ def _integrand_gauss_legendre(norm_q, norm_p, scal_qpq, scal_qpp, scal_pq, norm_qp):
456
+ total = 0.0
457
+ for i in range(_GL_ORDER):
458
+ xi = _GL_X[i]
459
+ wi = _GL_W[i]
460
+ for j in range(_GL_ORDER):
461
+ yj = _GL_X[j]
462
+ wj = _GL_W[j]
463
+ expr = (yj * yj * norm_q
464
+ + xi * xi * norm_p
465
+ - 2.0 * yj * scal_qpq
466
+ + 2.0 * xi * scal_qpp
467
+ - 2.0 * xi * yj * scal_pq
468
+ + norm_qp)
469
+ if expr > 0.0:
470
+ total += wi * wj * np.log(expr) * scal_pq
471
+ return total
472
+
473
+
474
+ @njit
475
+ def _compute_viewfactor_gauss_legendre(pts1, pts2, constante):
478
476
  """
479
- n1 = cell_1_points.shape[0]
480
- n2 = cell_2_points.shape[0]
481
- matL = cell_2_points[None, :, :] - cell_1_points[:, None, :]
482
- norm1 = np.sum(vect_intra_1 * vect_intra_1, axis=1)
483
- norm2 = np.sum(vect_intra_2 * vect_intra_2, axis=1)
484
- scal = np.dot(vect_intra_1, vect_intra_2.T)
477
+ The Numba‐JITed version: no scipy, fast fixed‐order GL quadrature.
478
+ """
479
+ n1 = pts1.shape[0]
480
+ n2 = pts2.shape[0]
481
+ v1 = np.empty((n1, 3))
482
+ for k in range(n1 - 1):
483
+ v1[k, 0] = pts1[k + 1, 0] - pts1[k, 0]
484
+ v1[k, 1] = pts1[k + 1, 1] - pts1[k, 1]
485
+ v1[k, 2] = pts1[k + 1, 2] - pts1[k, 2]
486
+ # last edge back to first point
487
+ v1[n1 - 1, 0] = pts1[0, 0] - pts1[n1 - 1, 0]
488
+ v1[n1 - 1, 1] = pts1[0, 1] - pts1[n1 - 1, 1]
489
+ v1[n1 - 1, 2] = pts1[0, 2] - pts1[n1 - 1, 2]
490
+
491
+ v2 = np.empty((n2, 3))
492
+ for k in range(n2 - 1):
493
+ v2[k, 0] = pts2[k + 1, 0] - pts2[k, 0]
494
+ v2[k, 1] = pts2[k + 1, 1] - pts2[k, 1]
495
+ v2[k, 2] = pts2[k + 1, 2] - pts2[k, 2]
496
+ v2[n2 - 1, 0] = pts2[0, 0] - pts2[n2 - 1, 0]
497
+ v2[n2 - 1, 1] = pts2[0, 1] - pts2[n2 - 1, 1]
498
+ v2[n2 - 1, 2] = pts2[0, 2] - pts2[n2 - 1, 2]
499
+ # precompute norms & dot‐products
500
+ norm1 = np.sum(v1 * v1, axis=1)
501
+ norm2 = np.sum(v2 * v2, axis=1)
502
+ scal = v1 @ v2.T
503
+ # 4π·area
504
+ # (you’ll need to pass 'constante' as argument, or recompute area here)
505
+ # A2 = 0.0 # you can pre‐compute outside and pass in
506
+ # constante = 4.0 * np.pi * A2
507
+
485
508
  total = 0.0
486
509
  for i in range(n1):
487
- nqi = norm1[i]
510
+ nq = norm1[i]
511
+ e1 = v1[i]
488
512
  for j in range(n2):
489
- npj = norm2[j]
490
- ld = matL[i, j]
491
- nl = np.dot(ld, ld)
492
- sqpq = np.dot(ld, vect_intra_1[i])
493
- sqpp = np.dot(ld, vect_intra_2[j])
513
+ np_ = norm2[j]
514
+ e2 = v2[j]
515
+ d = pts2[j] - pts1[i]
516
+ nqp = np.dot(d, d)
517
+ sqpq = np.dot(d, e1)
518
+ sqpp = np.dot(d, e2)
494
519
  spq = scal[i, j]
495
- val = fast_integrand(nqi, npj, sqpq, sqpp, spq, nl)
496
- total += round(val / constante, 11)
497
- return total if total > 0 else 0.0
520
+ total += _integrand_gauss_legendre(nq, np_, sqpq, sqpp, spq, nqp)
521
+ vf = total / constante
522
+ if vf > 0:
523
+ return vf
524
+ else:
525
+ return 0.0
498
526
 
499
527
 
500
- def compute_viewfactor(cell_1, cell_2, epsilon=0.00001, rounding_decimal=6):
528
+ def compute_viewfactor(cell1, cell2, *, epsilon=1e-6, rounding_decimal=6):
529
+ """
530
+ Dispatch to either the fast @njit GL kernel or the
531
+ robust scipy.dblquad backend if the two facets share an edge/vertex.
501
532
  """
502
- Compute the radiation view factor from cell_2 to cell_1 using contour integration.
533
+ # 1) Extract & round points
534
+ pts1 = np.round(
535
+ cell1.cast_to_unstructured_grid().get_cell(0).points,
536
+ rounding_decimal
537
+ )
538
+ pts2 = np.round(
539
+ cell2.cast_to_unstructured_grid().get_cell(0).points,
540
+ rounding_decimal
541
+ )
503
542
 
504
- This function casts each face to an unstructured grid, extracts and rounds
505
- its vertices, applies a small displacement if cells share vertices, and
506
- then calls a fast Numba-compiled core to evaluate the contour integral
507
- via Gauss-Legendre quadrature.
543
+ # 2) Small shift along normal‐bisector if they share vertices
544
+ set1 = {tuple(p) for p in pts1}
545
+ set2 = {tuple(p) for p in pts2}
546
+ if set1 & set2:
547
+ c1 = cell1.cell_centers().points[0]
548
+ c2 = cell2.cell_centers().points[0]
549
+ direction = c2 - c1
550
+ norm = np.linalg.norm(direction)
551
+ if norm > 0.0:
552
+ direction /= norm
553
+ pts2 += epsilon * direction
554
+ use_dblquad = True
555
+ else:
556
+ use_dblquad = False
508
557
 
509
- Parameters
510
- ----------
511
- cell_1 : pyvista.PolyData
512
- The receiving facet (must be a single face PolyData).
513
- cell_2 : pyvista.PolyData
514
- The emitting facet (must be a single face PolyData).
515
- epsilon : float, optional
516
- Small displacement applied when facets share vertices to avoid singularities
517
- (default=0.001).
518
- rounding_decimal : int, optional
519
- Number of decimal places to round vertex coordinates for numerical stability
520
- (default=6).
558
+ # 3) Compute constante = 4π·Area(cell2)
559
+ area2 = cell2.compute_cell_sizes(area=True)['Area'][0]
560
+ constante = 4.0 * np.pi * area2
521
561
 
522
- Returns
523
- -------
524
- float
525
- View factor from cell_2 onto cell_1 (dimensionless, between 0 and 1).
562
+ # 4) Dispatch
563
+ if use_dblquad:
564
+ VF = _compute_viewfactor_dblquad(pts1, pts2, constante)
565
+ else:
566
+ VF = _compute_viewfactor_gauss_legendre(pts1, pts2, constante)
567
+ return VF
526
568
 
527
- Examples
528
- --------
529
- >>> import pyvista as pv
530
- >>> tri1 = pv.Triangle([[0,0,0],[1,0,0],[0,1,0]])
531
- >>> tri2 = pv.Triangle([[0,0,1],[1,0,1],[0,1,1]])
532
- >>> vf = compute_viewfactorNew(tri1, tri2)
533
- >>> isinstance(vf, float)
534
- True
569
+
570
+
571
+ def _is_blocked(f_i, f_j, obstacles, obstruction_kwargs, skip_obstruction):
572
+ """Return True if any obstacle blocks f_i→f_j."""
573
+ if skip_obstruction or not obstacles:
574
+ return False
575
+ for obs in obstacles:
576
+ vis_obs, _ = get_obstruction(f_i, f_j, obs, **(obstruction_kwargs or {}))
577
+ if not vis_obs:
578
+ return True
579
+ return False
580
+
581
+
582
+ def _compute_pair(i, j,
583
+ faces, areas,
584
+ obstacles,
585
+ skip_visibility, skip_obstruction,
586
+ visibility_kwargs, obstruction_kwargs,
587
+ epsilon, rounding_decimal,
588
+ use_reciprocity):
535
589
  """
536
- # 1) Cast to PolyData & unstructured grid
537
- c1_poly = cell_1
538
- c2_poly = cell_2
539
- ug1 = c1_poly.cast_to_unstructured_grid()
540
- ug2 = c2_poly.cast_to_unstructured_grid()
541
-
542
- # 2) Get and round the points
543
- pts1 = np.round(ug1.get_cell(0).points, rounding_decimal)
544
- pts2 = np.round(ug2.get_cell(0).points, rounding_decimal)
545
-
546
- # 3) Detect shared vertices
547
- # Build a set of tuples for quick compare
548
- set1 = {tuple(p) for p in pts1}
549
- set2 = {tuple(p) for p in pts2}
550
- if set1 & set2: # non-empty intersection → shared vertex/edge
551
- # compute unit centroid direction
552
- cen1 = c1_poly.cell_centers().points[0]
553
- cen2 = c2_poly.cell_centers().points[0]
554
- dir_vec = cen2 - cen1
555
- dir_vec = dir_vec / np.linalg.norm(dir_vec)
556
- # translate pts2 by epsilon
557
- pts2 = pts2 + epsilon * dir_vec
558
-
559
- # 4) Recompute auxiliary arrays for the Numba core
560
- # Build the intra‐edge (directed edge) vectors for each facet
561
- pts1_roll = np.roll(pts1, -1, axis=0)
562
- vect_intra_1 = pts1_roll - pts1
563
- pts2_roll = np.roll(pts2, -1, axis=0)
564
- vect_intra_2 = pts2_roll - pts2
565
-
566
- # Compute the 4π·Area constant from cell_2
567
- area2 = cell_2.compute_cell_sizes(area=True)['Area'][0]
568
- constante = 4.0 * np.pi * area2
569
- # 5) Call the Numba core:
570
- return compute_viewfactor_core(pts1, pts2,
571
- vect_intra_1, vect_intra_2,
572
- constante)
590
+ Compute F_ij and F_ji for faces[i] and faces[j], with all flags.
591
+ Always returns (i, j, F_ij, F_ji).
592
+ """
593
+ f_i, f_j = faces[i], faces[j]
594
+
595
+ # 1) Visibility
596
+ if not skip_visibility:
597
+ vis, _ = get_visibility(f_i, f_j, **visibility_kwargs)
598
+ if not vis:
599
+ return i, j, 0.0, 0.0
600
+
601
+ # 2) Obstruction
602
+ if _is_blocked(f_i, f_j, obstacles, obstruction_kwargs, skip_obstruction):
603
+ return i, j, 0.0, 0.0
604
+
605
+ # 3) View-factor
606
+ F_ij = compute_viewfactor(f_i, f_j,
607
+ epsilon=epsilon,
608
+ rounding_decimal=rounding_decimal)
609
+ if use_reciprocity:
610
+ F_ji = F_ij * (areas[j] / areas[i])
611
+ else:
612
+ F_ji = compute_viewfactor(f_j, f_i,
613
+ epsilon=epsilon,
614
+ rounding_decimal=rounding_decimal)
615
+ return i, j, F_ij, F_ji
573
616
 
574
617
 
575
618
  def compute_viewfactor_matrix(mesh, obstacle=None,
576
- use_reciprocity=True,
577
- visibility_kwargs=None, obstruction_kwargs=None,
578
- skip_visibility=False, skip_obstruction=False,
579
- n_jobs=1):
619
+ use_reciprocity=True,
620
+ visibility_kwargs=None,
621
+ obstruction_kwargs=None,
622
+ compute_kwargs=None,
623
+ skip_visibility=False,
624
+ skip_obstruction=False,
625
+ n_jobs=1):
580
626
  """
581
627
  Compute the view factor matrix for all faces in a mesh, skipping
582
628
  pairs that are not mutually visible or are obstructed.
@@ -599,8 +645,10 @@ def compute_viewfactor_matrix(mesh, obstacle=None,
599
645
 
600
646
  Returns
601
647
  -------
602
- F : ndarray, shape (n_faces, n_faces)
603
- Symmetric view factor matrix.
648
+ F : ndarray, shape (n_cells, n_cells)
649
+ The view‐factor matrix for the mesh. By convention
650
+ F[i, j] = view factor from cell j → cell i
651
+ i.e. the fraction of energy leaving cell *j* that arrives at cell *i*.
604
652
 
605
653
  Examples
606
654
  --------
@@ -628,11 +676,16 @@ def compute_viewfactor_matrix(mesh, obstacle=None,
628
676
  """
629
677
 
630
678
  # Prepare faces and areas
679
+ compute_kwargs = compute_kwargs or {}
680
+ epsilon = compute_kwargs.get("epsilon", 1e-6)
681
+ rounding_decimal = compute_kwargs.get("rounding_decimal", 6)
682
+
631
683
  faces = []
632
684
  areas = []
685
+
633
686
  for i in range(mesh.n_cells):
634
687
  raw = mesh.extract_cells(i)
635
- face = fc_unstruc2poly(raw)
688
+ face = fc_unstruc2poly(raw)
636
689
  faces.append(face)
637
690
  areas.append(face.compute_cell_sizes(area=True)['Area'][0])
638
691
  n = len(faces)
@@ -650,68 +703,39 @@ def compute_viewfactor_matrix(mesh, obstacle=None,
650
703
  else:
651
704
  obstacles = [obstacle]
652
705
 
653
- def _is_blocked(f1, f2):
654
- for obs in obstacles:
655
- vis_obs, _ = get_obstruction(f1, f2, obs, **obstruction_kwargs)
656
- if not vis_obs:
657
- return True
658
- return False
659
-
660
- # Helper to compute a single pair
661
- def _compute_pair(i, j):
662
- """
663
- Compute a single pair (i,j) in the view‐factor matrix:
664
- - Optionally cull by visibility (skip_visibility)
665
- - Optionally cull by one or more obstacles
666
- - Compute F_ij and F_ji (via reciprocity or explicit)
667
- Always returns (i, j, F_ij, F_ji).
668
- """
669
- f_i = faces[i]
670
- f_j = faces[j]
671
-
672
- # 1) Visibility cull
673
- if not skip_visibility:
674
- vis, _ = get_visibility(f_i, f_j, **(visibility_kwargs or {}))
675
- if not vis:
676
- return i, j, 0.0, 0.0
677
-
678
- # 2) Obstruction cull (all obstacles must be clear)
679
- if obstacles:
680
- for obs in obstacles:
681
- vis_obs, _ = get_obstruction(f_i, f_j, obs, **(obstruction_kwargs or {}))
682
- if not vis_obs:
683
- return i, j, 0.0, 0.0
684
-
685
- # 3) Compute the view factor
686
- F_ij = compute_viewfactor(f_i, f_j)
687
- if use_reciprocity:
688
- F_ji = F_ij * (areas[i] / areas[j])
689
- else:
690
- F_ji = compute_viewfactor(f_j, f_i)
691
- return i, j, F_ij, F_ji
692
706
 
707
+ # build a callable with all those locals pre-filled
708
+ compute_pair = partial(
709
+ _compute_pair,
710
+ faces=faces,
711
+ areas=areas,
712
+ obstacles=obstacles,
713
+ skip_visibility=skip_visibility,
714
+ skip_obstruction=skip_obstruction,
715
+ visibility_kwargs=visibility_kwargs,
716
+ obstruction_kwargs=obstruction_kwargs,
717
+ epsilon=epsilon,
718
+ rounding_decimal=rounding_decimal,
719
+ use_reciprocity=use_reciprocity,
720
+ )
693
721
  # Prepare all unique pairs
694
722
  pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
695
723
 
696
724
  # Compute in parallel or sequential
697
725
  if n_jobs and n_jobs != 1:
698
726
  results = Parallel(n_jobs=n_jobs)(
699
- delayed(_compute_pair)(i, j) for (i, j) in pairs
727
+ delayed(compute_pair)(i, j) for (i, j) in pairs
700
728
  )
701
729
  else:
702
730
  results = []
703
731
  for (i, j) in tqdm(pairs, desc="Computing view factors", total=len(pairs)):
704
- results.append(_compute_pair(i, j))
732
+ results.append(compute_pair(i, j))
705
733
 
706
734
  # Fill matrix
707
735
  for res in results:
708
- if len(res) == 3:
709
- i, j, val = res
710
- F[i, j] = val
711
- else:
712
- i, j, fij, fji = res
713
- F[i, j] = fij
714
- F[j, i] = fji
736
+ i, j, fij, fji = res
737
+ F[i, j] = fij
738
+ F[j, i] = fji
715
739
  return F
716
740
 
717
741
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyviewfactor
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: A python library to calculate numerically exact radiation view factors between planar faces.
5
5
  Home-page: https://gitlab.com/arep-dev/pyViewFactor/
6
6
  Author: Mateusz BOGDAN, Edouard WALTHER, Marc ALECIAN, Mina CHAPON
@@ -0,0 +1,42 @@
1
+ """ PVF tests utility functions"""
2
+
3
+ import numpy as np
4
+ import pyvista as pv
5
+ import pytest
6
+ import pyviewfactor as pvf
7
+
8
+
9
+ def test_trunc_scalar():
10
+ assert pvf.trunc(1.234567, 2) == pytest.approx(1.23)
11
+
12
+
13
+ def test_trunc_array():
14
+ arr = np.array([1.2345, 2.3456])
15
+ out = pvf.trunc(arr, 3)
16
+ assert np.allclose(out, [1.234, 2.345])
17
+
18
+
19
+ def test_fc_unstruc2poly_roundtrip():
20
+ sphere = pv.Sphere(radius=0.5)
21
+ ug = sphere.cast_to_unstructured_grid()
22
+ poly = pvf.fc_unstruc2poly(ug)
23
+ # Should be PolyData with same number of cells
24
+ assert isinstance(poly, pv.PolyData)
25
+ assert poly.n_cells == ug.n_cells
26
+
27
+
28
+ def test_plotter_runs_and_returns_plotter():
29
+ # Create a minimal mesh with 2 cells
30
+ mesh = pv.PolyData()
31
+ pts = np.array([[0,0,0], [1,0,0], [0,1,0], [0,0,1]])
32
+ # two triangles sharing a point
33
+ faces = np.hstack([[3, 0,1,2], [3, 0,2,3]])
34
+ mesh.points = pts
35
+ mesh.faces = faces
36
+
37
+ # Dummy VF vector of length n_cells
38
+ vf = np.array([[0.3, 0.7],[0.2,0.8]])
39
+
40
+ # Should not raise and should return a Plotter
41
+ pl = pvf.plot_viewfactor(mesh, vf, cell_id=1, show=False)
42
+ assert isinstance(pl, pv.Plotter)
@@ -0,0 +1,204 @@
1
+ # import numpy as np
2
+ import pyvista as pv
3
+ import pytest
4
+ import pyviewfactor as pvf
5
+ import numpy as np
6
+ from pyviewfactor.pyviewfactor import _compute_viewfactor_fixed
7
+ from pyviewfactor.pyviewfactor import _integrand_gauss_legendre
8
+ from pyviewfactor.pyviewfactor import _integrand_dblquad
9
+
10
+ def test_integrand_raw_kernel():
11
+ # at (0,0) → log(nqp)*spq
12
+ v = pvf.integrand_dblquad.py_func(0.0,0.0, 2.0,3.0, 0.0,0.0, 5.0, 4.0)
13
+ assert v == pytest.approx(np.log(4.0)*5.0)
14
+
15
+
16
+ # two identical parallel unit squares 1 unit apart → known VF = 1/(π)
17
+ pointa = [1.0, 0.0, 0.0]
18
+ pointb = [1.0, 1.0, 0.0]
19
+ pointc = [0.0, 1.0, 0.0]
20
+ rectangle1 = pv.Rectangle([pointa, pointb, pointc])
21
+
22
+ pointa = [1.0, 0.0, 1.0]
23
+ pointb = [1.0, 1.0, 1.0]
24
+ pointc = [0.0, 1.0, 1.0]
25
+ rectangle2 = pv.Rectangle([pointc, pointb, pointa])
26
+
27
+
28
+ def test_compute_viewfactor_basic():
29
+ vf = pvf.compute_viewfactor(rectangle2, rectangle1)
30
+ assert vf == pytest.approx(0.199824, rel=1e-5)
31
+
32
+
33
+ rect1 = pv.Rectangle([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
34
+ rect2 = pv.Rectangle([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]])
35
+
36
+
37
+ def test_compute_viewfactor_common_edge_basic():
38
+ vf = pvf.compute_viewfactor(rect1, rect2, epsilon=0.000001)
39
+ assert vf == pytest.approx(0.20004, rel=1e-4)
40
+
41
+
42
+ def test_closed_geometry_parrallel():
43
+ # create a raw sphere with pyvista
44
+ sphere = pv.Sphere(radius=10, center=(0, 0, 0), direction=(0, 0, 1),
45
+ theta_resolution=5, phi_resolution=5,
46
+ start_theta=0, end_theta=360,
47
+ start_phi=0, end_phi=180)
48
+ # triangulate
49
+ sphere.triangulate(inplace=True)
50
+ # and put the normals inwards please
51
+ sphere.flip_faces(inplace=True)
52
+
53
+ # let us chose a cell to compute view factors to
54
+ cell_extracted_id = 2
55
+ # let us chose a cell to compute view factors to
56
+ chosen_face = sphere.extract_cells(cell_extracted_id)
57
+ # convert to PolyData
58
+ chosen_face = pvf.fc_unstruc2poly(chosen_face)
59
+
60
+ F = pvf.compute_viewfactor_matrix(
61
+ sphere,
62
+ skip_visibility=True,
63
+ skip_obstruction=True,
64
+ compute_kwargs={"epsilon": 1e-4, "rounding_decimal": 8},
65
+ n_jobs=2
66
+ )
67
+ sum_vf = F[:, cell_extracted_id].sum()
68
+ assert sum_vf == pytest.approx(1.0, rel=1e-3)
69
+
70
+
71
+
72
+ def test_skip_obstruction_flag_respected():
73
+ # use the same two‐triangle mesh and place an obstacle that blocks only 1→0
74
+ pts = np.array([
75
+ [0.0, 0.0, 0.0],
76
+ [1.0, 0.0, 0.0],
77
+ [0.0, 1.0, 0.0],
78
+ [0.0, 0.0, 1.0]
79
+ ], float)
80
+ # triangle 0: pts[0,1,2], triangle 1: pts[0,2,3]
81
+ faces = np.hstack([[3,0,1,2], [3,0,2,3]])
82
+ mesh = pv.PolyData(pts, faces)
83
+ mesh.triangulate(inplace=True)
84
+ tri0 = mesh.extract_cells(0)
85
+ tri1 = mesh.extract_cells(1)
86
+ # obstacle: a small triangle between centroids
87
+ obs = tri0.translate([0.1,0.0,0.3])
88
+ obs = pvf.fc_unstruc2poly(obs)
89
+ # compute with obstruction
90
+ F_blocked = pvf.compute_viewfactor_matrix(
91
+ mesh,
92
+ obstacle=obs,
93
+ skip_visibility=True,
94
+ skip_obstruction=False,
95
+ visibility_kwargs={"strict": True},
96
+ obstruction_kwargs={"strict": True},
97
+ compute_kwargs={"epsilon":1e-6, "rounding_decimal":6},
98
+ n_jobs=1
99
+ )
100
+ # compute with skip_obstruction=True
101
+ F_no_block = pvf.compute_viewfactor_matrix(
102
+ mesh,
103
+ obstacle=obs,
104
+ skip_visibility=True,
105
+ skip_obstruction=True,
106
+ visibility_kwargs={"strict": False},
107
+ obstruction_kwargs={"strict": False},
108
+ compute_kwargs={"epsilon":1e-6, "rounding_decimal":6},
109
+ n_jobs=1
110
+ )
111
+ # now only in the first case do we zero out the blocked direction
112
+ assert F_blocked[0, 1] == pytest.approx(0.0)
113
+ assert F_no_block[0, 1] > 0.0
114
+ # tests avec plusieurs cioeurs
115
+ #tests avec un full mesh
116
+
117
+ def test_compute_matrix_against_individual_calls():
118
+ pts = np.array([
119
+ [0.0, 0.0, 0.0],
120
+ [1.0, 0.0, 0.0],
121
+ [0.0, 1.0, 0.0],
122
+ [0.0, 0.0, 1.0]
123
+ ], float)
124
+ # triangle 0: pts[0,1,2], triangle 1: pts[0,2,3]
125
+ faces = np.hstack([[3, 0, 1, 2], [3, 0, 2, 3]])
126
+ mesh = pv.PolyData(pts, faces)
127
+ mesh.triangulate(inplace=True)
128
+ from pyviewfactor import compute_viewfactor_matrix
129
+ from pyviewfactor import compute_viewfactor
130
+ from pyviewfactor import fc_unstruc2poly
131
+
132
+ F = compute_viewfactor_matrix(
133
+ mesh,
134
+ skip_visibility=True,
135
+ skip_obstruction=True,
136
+ compute_kwargs={'epsilon':1e-6, 'rounding_decimal':6},
137
+ n_jobs=1
138
+ )
139
+
140
+ # convert to PolyData
141
+ from pyviewfactor import fc_unstruc2poly
142
+ f0 = fc_unstruc2poly(mesh.extract_cells(0))
143
+ f1 = fc_unstruc2poly(mesh.extract_cells(1))
144
+ direct = compute_viewfactor(f0, f1, epsilon=1e-6, rounding_decimal=6)
145
+ assert F[0, 1] == pytest.approx(direct)
146
+
147
+
148
+ def test_compute_viewfactor_fixed_nonzero_overlap():
149
+ # Two identical triangles, coplanar but offset in x so they partially face each other
150
+ pts1 = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0],[0.0, 1.0, 0.0]], float)
151
+ # shift only in x by 0.5: they “face” each other partially
152
+ pts2 = pts1 + np.array([0.5, 0.0, 1.0])
153
+ pts2 = pts2[::-1]
154
+ constante = 4.0 * np.pi * 0.5
155
+ vf = _compute_viewfactor_fixed.py_func(pts1, pts2, constante)
156
+ # Should be positive but <1
157
+ assert vf > 0.0
158
+ assert vf < 1.0
159
+
160
+
161
+ def test_fast_integrand_zero_when_scal_pq_zero():
162
+ """
163
+ If scal_pq==0, then integrand = log(expr)*0 == 0 everywhere,
164
+ so the fixed‐order quadrature must return exactly 0.
165
+ """
166
+ # pick arbitrary positive parameters for everything else
167
+ nq = 2.3
168
+ np_ = 1.7
169
+ sqpq = -0.5
170
+ sqpp = 0.8
171
+ nqp = 10.0
172
+ val = _fast_integrand.py_func(nq, np_, sqpq, sqpp, 0.0, nqp)
173
+ assert val == pytest.approx(0.0, abs=0.0)
174
+
175
+
176
+ def test_compute_matrix_len3_visibility_cull():
177
+ # Build two triangles whose normals both point +Z
178
+ tri1 = pv.Triangle([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) # at z=0
179
+ tri2 = pv.Triangle([[0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0]]) # at z=1, same orientation
180
+
181
+ # Merge them into one mesh
182
+ mesh = tri1.merge(tri2)
183
+ mesh.triangulate(inplace=True)
184
+
185
+ # Compute with visibility culling ON (default) and no obstruction cull
186
+ F = pvf.compute_viewfactor_matrix(
187
+ mesh,
188
+ skip_visibility=False,
189
+ skip_obstruction=True,
190
+ n_jobs=1
191
+ )
192
+
193
+ # We only have 2 cells
194
+ assert F.shape == (2, 2)
195
+
196
+ # Since their normals face the same way, the centroid‐visibility test fails,
197
+ # so _compute_pair returns (i,j,0.0) -> len(res)==3 branch.
198
+ # That sets F[0,1] = 0.0, and F[1,0] is untouched (stays 0.0).
199
+ assert F[0, 1] == pytest.approx(0.0)
200
+ assert F[1, 0] == pytest.approx(0.0)
201
+
202
+ # And obviously self‐view is zero
203
+ assert F[0,0] == pytest.approx(0.0)
204
+ assert F[1,1] == pytest.approx(0.0)
@@ -3,8 +3,10 @@ import pyvista as pv
3
3
  # import pytest
4
4
  from pyviewfactor import get_visibility
5
5
  from pyviewfactor import get_obstruction
6
- # from pyviewfactor import batch_ray_obstruction
7
- # from pyviewfactor import is_ray_obstructed
6
+ from pyviewfactor import is_ray_obstructed
7
+ from pyviewfactor import batch_ray_obstruction
8
+
9
+ import numpy as np
8
10
 
9
11
  # two parallel triangles facing each other
10
12
  tri1 = pv.Triangle([[0.0, 0.0, 0.0],
@@ -23,11 +25,14 @@ triP.translate([0.0, 0.0, -0.25], inplace=True)
23
25
 
24
26
  # obstacle blocking in between
25
27
  obs = pv.Plane(i_size=2, j_size=2, i_resolution=1, j_resolution=1)
26
-
27
- obs.translate([0, 0, 0.5], inplace=True)
28
+ obs.translate([0.0, 0.0, 0.5], inplace=True)
28
29
  obs3 = obs.copy()
29
30
  obs3.translate([1.7, 0.0, 0.0], inplace=True)
30
31
 
32
+ obs_multi = pv.Plane(i_size=2, j_size=2, i_resolution=5, j_resolution=5)
33
+ obs_multi.translate([0, 0, 0.5], inplace=True)
34
+ obs_multi2 = obs_multi.copy()
35
+ obs_multi2.translate([1.7, 0.0, 0.0], inplace=True)
31
36
 
32
37
  def test_visibility_strict_true():
33
38
  vis, warn = get_visibility(tri1, tri2, strict=True)
@@ -47,6 +52,13 @@ def test_visibility_strict_false():
47
52
  assert not vis and warn == ""
48
53
 
49
54
 
55
+ def test_visibility_strict_false_warn():
56
+ # flip tri2 so normals face away
57
+ tri3 = tri2.copy()
58
+ tri3.flip_faces(inplace=True)
59
+ vis, warn = get_visibility(tri1, tri3, strict=False, print_warning=True)
60
+ assert not vis and warn == ""
61
+
50
62
  def test_visibility_not_strict_false():
51
63
  # flip tri2 so normals face away
52
64
  tri3 = tri2.copy()
@@ -59,12 +71,18 @@ def test_visibility_partial_strict_true():
59
71
  vis, warn = get_visibility(tri1, triP, strict=True)
60
72
  assert not vis and "[PVF-Warning-1]" in warn
61
73
 
74
+ def test_visibility_partial_strict_true_debug():
75
+ vis, warn = get_visibility(tri1, triP, strict=True, print_warning=True)
76
+ assert not vis and "[PVF-Warning-1]" in warn
62
77
 
63
78
  def test_visibility_partial_strict_false():
64
79
  vis, warn = get_visibility(tri1, triP, strict=False)
65
80
  assert vis and "[PVF-Warning-2]" in warn
66
81
 
67
-
82
+ def test_visibility_partial_strict_false_debug():
83
+ vis, warn = get_visibility(tri1, triP, strict=False, print_warning=True)
84
+ assert vis and "[PVF-Warning-2]" in warn
85
+
68
86
  def test_obstruction_strict_true():
69
87
  # obstacle sits between tri1 and tri2
70
88
  vis, warn = get_obstruction(tri1, tri2, obs, strict=True)
@@ -85,3 +103,36 @@ def test_partial_obstruction_strict_false():
85
103
  def test_partial_obstruction_strict_true():
86
104
  vis, warn = get_obstruction(tri1, tri2, obs3, strict=True)
87
105
  assert not vis and "[PVF-Warning-4]" in warn
106
+
107
+
108
+
109
+
110
+ def test_obstruction_multi_strict_true():
111
+ # obstacle sits between tri1 and tri2
112
+ vis, warn = get_obstruction(tri1, tri2, obs_multi, strict=True)
113
+ assert not vis and warn == ""
114
+
115
+
116
+ def test_obstruction_multi_strict_false():
117
+ # obstacle sits between tri1 and tri2
118
+ vis, warn = get_obstruction(tri1, tri2, obs_multi, strict=False)
119
+ assert not vis and warn == ""
120
+
121
+
122
+ def test_partial_multi_obstruction_strict_false():
123
+ vis, warn = get_obstruction(tri1, tri2, obs_multi2, strict=False)
124
+ assert vis and warn == ""
125
+
126
+
127
+ def test_partial_multi_obstruction_strict_true():
128
+ vis, warn = get_obstruction(tri1, tri2, obs_multi2, strict=True)
129
+ assert not vis and "[PVF-Warning-4]" in warn
130
+
131
+
132
+ def test_batch_ray_obstruction_hits_and_misses():
133
+ tri_arr = np.array([[[0,0,0],[1,0,0],[0,1,0]]], dtype=np.float64)
134
+ # one ray misses, one hits
135
+ starts = np.array([[2,2,1.0],[0.2,0.2,1.0]], dtype=np.float64)
136
+ ends = np.array([[2,2,-1.0],[0.2,0.2,-1.0]], dtype=np.float64)
137
+ mask = batch_ray_obstruction.py_func(starts, ends, tri_arr)
138
+ assert mask.tolist() == [True, False]
@@ -1,25 +0,0 @@
1
- """ PVF tests utility functions"""
2
-
3
- import numpy as np
4
- import pyvista as pv
5
- import pytest
6
- from pyviewfactor import trunc, fc_unstruc2poly
7
-
8
-
9
- def test_trunc_scalar():
10
- assert trunc(1.234567, 2) == pytest.approx(1.23)
11
-
12
-
13
- def test_trunc_array():
14
- arr = np.array([1.2345, 2.3456])
15
- out = trunc(arr, 3)
16
- assert np.allclose(out, [1.234, 2.345])
17
-
18
-
19
- def test_fc_unstruc2poly_roundtrip():
20
- sphere = pv.Sphere(radius=0.5)
21
- ug = sphere.cast_to_unstructured_grid()
22
- poly = fc_unstruc2poly(ug)
23
- # Should be PolyData with same number of cells
24
- assert isinstance(poly, pv.PolyData)
25
- assert poly.n_cells == ug.n_cells
@@ -1,46 +0,0 @@
1
- # import numpy as np
2
- import pyvista as pv
3
- import pytest
4
- from pyviewfactor import compute_viewfactor
5
-
6
- # two identical parallel unit squares 1 unit apart → known VF = 1/(π)
7
- pointa = [1.0, 0.0, 0.0]
8
- pointb = [1.0, 1.0, 0.0]
9
- pointc = [0.0, 1.0, 0.0]
10
- rectangle1 = pv.Rectangle([pointa, pointb, pointc])
11
-
12
- pointa = [1.0, 0.0, 1.0]
13
- pointb = [1.0, 1.0, 1.0]
14
- pointc = [0.0, 1.0, 1.0]
15
- rectangle2 = pv.Rectangle([pointc, pointb, pointa])
16
-
17
-
18
- def test_compute_viewfactor_basic():
19
- vf = compute_viewfactor(rectangle2, rectangle1)
20
- assert vf == pytest.approx(0.199824, rel=1e-5)
21
-
22
-
23
- # Ajouter tests pour quand 2 carrés perpendicualires se touchent
24
- # FF = 0.1493 (à confirmer)
25
-
26
-
27
- # two identical parallel unit squares 1 unit apart → known VF = 1/(π)
28
-
29
- # sq1 = pv.Plane(i_size=1, j_size=1, i_resolution=1, j_resolution=1)
30
- # sq2 = sq1.copy()
31
- # sq2.translate([0,0,1], inplace=True)
32
-
33
-
34
- # def test_reciprocity_property():
35
- # F = compute_viewfactor_matrix(pv.MultiBlock([sq1, sq2]), n_jobs=1)
36
- # A1 = sq1.compute_cell_sizes(area=True)['Area'][0]
37
- # A2 = A1
38
- # F12 * A1 ≈ F21 * A2
39
- # assert (F[0,1]*A1) == pytest.approx(F[1,0]*A2)
40
-
41
-
42
- # def test_matrix_size():
43
- # mesh = pv.Sphere(theta_resolution=8, phi_resolution=8).triangulate()
44
- # F = compute_viewfactor_matrix(mesh, n_jobs=1)
45
- # assert F.shape == (mesh.n_cells, mesh.n_cells)
46
- # assert np.all(F >= 0) and np.all(F <= 1)
File without changes
File without changes
File without changes
File without changes