1 | """ |
---|

2 | operations.py |
---|

3 | ============= |
---|

4 | |
---|

5 | Holds the Operations class used to decide and undertake various mathematical |
---|

6 | operations involving two variables. |
---|

7 | |
---|

8 | """ |
---|

9 | |
---|

10 | # Import library modules |
---|

11 | import os |
---|

12 | import sys |
---|

13 | |
---|

14 | # Import external modules |
---|

15 | import cdms |
---|

16 | |
---|

17 | # Import package modules |
---|

18 | from config import * |
---|

19 | |
---|

20 | class Operations: |
---|

21 | """ |
---|

22 | Class to decide which type of operation should be performed and then to |
---|

23 | undertake the operation. |
---|

24 | """ |
---|

25 | |
---|

26 | def __init__(self, opstring, variables): |
---|

27 | """ |
---|

28 | Method to take in the operation string and map it to an operation using |
---|

29 | variables provided. |
---|

30 | """ |
---|

31 | self.variables=variables |
---|

32 | self.outputVariables=[] |
---|

33 | |
---|

34 | if len(self.variables)==1: |
---|

35 | raise "Cannot perform operations on only one variable" |
---|

36 | elif len(self.variables)>2: |
---|

37 | raise "Cannot yet perform operations on more than two variables" |
---|

38 | |
---|

39 | self.operation=self._chooseOperation(opstring) |
---|

40 | |
---|

41 | |
---|

42 | def _chooseOperation(self, opstring): |
---|

43 | """ |
---|

44 | Method to map operation string to a known method. |
---|

45 | """ |
---|

46 | if opstring=="var1 - var2": |
---|

47 | method=self.v1minusv2 |
---|

48 | elif opstring=="var2 - var1": |
---|

49 | method=self.v2minusv1 |
---|

50 | elif opstring=="var1 + var2": |
---|

51 | method=self.v1addv2 |
---|

52 | elif opstring=="var1 * var2": |
---|

53 | method=self.v1timesv2 |
---|

54 | elif opstring=="var1 / var2": |
---|

55 | method=self.v1dividedbyv2 |
---|

56 | elif opstring=="var2 / var1": |
---|

57 | method=self.v2dividedbyv1 |
---|

58 | elif opstring=="((var1**2) + (var2**2))**0.5": |
---|

59 | method=self.magv1v2 |
---|

60 | elif opstring=="var1, var2 (as they come)": |
---|

61 | method=self.v1andv2 |
---|

62 | return method |
---|

63 | |
---|

64 | |
---|

65 | def processOperation(self): |
---|

66 | """ |
---|

67 | Method to actually process the operation chosen in _chooseOperation. |
---|

68 | """ |
---|

69 | vars=self.operation() |
---|

70 | return vars |
---|

71 | |
---|

72 | |
---|

73 | def v1minusv2(self): |
---|

74 | """ |
---|

75 | Method to subtract var2 from var1. |
---|

76 | """ |
---|

77 | return (self.variables[0]-self.variables[1]) |
---|