OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
value_locate.py
Go to the documentation of this file.
1 '''
2 Created on Feb 9, 2016
3 
4 @author: rhealy
5 retrieved from https://github.com/marcelhaas/python/blob/master/value_locate.py
6 
7 '''
8 import numpy as np
9 
10 
11 def value_locate(refx, x):
12  """
13  VALUE_LOCATE locates the positions of given values within a
14  reference array. The reference array need not be regularly
15  spaced. This is useful for various searching, sorting and
16  interpolation algorithms.
17  The reference array should be a monotonically increasing or
18  decreasing list of values which partition the real numbers. A
19  reference array of NBINS numbers partitions the real number line
20  into NBINS+1 regions, like so:
21  REF: X[0] X[1] X[2] X[3] X[NBINS-1]
22  <----------|-------------|------|---|----...---|--------------->
23  INDICES: -1 0 1 2 3 NBINS-1
24  VALUE_LOCATE returns which partition each of the VALUES falls
25  into, according to the figure above. For example, a value between
26  X[1] and X[2] would return a value of 1. Values below X[0] return
27  -1, and above X[NBINS-1] return NBINS-1. Thus, besides the value
28  of -1, the returned INDICES refer to the nearest reference value
29  to the left of the requested value.
30 
31  Example:
32  >>> refx = [2, 4, 6, 8, 10]
33  >>> x = [-1, 1, 2, 3, 5, 5, 5, 8, 12, 30]
34  >>> print value_locate(refx, x)
35  array([-1, -1, 0, 0, 1, 1, 1, 3, 4, 4])
36 
37 
38  This implementation is likely no the most efficient one, as there is
39  a loop over all x, which will in practice be long. As long as x is
40  shorter than 1e6 or so elements, it should still be fast (~sec).
41 
42 
43  """
44  print ("TODO: check if refx is monotonically increasing.")
45 
46  refx = np.array(refx)
47  x = np.array(x)
48  loc = np.zeros(len(x), dtype='int')
49 
50  for i in range(len(x)):
51  ix = x[i]
52  ind = ((refx - ix) <= 0).nonzero()[0]
53  if len(ind) == 0:
54  loc[i] = -1
55  else: loc[i] = ind[-1]
56 
57  return loc
58 
59 
60 
61 if __name__ =="__main__":
62  # test case
63  refx = [2, 4, 6, 8, 10]
64  x = [-1, 1, 2, 3, 5, 5, 5, 8, 12, 30]
65 
66  res = value_locate(refx, x)
67  assert list(res) == [-1, -1, 0, 0, 1, 1, 1, 3, 4, 4]
68  print ("Test(s) passed!")
69 
70  x= np.random.random(1e6)*20
71  res = value_locate(refx, x)
72  print ("Done!")
def value_locate(refx, x)
Definition: value_locate.py:11
list(APPEND LIBS ${PGSTK_LIBRARIES}) add_executable(atteph_info_modis atteph_info_modis.c) target_link_libraries(atteph_info_modis $
Definition: CMakeLists.txt:7