def test_positive_1(self): d = np.positive([-1, -0, 1]) print(d) e = np.positive([[1, 0, -1], [-2, 3, -4]]) print(e)
def test_RsRCRC(self): response = circuits.cir_RsRCRC(f_range[1], Rs=Resistance, Rp1=Parallel_Resistance, C1=Capacitance, Rp2=Parallel_Resistance, C2=Capacitance) assert np.positive(Resistance), \ 'The input resistance is invalid' assert np.positive(Parallel_Resistance), \ 'The input resistance is invalid' assert np.positive(Capacitance), \ 'The input capacitance is invalid' assert len(response) == len(f_range[1]), \ 'The returned response is not valid' for item in response: assert isinstance(item, complex), \ 'The returned response includes invalid impedance' real_Z = item.real imag_Z = item.imag total_Z = np.sqrt((real_Z**2) + (imag_Z**2)) assert total_Z > Resistance,\ 'The Impedance value returned is lower than the' +\ 'Solution Resistance'
def test_randles(self): response = circuits.cir_Randles_simplified(f_range[1], Rs=Resistance, Rp=Parallel_Resistance, alpha=alpha, sigma=sigma, Q=Constant_phase_element) assert np.positive(Resistance), \ 'The input resistance is invalid' assert np.positive(Parallel_Resistance), \ 'The input resistance is invalid' assert alpha > 0 or alpha <= 1, \ 'The values of alpha is nonpositive' assert np.positive(Constant_phase_element), \ 'The input constant phase element is non-positive' assert np.positive(sigma), 'The input coefficient is non-positive' assert len(response) == len(f_range[1]),\ 'The returned response is not valid' for item in response: assert isinstance(item, complex), \ 'The returned response includes invalid impedance' real_Z = item.real imag_Z = item.imag total_Z = np.sqrt((real_Z**2) + (imag_Z**2)) assert total_Z > Resistance, \ 'The Impedance value returned is lower than the' +\ 'Solution Resistance'
def test_RsRQRQ(self): response = circuits.cir_RsRQRQ(f_range[1], Rs=Resistance, Rp1=Parallel_Resistance, Q1=Constant_phase_element, alpha1=alpha, Rp2=Parallel_Resistance, Q2=Constant_phase_element, alpha2=alpha) assert np.positive(Resistance), \ 'The input resistance is invalid' assert np.positive(Parallel_Resistance), \ 'The input resistance is invalid' assert np.positive(Constant_phase_element), \ 'The input phase element is invalid' assert alpha > 0 or alpha <= 1, 'The values of alpha is invalid' assert len(response) == len(f_range[1]), \ 'The returned response is not valid' for item in response: assert isinstance(item, complex), \ 'The returned response includes invalid impedance' real_Z = item.real imag_Z = item.imag total_Z = np.sqrt((real_Z**2) + (imag_Z**2)) assert total_Z > Resistance, \ 'The Impedance value returned is lower than the' +\ 'Solution Resistance'
def test_rc_series(self): high_freq = 10**8 # Hz low_freq = 0.01 # Hz decades = 7 assert isinstance(decades, int),\ 'The number of decades should be an integer' assert high_freq >= low_freq,\ 'The low frequency should be smaller than the high\ frequency limit value. Check again.' f_range = circuits.freq_gen(high_freq, low_freq, decades) Resistance = 10 Capacitance = 10**-6 assert np.positive(Resistance), 'The input resistance\ is invalid' assert np.positive(Capacitance), 'The input capacitance\ is invalid' response = circuits.cir_RC_series(f_range[1], Resistance, Capacitance) assert len(response) == len(f_range[1]), 'The returned response\ is not valid' for item in response: assert isinstance(item, complex), 'The returned response\
def on_same_side(self, a, b, l1, l2): z1 = self.cross_product_z_coord(l2 - l1, a - l1) z2 = self.cross_product_z_coord(l2 - l1, b - l1) if z1 == 0 or z2 == 0: return True else: return np.positive(z1) == np.positive(z2)
def test_out_dtype(): a = sparse.eye(5, dtype="float32") b = sparse.eye(5, dtype="float64") assert (np.positive(a, out=b).dtype == np.positive(a.todense(), out=b.todense()).dtype) assert (np.positive(a, out=b, dtype="float64").dtype == np.positive( a.todense(), out=b.todense(), dtype="float64").dtype)
def test_unary_unary(dtype): # unary input, unary output values = np.array([[-1, -1], [1, 1]], dtype="int64") df = pd.DataFrame(values, columns=["A", "B"], index=["a", "b"]).astype(dtype=dtype) result = np.positive(df) expected = pd.DataFrame( np.positive(values), index=df.index, columns=df.columns ).astype(dtype) tm.assert_frame_equal(result, expected)
def test_RsRQRQ(self): high_freq = 10**8 # Hz low_freq = 0.01 # Hz decades = 7 assert isinstance(decades, int),\ 'The number of decades should be an integer' assert high_freq >= low_freq,\ 'The low frequency should be smaller than the high\ frequency limit value. Check again.' f_range = circuits.freq_gen(high_freq, low_freq, decades) Solution_Resistance = 10 Parallel_Resistance_1 = 100 Parallel_Resistance_2 = 100 Constant_phase_element_1 = 10**-6 Constant_phase_element_2 = 10**-6 alpha_1 = 1 alpha_2 = 1 assert np.positive(Solution_Resistance), 'The input resistance\ is invalid' assert np.positive(Parallel_Resistance_1), 'The input resistance\ is invalid' assert np.positive(Parallel_Resistance_2), 'The input resistance\ is invalid' assert np.positive(Constant_phase_element_1), 'The input cnstant\ phase element is invalid' assert np.positive(Constant_phase_element_2), 'The input contant\ phase element is invalid' assert alpha_1 > 0 or alpha_1 <= 1, 'The values of alpha is invalid' assert alpha_2 > 0 or alpha_2 <= 1, 'The values of alpha is invalid' response = circuits.cir_RsRQRQ(f_range[1], Solution_Resistance, Parallel_Resistance_1, Constant_phase_element_1, alpha_1, Parallel_Resistance_2, Constant_phase_element_2, alpha_2) assert len(response) == len(f_range[1]), 'The returned response\ is not valid' for item in response: assert isinstance(item, complex), 'The returned response\ includes invalid impedance' real_Z = item.real imag_Z = item.imag total_Z = np.sqrt((real_Z**2) + (imag_Z**2)) assert total_Z > Solution_Resistance, 'The Impedance value\
def test_RQ_series(self): response = circuits.cir_RQ_series(f_range[1], R=Resistance, Q=Constant_phase_element, alpha=alpha) assert np.positive(Resistance), \ 'The input resistance is invalid' assert np.positive(Constant_phase_element), \ 'The input phase element is invalid' assert len(response) == len(f_range[1]), \ 'The returned response is not valid' for item in response: assert isinstance(item, complex), \ 'The returned response includes invalid impedance'
def test_half_ufuncs(self): """Test the various ufuncs""" a = np.array([0, 1, 2, 4, 2], dtype=float16) b = np.array([-2, 5, 1, 4, 3], dtype=float16) c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16) assert_equal(np.add(a, b), [-2, 6, 3, 8, 5]) assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1]) assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6]) assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625]) assert_equal(np.equal(a, b), [False, False, False, True, False]) assert_equal(np.not_equal(a, b), [True, True, True, False, True]) assert_equal(np.less(a, b), [False, True, False, False, True]) assert_equal(np.less_equal(a, b), [False, True, False, True, True]) assert_equal(np.greater(a, b), [True, False, True, False, False]) assert_equal(np.greater_equal(a, b), [True, False, True, True, False]) assert_equal(np.logical_and(a, b), [False, True, True, True, True]) assert_equal(np.logical_or(a, b), [True, True, True, True, True]) assert_equal(np.logical_xor(a, b), [True, False, False, False, False]) assert_equal(np.logical_not(a), [True, False, False, False, False]) assert_equal(np.isnan(c), [False, False, False, True, False]) assert_equal(np.isinf(c), [False, False, True, False, False]) assert_equal(np.isfinite(c), [True, True, False, False, True]) assert_equal(np.signbit(b), [True, False, False, False, False]) assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3]) assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3]) x = np.maximum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [0, 5, 1, 0, 6]) assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2]) x = np.minimum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [-2, -1, -np.inf, 0, 3]) assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3]) assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6]) assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2]) assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3]) assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0]) assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2]) assert_equal(np.square(b), [4, 25, 1, 16, 9]) assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125]) assert_equal(np.ones_like(b), [1, 1, 1, 1, 1]) assert_equal(np.conjugate(b), b) assert_equal(np.absolute(b), [2, 5, 1, 4, 3]) assert_equal(np.negative(b), [2, -5, -1, -4, -3]) assert_equal(np.positive(b), b) assert_equal(np.sign(b), [-1, 1, 1, 1, 1]) assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b)) assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2])) assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
def clip(self, min=None, max=None, out=None, **kwargs): """Return an array whose values are limited to ``[min, max]``. Like `~numpy.clip`, but any masked values in ``min`` and ``max`` are ignored for clipping. The mask of the input array is propagated. """ # TODO: implement this at the ufunc level. dmin, mmin = self._get_data_and_mask(min) dmax, mmax = self._get_data_and_mask(max) if mmin is None and mmax is None: # Fast path for unmasked max, min. return super().clip(min, max, out=out, **kwargs) masked_out = np.positive(self, out=out) out = masked_out.unmasked if dmin is not None: np.maximum(out, dmin, out=out, where=True if mmin is None else ~mmin) if dmax is not None: np.minimum(out, dmax, out=out, where=True if mmax is None else ~mmax) return masked_out
def test_half_ufuncs(self): """Test the various ufuncs""" a = np.array([0, 1, 2, 4, 2], dtype=float16) b = np.array([-2, 5, 1, 4, 3], dtype=float16) c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16) assert_equal(np.add(a, b), [-2, 6, 3, 8, 5]) assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1]) assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6]) assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625]) assert_equal(np.equal(a, b), [False, False, False, True, False]) assert_equal(np.not_equal(a, b), [True, True, True, False, True]) assert_equal(np.less(a, b), [False, True, False, False, True]) assert_equal(np.less_equal(a, b), [False, True, False, True, True]) assert_equal(np.greater(a, b), [True, False, True, False, False]) assert_equal(np.greater_equal(a, b), [True, False, True, True, False]) assert_equal(np.logical_and(a, b), [False, True, True, True, True]) assert_equal(np.logical_or(a, b), [True, True, True, True, True]) assert_equal(np.logical_xor(a, b), [True, False, False, False, False]) assert_equal(np.logical_not(a), [True, False, False, False, False]) assert_equal(np.isnan(c), [False, False, False, True, False]) assert_equal(np.isinf(c), [False, False, True, False, False]) assert_equal(np.isfinite(c), [True, True, False, False, True]) assert_equal(np.signbit(b), [True, False, False, False, False]) assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3]) assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3]) x = np.maximum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [0, 5, 1, 0, 6]) assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2]) x = np.minimum(b, c) assert_(np.isnan(x[3])) x[3] = 0 assert_equal(x, [-2, -1, -np.inf, 0, 3]) assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3]) assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6]) assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2]) assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3]) assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0]) assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2]) assert_equal(np.divmod(a, b), ([0, 0, 2, 1, 0], [0, 1, 0, 0, 2])) assert_equal(np.square(b), [4, 25, 1, 16, 9]) assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125]) assert_equal(np.ones_like(b), [1, 1, 1, 1, 1]) assert_equal(np.conjugate(b), b) assert_equal(np.absolute(b), [2, 5, 1, 4, 3]) assert_equal(np.negative(b), [2, -5, -1, -4, -3]) assert_equal(np.positive(b), b) assert_equal(np.sign(b), [-1, 1, 1, 1, 1]) assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b)) assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2])) assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
def average_squares(squares): new_squares = [] for (x, y, w, h) in squares: for (_x, _y, _w, _h) in last_frame_squares: dist_x = np.positive(x - _x) dist_y = np.positive(y - _y) size_w = np.positive(w - _w) size_h = np.positive(h - _h) if dist_x < dist_threshold and dist_y < dist_threshold and \ size_w < size_threshold and size_h < dist_threshold: new_squares.append([int(_sum / 2) for _sum in [(x + _x), (y + _y), (w + _w), (h + _h)]]) break last_frame_squares.clear() last_frame_squares.extend(squares) return np.array(new_squares)
def test_randles(self): high_freq = 10**8 # Hz low_freq = 0.01 # Hz decades = 7 assert isinstance(decades, int),\ 'The number of decades should be an integer' assert high_freq >= low_freq,\ 'The low frequency should be smaller than the high\ frequency limit value. Check again.' f_range = circuits.freq_gen(high_freq, low_freq, decades) Solution_Resistance = 10 Parallel_Resistance = 100 alpha = 1 Constant_phase_element = 10**-6 sigma = 500 assert np.positive(Solution_Resistance), 'The input resistance\ is non-positive' assert np.positive(Parallel_Resistance), 'The input resistance\ is non-positive' assert alpha > 0 or alpha <= 1, 'The values of alpha is\ nonpositive' assert np.positive(Constant_phase_element), 'The input constant\ phase element is non-positive' assert np.positive(sigma), 'The input coefficient is non-positive' response = circuits.cir_Randles_simplified(f_range[1], Solution_Resistance, Parallel_Resistance, alpha, sigma, Constant_phase_element) assert len(response) == len(f_range[1]), 'The returned response\ is not valid' for item in response: assert isinstance(item, complex), 'The returned response\ includes invalid impedance' real_Z = item.real imag_Z = item.imag total_Z = np.sqrt((real_Z**2) + (imag_Z**2)) assert total_Z > Solution_Resistance, 'The Impedance value\
def test_RC_series(self): response = circuits.cir_RC_series(f_range[1], R=Resistance, C=Capacitance) assert np.positive(Resistance), \ 'The input resistance is invalid' assert np.positive(Capacitance), \ 'The input capacitance is invalid' assert isinstance(Capacitance, float), \ 'the capacitance should be a float, not an integer' assert len(response) == len(f_range[1]), \ 'The returned response is not valid' for item in response: assert isinstance(item, complex),\ 'The returned response includes invalid impedance'
def positive(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in positive") return Array._new(np.positive(x._array))
def test_pos(self): vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]") arr = TimedeltaArray(vals) result = +arr tm.assert_timedelta_array_equal(result, arr) result2 = np.positive(arr) tm.assert_timedelta_array_equal(result2, arr)
def __call__(self, a, where=True): """ Parameters ---------- a: mygrad.Tensor where : array_like, optional Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.""" self.variables = (a,) self.conf = dict(where=where) return np.positive(a.data, where=where)
def math_example(): #math math_arr = np.random.rand(100000, 50) - 0.5 math_arr_neg = np.negative(math_arr) math_arr = np.positive(math_arr) sin_arr = np.sin(math_arr) cos_arr = np.cos(math_arr) tan_arr = np.tan(math_arr) same_math_arr = np.arctan(tan_arr) print("\n") return
def test_unary_nullable(self): df = pd.DataFrame({ "a": pd.array([1, -2, 3, pd.NA], dtype="Int64"), "b": pd.array([4.0, -5.0, 6.0, pd.NA], dtype="Float32"), "c": pd.array([True, False, False, pd.NA], dtype="boolean"), # include numpy bool to make sure bool-vs-boolean behavior # is consistent in non-NA locations "d": np.array([True, False, False, True]), }) result = +df res_ufunc = np.positive(df) expected = df # TODO: assert that we have copies? tm.assert_frame_equal(result, expected) tm.assert_frame_equal(res_ufunc, expected) result = -df res_ufunc = np.negative(df) expected = pd.DataFrame({ "a": pd.array([-1, 2, -3, pd.NA], dtype="Int64"), "b": pd.array([-4.0, 5.0, -6.0, pd.NA], dtype="Float32"), "c": pd.array([False, True, True, pd.NA], dtype="boolean"), "d": np.array([False, True, True, False]), }) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(res_ufunc, expected) result = abs(df) res_ufunc = np.abs(df) expected = pd.DataFrame({ "a": pd.array([1, 2, 3, pd.NA], dtype="Int64"), "b": pd.array([4.0, 5.0, 6.0, pd.NA], dtype="Float32"), "c": pd.array([True, False, False, pd.NA], dtype="boolean"), "d": np.array([True, False, False, True]), }) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(res_ufunc, expected)
def test_RsRC(self): high_freq = 10**8 # Hz low_freq = 0.01 # Hz decades = 7 assert isinstance(decades, int),\ 'The number of decades should be an integer' assert high_freq >= low_freq,\ 'The low frequency should be smaller than the high\ frequency limit value. Check again.' f_range = circuits.freq_gen(high_freq, low_freq, decades) Solution_Resistance = 10 Parallel_Resistance = 100 Capacitance = 10**-6 assert np.positive(Solution_Resistance), 'The input resistance\ is invalid' assert np.positive(Parallel_Resistance), 'The input resistance\ is invalid' assert np.positive(Capacitance), 'The input capacitance\ is invalid' response = circuits.cir_RQ_series(f_range[1], Solution_Resistance, Parallel_Resistance, Capacitance) assert len(response) == len(f_range[1]), 'The returned response\ is not valid' for item in response: assert isinstance(item, complex), 'The returned response\ includes invalid impedance' real_Z = item.real imag_Z = item.imag total_Z = np.sqrt((real_Z**2) + (imag_Z**2)) assert total_Z > Solution_Resistance, 'The Impedance value\
def genVectorPaths(start: Sequence[int], end: Sequence[int], nodes: Mapping[T, Tuple[Sequence[int], Sequence[int]]], trunc: int) -> Generator[List[Tuple[T, Sequence[int], Sequence[int]]], None, None]: start, end = numpy.asarray(start), numpy.asarray(end) if trunc == 0: yield [] for node in nodes: node_tuple = (node, nodes[node][0], nodes[node][1]) required_particles, produced_particles = numpy.asarray(nodes[node][0]), numpy.asarray(nodes[node][1]) comb = start + required_particles if not numpy.all(numpy.positive(comb)): continue after_inter = comb + produced_particles if numpy.array_equal(after_inter, end): yield [node_tuple] else: for subpath in genVectorPaths(start, end, nodes, trunc - 1): yield [node_tuple] + subpath
def get_cumCost(self, duration, cumDuration, fixedCosts): '''calculte cummulative cost at each end of the period total cost = (variable cost + fixed cost) * (1 + PM cost) ''' # change metric, from day to period, in duration matrix taskStart = cumDuration - duration totalDuration = self.get_totalDuration(cumDuration) maxPeriods = int(totalDuration.max() / self.daysPerPeriod) + 1 endDays = self.daysPerPeriod * np.arange(1, maxPeriods + 1) # calculate variable cost, variable cost = running duration * daily cost # running duration as of each period # = min(duration,(asofdays-taskStartDate)^+) # = min(cumDuration,max(asofdays,taskStartDate)) - taskStartDate # cumCost = np.array([np.matmul( # np.minimum(cumDuration, np.maximum(endDay,taskStart)), # self.dailyCosts) for endDay in endDays]).T # cumCost -= np.matmul(taskStart,self.dailyCosts)[:,None] # completedFlag = np.arange(maxPeriods)*self.daysPerPeriod>totalDuration[:,None] # cumCost[completedFlag] = np.nan tmp, cumCost = taskStart.copy(), [] for endDay in endDays: tmp[taskStart < endDay] = endDay _ = np.positive(cumDuration, out=tmp, where=cumDuration < endDay) cumCost.append(np.matmul(tmp, self.dailyCosts)) cumCost = np.array(cumCost - np.matmul(taskStart, self.dailyCosts)).T # apply fixed cost and PM cost to variable cost TaskIdHasCosts = [i for i, a in enumerate(fixedCosts) if a is not 0.] if TaskIdHasCosts: row = np.arange(len(cumDuration)) cost = np.zeros(cumCost.shape) # fixed cost at each period for taskId in TaskIdHasCosts: # fixed cost applied at task start date col = (taskStart[:, taskId] // self.daysPerPeriod).astype(int) cost[row, col] += fixedCosts[taskId] cumCost += cost.cumsum(axis=1) if self.PMcost: cumCost *= (1 + self.PMcost) return cumCost
def onp_positive(x, out, where): return onp.positive(x, out=out, where=where)
def test_ufunc_positive_f(A: dace.float32[10]): return np.positive(A)
def __array_ufunc__(self, function, method, *inputs, **kwargs): """Wrap numpy ufuncs, taking care of units. Parameters ---------- function : callable ufunc to wrap. method : str Ufunc method: ``__call__``, ``at``, ``reduce``, etc. inputs : tuple Input arrays. kwargs : keyword arguments As passed on, with ``out`` containing possible quantity output. Returns ------- result : array_like Results of the ufunc, with the unit set properly, `~baseband_tasks.phases.Phase` if possible (i.e., with units of cycles), otherwise `~astropyy.units.Quantity` or `~numpy.ndarray` as appropriate. """ # Do *not* use inputs.index(self) since that will use __eq__ for i_self, input_ in enumerate(inputs): if input_ is self: break else: i_self += 1 # Some bools for use in the if-statements below. # TODO: support reductions on add, minimum, maximum; others? basic = method == '__call__' and i_self < function.nin basic_real = basic and not self.imaginary basic_phase_out = basic out = kwargs.get('out', None) if out is not None: if len(out) == 1 and isinstance(out[0], Phase): phase_out = out[0] out = None else: phase_out = None basic_phase_out = False else: phase_out = None if function in {np.add, np.subtract} and basic and out is None: try: phases = [Phase(input_, copy=False, subok=True) for input_ in inputs] except Exception: return NotImplemented if phases[0].imaginary == phases[1].imaginary: return self.from_angles( function(phases[0]['int'], phases[1]['int']), function(phases[0]['frac'], phases[1]['frac']), out=phase_out) elif function in COMPARISON_UFUNCS and basic: phases = list(inputs) try: phases[1-i_self] = Phase(inputs[1-i_self], copy=False, subok=True) except Exception: return NotImplemented if phases[0].imaginary == phases[1].imaginary: diff = ((phases[0]['int'] - phases[1]['int']) + (phases[0]['frac'] - phases[1]['frac'])) return getattr(function, method)(diff, 0, **kwargs) elif ((function is np.multiply or function is np.divide and i_self == 0) and basic_phase_out): try: other = u.Quantity(inputs[1-i_self], u.dimensionless_unscaled, copy=False).value if function is np.multiply: return self.from_angles(self['int'], self['frac'], factor=other, out=phase_out) else: return self.from_angles(self['int'], self['frac'], divisor=other, out=phase_out) except Exception: # If not consistent with a dimensionless quantity, or mixed # real and complex, we follow the standard route of # downgrading ourself to a quantity and see if things work. pass elif (function in {np.floor_divide, np.remainder, np.divmod} and basic_real): fd_out = None if out is not None: if function is np.divmod: fd_out = out[0] phase_out = out[1] elif function is np.floor_divide: fd_out = out[0] elif phase_out is not None and function is np.floor_divide: return NotImplemented fd = np.floor_divide(self.cycle, inputs[1], out=fd_out) corr = Phase.from_angles(inputs[1], factor=fd, out=phase_out) remainder = np.subtract(self, corr, out=corr) fdx = np.floor_divide(remainder.cycle, inputs[1]) # This can likely be optimized... # Note: one cannot just loop, because rounding of exact 0.5. # TODO: check this method is really correct. if np.count_nonzero(fdx): fd += fdx corr = Phase.from_angles(inputs[1], factor=fd, out=corr) remainder = np.subtract(self, corr, out=corr) if function is np.floor_divide: return fd elif function is np.remainder: return remainder else: return fd, remainder elif function is np.positive and basic_phase_out: return self.from_angles(self['int'], self['frac'], out=phase_out) elif function is np.negative and basic_phase_out: return self.from_angles(-self['int'], -self['frac'], out=phase_out) elif function in {np.absolute, np.fabs} and basic_phase_out: # Go via view to avoid having to deal with imaginary. v = self.view(np.ndarray) return self.from_angles(u.Quantity(v['int'], u.cycle, copy=False), u.Quantity(v['frac'], u.cycle, copy=False), factor=np.sign(v['int'] + v['frac']), out=phase_out) elif function is np.rint and basic: return np.positive(self['int'], **kwargs) elif function in FRACTION_UFUNCS and basic_real: frac = self.frac.view(Angle) return function(frac, **kwargs) elif function is np.exp and basic and self.imaginary: # Avoid dimensionless_angles, but still get Quantity out. exponent = u.Quantity(self.frac.to_value(u.radian), copy=False) return function(exponent, **kwargs) # Fall-back: treat Phase as a simple Quantity. if basic: inputs = tuple((input_.cycle if isinstance(input_, Phase) else input_) for input_ in inputs) quantity = inputs[i_self] else: quantity = self.cycle if phase_out is None: return quantity.__array_ufunc__(function, method, *inputs, **kwargs) else: # We won't be able to store in a phase directly, but might # as well use one of its elements to store the angle. kwargs['out'] = (phase_out['int'],) result = quantity.__array_ufunc__(function, method, *inputs, **kwargs) return phase_out.from_angles(result, out=phase_out)
def __pos__(self): return numpy.positive(self)
def backward(self, grad, **kwargs): self.variables[0].backward(np.positive(grad))
def __call__(self, a): self.variables = (a, ) return np.positive(a.data)
def func(arr): return np.positive(arr)