-
Notifications
You must be signed in to change notification settings - Fork 19
/
query.py
2810 lines (2104 loc) · 76.5 KB
/
query.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
from copy import deepcopy
from operator import __and__ as operator_and
from operator import __or__ as operator_or
import numpy as np
from cfdm import is_log_level_info
from .data import Data
from .decorators import (
_deprecated_kwarg_check,
_display_or_return,
_manage_log_level_via_verbosity,
)
from .functions import (
_DEPRECATION_ERROR_ATTRIBUTE,
_DEPRECATION_ERROR_FUNCTION,
_DEPRECATION_ERROR_FUNCTION_KWARGS,
)
from .functions import atol as cf_atol
from .functions import equals as cf_equals
from .functions import inspect as cf_inspect
from .functions import rtol as cf_rtol
from .units import Units
logger = logging.getLogger(__name__)
# Alias for builtin set, since there is a 'set' function
builtin_set = set
class Query:
"""Encapsulate a condition for subsequent evaluation.
A condition that may be applied to any object may be stored in a
`Query` object. A `Query` object encapsulates a condition, such as
"strictly less than 3". When applied to an object, via its
`evaluate` method or the Python `==` operator, the condition is
evaluated in the context of that object.
>>> c = cf.Query('lt', 3)
>>> c
<CF Query: (lt 3)>
>>> c.evaluate(2)
True
>>> c == 2
True
>>> c != 2
False
>>> c.evaluate(3)
False
>>> c == cf.Data([1, 2, 3])
<CF Data(3): [True, True, False]>
>>> c == numpy.array([1, 2, 3])
array([True, True, False])
The following operators are supported when constructing `Query`
instances:
============= ===================================
Operator Description
============= ===================================
``'lt'`` A "strictly less than" condition
``'le'`` A "less than or equal" condition
``'gt'`` A "strictly greater than" condition
``'ge'`` A "greater than or equal" condition
``'eq'`` An "equal" condition
``'ne'`` A "not equal" condition
``'wi'`` A "within a range" condition
``'wo'`` A "without a range" condition
``'set'`` A "member of set" condition
``'isclose'`` An "is close" condition
============= ===================================
**Compound queries**
Multiple conditions may be combined with the Python bitwise "and"
(`&`) and "or" (`|`) operators to form a new `Query` object.
>>> ge3 = cf.Query('ge', 3)
>>> lt5 = cf.Query('lt', 5)
>>> c = ge3 & lt5
>>> c
<CF Query: [(ge 3) & (lt 5)]>
>>> c == 2
False
>>> c != 2
True
>>> c = ge3 | lt5
>>> c
<CF Query: [(ge 3) | (lt 5)]>
>>> c == 2
True
>>> c &= cf.Query('set', [1, 3, 5])
>>> c
<CF Query: [[(ge 3) | (lt 5)] & (set [1, 3, 5])]>
>>> c == 2
False
>>> c == 3
True
A condition can be applied to an attribute of an object.
>>> upper_bounds_ge_minus4 = cf.Query('ge', -4, attr='upper_bounds')
>>> x
<CF DimensionCoordinate: grid_longitude(9) degrees>
>>> print(x.bounds.array)
[[-4.92 -4.48]
[-4.48 -4.04]
[-4.04 -3.6 ]
[-3.6 -3.16]
[-3.16 -2.72]
[-2.72 -2.28]
[-2.28 -1.84]
[-1.84 -1.4 ]
[-1.4 -0.96]]
>>> print((upper_bounds_ge_minus4 == x).array)
[False False True True True True True True True]
>>> upper_bounds_ge_minus4 = cf.Query('ge', -4, attr='upper_bounds')
A condition can also be applied to attributes of attributes of an
object.
>>> t
<CF DimensionCoordinate: time(4) >
>>> t.lower_bounds.month.array
array([12, 3, 6, 9])
>>> c = cf.Query('ge', 8, attr='lower_bounds.month')
>>> c == t
<CF Data(4): [True, ..., True]>
>>> (c == t).array
array([ True, False, False, True])
**The query interface**
In general, the query operator must be permitted between the value
of the condition and the operand for which it is being
evaluated. For example, when the value is an `int`, the query
works if the operand is also an `int`, but fails if it is a
`list`:
>>> c = cf.Query('lt', 2)
>>> c == 1
True
>>> c == [1, 2, 3]
TypeError: '<' not supported between instances of 'list' and 'int'
This behaviour is overridden if the operand has an appropriate
"query interface" method. When such a method exists, it is used
instead of the equivalent built-in Python operator.
====================== ==============================================
Query interface method Description
====================== ==============================================
`__query_lt__` Called when a ``'lt'`` condition is evaluated
`__query_le__` Called when a ``'le'`` condition is evaluated
`__query_gt__` Called when a ``'gt'`` condition is evaluated
`__query_ge__` Called when a ``'ge'`` condition is evaluated
`__query_eq__` Called when an ``'eq'`` condition is evaluated
`__query_ne__` Called when a ``'ne'`` condition is evaluated
`__query_wi__` Called when a ``'wi'`` condition is evaluated
`__query_wo__` Called when a ``'wo'`` condition is evaluated
`__query_set__` Called when a ``'set'`` condition is evaluated
`__query_isclose__` Called when an ``'isclose'`` condition is
evaluated.
====================== ==============================================
In general, each method must have the query value as it's only
parameter. The only exception is for `__query_isclose__`, which
also requires the absolute and relative numerical tolerances to be
provided.
When the condition is on an attribute, or nested attributes, of
the operand, the query interface method is looked for on the
attribute object, rather than the parent object.
If the value has units then the argument passed to query interface
method is automatically a `Data` object that attaches the units to
the value.
For example:
>>> class myList(list):
... pass
...
>>> class myList_with_interface(list):
... def __query_lt__(self, value):
... return type(self)([x < value for x in self])
...
>>> c == myList([1, 2, 3])
TypeError: '<' not supported between instances of 'myList' and 'int'
>>> c == myList_with_interface([1, 2, 3])
[True, False, False]
"""
isquery = True
@_deprecated_kwarg_check("exact", version="3.0.0", removed_at="4.0.0")
def __init__(
self,
operator,
value,
units=None,
attr=None,
exact=True,
rtol=None,
atol=None,
open_lower=False,
open_upper=False,
):
"""**Initialisation**
:Parameters:
operator: `str`
The query operator.
value:
The value of the condition.
units: `str` or `Units`, optional
The units of *value*. By default, the same units as
the operand being tested are assumed, if
applicable. If *units* is specified and *value*
already has units (such as those attached to a `Data`
object), then the pair of units must be equivalent.
attr: `str`, optional
Apply the condition to the attribute, or nested
attributes, of the operand, rather than the operand
itself. Nested attributes are specified by separating
them with a ``.``. For example, the "month" attribute
of the "bounds" attribute is specified as
``'bounds.month'``. See also the `addattr` method.
rtol: number, optional
Only applicable to the ``'isclose'`` operator. The
tolerance on relative numerical differences. If
`None`, the default, then the value returned by
`cf.rtol` is used at evaluation time.
.. versionadded:: 3.15.2
atol: number, optional
Only applicable to the ``'isclose'`` operator. The
tolerance on absolute numerical differences. If
`None`, the default, then the value returned by
`cf.atol` is used at evaluation time.
.. versionadded:: 3.15.2
open_lower: `bool`, optional
Only applicable to the ``'wi'`` operator.
If True, open the interval at the lower
bound so that value0 is excluded from the
range. By default the interval is closed
so that value0 is included.
.. versionadded:: NEXTVERSION
open_upper: `bool`, optional
Only applicable to the ``'wi'`` operator.
If True, open the interval at the upper
bound so that value1 is excluded from the
range. By default the interval is closed
so that value1 is included.
.. versionadded:: NEXTVERSION
exact: deprecated at version 3.0.0.
Use `re.compile` objects in *value* instead.
"""
if units is not None:
value_units = getattr(value, "Units", None)
if value_units is None:
value = Data(value, units)
elif not value_units.equivalent(Units(units)):
raise ValueError(
f"'{value_units}' and '{Units(units)}' are not "
f"equivalent units therefore the query does not make "
"physical sense."
)
self._operator = operator
self._value = value
self._compound = False
if attr:
self._attr = tuple(attr.split("."))
else:
self._attr = ()
self._bitwise_operator = None
self.query_type = operator
self._NotImplemented_RHS_Data_op = True
if rtol is not None or atol is not None:
if operator != "isclose":
raise ValueError(
"Can only set the 'rtol' and 'atol' parameters "
"for the 'isclose' operator"
)
self._rtol = rtol
self._atol = atol
if open_lower or open_upper:
if operator != "wi":
raise ValueError(
"Can only set the 'open_lower' and 'open_upper' "
"parameters for the 'wi' operator"
)
self._open_lower = open_lower
self._open_upper = open_upper
def __dask_tokenize__(self):
"""Return a hashable value fully representative of the object.
.. versionadded:: 3.15.2
"""
compound = self._compound
if compound:
return (
compound[0].__dask_tokenize__(),
self._bitwise_operator,
compound[1].__dask_tokenize__(),
)
value = self._value
if isinstance(value, Data):
value = (
value.tolist(),
value.Units.formatted(definition=True),
)
else:
value = (value,)
operator = self._operator
if operator == "isclose":
value += (self.rtol, self.atol)
if operator == "wi":
value += (self.open_lower, self.open_upper)
return (self.__class__, operator, self._attr) + value
def __deepcopy__(self, memo):
"""Used if copy.deepcopy is called on the variable."""
return self.copy()
def __eq__(self, x):
"""The rich comparison operator ``==``
x.__eq__(y) <==> x==y
x.__eq__(y) <==> x.evaluate(y)
"""
return self._evaluate(x, ())
def __ne__(self, x):
"""The rich comparison operator ``!=``
x.__ne__(y) <==> x!=y
x.__ne__(y) <==> (x==y)==False
"""
# Note that it is important to use the == operator
return self._evaluate(x, ()) == False # ignore PEP8 E712 due to above
def __and__(self, other):
"""The binary bitwise operation ``&``
Combine two queries with a logical And operation. If the
`!value` of both queries is the same then it will be retained
on the compound query.
x.__and__(y) <==> x&y
"""
Q = type(self)
new = Q.__new__(Q)
new._operator = None
new._compound = (self.copy(), other.copy())
new._bitwise_operator = operator_and
new._attr = ()
# If the value of the two queries is the same then retain it
# on the compound query
value0 = self._value
value1 = other._value
new_value = None
if value0 is not None and value1 is not None:
try:
if (value0 == value1).all():
new_value = deepcopy(value0)
except AttributeError:
if value0 == value1:
new_value = deepcopy(value0)
except ValueError:
pass
new._value = new_value
new._NotImplemented_RHS_Data_op = True
return new
def __iand__(self, other):
"""The augmented bitwise assignment ``&=``
x.__iand__(y) <==> x&=y
"""
return self & other
def __or__(self, other):
"""The binary bitwise operation ``|``
Combine two queries with a logical Or operation. If the
`!value` of both queries is the same then it will be retained
on the compound query.
x.__or__(y) <==> x|y
"""
Q = type(self)
new = Q.__new__(Q)
new._operator = None
new._compound = (self, other)
new._bitwise_operator = operator_or
new._attr = ()
# If the value of the two queries is the same then retain it
# on the compound query
value0 = self._value
value1 = other._value
new_value = None
if value0 is not None and value1 is not None:
try:
if (value0 == value1).all():
new_value = deepcopy(value0)
except AttributeError:
if value0 == value1:
new_value = deepcopy(value0)
except ValueError:
pass
new._value = new_value
new._NotImplemented_RHS_Data_op = True
return new
def __ior__(self, other):
"""The augmented bitwise assignment ``|=``
x.__ior__(y) <==> x|=y
"""
return self | other
def __repr__(self):
"""Called by the `repr` built-in function.
x.__repr__() <==> repr(x)
"""
return f"<CF {self.__class__.__name__}: {self}>"
def __str__(self):
"""Called by the `str` built-in function.
x.__str__() <==> str(x)
"""
attr = ".".join(self._attr)
operator = self._operator
compound = self._compound
# For "wi" queries only, open intervals are supported. For "wi" _value
# is a list of two values, with representation from string list form
# of '[a, b]' which corresponds to the standard mathematical notation
# for a closed interval, the default. But an open endpoint is indicated
# by a parenthesis, so adjust repr. to convert square bracket(s).
repr_value = str(self._value)
if self.open_lower:
repr_value = "(" + repr_value[1:]
if self.open_upper:
repr_value = repr_value[:-1] + ")"
if not compound:
out = f"{attr}({operator} {repr_value}"
rtol = self.rtol
if rtol is not None:
out += f" rtol={rtol}"
atol = self.atol
if atol is not None:
out += f" atol={atol}"
out += ")"
return out
bitwise_operator = repr(self._bitwise_operator)
if "and_" in bitwise_operator:
bitwise_operator = "&"
elif "or_" in bitwise_operator:
bitwise_operator = "|"
return f"{attr}[{compound[0]} {bitwise_operator} {compound[1]}]"
@property
def atol(self):
"""The tolerance on absolute numerical differences.
Returns the tolerance on absolute numerical differences that
is used when evaluating numerically tolerant conditions
(i.e. those defined by the ``'isclose'`` operator). If `None`
then the value returned by `cf.atol` is used instead.
For compound queries `atol` is always `None`, even if some of
the constituent conditions have a different value.
.. versionadded:: 3.15.2
.. seealso:: `rtol`, `setdefault`
"""
return getattr(self, "_atol", None)
@property
def attr(self):
"""The object attribute on which to apply the query condition.
For compound queries `attr` is always ``()``, even if some of
the constituent conditions have a different value.
.. seealso:: `addattr`
**Examples**
>>> q = cf.Query('ge', 4)
>>> print(q.attr)
()
>>> r = cf.Query('le', 6, attr='year')
>>> r.attr
('year',)
>>> (q | r).attr
()
"""
return self._attr
@property
def operator(self):
"""The query operator.
For compound queries `operator` is always ``None``, regardless
of the operators of the constituent conditions.
**Examples**
>>> q = cf.Query('ge', 4)
>>> q.operator
'ge'
>>> q |= cf.Query('le', 6)
>>> print(q.operator)
None
"""
return self._operator
@property
def Units(self):
"""Return the units of the query.
.. versionadded:: 3.15.2
:Returns:
`Units`
The units of the query value.
**Examples**
>>> cf.eq(9).Units
<Units: >
>>> cf.eq(9, 'm s-1').Units
<Units: m s-1>
>>> cf.eq(cf.Data(9, 'km')).Units
<Units: km>
>>> (cf.eq(9) | cf.gt(10)).Units
<Units: >
>>> (cf.eq(9, 'm') | cf.gt(10, 'm')).Units
<Units: >
>>> (cf.eq(9, 'm') | cf.gt(9, 'm')).Units
<Units: m>
>>> (cf.eq(9, 'm') | cf.gt(45)).Units
<Units: m>
>>> (cf.eq(9, 'm') | cf.gt(9, 'day')).Units
AttributeError: <CF Query: [(eq 9 m) | (gt 9 day)]> has indeterminate units
"""
value = self._value
if value is not None:
try:
return value.Units
except AttributeError:
return Units()
compound = self._compound
if compound:
# Still here? Then we have compund units with no common
# value, so see if the units of each embedded query are
# equivalent.
q0, q1 = compound
units0 = getattr(q0, "Units", Units())
units1 = getattr(q1, "Units", Units())
if not units0:
if not units1:
return Units()
return units1
if not units1:
return units0
if units0.equivalent(units1):
return units0
raise AttributeError(f"{self!r} has indeterminate units")
@property
def open_lower(self):
"""True if the interval is open at the (excludes the) lower bound.
.. versionadded:: NEXTVERSION
.. seealso:: `open_upper`
"""
return getattr(self, "_open_lower", False)
@property
def open_upper(self):
"""True if the interval is open at the (excludes the) upper bound.
.. versionadded:: NEXTVERSION
.. seealso:: `open_lower`
"""
return getattr(self, "_open_upper", False)
@property
def rtol(self):
"""The tolerance on relative numerical differences.
Returns the tolerance on relative numerical differences that
is used when evaluating numerically tolerant conditions
(i.e. those defined by the ``'isclose'`` operator). If `None`
then the value returned by `cf.rtol` is used instead.
For compound queries `rtol` is always `None`, even if some of
the constituent conditions have a different value.
.. versionadded:: 3.15.2
.. seealso:: `atol`, `setdefault`
"""
return getattr(self, "_rtol", None)
@Units.setter
def Units(self, value):
self.set_condition_units(value)
@property
def value(self):
"""The value of the condition encapsulated by the query.
An exception is raised for compound conditions.
**Examples**
>>> q = cf.Query('ge', 4)
>>> q.value
4
>>> q |= cf.Query('le', 6)
>>> q.value
AttributeError: Compound query doesn't have attribute 'value'
"""
value = self._value
if value is None:
raise AttributeError(
"Compound query doesn't have attribute 'value'"
)
return value
def addattr(self, attr):
"""Redefine the query to be on an object's attribute.
If another attribute has previously been specified, then the new
attribute is considered to be an attribute of the existing
attribute.
.. seealso:: `attr`
:Parameters:
attr: `str`
The attribute name.
:Returns:
`Query`
The new query object.
**Examples**
>>> q = cf.eq(2001)
>>> q
<CF Query: (eq 2001)>
>>> q = q.addattr('year')
>>> q
<CF Query: year(eq 2001)>
>>> q = cf.lt(2)
>>> q = q.addattr('A')
>>> q = q.addattr('B')
>>> q
<CF Query: A.B(lt 2)>
>>> q = q.addattr('C')
>>> q
<CF Query: A.B.C(lt 2)>
"""
Q = type(self)
new = Q.__new__(Q)
new.__dict__ = self.__dict__.copy()
new._attr += (attr,)
new._NotImplemented_RHS_Data_op = True
return new
def copy(self):
"""Return a deep copy.
``q.copy()`` is equivalent to ``copy.deepcopy(q)``.
:Returns:
The deep copy.
**Examples**
>>> r = q.copy()
"""
Q = type(self)
new = Q.__new__(Q)
d = self.__dict__.copy()
new.__dict__ = d
compound = d["_compound"]
if compound:
d["_compound"] = deepcopy(compound)
else:
d["_value"] = deepcopy(d["_value"])
return new
@_display_or_return
def dump(self, display=True):
"""Return a string containing a full description of the
instance.
:Parameters:
display: `bool`, optional
If `False` then return the description as a string. By
default the description is printed.
:Returns:
`None` or `str`
The description. If *display* is True then the description
is printed and `None` is returned. Otherwise the
description is returned as a string.
"""
return str(self)
@_deprecated_kwarg_check("traceback", version="3.0.0", removed_at="4.0.0")
@_manage_log_level_via_verbosity
def equals(self, other, verbose=None, traceback=False):
"""True if two `Query` objects are the same."""
if self._compound:
if not other._compound:
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different compound components"
) # pragma: no cover
return False
if self._bitwise_operator != other._bitwise_operator:
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different compound "
f"operators: {self._bitwise_operator!r}, "
f"{other._bitwise_operator!r}"
) # pragma: no cover
return False
if not self._compound[0].equals(other._compound[0]):
if not self._compound[0].equals(other._compound[1]):
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different compound components"
) # pragma: no cover
return False
if not self._compound[1].equals(other._compound[0]):
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different compound components"
) # pragma: no cover
return False
elif not self._compound[1].equals(other._compound[1]):
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different compound components"
) # pragma: no cover
return False
elif other._compound:
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different compound components"
) # pragma: no cover
return False
for attr in (
"_NotImplemented_RHS_Data_op",
"_attr",
"_value",
"_operator",
"_rtol",
"_atol",
"_open_lower",
"_open_upper",
):
x = getattr(self, attr, None)
y = getattr(other, attr, None)
if not cf_equals(x, y, verbose=verbose):
if is_log_level_info(logger):
logger.info(
f"{self.__class__.__name__}: Different {attr!r} "
f"attributes: {x!r}, {y!r}"
) # pragma: no cover
return False
return True
def evaluate(self, x):
"""Evaluate the query operation for a given left hand side
operand.
Note that for the query object ``q`` and any object, ``x``,
``x==q`` is equivalent to ``q.evaluate(x)`` and ``x!=q`` is
equivalent to ``q.evaluate(x)==False``.
:Parameters:
x:
The object for the left hand side operand of the query.
:Returns:
The result of the query. The nature of the result is
dependent on the object type of *x*.
**Examples**
>>> q = cf.Query('lt', 5.5)
>>> q.evaluate(6)
False
>>> q = cf.Query('wi', (1,2))
>>> array = numpy.arange(4)
>>> array
array([0, 1, 2, 3])
>>> q.evaluate(array)
array([False, True, True, False], dtype=bool)
"""
return self._evaluate(x, ())
def _evaluate(self, x, parent_attr):
"""Evaluate the query operation for a given object.
.. seealso:: `evaluate`
:Parameters:
x:
See `evaluate`.
parent_attr: `tuple`
:Returns:
See `evaluate`.
"""
compound = self._compound
attr = parent_attr + self._attr
# ------------------------------------------------------------
# Evaluate a compound condition
# ------------------------------------------------------------
if compound:
c = compound[0]._evaluate(x, attr)
d = compound[1]._evaluate(x, attr)
return self._bitwise_operator(c, d)
# ------------------------------------------------------------
# Still here? Then evaluate a simple (non-compoundnd)
# condition.
# ------------------------------------------------------------
for a in attr:
x = getattr(x, a)
operator = self._operator
value = self._value
# TODO: Once Python 3.9 is no longer supported, this is a good
# candidate for PEP 622 – Structural Pattern Matching
# (https://peps.python.org/pep-0622)
if operator == "gt":
_gt = getattr(x, "__query_gt__", None)
if _gt is not None:
return _gt(value)
return x > value
if operator == "wi":
_wi = getattr(x, "__query_wi__", None)
if _wi is not None:
return _wi(value)
if self.open_lower:
lower_bound = x > value[0]
else:
lower_bound = x >= value[0]
if self.open_upper:
upper_bound = x < value[1]
else:
upper_bound = x <= value[1]
return lower_bound & upper_bound
if operator == "eq":
try:
return bool(value.search(x))
except AttributeError:
return x == value
except TypeError:
raise ValueError(
"Can't perform regular expression search on a "
f"non-string: {x!r}"
)