Coverage for hml/findFractionOfPixelWithinCircle.py: 86%

14 statements  

« prev     ^ index     » next       coverage.py v7.8.1, created at 2025-05-23 08:31 +0000

1#!/usr/bin/env python3 

2 

3# Define function ... 

4def findFractionOfPixelWithinCircle(xmin, xmax, ymin, ymax, r, /, *, cx = 0.0, cy = 0.0, ndiv = 16): 

5 """ 

6 Find the fraction of a pixel that is within a hard circular mask. 

7 

8 Arguments: 

9 xmin -- left edge 

10 xmax -- right edge 

11 ymin -- lower edge 

12 ymax -- upper edge 

13 r -- radius of circle 

14 

15 Keyword arguments: 

16 cx -- x position of centre of circle (default 0.0) 

17 cy -- y position of centre of circle (default 0.0) 

18 ndiv -- number sub-divisions (default 16) 

19 

20 Note: 

21 This function is crying out for FORTRAN+OpenMP. 

22 """ 

23 

24 # Import special modules ... 

25 try: 

26 import numpy 

27 except: 

28 raise Exception("\"numpy\" is not installed; run \"pip install --user numpy\"") from None 

29 

30 # Create nodes relative to the centre of the circle ... 

31 xaxis = numpy.linspace(xmin, xmax, num = ndiv + 1) - cx 

32 yaxis = numpy.linspace(ymin, ymax, num = ndiv + 1) - cy 

33 

34 # Convert the nodes to centroids ... 

35 # NOTE: https://stackoverflow.com/a/23856065 

36 xaxis = 0.5 * (xaxis[1:] + xaxis[:-1]) 

37 yaxis = 0.5 * (yaxis[1:] + yaxis[:-1]) 

38 

39 # Find out the distance of each centroid to the centre of the circle ... 

40 dist = numpy.zeros((ndiv, ndiv), dtype = numpy.float64) 

41 for ix in range(ndiv): 

42 for iy in range(ndiv): 

43 dist[iy, ix] = numpy.hypot(xaxis[ix], yaxis[iy]) 

44 

45 # Return answer ... 

46 return float((dist <= r).sum()) / float(ndiv * ndiv)