コード例 #1
0
	def symOrtho(self, a, b):
		""" Computes the radius, cosine, and sine for the
		orthogonal transformation.
		@param a x vector.
		@param b y vector.
		@return [c,s,r]. Cosine value, Sine value, and the radius.
		"""
		s = 0
		c = 0
		r = 0
		if not b:
			r = np.abs(a)
			c = np.copysign(1,0,a)
		elif not a:
			r = np.abs(b)
			s = np.copysign(1,0,b)
		elif np.abs(b) > np.abs(a):
			t = a / b
			s = np.copysign(1.0,b) / np.sqrt(1.0 + t**2)
			c = s * t
			r = b / s
		else:
			t = b / a
			c = np.copysign(1.0,a) / np.sqrt(1.0 + t**2)
			s = c * t
			r = a / c
		return [c,s,r]
コード例 #2
0
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1)))
コード例 #3
0
ファイル: test_ufuncs.py プロジェクト: Qointum/pypy
    def test_signbit(self):
        from numpy import signbit, add, copysign, nan

        assert signbit(add.identity) == False
        assert (signbit([0, 0.0, 1, 1.0, float("inf")]) == [False, False, False, False, False]).all()
        assert (signbit([-0, -0.0, -1, -1.0, float("-inf")]) == [False, True, True, True, True]).all()
        assert (signbit([copysign(nan, 1), copysign(nan, -1)]) == [False, True]).all()
コード例 #4
0
ファイル: test_op_div.py プロジェクト: you13/hope
def test_cross_div(dtypea, dtypeb, dtypec):
    if dtypea == np.int8 and dtypeb == np.int8:
        pytest.skip("Different behaviour in c++ and python for int8 / int8".format(dtypea, dtypeb))

    def fkt(a, b, c):
        c[:] = a / b

    hfkt = hope.jit(fkt)
    (ao, ah), (bo, bh), (co, ch) = random(dtypea, [10]), random(dtypeb, [10]), random(dtypec, [10])
    ao, ah, bo, bh = ao.astype(np.float64), ah.astype(np.float64), bo.astype(np.float64), bh.astype(np.float64)
    ao, ah = (
        np.copysign(np.power(np.abs(ao), 1.0 / 4.0), ao).astype(dtypea),
        np.copysign(np.power(np.abs(ah), 1.0 / 4.0), ah).astype(dtypea),
    )
    bo, bh = (
        np.copysign(np.power(np.abs(bo), 1.0 / 4.0), bo).astype(dtypeb),
        np.copysign(np.power(np.abs(bh), 1.0 / 4.0), bh).astype(dtypeb),
    )
    if np.count_nonzero(bo == 0) > 0:
        bo[bo == 0] += 1
    if np.count_nonzero(bh == 0) > 0:
        bh[bh == 0] += 1
    fkt(ao, bo, co), hfkt(ah, bh, ch)
    assert check(co, ch)
    fkt(ao, bo, co), hfkt(ah, bh, ch)
    assert check(co, ch)
コード例 #5
0
ファイル: model.py プロジェクト: alexeyden/Robot-Stuff
    def __step(self, t, y, dt, control):
        u_v, u_s = control(t, y)
        v_x, v_y, r, s_f, x, y, o = y

        a_f = (v_y + self.L_f * r) / (v_x + 0.00001) - s_f
        a_r = (v_y - self.L_r * r) / (v_x + 0.00001)

        F_yf = -self.C_af * a_f
        F_yr = -self.C_ar * a_r

        n_v = self.noise_v(t) if self.noise_v else 0
        n_s = self.noise_s(t) if self.noise_s else 0

        u_s = u_s if abs(u_s) < self.max_u_s else np.copysign(self.max_u_s, u_s)
        u_v = u_v if abs(u_v) < self.max_u_v else np.copysign(self.max_u_v, u_v)

        if abs(s_f + u_s * dt) > self.max_s:
            u_s = np.copysign(self.max_s - 0.05, s_f) - s_f

        self._uv = u_v
        self._us = u_s

        F_res = self.F_res() * v_x

        d_v_x = (-F_yf * np.sin(s_f) + u_v - F_res * np.cos(s_f) - F_res + n_v) / self.m + v_y * r
        d_v_y = (F_yf * np.cos(s_f) + F_yr - F_res * np.sin(s_f)) / self.m - v_x * r
        d_r = self.L_f * (F_yf * np.cos(s_f) - F_res * np.sin(s_f)) / self.I_z - self.L_r * F_yr / self.I_z + n_s
        d_s = u_s
        d_x = v_x * np.cos(o) - v_y * np.sin(o)
        d_y = v_x * np.sin(o) + v_y * np.cos(o)
        d_o = r

        return [d_v_x, d_v_y, d_r, d_s, d_x, d_y, d_o]
コード例 #6
0
ファイル: test_quantity_ufuncs.py プロジェクト: n0d/astropy
    def test_copysign_array(self):
        assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1.) == -np.array([1., 2., 3.]) * u.s)
        assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1. * u.m) == -np.array([1., 2., 3.]) * u.s)
        assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, np.array([-2.,2.,-4.]) * u.m) == np.array([-1., 2., -3.]) * u.s)

        q = np.copysign(np.array([1., 2., 3.]), -3 * u.m)
        assert np.all(q == np.array([-1., -2., -3.]))
        assert not isinstance(q, u.Quantity)
コード例 #7
0
ファイル: AOM.py プロジェクト: AdriaanRol/measurement
    def calibrate(self, steps): # calibration values in uW
        rng = np.arange(0,steps)
        x = np.zeros(steps,dtype = float)
        y = np.zeros(steps,dtype = float)
        
        self.set_power(0)
        self._ins_pm.set_wavelength(self._wavelength)
        time.sleep(2)
        bg = self._ins_pm.get_power()

        print 'background power: %.4f uW' % (bg*1e6)

        time.sleep(.2)

        V_max = self.get_V_max()
        V_min = self.get_V_min()
        
        if V_max + V_min < 0: rng=np.flipud(rng)
        
        for a in rng:
            x[a] = a*(V_max-V_min)/float(steps-1)+V_min
            self.apply_voltage(x[a])
            time.sleep(0.5)
            y[a] = self._ins_pm.get_power() - bg
            
            print 'measured power at %.2f V: %.4f uW' % \
                    (x[a], y[a]*1e6)
        
        #x= x*(V_max-V_min)/float(steps-1)+V_min 
        a, xc, k = np.copysign(np.max(y), V_max + V_min), np.copysign(.1, V_max + V_min), np.copysign(5., V_max + V_min)
        fitres = fit.fit1d(x,y, common.fit_AOM_powerdependence, 
                a, xc, k, do_print=True, ret=True)
     
        fd = np.zeros(len(x))        
        if type(fitres) != type(False):
            p1 = fitres['params_dict']
            self.set_cal_a(p1['a'])
            self.set_cal_xc(p1['xc'])
            self.set_cal_k(p1['k'])
            fd = fitres['fitfunc'](x)
        else:
            print 'could not fit calibration curve!'
        
        dat = qt.Data(name= 'aom_calibration_'+self._name+'_'+\
                self._cur_controller)
        dat.add_coordinate('Voltage [V]')
        dat.add_value('Power [W]')
        dat.add_value('fit')
        dat.create_file()
        plt = qt.Plot2D(dat, 'rO', name='aom calibration', coorddim=0, valdim=1, 
                clear=True)
        plt.add_data(dat, coorddim=0, valdim=2)
        dat.add_data_point(x,y,fd)
        dat.close_file()
        plt.save_png(dat.get_filepath()+'png')

        self.save_cfg()
        print (self._name+' calibration finished')
コード例 #8
0
ファイル: test_umath.py プロジェクト: jarrodmillman/numpy
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    old_err = np.seterr(divide="ignore")
    try:
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    finally:
        np.seterr(**old_err)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1)))
コード例 #9
0
ファイル: test_op_pow.py プロジェクト: BrainGrylls/hope
def test_binary_pow(dtype, shape):
    def fkt(a, c):
        c[:] = a ** 2
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, shape), random(dtype, shape)
    ao, ah = np.copysign(np.sqrt(np.abs(ao)), ao).astype(dtype), np.copysign(np.sqrt(np.abs(ah)), ah).astype(dtype)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
コード例 #10
0
ファイル: test_op_mult.py プロジェクト: BrainGrylls/hope
def test_augmented_mult(dtype, shape):
    def fkt(a, c):
        c[:] *= a
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, shape), random(dtype, shape)
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 4.), ao).astype(dtype), np.copysign(np.power(np.abs(ah), 1. / 4.), ah).astype(dtype)
    co, ch = np.copysign(np.power(np.abs(co), 1. / 4.), co).astype(dtype), np.copysign(np.power(np.abs(ch), 1. / 4.), ch).astype(dtype)
    ro, rh = fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    ro, rh = fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
コード例 #11
0
def adjustDxn(dx1,dx2,rcore,tol=1e-10):
    r = np.sqrt(dx1**2 + dx2**2)     
    if (r**2 < rcore**2*tol):
        rcorefac = rcore/np.sqrt(2.0)
        dx1 = np.copysign(rcorefac,dx1)
        dx2 = np.copysign(rcorefac,dx2)
    elif (r**2 < rcore**2):
        rfac = rcore/r
        dx1 = dx1*rfac
        dx2 = dx2*rfac
    return dx1, dx2
コード例 #12
0
ファイル: proplyds.py プロジェクト: deprecated/proplyd-slits
def dms2deg(char):
    
    """
    Function used to transform the Declination from the fits file given in degrees, minutes and seconds
    to degrees.
    Argument: The dec as a string of characters
    output: A float number: the Dec written in degrees
    """
    d,m,s = [float(x) for x in char.split()]
    m,s = np.copysign(m,d),np.copysign(s,d) # The arcminutes and arcseconds adquire the same sign of degrees to be added later
    out = (d + m/60.+ s/3600.) 
    return out
コード例 #13
0
ファイル: test_optimize.py プロジェクト: BrainGrylls/hope
def test_opt_pow_array(dtype, shape):
    def fkt(a, c):
        c[:] = a ** 2.0 + a ** 4 + a ** 7
    hope.config.optimize = True
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, shape), random(dtype, shape)
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 8.), ao).astype(dtype), np.copysign(np.power(np.abs(ah), 1. / 8.), ah).astype(dtype)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    hope.config.optimize = False
コード例 #14
0
ファイル: test_return.py プロジェクト: BrainGrylls/hope
def test_return_arr_expr(dtype, shape):
    def fkt(a, c):
        return a ** -2 + a ** -4.0 + a ** -7
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, shape), random(dtype, shape)
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 8.), ao).astype(dtype), np.copysign(np.power(np.abs(ah), 1. / 8.), ah).astype(dtype)
    if np.count_nonzero(ao == 0) > 0: ao[ao == 0] += 1
    if np.count_nonzero(ah == 0) > 0: ah[ah == 0] += 1
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
コード例 #15
0
ファイル: test_optimize.py プロジェクト: BrainGrylls/hope
def test_opt_pow_scalar(dtype):
    def fkt(a, c):
        c[0] = a ** 2 + a ** 4 + a ** 7.0
    hope.config.optimize = True
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, []), random(dtype, [1])
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 8.), ao).astype(dtype), np.copysign(np.power(np.abs(ah), 1. / 8.), ah).astype(dtype)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    hope.config.optimize = False
コード例 #16
0
ファイル: test_op_mult.py プロジェクト: BrainGrylls/hope
def test_binary_mult(dtype, shape):
    def fkt(a, b, c):
        c[:] = a * b
    hfkt = hope.jit(fkt)
    (ao, ah), (bo, bh), (co, ch) = random(dtype, shape), random(dtype, shape), random(dtype, shape)
    ao = np.copysign(np.sqrt(np.abs(ao.astype(np.float64))).astype(dtype), ao).astype(dtype)
    ah = np.copysign(np.sqrt(np.abs(ah.astype(np.float64))).astype(dtype), ah).astype(dtype)
    bo = np.copysign(np.sqrt(np.abs(bo.astype(np.float64))).astype(dtype), bo).astype(dtype)
    bh = np.copysign(np.sqrt(np.abs(bh.astype(np.float64))).astype(dtype), bh).astype(dtype)
    ro, rh = fkt(ao, bo, co),  hfkt(ah, bh, ch)
    assert check(co, ch)
    ro, rh = fkt(ao, bo, co),  hfkt(ah, bh, ch)
    assert check(co, ch)
コード例 #17
0
ファイル: test_op_pow.py プロジェクト: BrainGrylls/hope
def test_augmented_pow(dtype, shape):
    def fkt(a, c): 
        c[:] **= a
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(np.uint8, shape), random(dtype, shape)
    if np.count_nonzero(ao == 0) > 0: ao[ao == 0] += 1
    if np.count_nonzero(ah == 0) > 0: ah[ah == 0] += 1
    if np.count_nonzero(co == 0) > 0: co[co == 0] += 1
    if np.count_nonzero(ch == 0) > 0: ch[ch == 0] += 1
    co, ch = np.copysign(np.sqrt(np.abs(co)), co).astype(dtype), np.copysign(np.sqrt(np.abs(ch)), ch).astype(dtype)
    ao, ah = np.power(np.abs(ao).astype(np.float64), 1. / co.astype(np.float64)).astype(dtype), np.power(np.abs(ah).astype(np.float64), 1. / ch.astype(np.float64)).astype(dtype)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
コード例 #18
0
ファイル: test_optimize.py プロジェクト: BrainGrylls/hope
def test_opt_neg_pow_array(dtype, shape):
    def fkt(a, c):
        c[:] = a ** -2 + a ** -4.0 + a ** -7
    hope.config.optimize = True
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, shape), random(dtype, shape)
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 8.), ao).astype(dtype), np.copysign(np.power(np.abs(ah), 1. / 8.), ah).astype(dtype)
    if np.count_nonzero(ao == 0) > 0: ao[ao == 0] += 1
    if np.count_nonzero(ah == 0) > 0: ah[ah == 0] += 1
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    hope.config.optimize = False
コード例 #19
0
ファイル: test_optimize.py プロジェクト: BrainGrylls/hope
def test_opt_basic_scalar(dtype):
    def fkt(a, c):
        c[0] = (a + a) * a - 1 / a
    hope.config.optimize = True
    hfkt = hope.jit(fkt)
    (ao, ah), (co, ch) = random(dtype, []), random(dtype, [1])
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 4.), ao).astype(dtype), np.copysign(np.power(np.abs(ah), 1. / 4.), ah).astype(dtype)
    if np.count_nonzero(ao == 0) > 0: ao[ao == 0] += 1
    if np.count_nonzero(ah == 0) > 0: ah[ah == 0] += 1
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    fkt(ao, co),  hfkt(ah, ch)
    assert check(co, ch)
    hope.config.optimize = False
コード例 #20
0
ファイル: test_ufuncs.py プロジェクト: Qointum/pypy
    def test_copysign(self):
        from numpy import array, copysign

        reference = [5.0, -0.0, 0.0, -6.0]
        a = array([-5.0, 0.0, 0.0, 6.0])
        b = array([5.0, -0.0, 3.0, -6.0])
        c = copysign(a, b)
        for i in range(4):
            assert c[i] == reference[i]

        b = array([True, True, True, True], dtype=bool)
        c = copysign(a, b)
        for i in range(4):
            assert c[i] == abs(a[i])
コード例 #21
0
ファイル: Kinisot.py プロジェクト: bobbypaton/Kinisot
   def __init__(self, file, isomer, *args):
      # Frequencies in waveunmbers
      self.frequency_wn = []

      # Extract the Force constants from a g09 logfile and generate the
      # mass-weighted Hessian matrix in Hartree/(amu Bohr^2)
      mw_hessmat = read_hess(file, isomer)

      # Convert from atomic units - a bit ugly
      unit_conversion = ENERGY_AU / (BOHR_RADIUS**2 * ATOMIC_MASS_UNIT) / ((SPEED_OF_LIGHT * 2 * np.pi)**2)
      eigs = np.linalg.eigvalsh(mw_hessmat * unit_conversion)
      freqs = [ np.copysign(np.sqrt(np.abs(freq)),freq) for freq in eigs ]

      # 5 or 6 small normal modes will be removed (depending on whether the molecule is linear or non-linear)
      if is_linear(file) == 'linear': trans_rot_modes = 5
      else: trans_rot_modes = 6

      # Keep a single imaginary frequency. It should be larger than the predefined cut-off
      if np.abs(freqs[0]) > freq_cutoff:
         self.im_frequency_wn = -1.0 * freqs[0]
         trans_rot_modes = trans_rot_modes + 1
      for freq in freqs[trans_rot_modes:]: self.frequency_wn.append(freq)

      # Calculate the excitation factor (EXC), the ZPE (ZPE) and Teller-Redlich product factor (PF)
      # returns a 1D-array of all terms
      self.PF = calc_product_factor(self.frequency_wn, freq_scale_factor)
      self.ZPE = calc_zpe_factor(self.frequency_wn, temperature, freq_scale_factor)
      self.EXC = calc_excitation_factor(self.frequency_wn, temperature, freq_scale_factor)
コード例 #22
0
ファイル: Hardy_Cross_Suite.py プロジェクト: gpamfilis/WSNS
    def run_hc(self):
        self.compute_pipe_diameter_of_each_loop()
        for run in range(self.runs):
            for i, loop in enumerate(self.loops):
                # perform initial calculations
                loop['J'] = j_loss_10atm(loop['D'], loop['Q'])
                loop['hf'] = np.copysign(loop['J'] * loop['L'], loop['Q'])
                loop['hf/Q'] = loop['hf'] / loop['Q']
                self.delta_Qs[i] = (flow_correction_dq(loop['hf'], loop['hf/Q']))
                loop['Q'] = loop['Q'] + self.delta_Qs[i]
                self.delta_Qs[i] = (flow_correction_dq(loop['hf'], loop['hf/Q']))

                # do the common loop correction
                loop['Q'] = loop['Q'] - np.dot(self.common_loops[i], self.delta_Qs)

                self.smallest_flow_rate.append(np.min(np.abs(loop['Q'])))

            largest_delta_qs_flow_rate = np.max(abs(self.delta_Qs))
            if largest_delta_qs_flow_rate / np.min(self.smallest_flow_rate) * 100 < self.threshold:
                print('Completed on run {}'.format(run))
                print('dqmin / Qmin * 100 =  {0:.2f}'.format((largest_delta_qs_flow_rate /
                                                              np.min(self.smallest_flow_rate)) * 100))
                for k, l in enumerate(loops_from_input_file):
                    print('the corrected loops {} are \n {}'.format(k, l))
                break
            else:
                print('Not Done {}'.format(run))
                pass
        return self.loops, self.delta_Qs
コード例 #23
0
ファイル: lattice.py プロジェクト: cchenae/pymatgen
    def get_all_distance_and_image(self, frac_coords1, frac_coords2):
        """
        Gets distance between two frac_coords and nearest periodic images.

        Args:
            fcoords1 (3x1 array): Reference fcoords to get distance from.
            fcoords2 (3x1 array): fcoords to get distance from.

        Returns:
            [(distance, jimage)] List of distance and periodic lattice
            translations of the other site for which the distance applies.
            This means that the distance between frac_coords1 and (jimage +
            frac_coords2) is equal to distance.
        """
        #The following code is heavily vectorized to maximize speed.
        #Get the image adjustment necessary to bring coords to unit_cell.
        adj1 = np.floor(frac_coords1)
        adj2 = np.floor(frac_coords2)
        #Shift coords to unitcell
        coord1 = frac_coords1 - adj1
        coord2 = frac_coords2 - adj2
        # Generate set of images required for testing.
        # This is a cheat to create an 8x3 array of all length 3
        # combinations of 0,1
        test_set = np.unpackbits(np.array([5, 57, 119],
                                          dtype=np.uint8)).reshape(8, 3)
        images = np.copysign(test_set, coord1 - coord2)
        # Create tiled cartesian coords for computing distances.
        vec = np.tile(coord2 - coord1, (8, 1)) + images
        vec = self.get_cartesian_coords(vec)
        # Compute distances manually.
        dist = np.sqrt(np.sum(vec ** 2, 1)).tolist()
        return list(zip(dist, adj1 - adj2 + images))
コード例 #24
0
def dms_to_degrees(d, m, s=None):
    """
    Convert degrees, arcminute, arcsecond to a float degrees value.
    """

    _check_minute_range(m)
    _check_second_range(s)

    # determine sign
    sign = np.copysign(1.0, d)

    try:
        d = np.floor(np.abs(d))
        if s is None:
            m = np.abs(m)
            s = 0
        else:
            m = np.floor(np.abs(m))
            s = np.abs(s)
    except ValueError:
        raise ValueError(format_exception(
            "{func}: dms values ({1[0]},{2[1]},{3[2]}) could not be "
            "converted to numbers.", d, m, s))

    return sign * (d + m / 60. + s / 3600.)
コード例 #25
0
def quat_from_rotmx(R):
    r"""
    Obtain the quaternion from a given rotation matrix (ref. [euclidianspace_mxToQuat]_)

    Args:
       :R: 3x3 array that represent the rotation matrix (see `Conventions <conventions.html#matrices>`_)
    """
    q = numpy.zeros(4, dtype="float")
    q[0] = numpy.sqrt( max( 0, 1 + R[0,0] + R[1,1] + R[2,2] ) ) / 2.
    q[1] = numpy.sqrt( max( 0, 1 + R[0,0] - R[1,1] - R[2,2] ) ) / 2.
    q[2] = numpy.sqrt( max( 0, 1 - R[0,0] + R[1,1] - R[2,2] ) ) / 2.
    q[3] = numpy.sqrt( max( 0, 1 - R[0,0] - R[1,1] + R[2,2] ) ) / 2.
    q[1] = numpy.copysign( q[1], R[2,1] - R[1,2] ) 
    q[2] = numpy.copysign( q[2], R[0,2] - R[2,0] ) 
    q[3] = numpy.copysign( q[3], R[1,0] - R[0,1] )
    return q
コード例 #26
0
ファイル: model12.py プロジェクト: tracholar/alibaba2015
def GetFeature(data):

	nolog = ['user_id','item_id', 'buy']
	nolog2 = ['user_cat_aveThreeDayDelta_click','user_cat_aveThreeDayDelta_star','user_cat_aveThreeDayDelta_add_car','user_cat_aveThreeDayDelta_buy','user_item_aveThreeDayDelta_click','user_item_aveThreeDayDelta_star','user_item_aveThreeDayDelta_add_car','user_item_aveThreeDayDelta_buy']
	factor_features = [
		"user_item_click_nobuy",
		"user_item_star_nobuy",
		"user_item_cart_nobuy",
		"user_item_buy_again",
		"user_geo_b","user_geo_f","user_geo_i","user_geo_m","user_geo_o","user_geo_5","user_geo_4","user_geo_v","user_geo_9","user_geo_t",
		"item_geo_9","item_geo_4","item_geo_m","item_geo_t","item_geo_f",
	]
	feature_names = [i for i in data.columns if i not in nolog and i not in factor_features and i not in nolog2]
	
	X1 = np.log(0.3+data[feature_names])
	X2 = dict()
	X2['user_convert_rate'] = data['user_buy_count'] / (1+data['user_action_count'])
	X2['item_convert_rate'] = data['item_buy_count'] / (1+data['item_click_count'])
	X2 = pandas.DataFrame(X2)
	
	X3 = data[factor_features]
	
	feature_names2= [i for i in data.columns if i in nolog2]
	
	X4 = np.copysign(np.log(0.3+np.abs(data[feature_names2])),np.sign(data[feature_names2]))
	
	X = pandas.concat([X1, X2, X3, X4], axis=1)
	
	
	
	return X[_feature_names]
コード例 #27
0
ファイル: units.py プロジェクト: liavkoren/python-skyfield
def _unsexagesimalize(value):
    """Return `value` after interpreting a (units, minutes, seconds) tuple.

    When `value` is not a tuple, it is simply returned.

    >>> _unsexagesimalize(3.25)
    3.25

    An input tuple is interpreted as units, minutes, and seconds.  Note
    that only the sign of `units` is significant!  So all of the
    following tuples convert into exactly the same value:

    >>> '%f' % _unsexagesimalize((-1, 2, 3))
    '-1.034167'
    >>> '%f' % _unsexagesimalize((-1, -2, 3))
    '-1.034167'
    >>> '%f' % _unsexagesimalize((-1, -2, -3))
    '-1.034167'

    """
    if isinstance(value, tuple):
        for i, component in enumerate(value):
            if i:
                value = value + copysign(component, value) * 60.0 ** -i
            else:
                value = component
    return value
コード例 #28
0
ファイル: rtl.py プロジェクト: chuxpy/dandelion-frm
 def correlate(self):
     '''Estimates the time-delay in whole samples, then aligns and finds the complex visibility for two signals in the data key of self.parent_row and self.child_row.
     Generates self.convolution_spectrum, self.zscore, self.expected_overlap, and self.real_overlap, which can be used for plotting purposes.
     Creates two signals, one corresponding to the cos and the other to the sin signal, as self.cos_signal and self.sin_signal
     In order to do a correlation without opening a file and populating self.child_row and self.parent_row, assign these variables manually.'''
     child_fft = scipy.fftpack.fft(self.child_row['data'])
     parent_fft = scipy.fftpack.fft(self.parent_row['data'])
     child_inverse_conjugate = -child_fft.conjugate()
     fft_auto_child = child_fft*child_inverse_conjugate
     fft_convolution = parent_fft*child_inverse_conjugate
     self.convolution_spectrum = numpy.abs(scipy.fftpack.ifft(fft_convolution/fft_auto_child)) #Roth window saved in self.convolution_spectrum
     assert self.time_inacc < sec/2, "This system clock cannot *possibly* be that inaccurate!"
     expected_tdiff = int((self.child_row['utcendtime']-self.parent_row['utcendtime'])*hz) #our initial guess for the location of the tdiff peak
     sample_inacc = int(self.time_inacc*hz) #around the guessed place of tdiff.
     if expected_tdiff-sample_inacc < 0: expected_tdiff = sample_inacc
     elif expected_tdiff+sample_inacc > sample_size: expected_tdiff = sample_size-sample_inacc
     cropped_convolution_spectrum = self.convolution_spectrum[expected_tdiff-sample_inacc:expected_tdiff+sample_inacc]
     #later measurements of tdiff will have a 0 point at expected_tdiff-sample_inacc and a total length of around 2*sample_inacc (may wrap around)
     tdiff = numpy.argmax(cropped_convolution_spectrum)
     tdiff += expected_tdiff-sample_inacc #offset for the real convolution_spectrum
     self.zscore = (self.convolution_spectrum[tdiff]-numpy.average(self.convolution_spectrum))/numpy.std(self.convolution_spectrum)
     #timespan = math.fabs(child_row['utcendtime'] - parent_row['utcendtime']) + sec
     self.expected_overlap = (float(sec) - 1.0*math.fabs(self.child_row['utcendtime']-self.parent_row['utcendtime']))*hz
     self.real_overlap = (float(sec) - 1.0*math.fabs(float(tdiff)/hz))*hz
     int_delay = int(numpy.copysign(numpy.floor(numpy.fabs(tdiff)), tdiff))
     self.abs_delay = int(abs(int_delay)) #always positive :)
     parent_signal, child_signal = self.parent_row['data'][self.abs_delay:], self.child_row['data'][0:len(self.child_row['data'])-self.abs_delay]
     h_child_length = len(child_signal)
     h_child_new_length = int(2**numpy.ceil(numpy.log2(h_child_length)))
     h_child_diff_length = h_child_new_length - h_child_length
     h_child_signal = scipy.fftpack.hilbert(numpy.append(child_signal, numpy.zeros(h_child_diff_length)))[0:h_child_length]
     self.cos_signal, self.sin_signal = evaluate("parent_signal*child_signal"), evaluate("h_child_signal*parent_signal")
コード例 #29
0
ファイル: tmp.py プロジェクト: bryangsmith/simple-mpm
def getgimp(X):
    s = []
    g = []
    for x in X:

        r = np.abs(x)
        l = .125
        h = 1.
        sgn = np.copysign(1.,x)		    
        if (r < l):
            S = 1. - (r*r+l*l)/(2.*h*l)
            G = -x/(h*l)
        elif (r < h-l):
            S = 1. - r/h
            G = -sgn/h
        elif (r < h+l):
            S = (h+l-r)*(h+l-r) / (4.*h*l)
            G = (h+l-r) / (-2.*sgn*h*l)
        else:
            S = 0.
            G = 0.
        s.append(S)
        g.append(G)
            
    S = np.array(s)
    G = np.array(g)
    return (S,G)    
コード例 #30
0
ファイル: orbits_py.py プロジェクト: hpparvi/PyTransit
def z_ip_s(t, t0, p, a, i, e, w, es, ms, tae):
    Ma = mean_anomaly(t, t0, p, e, w)
    if e < 0.01:
        Ta = Ma
    else:
        de = es[1] - es[0]
        dm = ms[1] - ms[0]

        ie = int(floor(e / de))
        ae = (e - de * ie) / de

        if Ma < pi:
            x = Ma
            s = 1.
        else:
            x = TWO_PI - Ma
            s = -1.

        im = int(floor(x / dm))
        am = (x - im * dm) / dm

        Ta = (tae[ie, im] * (1.0 - ae) * (1.0 - am)
              + tae[ie + 1, im] * ae * (1.0 - am)
              + tae[ie, im + 1] * (1.0 - ae) * am
              + tae[ie + 1, im + 1] * ae * am)
        Ta = Ma + s * Ta

        if (Ta < 0.0):
            Ta = Ta + TWO_PI

    z = a * (1.0 - e ** 2) / (1.0 + e * cos(Ta)) * sqrt(1.0 - sin(w + Ta) ** 2 * sin(i) ** 2)
    z *= copysign(1.0, sin(w + Ta))
    return z
コード例 #31
0
def round_away_from_zero(data):
    result = np.copysign(.5, data)
    result += data
    np.trunc(result, out=result)
    return result.astype(MV_MAT_TYPE)
コード例 #32
0
        def householder_transformation(a):
            v = a / (a[0] + np.copysign(np.linalg.norm(a), a[0]))
            v[0] = 1

            return v, 2 / np.dot(v.T, v)
コード例 #33
0
 def __init__(self, asset, quantity, order_id=None):
     self.asset = asset
     self.quantity = quantity
     self.order_id = 1 if order_id is None else order_id
     self.direction = np.copysign(1, self.quantity)
コード例 #34
0
    pandas_udf(lambda s: np.tanh(s), DoubleType()),  # type: ignore
    "trunc":
    pandas_udf(lambda s: np.trunc(s), DoubleType()),  # type: ignore
})

binary_np_spark_mappings = OrderedDict({
    "arctan2":
    F.atan2,
    "bitwise_and":
    lambda c1, c2: c1.bitwiseAND(c2),
    "bitwise_or":
    lambda c1, c2: c1.bitwiseOR(c2),
    "bitwise_xor":
    lambda c1, c2: c1.bitwiseXOR(c2),
    "copysign":
    pandas_udf(lambda s1, s2: np.copysign(s1, s2),
               DoubleType()),  # type: ignore
    "float_power":
    pandas_udf(  # type: ignore
        lambda s1, s2: np.float_power(s1, s2), DoubleType()),
    "floor_divide":
    pandas_udf(  # type: ignore
        lambda s1, s2: np.floor_divide(s1, s2), DoubleType()),
    "fmax":
    pandas_udf(lambda s1, s2: np.fmax(s1, s2), DoubleType()),  # type: ignore
    "fmin":
    pandas_udf(lambda s1, s2: np.fmin(s1, s2), DoubleType()),  # type: ignore
    "fmod":
    pandas_udf(lambda s1, s2: np.fmod(s1, s2), DoubleType()),  # type: ignore
    "gcd":
    pandas_udf(lambda s1, s2: np.gcd(s1, s2), DoubleType()),  # type: ignore
コード例 #35
0
import argparse
from copy import deepcopy
import os
import sys

import scipy as sp
import matplotlib as mpl
if __name__ == "__main__": mpl.use('Agg')  # we need to do this right away
import numpy as np
from numpy import pi, floor, copysign, sqrt, mean
import matplotlib.pyplot as plt
from scipy import optimize, stats
from scipy.signal import sawtooth

sign = lambda x: copysign(1, x)


class Dot:
    "Simple class to hold an (x,y) pair."

    def __init__(self, xpos, ypos, perim):
        self.xpos = xpos
        self.ypos = ypos
        self.perim = perim

    def __repr__(self):
        return 'Dot(xpos=%f, ypos=%f, perim=%f)' % (self.xpos, self.ypos,
                                                    self.perim)

コード例 #36
0
ファイル: resonator.py プロジェクト: ydwu0810/gdshelpers
 def opposite_side_port_out(self):
     return self.port.parallel_offset(
         np.copysign(2 * self.radius +
                     self.vertical_race_length, self.opposite_gap) +
         self._offset + self._offset_opposite)
コード例 #37
0
def steffen_3d(
    v_in,
    z_in,
    z_out,
    z_min_surface,
    z_max_surface,
    lower_extrapolation_with_gradient=False,
    upper_extrapolation_with_gradient=False,
):
    """
    Performs Steffen interpolation on each individual column.
    Steffen, M. (1990). A simple method for monotonic interpolation
    in one dimension. Astronomy and Astrophysics, 239, 443.

    `z_min_surface` and `z_max_surface` define the minimum and maximum height
    outside of which the interpolated value will be set to nan (useful for not
    interpolating pressure into solid ground for example).
    `lower_extrapolation_with_gradient` and `upper_extrapolation_with_gradient`
    enables the use of one-sided gradient when extrapolating outside the range
    of `z_in`, otherwise the limit value of `v_in` is used by default
    """
    assert v_in.shape[1:] == z_min_surface.shape
    k_max = v_in.shape[0]
    j_max = v_in.shape[1]
    i_max = v_in.shape[2]
    k_max_output = z_out.shape[0]
    k_max_minus = k_max - 1
    linear_slope = np.empty((k_max))
    v_out = np.empty((k_max_output, j_max, i_max))
    for i in range(i_max):
        for j in range(j_max):
            # first point
            delta_lower = z_in[1, j, i] - z_in[0, j, i]
            delta_upper = z_in[2, j, i] - z_in[1, j, i]
            if delta_lower < 0:
                raise Exception("Non-montonic increase in z_in")
            if delta_upper < 0:
                raise Exception("Non-montonic increase in z_in")
            slope_lower = (v_in[1, j, i] - v_in[0, j, i]) / delta_lower
            slope_upper = (v_in[2, j, i] - v_in[1, j, i]) / delta_upper

            weighted_slope = slope_lower * (
                1 + delta_lower /
                (delta_lower + delta_upper)) - slope_upper * delta_lower / (
                    delta_lower + delta_upper)
            if weighted_slope * slope_lower <= 0.0:
                linear_slope[0] = 0.0
            elif np.abs(weighted_slope) > 2 * np.abs(slope_lower):
                linear_slope[0] = 2.0 * slope_lower
            else:
                linear_slope[0] = weighted_slope

            # intermediate points
            for k in range(1, k_max_minus):
                delta_lower = z_in[k, j, i] - z_in[k - 1, j, i]
                delta_upper = z_in[k + 1, j, i] - z_in[k, j, i]
                slope_lower = (v_in[k, j, i] - v_in[k - 1, j, i]) / delta_lower
                slope_upper = (v_in[k + 1, j, i] - v_in[k, j, i]) / delta_upper
                weighted_slope = (slope_lower * delta_upper + slope_upper *
                                  delta_lower) / (delta_lower + delta_upper)

                if slope_lower * slope_upper <= 0.0:
                    linear_slope[k] = 0.0
                elif np.abs(weighted_slope) > 2.0 * np.abs(slope_lower):
                    linear_slope[k] = np.copysign(2.0, slope_lower) * min(
                        np.abs(slope_lower), np.abs(slope_upper))
                elif np.abs(weighted_slope) > 2.0 * np.abs(slope_upper):
                    linear_slope[k] = np.copysign(2.0, slope_lower) * min(
                        np.abs(slope_lower), np.abs(slope_upper))
                else:
                    linear_slope[k] = weighted_slope

            # last point
            delta_lower = z_in[k_max_minus - 1, j, i] - z_in[k_max_minus - 2,
                                                             j, i]
            delta_upper = z_in[k_max_minus, j, i] - z_in[k_max_minus - 1, j, i]
            slope_lower = (v_in[k_max_minus - 1, j, i] -
                           v_in[k_max_minus - 2, j, i]) / delta_lower
            slope_upper = (v_in[k_max_minus, j, i] -
                           v_in[k_max_minus - 1, j, i]) / delta_upper
            weighted_slope = slope_upper * (
                1 + delta_upper /
                (delta_upper + delta_lower)) - slope_lower * delta_upper / (
                    delta_upper + delta_lower)
            if weighted_slope * slope_upper <= 0.0:
                linear_slope[k_max_minus] = 0.0
            elif np.abs(weighted_slope) > 2.0 * np.abs(slope_upper):
                linear_slope[k_max_minus] = 2.0 * slope_upper
            else:
                linear_slope[k_max_minus] = weighted_slope

            # loop over output points
            k_temp = 0
            for k_out in range(k_max_output):
                while (k_temp < k_max) and (z_in[k_temp, j, i] < z_out[k_out]):
                    k_temp = k_temp + 1
                if 0 < k_temp < k_max:
                    k_high = k_temp
                    k_low = k_high - 1
                    delta = z_in[k_high, j, i] - z_in[k_low, j, i]
                    slope = (v_in[k_high, j, i] - v_in[k_low, j, i]) / delta
                    a = (linear_slope[k_low] + linear_slope[k_high] -
                         2 * slope) / (delta * delta)
                    b = (3 * slope - 2 * linear_slope[k_low] -
                         linear_slope[k_high]) / delta
                    c = linear_slope[k_low]
                    d = v_in[k_low, j, i]
                    t_1 = z_out[k_out] - z_in[k_low, j, i]
                    t_2 = t_1 * t_1
                    t_3 = t_2 * t_1
                    v_out[k_out, j, i] = a * t_3 + b * t_2 + c * t_1 + d
                elif (k_temp == 0) and (z_out[k_out] >= z_min_surface[j, i]):
                    if lower_extrapolation_with_gradient:
                        v_out[k_out, j,
                              i] = v_in[0, j, i] + linear_slope[0] * (
                                  z_out[k_out] - z_in[0, j, i])
                    else:
                        v_out[k_out, j, i] = v_in[0, j, i]
                elif (k_temp
                      == k_max) and (z_out[k_out] <= z_max_surface[j, i]):
                    if upper_extrapolation_with_gradient:
                        v_out[k_out, j, i] = v_in[
                            k_max - 1, j, i] + linear_slope[k_max - 1] * (
                                z_out[k_out] - z_in[k_max - 1, j, i])
                    else:
                        v_out[k_out, j, i] = v_in[k_max - 1, j, i]
                else:
                    v_out[k_out, j, i] = np.nan
    return v_out
コード例 #38
0
def prepare_data(data, window, STATE):
    """
        Firstly, data should be 'trimmed' to exclude any data points at which the
        robot was not being commanded to do anything.

        Secondly, robot acceleration should be calculated from robot velocity and time.
        We have found it effective to do this by taking the slope of the secant line
        of velocity over a 60ms (3 standard loop iterations) window.

        Thirdly, data from the quasi-static test should be trimmed to exclude the
        initial period in which the robot is not moving due to static friction
        Fourthly, data from the step-voltage acceleration tests must be trimmed to
        remove the initial 'ramp-up' period that exists due to motor inductance; this
        can be done by simply removing all data points before maximum acceleration is
        reached.

        Finally, the data can be analyzed: pool your trimmed data into four data sets
        - one for each side of the robot (left or right) and each direction (forwards
        or backwards).

        For each set, run a linear regression of voltage seen at the motor
        (or battery voltage if you do not have Talon SRXs) versus velocity and
        acceleration.

        Voltage should be in units of volts, velocity in units of feet per second,
        and acceleration in units of feet per second squared.

        Each data pool will then yield three parameters -
        intercept, Kv (the regression coefficient of velocity), and Ka (the regression
        coefficient of acceleration).
    """

    # ensure voltage sign matches velocity sign

    for x in JSON_DATA_KEYS:
        data[x][L_VOLTS_COL] = np.copysign(data[x][L_VOLTS_COL],
                                           data[x][L_ENCODER_V_COL])
        data[x][R_VOLTS_COL] = np.copysign(data[x][R_VOLTS_COL],
                                           data[x][R_ENCODER_V_COL])

    # trim quasi data before computing acceleration
    sf_trim = trim_quasi_testdata(data["slow-forward"], STATE)
    sb_trim = trim_quasi_testdata(data["slow-backward"], STATE)

    if sf_trim is None or sb_trim is None:
        return [None] * 8

    sf_l, sf_r = compute_accel(sf_trim, window)
    sb_l, sb_r = compute_accel(sb_trim, window)

    if sf_l is None or sf_r is None or sb_l is None or sb_r is None:
        return [None] * 8

    # trim step data after computing acceleration
    ff_l, ff_r = compute_accel(data["fast-forward"], window)
    fb_l, fb_r = compute_accel(data["fast-backward"], window)

    if ff_l is None or ff_r is None or fb_l is None or fb_r is None:
        return [None] * 8

    ff_l = trim_step_testdata(ff_l)
    ff_r = trim_step_testdata(ff_r)
    fb_l = trim_step_testdata(fb_l)
    fb_r = trim_step_testdata(fb_r)

    return sf_l, sb_l, ff_l, fb_l, sf_r, sb_r, ff_r, fb_r
コード例 #39
0
ファイル: hillas.py プロジェクト: ohhPaaRa/ctapipe
def hillas_parameters_3(pix_x, pix_y, image, recalculate_pixels=True):
    """Compute Hillas parameters for a given shower image.

    MP: probably better to use Whipple Reynolds et al 1993 paper:
    http://adsabs.harvard.edu/abs/1993ApJ...404..206R
    which should be the same as one of my ICRC 1991 papers and my thesis.

    Parameters
    ----------
    pix_x : array_like
        Pixel x-coordinate
    pix_y : array_like
        Pixel y-coordinate
    image : array_like
        Pixel values corresponding
    recalculate_pixels : Boolean (default True)
        Recalculate the pixel higher multiples (e.g., if pixels move (!) or pixel list changes between calls)

    Returns
    -------
    hillas_parameters : `MomentParameters`
    """

    if type(pix_x) == Quantity:
        unit = pix_x.unit
        assert pix_x.unit == pix_y.unit
    else:
        unit = 1.0

    pix_x = Quantity(np.asanyarray(pix_x, dtype=np.float64)).value
    pix_y = Quantity(np.asanyarray(pix_y, dtype=np.float64)).value

    # make sure they are numpy arrays so we can use numpy operations
    #pix_x = np.asanyarray(pix_x)
    #pix_y = np.asanyarray(pix_y)
    image = np.asanyarray(image, dtype=np.float64)

    assert pix_x.shape == image.shape
    assert pix_y.shape == image.shape

    # Code to interface with historic version
    wxdeg = pix_x
    wydeg = pix_y
    event = image

    # Code below is from the historical Whipple routine, with original comments
    # MJL is Mark Lang, MP is Michael Punch, GV is Giuseppe Vacanti, CA is Carl Akerlof, RCL is Dick Lamb,

    # Translated from ForTran to c with "fable": https://github.com/ctessum/fable-go
    # and from c to Python with "cpp2python:  https://github.com/andreikop/cpp2python , then edited by hand
    # C***********************************************************************
    # C                              HILLAKPAR                               *
    # C***********************************************************************
    # C-- This version also calculates the asymmetry of the image.
    # C-- Use of Akerlof Azwidth (Akwidth?) implemented MP 910112
    # C-- Simpler Miss formula suggested CA, MP, 901101
    # C-- Simpler Width and Length formulae suggested CA, 901017
    # C-- Yet another little bug fixed by MP 900418- Generalize the case of
    # C--      the horizontal line.
    # C-- Bug fixed by RCL 900307-The case of the horizontal line image was
    # C--     never considered.
    # C-- Bug fixed by GV 900215
    # C** This version takes events in WHIPPLE format and parameterises them.
    # C**    M. Punch ,900105
    # C-- G. Vacanti introduces the common statement: coordinates are
    # C-- computed only in the main program.
    # C-- Modified by M. Punch to make it faster April, 1989
    # C-- mjl 10 dec 87
    # C--
    # -- routine to calculate the six hillas iarameters

    sumsig, sumxsig, sumysig, sumx2sig, sumy2sig, sumxysig, sumx3sig, sumx2ysig, sumxy2sig, sumy3sig = np.zeros(
        10)

    for i in range(np.size(event)):
        if event[i] != 0.0:
            wxbyev = wxdeg[i] * event[i]
            wybyev = wydeg[i] * event[i]
            sumsig += event[i]
            sumxsig += wxbyev
            sumx2sig += wxdeg[i] * wxbyev
            sumysig += wybyev
            sumy2sig += wydeg[i] * wybyev
            sumxysig += wxdeg[i] * wybyev
            sumx3sig += wxdeg[i] * wxdeg[i] * wxbyev
            sumx2ysig += wxdeg[i] * wxdeg[i] * wybyev
            sumxy2sig += wxdeg[i] * wydeg[i] * wybyev
            sumy3sig += wydeg[i] * wydeg[i] * wybyev

    if sumsig == 0.0:
        raise (HillasParameterizationError(
            "Empty pixels! Cannot calculate image parameters. Exiting..."))

    xm = sumxsig / sumsig
    x2m = sumx2sig / sumsig
    ym = sumysig / sumsig
    y2m = sumy2sig / sumsig
    xym = sumxysig / sumsig

    xm2 = xm * xm
    ym2 = ym * ym
    xmym = xm * ym

    vx2 = x2m - xm2
    vy2 = y2m - ym2
    vxy = xym - xmym

    x3m = sumx3sig / sumsig
    x2ym = sumx2ysig / sumsig
    xy2m = sumxy2sig / sumsig
    y3m = sumy3sig / sumsig

    vx3 = x3m - 3.0 * xm * x2m + 2.0 * xm2 * xm
    vx2y = x2ym - x2m * ym - 2.0 * xym * xm + 2.0 * xm2 * ym
    vxy2 = xy2m - y2m * xm - 2.0 * xym * ym + 2.0 * xm * ym2
    vy3 = y3m - 3.0 * ym * y2m + 2.0 * ym2 * ym

    d = vy2 - vx2
    dist = np.sqrt(xm2 + ym2)
    phi = np.arctan2(ym, xm)

    # -- simpler formulae for length & width suggested CA 901019
    z = np.sqrt(d * d + 4.0 * vxy * vxy)
    length = np.sqrt((vx2 + vy2 + z) / 2.0)
    width = np.sqrt((vy2 + vx2 - z) / 2.0)

    # -- simpler formula for miss introduced CA, 901101
    # -- revised MP 910112
    if z == 0.0:
        miss = dist
    else:
        uu = 1 + d / z
        vv = 2 - uu
        miss = np.sqrt((uu * xm2 + vv * ym2) / 2.0 - xmym * (2.0 * vxy / z))

    # Code to de-interface with historical code
    size = sumsig
    m_x = xm
    m_y = ym
    length = length
    width = width
    r = dist

    psi = np.arctan2((d + z) * ym + 2.0 * vxy * xm,
                     2.0 * vxy * ym - (d - z) * xm)
    cpsi = np.cos(psi)
    spsi = np.sin(psi)

    # -- Asymmetry
    if length == 0.0:
        asymm = 0.0
    else:
        asymm = (vx3 * np.power(cpsi, 3) +
                 3.0 * vx2y * spsi * np.power(cpsi, 2) +
                 3.0 * vxy2 * cpsi * np.power(spsi, 2) +
                 vy3 * np.power(spsi, 3))
        asymm = np.copysign(np.exp(np.log(np.abs(asymm)) / 3.0),
                            asymm) / length

    # # -- Akerlof azwidth now used, 910112
    # d = y2m - x2m
    # z = np.sqrt(d * d + 4 * xym * xym)
    # azwidth = np.sqrt((x2m + y2m - z) / 2.0)
    #
    # isize = int(sumsig)

    # Code to de-interface with historical code
    skewness = asymm * asymm * asymm
    kurtosis = np.nan

    return MomentParameters(size=size,
                            cen_x=m_x * unit,
                            cen_y=m_y * unit,
                            length=length * unit,
                            width=width * unit,
                            r=r * unit,
                            phi=Angle(phi * u.rad),
                            psi=Angle(psi * u.rad),
                            miss=miss * unit,
                            skewness=skewness,
                            kurtosis=kurtosis)
コード例 #40
0
ファイル: numpy_compat.py プロジェクト: zimaxeg/koalas
    F.pandas_udf(lambda s: np.tanh(s), DoubleType()),
    "trunc":
    F.pandas_udf(lambda s: np.trunc(s), DoubleType()),
})

binary_np_spark_mappings = OrderedDict({
    "arctan2":
    F.atan2,
    "bitwise_and":
    lambda c1, c2: c1.bitwiseAND(c2),
    "bitwise_or":
    lambda c1, c2: c1.bitwiseOR(c2),
    "bitwise_xor":
    lambda c1, c2: c1.bitwiseXOR(c2),
    "copysign":
    F.pandas_udf(lambda s1, s2: np.copysign(s1, s2), DoubleType()),
    "float_power":
    F.pandas_udf(lambda s1, s2: np.float_power(s1, s2), DoubleType()),
    "floor_divide":
    F.pandas_udf(lambda s1, s2: np.floor_divide(s1, s2), DoubleType()),
    "fmax":
    F.pandas_udf(lambda s1, s2: np.fmax(s1, s2), DoubleType()),
    "fmin":
    F.pandas_udf(lambda s1, s2: np.fmin(s1, s2), DoubleType()),
    "fmod":
    F.pandas_udf(lambda s1, s2: np.fmod(s1, s2), DoubleType()),
    "gcd":
    F.pandas_udf(lambda s1, s2: np.gcd(s1, s2), DoubleType()),
    "heaviside":
    F.pandas_udf(lambda s1, s2: np.heaviside(s1, s2), DoubleType()),
    "hypot":
コード例 #41
0
ファイル: resonator.py プロジェクト: ydwu0810/gdshelpers
 def center_coordinates(self):
     return self._origin_port.longitudinal_offset(
         self.race_length / 2.).parallel_offset(
             self._offset +
             np.copysign(self.radius +
                         0.5 * self.vertical_race_length, self.gap)).origin
コード例 #42
0
ファイル: resonator.py プロジェクト: ydwu0810/gdshelpers
 def opposite_side_port_in(self):
     return self._origin_port.parallel_offset(
         np.copysign(2 * self.radius +
                     self.vertical_race_length, self.opposite_gap) +
         self._offset + self._offset_opposite).inverted_direction
コード例 #43
0
def copysign(value, sign):
    return np.copysign(value, sign)
コード例 #44
0
    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])
コード例 #45
0
def householder(a):
    u = a.copy()
    u[0] = u[0] + np.copysign(np.linalg.norm(a), a[0])
    return np.identity(len(u)) - ((2 * (u @ u.transpose())) /
                                  (u.transpose() @ u))
コード例 #46
0
ファイル: QEq.py プロジェクト: hopefulp/sandbox
    def calc_energy_and_potential(self, Jij=False, fill_Jii=True, core_pot=False, constrain=False, debug=None):
        """
        Compute energies and potentials for QEq_finish

        :Parameters:

            - Jij (boolean) : set to `True` to call the calc_Jmat method of the mme
            - fill_Jij (boolean) : set to `True` to fill the diagonal elements of Jij
            - core_pot (boolean) : use core potentials
            - constrain (boolean) : constrain charge to Qtot (if "molconst on" is specified in the input a per molecule contraint is used)

        """
        #flag for the calculation of degrees of freedom for get_dof()
        if constrain:
            self.constraint = True
        # first compute the twocenter part with the MM engine
        if Jij:
            if self.recalc_Jij:
                self.timer.switch_to("CORE calc_Jmat")
                if core_pot:
                    self.E_ij, self.qpot_ij, self.Jij, self.core_qpot = self.pd.calc_Jmat(get_core_pot=True)
                    #print "DEBUG DEBUG DEBUG"
                    #print "E_ij from fortran code", self.E_ij
                    #print "Eval   ", self.pd.get_val_energy()
                    #print "Ecore  ", self.pd.get_core_energy()
                    #print "Ecore_val  ", self.pd.get_coreval_energy()
                    #print "Ecoreval from core_pot",  numpy.sum(self.core_qpot*self.q)
                    #print "Eij_val_only from qpot", numpy.sum(self.qpot_ij*self.q)
                else:
                    self.E_ij, self.qpot_ij, self.Jij = self.pd.calc_Jmat()
                self.Jij *= self.unit
                self.E_ij    *= self.unit
                self.qpot_ij *= self.unit
                self.recalc_Jij = False
                self.recalc_qpot = False
        else:
            if self.recalc_qpot:
                self.timer.switch_to("CORE calc_Jij")
                if core_pot:
                    self.E_ij, self.qpot_ij, self.core_qpot = self.pd.calc_coul_energy(get_core_pot=True)
                    #print "DEBUG DEBUG DEBUG"
                    #print "E_ij from fortran code", self.E_ij
                    #print "Eval   ", self.pd.get_val_energy()
                    #print "Ecore  ", self.pd.get_core_energy()
                    #print "Ecore_val  ", self.pd.get_coreval_energy()
                    #print "Ecoreval from core_pot",  numpy.sum(self.core_qpot*self.q)
                    #print "Eij_val_only from qpot", numpy.sum(self.qpot_ij*self.q)
                else:
                    self.E_ij_for, self.qpot_ij = self.pd.calc_coul_energy()
                    #print "DEBUG DEBUG DEBUG"
                    #print "E_ij from fortran code", self.E_ij_for
                    #print "Eij_val_only from qpot", 0.5*numpy.sum(self.qpot_ij*self.q)
                    # FIX this ... fortran gives us wrong E_ij ... on the second call. must be an initalization error.
                    #self.E_ij = 0.5*numpy.sum(self.qpot_ij*self.q)
                    self.E_ij = self.E_ij_for
                self.E_ij    *= self.unit
                self.qpot_ij *= self.unit
                self.recalc_qpot = False
        self.timer.switch_to("CORE calc qpot")
        # now add the one-center terms, note that following the original implementation the Jii is really 2*Jii
        # as we can add it directly (times the charge) to the potential
        # => this convention means we need to take it 0.5 for the energy
        qpot_ii = self.Jii*self.q
        self.qpot = self.En + qpot_ii + self.qpot_ij
        # add core_pot if core charges are used. Note: the flag core_pot triggers a recalc but if
        #     core charges are used we add it in any case .. so it needs to be generated in the first call
        if self.use_core_charge:
            self.qpot += self.core_qpot
        self.E_ii = numpy.sum(self.q*(self.En + 0.5*qpot_ii))
        if self.limit_q:
            q_large = numpy.clip(numpy.fabs(self.q)-self.q_thresh, 0.0, 1.0e6)
            q_large2 = q_large*q_large
            qpot_ii3 = numpy.copysign(3.0*self.Jij3*q_large2, self.q)
            self.qpot += qpot_ii3
            self.E_ii3 = numpy.sum(self.Jij3*q_large*q_large2)
            self.E_ii += self.E_ii3
        self.E    = self.E_ii+self.E_ij
        if debug:
            self.pprint("DEBUG This is QEq calc_energy_force! called from %s \n Eii = %12.6f Eij = %12.6f E = %12.6f" % (debug, self.E_ii, self.E_ij, self.E))
        if Jij:
            if fill_Jii:
                for i in xrange(self.natoms):
                    self.Jij[i,i] = self.Jii[i]
        # charge conservation constraint
        # NOTE: this is currently terribly non-parrallel
        # could be done in two loops first summing up and then correcting
        # with a allreduce sum inbetween.
        if constrain:
            self.timer.switch_to("CORE constrain")
            if self.molconst:
                #for m in self.pd.molecules.mlist:
                #    molpot = self.qpot[m.matoms]
                #    tot_mpot = molpot.sum()
                #    molpot -= tot_mpot/m.natoms
                #    self.qpot[m.matoms] = molpot[:]
                # NOTE this is a bit of a hack ... the fortran constrain is private to QEq, but I did not
                #      want to have another module for it, so i put it into the coulomb module of pydlpoly ... so this is not a "generic mme"
                #      interface any more
                self.pd.dlp_coul.constrain_qpot_permol(self.idnode, self.nodes, self.qpot, self.natoms,
                                                    self.mol_pot, self.pd.molecules.nmolecules, self.mol_natoms)
            else:
                # constrain for the total system
                tot_pot = numpy.sum(self.qpot)
                self.qpot -= tot_pot/self.natoms

        #NEWNEW
        if self.acks2:
            self.calc_acks2_X()
            self.calc_acks2_u()
            self.E += self.calc_acks2_energy(self.u)
            self.qpot += self.u

        if self.exclude:
            for i in self.exclude:
                self.qpot[self.pd.molecules.mlist[i].matoms]=0
        #self.pprint("###Forces from calc_energy_and_potential###")
#        self.pprint("Identical with qpot sh, only here to show initial lbfgs forces")
        #self.pprint(self.qpot_ij)
        #self.pprint(self.qpot)
#        self.print_charges()
        return self.E
コード例 #47
0
 def round(x):
     val = np.trunc(x + np.copysign(0.5, x))
     return int(val)
コード例 #48
0
def eval_quad_z_s(z: float, k: float, u: ndarray):
    """Evaluates the transit model for scalar normalized distance.

    Parameters
    ----------
    z: float
        Normalized distance
    k: float
        Planet-star radius ratio
    u: 1D array
        Limb darkening coefficients

    Returns
    -------
    Transit model evaluated at `z`.

    """
    if abs(k - 0.5) < 1.0e-4:
        k = 0.5

    k2 = k**2
    omega = 1.0 - u[0] / 3.0 - u[1] / 6.0

    if abs(z - k) < 1e-6:
        z += 1e-6

    # The source is unocculted
    if z > 1.0 + k or (copysign(1, z) < 0.0):
        return 1.0

    # The source is completely occulted
    elif (k >= 1.0 and z <= k - 1.0):
        return 0.0

    z2 = z**2
    x1 = (k - z)**2
    x2 = (k + z)**2
    x3 = k**2 - z**2

    # LE
    # --
    # Case I: The occulting object fully inside the disk of the source
    if z <= 1.0 - k:
        le = k2

    # Case II: ingress and egress
    elif z >= abs(1.0 - k) and z <= 1.0 + k:
        kap1 = arccos(min((1.0 - k2 + z2) / (2.0 * z), 1.0))
        kap0 = arccos(min((k2 + z2 - 1.0) / (2.0 * k * z), 1.0))
        le = k2 * kap0 + kap1
        le = (le - 0.5 * sqrt(max(4.0 * z2 -
                                  (1.0 + z2 - k2)**2, 0.0))) * INV_PI

    # LD and ED
    # ---------
    is_edge_at_origin = abs(z - k) < 1.e-4 * (z + k)
    is_full_transit = k <= 1.0 and z < (1.0 - k)

    # Case 0: The edge of the occulting object lies at the origin
    if is_edge_at_origin:
        if (k == 0.5):
            ld = 1.0 / 3.0 - 4.0 * INV_PI / 9.0
            ed = 3.0 / 32.0

        elif (z > 0.5):
            q = 0.50 / k
            Kk = ellk(q)
            Ek = ellec(q)
            ld = 1.0 / 3.0 + 16.0 * k / 9.0 * INV_PI * (
                2.0 * k2 - 1.0) * Ek - (32.0 * k**4 - 20.0 * k2 +
                                        3.0) / 9.0 * INV_PI / k * Kk
            ed = 1.0 / 2.0 * INV_PI * (kap1 + k2 * (k2 + 2.0 * z2) * kap0 -
                                       (1.0 + 5.0 * k2 + z2) / 4.0 * sqrt(
                                           (1.0 - x1) * (x2 - 1.0)))

        elif (z < 0.5):
            q = 2.0 * k
            Kk = ellk(q)
            Ek = ellec(q)
            ld = 1.0 / 3.0 + 2.0 / 9.0 * INV_PI * (4.0 *
                                                   (2.0 * k2 - 1.0) * Ek +
                                                   (1.0 - 4.0 * k2) * Kk)
            ed = k2 / 2.0 * (k2 + 2.0 * z2)
    else:
        # Case I: The occulting object fully inside the disk of the source
        if is_full_transit:
            q = sqrt((x2 - x1) / (1.0 - x1))
            Kk = ellk(q)
            Ek = ellec(q)
            n = x2 / x1 - 1.0
            Pk = ellpicb(n, q)
            ld = 2.0 / 9.0 * INV_PI / sqrt(1.0 - x1) * (
                (1.0 - 5.0 * z2 + k2 + x3 * x3) * Kk + (1.0 - x1) *
                (z2 + 7.0 * k2 - 4.0) * Ek - 3.0 * x3 / x1 * Pk)
            if (z < k):
                ld = ld + 2.0 / 3.0
            if (abs(k + z - 1.0) < 1.e-4):
                ld = 2.0 / 3.0 * INV_PI * arccos(
                    1.0 - 2.0 * k) - 4.0 / 9.0 * INV_PI * sqrt(
                        k * (1.0 - k)) * (3.0 + 2.0 * k - 8.0 * k2)
            ed = k2 / 2.0 * (k2 + 2.0 * z2)

        # Case II: ingress and egress
        else:
            q = sqrt((1.0 - (k - z)**2) / 4.0 / z / k)
            Kk = ellk(q)
            Ek = ellec(q)
            n = 1.0 / x1 - 1.0
            Pk = ellpicb(n, q)
            ld = 1.0 / 9.0 * INV_PI / sqrt(k * z) * (
                ((1.0 - x2) * (2.0 * x2 + x1 - 3.0) - 3.0 * x3 *
                 (x2 - 2.0)) * Kk + 4.0 * k * z *
                (z2 + 7.0 * k2 - 4.0) * Ek - 3.0 * x3 / x1 * Pk)
            if (z < k):
                ld = ld + 2.0 / 3.0
            ed = 1.0 / 2.0 * INV_PI * (kap1 + k2 * (k2 + 2.0 * z2) * kap0 -
                                       (1.0 + 5.0 * k2 + z2) / 4.0 * sqrt(
                                           (1.0 - x1) * (x2 - 1.0)))

    flux = 1.0 - ((1.0 - u[0] - 2.0 * u[1]) * le +
                  (u[0] + 2.0 * u[1]) * ld + u[1] * ed) / omega
    return flux
コード例 #49
0
ファイル: interface.py プロジェクト: ahazra/pyro2
def states(a, ng, idir):
    r"""
    Predict the cell-centered state to the edges in one-dimension using the
    reconstructed, limited slopes. We use a fourth-order Godunov method.

    Our convention here is that:

        ``al[i,j]``   will be :math:`al_{i-1/2,j}`,

        ``al[i+1,j]`` will be :math:`al_{i+1/2,j}`.

    Parameters
    ----------
    a : ndarray
        The cell-centered state.
    ng : int
        The number of ghost cells
    idir : int
        Are we predicting to the edges in the x-direction (1) or y-direction (2)?

    Returns
    -------
    out : ndarray, ndarray
        The state predicted to the left and right edges.
    """

    qx, qy = a.shape

    al = np.zeros((qx, qy))
    ar = np.zeros((qx, qy))

    a_int = np.zeros((qx, qy))
    dafm = np.zeros((qx, qy))
    dafp = np.zeros((qx, qy))
    d2af = np.zeros((qx, qy))
    d2ac = np.zeros((qx, qy))
    d3a = np.zeros((qx, qy))

    C2 = 1.25
    C3 = 0.1

    nx = qx - 2 * ng
    ny = qy - 2 * ng
    ilo = ng
    ihi = ng + nx
    jlo = ng
    jhi = ng + ny

    # we need interface values on all faces of the domain
    if (idir == 1):

        for i in range(ilo - 2, ihi + 3):
            for j in range(jlo - 1, jhi + 1):

                # interpolate to the edges
                a_int[i, j] = (7.0 / 12.0) * (a[i - 1, j] + a[i, j]) - \
                    (1.0 / 12.0) * (a[i - 2, j] + a[i + 1, j])

                al[i, j] = a_int[i, j]
                ar[i, j] = a_int[i, j]

        for i in range(ilo - 2, ihi + 3):
            for j in range(jlo - 1, jhi + 1):
                # these live on cell-centers
                dafm[i, j] = a[i, j] - a_int[i, j]
                dafp[i, j] = a_int[i + 1, j] - a[i, j]

                # these live on cell-centers
                d2af[i,
                     j] = 6.0 * (a_int[i, j] - 2.0 * a[i, j] + a_int[i + 1, j])

        for i in range(ilo - 3, ihi + 3):
            for j in range(jlo - 1, jhi + 1):
                d2ac[i, j] = a[i - 1, j] - 2.0 * a[i, j] + a[i + 1, j]

        for i in range(ilo - 2, ihi + 3):
            for j in range(jlo - 1, jhi + 1):
                # this lives on the interface
                d3a[i, j] = d2ac[i, j] - d2ac[i - 1, j]

        # this is a look over cell centers, affecting
        # i-1/2,R and i+1/2,L
        for i in range(ilo - 1, ihi + 1):
            for j in range(jlo - 1, jhi + 1):

                # limit? MC Eq. 24 and 25
                if (dafm[i, j] * dafp[i, j] <= 0.0 or (a[i, j] - a[i - 2, j]) *
                    (a[i + 2, j] - a[i, j]) <= 0.0):

                    # we are at an extrema

                    s = np.copysign(1.0, d2ac[i, j])
                    if (s == np.copysign(1.0, d2ac[i - 1, j])
                            and s == np.copysign(1.0, d2ac[i + 1, j])
                            and s == np.copysign(1.0, d2af[i, j])):
                        # MC Eq. 26
                        d2a_lim = s * min(
                            abs(d2af[i, j]), C2 * abs(d2ac[i - 1, j]),
                            C2 * abs(d2ac[i, j]), C2 * abs(d2ac[i + 1, j]))
                    else:
                        d2a_lim = 0.0

                    if (abs(d2af[i, j]) <= 1.e-12 *
                            max(abs(a[i - 2, j]), abs(a[i - 1, j]), abs(
                                a[i, j]), abs(a[i + 1, j]), abs(a[i + 2, j]))):
                        rho = 0.0
                    else:
                        # MC Eq. 27
                        rho = d2a_lim / d2af[i, j]

                    if (rho < 1.0 - 1.e-12):
                        # we may need to limit -- these quantities are at cell-centers
                        d3a_min = min(d3a[i - 1, j], d3a[i, j], d3a[i + 1, j],
                                      d3a[i + 2, j])
                        d3a_max = max(d3a[i - 1, j], d3a[i, j], d3a[i + 1, j],
                                      d3a[i + 2, j])

                        if (C3 * max(abs(d3a_min), abs(d3a_max)) <=
                            (d3a_max - d3a_min)):
                            # limit
                            if (dafm[i, j] * dafp[i, j] < 0.0):
                                # Eqs. 29, 30
                                ar[i, j] = a[i, j] - rho * \
                                    dafm[i, j]  # note: typo in Eq 29
                                al[i + 1, j] = a[i, j] + rho * dafp[i, j]
                            elif (abs(dafm[i, j]) >= 2.0 * abs(dafp[i, j])):
                                # Eq. 31
                                ar[i, j] = a[i, j] - 2.0 * \
                                    (1.0 - rho) * dafp[i, j] - rho * dafm[i, j]
                            elif (abs(dafp[i, j]) >= 2.0 * abs(dafm[i, j])):
                                # Eq. 32
                                al[i + 1, j] = a[i, j] + 2.0 * \
                                    (1.0 - rho) * dafm[i, j] + rho * dafp[i, j]

                else:
                    # if Eqs. 24 or 25 didn't hold we still may need to limit
                    if (abs(dafm[i, j]) >= 2.0 * abs(dafp[i, j])):
                        ar[i, j] = a[i, j] - 2.0 * dafp[i, j]

                    if (abs(dafp[i, j]) >= 2.0 * abs(dafm[i, j])):
                        al[i + 1, j] = a[i, j] + 2.0 * dafm[i, j]

    elif (idir == 2):

        for i in range(ilo - 1, ihi + 1):
            for j in range(jlo - 2, jhi + 3):

                # interpolate to the edges
                a_int[i, j] = (7.0 / 12.0) * (a[i, j - 1] + a[i, j]) - \
                    (1.0 / 12.0) * (a[i, j - 2] + a[i, j + 1])

                al[i, j] = a_int[i, j]
                ar[i, j] = a_int[i, j]

        for i in range(ilo - 1, ihi + 1):
            for j in range(jlo - 2, jhi + 3):
                # these live on cell-centers
                dafm[i, j] = a[i, j] - a_int[i, j]
                dafp[i, j] = a_int[i, j + 1] - a[i, j]

                # these live on cell-centers
                d2af[i,
                     j] = 6.0 * (a_int[i, j] - 2.0 * a[i, j] + a_int[i, j + 1])

        for i in range(ilo - 1, ihi + 1):
            for j in range(jlo - 3, jhi + 3):
                d2ac[i, j] = a[i, j - 1] - 2.0 * a[i, j] + a[i, j + 1]

        for i in range(ilo - 1, ihi + 1):
            for j in range(jlo - 2, jhi + 2):
                # this lives on the interface
                d3a[i, j] = d2ac[i, j] - d2ac[i, j - 1]

        # this is a look over cell centers, affecting
        # j-1/2,R and j+1/2,L
        for i in range(ilo - 1, ihi + 1):
            for j in range(jlo - 1, jhi + 1):

                # limit? MC Eq. 24 and 25
                if (dafm[i, j] * dafp[i, j] <= 0.0 or (a[i, j] - a[i, j - 2]) *
                    (a[i, j + 2] - a[i, j]) <= 0.0):

                    # we are at an extrema

                    s = np.copysign(1.0, d2ac[i, j])
                    if (s == np.copysign(1.0, d2ac[i, j - 1])
                            and s == np.copysign(1.0, d2ac[i, j + 1])
                            and s == np.copysign(1.0, d2af[i, j])):
                        # MC Eq. 26
                        d2a_lim = s * min(
                            abs(d2af[i, j]), C2 * abs(d2ac[i, j - 1]),
                            C2 * abs(d2ac[i, j]), C2 * abs(d2ac[i, j + 1]))
                    else:
                        d2a_lim = 0.0

                    if (abs(d2af[i, j]) <= 1.e-12 *
                            max(abs(a[i, j - 2]), abs(a[i, j - 1]), abs(
                                a[i, j]), abs(a[i, j + 1]), abs(a[i, j + 2]))):
                        rho = 0.0
                    else:
                        # MC Eq. 27
                        rho = d2a_lim / d2af[i, j]

                    if (rho < 1.0 - 1.e-12):
                        # we may need to limit -- these quantities are at cell-centers
                        d3a_min = min(d3a[i, j - 1], d3a[i, j], d3a[i, j + 1],
                                      d3a[i, j + 2])
                        d3a_max = max(d3a[i, j - 1], d3a[i, j], d3a[i, j + 1],
                                      d3a[i, j + 2])

                        if (C3 * max(abs(d3a_min), abs(d3a_max)) <=
                            (d3a_max - d3a_min)):
                            # limit
                            if (dafm[i, j] * dafp[i, j] < 0.0):
                                # Eqs. 29, 30
                                ar[i, j] = a[i, j] - rho * \
                                    dafm[i, j]  # note: typo in Eq 29
                                al[i, j + 1] = a[i, j] + rho * dafp[i, j]
                            elif (abs(dafm[i, j]) >= 2.0 * abs(dafp[i, j])):
                                # Eq. 31
                                ar[i, j] = a[i, j] - 2.0 * \
                                    (1.0 - rho) * dafp[i, j] - rho * dafm[i, j]
                            elif (abs(dafp[i, j]) >= 2.0 * abs(dafm[i, j])):
                                # Eq. 32
                                al[i, j + 1] = a[i, j] + 2.0 * \
                                    (1.0 - rho) * dafm[i, j] + rho * dafp[i, j]

                else:
                    # if Eqs. 24 or 25 didn't hold we still may need to limit
                    if (abs(dafm[i, j]) >= 2.0 * abs(dafp[i, j])):
                        ar[i, j] = a[i, j] - 2.0 * dafp[i, j]

                    if (abs(dafp[i, j]) >= 2.0 * abs(dafm[i, j])):
                        al[i, j + 1] = a[i, j] + 2.0 * dafm[i, j]

    return al, ar
コード例 #50
0
ファイル: mna_lib.py プロジェクト: scamisay/mna-tp1
def householder(a):
    v = a / (a[0] + np.copysign(np.linalg.norm(a), a[0]))
    v[0] = 1
    H = np.eye(a.shape[0])
    H -= (2 / np.dot(v, v)) * np.dot(v[:, None], v[None, :])
    return H
コード例 #51
0
ファイル: lax_reference.py プロジェクト: gnecula/jax
def round(x):
  return np.trunc(
    x + np.copysign(np.nextafter(np.array(.5, dtype=x.dtype),
                                 np.array(0., dtype=x.dtype),
                                 dtype=x.dtype), x)).astype(x.dtype)
コード例 #52
0
ファイル: hillas.py プロジェクト: ohhPaaRa/ctapipe
def hillas_parameters_4(pix_x, pix_y, image, recalculate_pixels=True):
    """Compute Hillas parameters for a given shower image.

    As for hillas_parameters_3 (old Whipple Fortran code), but more Pythonized

    MP: Parameters calculated as Whipple Reynolds et al 1993 paper:
    http://adsabs.harvard.edu/abs/1993ApJ...404..206R
    which should be the same as one of my ICRC 1991 papers and my thesis.

    Parameters
    ----------
    pix_x : array_like
        Pixel x-coordinate
    pix_y : array_like
        Pixel y-coordinate
    image : array_like
        Pixel values corresponding
    recalculate_pixels : Boolean (default True)
        Recalculate the pixel higher multiples (e.g., if pixels move (!) or pixel list changes between calls)

    Returns
    -------
    hillas_parameters : `MomentParameters`
    """

    if type(pix_x) == Quantity:
        unit = pix_x.unit
        assert pix_x.unit == pix_y.unit
    else:
        unit = 1.0
    # MP: Actually, I don't know why we need to strip the units... shouldn' the calculations all work with them?

    pix_x = Quantity(np.asanyarray(pix_x, dtype=np.float64)).value
    pix_y = Quantity(np.asanyarray(pix_y, dtype=np.float64)).value
    image = np.asanyarray(image, dtype=np.float64)
    assert pix_x.shape == image.shape
    assert pix_y.shape == image.shape

    (sumsig, sumxsig, sumysig, sumx2sig, sumy2sig, sumxysig, sumx3sig,
     sumx2ysig, sumxy2sig, sumy3sig) = np.zeros(10)

    # Call static_xy to initialize the "static variables"
    # Actually, would be nice to just call this if we know the pixel positions have changed
    static_xy(pix_x, pix_y, recalculate_pixels)

    sumsig = image.sum()
    sumxsig = (image * pix_x).sum()
    sumysig = (image * pix_y).sum()
    sumx2sig = (image * static_xy.pix_x2).sum()
    sumy2sig = (image * static_xy.pix_y2).sum()
    sumxysig = (image * static_xy.pix_xy).sum()

    sumx3sig = (image * static_xy.pix_x3).sum()
    sumx2ysig = (image * static_xy.pix_x2y).sum()
    sumxy2sig = (image * static_xy.pix_xy2).sum()
    sumy3sig = (image * static_xy.pix_y3).sum()

    sumx4sig = (image * static_xy.pix_x4).sum()
    sumx3ysig = (image * static_xy.pix_x3y).sum()
    sumx2y2sig = (image * static_xy.pix_x2y2).sum()
    sumxy3sig = (image * static_xy.pix_xy3).sum()
    sumy4sig = (image * static_xy.pix_y4).sum()

    if sumsig == 0.0:
        raise (HillasParameterizationError(
            "Empty pixels! Cannot calculate image parameters. Exiting..."))

    xm = sumxsig / sumsig
    ym = sumysig / sumsig
    x2m = sumx2sig / sumsig
    y2m = sumy2sig / sumsig
    xym = sumxysig / sumsig

    x3m = sumx3sig / sumsig
    x2ym = sumx2ysig / sumsig
    xy2m = sumxy2sig / sumsig
    y3m = sumy3sig / sumsig

    x4m = sumx4sig / sumsig
    x3ym = sumx3ysig / sumsig
    x2y2m = sumx2y2sig / sumsig
    xy3m = sumxy3sig / sumsig
    y4m = sumy4sig / sumsig

    # Doing this should be same as above, but its 4us slower !?
    #(xm, ym, x2m, y2m, xym, x3m, x2ym, xy2m, y3m) = \
    #    (sumxsig, sumysig, sumx2sig, sumy2sig, sumxysig, sumx3sig,
    # sumx2ysig, sumxy2sig, sumy3sig) / sumsig

    xm2 = xm * xm
    ym2 = ym * ym
    xmym = xm * ym

    vx2 = x2m - xm2
    vy2 = y2m - ym2
    vxy = xym - xmym

    vx3 = x3m - 3.0 * xm * x2m + 2.0 * xm2 * xm
    vx2y = x2ym - x2m * ym - 2.0 * xym * xm + 2.0 * xm2 * ym
    vxy2 = xy2m - y2m * xm - 2.0 * xym * ym + 2.0 * xm * ym2
    vy3 = y3m - 3.0 * ym * y2m + 2.0 * ym2 * ym

    d = vy2 - vx2
    dist = np.sqrt(xm2 +
                   ym2)  #could use hypot(xm,ym), but already have squares
    phi = np.arctan2(ym, xm)

    # -- simpler formulae for length & width suggested CA 901019
    z = np.hypot(d, 2.0 * vxy)
    length = np.sqrt((vx2 + vy2 + z) / 2.0)
    width = np.sqrt((vy2 + vx2 - z) / 2.0)

    # -- simpler formula for miss introduced CA, 901101
    # -- revised MP 910112
    if z == 0.0:
        miss = dist
    else:
        uu = 1 + d / z
        vv = 2 - uu
        miss = np.sqrt((uu * xm2 + vv * ym2) / 2.0 - xmym * (2.0 * vxy / z))

    #Change to faster caluclation of psi and avoid inaccuracy for hyp
    #psi = np.arctan2((d + z) * ym + 2.0 * vxy * xm, 2.0 *vxy * ym - (d - z) * xm)
    #hyp = np.sqrt(2 * z * (z + d))  #! should be simplification of sqrt((d+z)**2+(2*vxy)**2 ... but not accurate!
    #hyp = np.hypot(d + z,2 * vxy)
    #psi = np.arctan2(d + z, 2 * vxy)
    #cpsi = np.cos(psi)
    #spsi = np.sin(psi)
    tanpsi_numer = (d + z) * ym + 2.0 * vxy * xm
    tanpsi_denom = 2.0 * vxy * ym - (d - z) * xm
    psi = np.arctan2(tanpsi_numer, tanpsi_denom)

    # Code to de-interface with historical code
    size = sumsig
    m_x = xm
    m_y = ym
    length = length
    width = width
    r = dist
    psi = psi

    # Note, "skewness" is the same as the Whipple/MP "asymmetry^3", which is fine.
    # ... and also, Whipple/MP "asymmetry" * "length" = MAGIC "asymmetry"
    # ... so, MAGIC "asymmetry" = MAGIC "skewness"^(1/3) * "length"
    # I don't know what MAGIC's "asymmetry" is supposed to be.

    # -- Asymmetry and other higher moments
    if length != 0.0:
        vx4 = x4m - 4.0 * xm * x3m + 6.0 * xm2 * x2m - 3.0 * xm2 * xm2
        vx3y = x3ym - 3.0 * xm * x2ym + 3.0 * xm2 * xym - x3m * ym \
                  + 3.0 * x2m * xmym - 3.0 * xm2 * xm * ym
        vx2y2 = x2y2m - 2.0 * ym * x2ym + x2m * ym2 \
                   - 2.0 * xm * xy2m + 4.0 * xym * xmym + xm2 * y2m - 3.0 * xm2 * ym2
        vxy3 = xy3m - 3.0 * ym * xy2m + 3.0 * ym2 * xym - y3m * xm \
                  + 3.0 * y2m * xmym - 3.0 * ym2 * ym * xm
        vy4 = y4m - 4.0 * ym * y3m + 6.0 * ym2 * y2m - 3.0 * ym2 * ym2
        # print("vs 4th: x4, x3y, x2y2, xy3, y4", vx4, vx3y, vx2y2, vxy3, vy4)
        # print("cross check vx4",(image*(pix_x-xm)**4).sum()/sumsig)
        # print("cross check vx3y",(image*(pix_x-xm)**3*(pix_y-ym)).sum()/sumsig)
        # print("cross check vx2y2",(image*(pix_x-xm)**2*(pix_y-ym)**2).sum()/sumsig)
        # print("cross check vxy3",(image*(pix_x-xm)*(pix_y-ym)**3).sum()/sumsig)
        # print("cross check vy4",(image*(pix_y-ym)**4).sum()/sumsig)

        hyp = np.hypot(tanpsi_numer, tanpsi_denom)
        if hyp != 0.:
            cpsi = tanpsi_denom / hyp
            spsi = tanpsi_numer / hyp
        else:
            cpsi = 1.
            spsi = 0.

        cpsi2 = cpsi * cpsi
        spsi2 = spsi * spsi
        cspsi = cpsi * spsi

        sk3bylen3 = (vx3 * cpsi * cpsi2 + 3.0 * vx2y * cpsi2 * spsi +
                     3.0 * vxy2 * cpsi * spsi2 + vy3 * spsi * spsi2)
        asym = np.copysign(np.power(np.abs(sk3bylen3), 1. / 3.),
                           sk3bylen3) / length
        skewness = asym * asym * asym  # for MP's asym... (not for MAGIC asym!)

        # Kurtosis
        kurt = (vx4 * cpsi2 * cpsi2 + 4.0 * vx3y * cpsi2 * cspsi +
                6.0 * vx2y2 * cpsi2 * spsi2 + 4.0 * vxy3 * cspsi * spsi2 +
                vy4 * spsi2 * spsi2)
        kurtosis = kurt / (length * length * length * length)

    else:  # Skip Higher Moments
        asym = 0.0
        psi = 0.0
        skewness = 0.0
        kurtosis = 0.0

    # Azwidth not used anymore
    # # -- Akerlof azwidth now used, 910112
    # d = y2m - x2m
    # z = np.sqrt(d * d + 4 * xym * xym)
    # azwidth = np.sqrt((x2m + y2m - z) / 2.0)

    return MomentParameters(size=size,
                            cen_x=m_x * unit,
                            cen_y=m_y * unit,
                            length=length * unit,
                            width=width * unit,
                            r=r * unit,
                            phi=Angle(phi * u.rad),
                            psi=Angle(psi * u.rad),
                            miss=miss * unit,
                            skewness=skewness,
                            kurtosis=kurtosis)
コード例 #53
0
def steffen_1d_no_ep_time(
    input_data,
    input_levels,
    output_level_array,
):
    """Performs Steffen interpolation on one individual column for
    each time step.
    Steffen, M. (1990). A simple method for monotonic interpolation in
    one dimension. Astronomy and Astrophysics, 239, 443."""
    t_max = input_data.shape[0]
    k_max = input_data.shape[1]
    k_max_output = output_level_array.shape[0]
    k_max_minus = k_max - 1
    linear_slope = np.empty((k_max))
    output_data = np.empty((t_max, k_max_output))
    # first point
    delta_lower = input_levels[1] - input_levels[0]
    delta_upper = input_levels[2] - input_levels[1]
    if delta_lower < 0:
        raise Exception("Non-montonic increase in input_levels")
    if delta_upper < 0:
        raise Exception("Non-montonic increase in input_levels")
    for time_index in range(t_max):
        slope_lower = (input_data[time_index, 1] -
                       input_data[time_index, 0]) / delta_lower
        slope_upper = (input_data[time_index, 2] -
                       input_data[time_index, 1]) / delta_upper
        weighted_slope = slope_lower * (
            1 + delta_lower /
            (delta_lower + delta_upper)) - slope_upper * delta_lower / (
                delta_lower + delta_upper)
        if weighted_slope * slope_lower <= 0.0:
            linear_slope[0] = 0.0
        elif np.abs(weighted_slope) > 2 * np.abs(slope_lower):
            linear_slope[0] = 2.0 * slope_lower
        else:
            linear_slope[0] = weighted_slope

        # intermediate points
        for k in range(1, k_max_minus):
            delta_lower = input_levels[k] - input_levels[k - 1]
            delta_upper = input_levels[k + 1] - input_levels[k]
            slope_lower = (input_data[time_index, k] -
                           input_data[time_index, k - 1]) / delta_lower
            slope_upper = (input_data[time_index, k + 1] -
                           input_data[time_index, k]) / delta_upper
            weighted_slope = (slope_lower * delta_upper + slope_upper *
                              delta_lower) / (delta_lower + delta_upper)

            if slope_lower * slope_upper <= 0.0:
                linear_slope[k] = 0.0
            elif np.abs(weighted_slope) > 2.0 * np.abs(slope_lower):
                linear_slope[k] = np.copysign(2.0, slope_lower) * min(
                    np.abs(slope_lower), np.abs(slope_upper))
            elif np.abs(weighted_slope) > 2.0 * np.abs(slope_upper):
                linear_slope[k] = np.copysign(2.0, slope_lower) * min(
                    np.abs(slope_lower), np.abs(slope_upper))
            else:
                linear_slope[k] = weighted_slope

        # last point
        delta_lower = input_levels[k_max_minus -
                                   1] - input_levels[k_max_minus - 2]
        delta_upper = input_levels[k_max_minus] - input_levels[k_max_minus - 1]
        slope_lower = (input_data[time_index, k_max_minus - 1] -
                       input_data[time_index, k_max_minus - 2]) / delta_lower
        slope_upper = (input_data[time_index, k_max_minus] -
                       input_data[time_index, k_max_minus - 1]) / delta_upper
        weighted_slope = slope_upper * (
            1 + delta_upper /
            (delta_upper + delta_lower)) - slope_lower * delta_upper / (
                delta_upper + delta_lower)
        if weighted_slope * slope_upper <= 0.0:
            linear_slope[k_max_minus] = 0.0
        elif np.abs(weighted_slope) > 2.0 * np.abs(slope_upper):
            linear_slope[k_max_minus] = 2.0 * slope_upper
        else:
            linear_slope[k_max_minus] = weighted_slope

        # loop over output points
        k_temp = 0
        for k_out in range(k_max_output):
            while (k_temp < k_max) and (input_levels[k_temp] <
                                        output_level_array[k_out]):
                k_temp = k_temp + 1
            if 0 < k_temp < k_max:
                k_high = k_temp
                k_low = k_high - 1
                delta = input_levels[k_high] - input_levels[k_low]
                slope = (input_data[time_index, k_high] -
                         input_data[time_index, k_low]) / delta
                a = (linear_slope[k_low] + linear_slope[k_high] -
                     2 * slope) / (delta * delta)
                b = (3 * slope - 2 * linear_slope[k_low] -
                     linear_slope[k_high]) / delta
                c = linear_slope[k_low]
                d = input_data[time_index, k_low]
                t_1 = output_level_array[k_out] - input_levels[k_low]
                t_2 = t_1 * t_1
                t_3 = t_2 * t_1
                output_data[time_index,
                            k_out] = a * t_3 + b * t_2 + c * t_1 + d
            # Allow for small deviations in upper/lower levels
            elif (k_temp == 0) and (abs(output_level_array[k_out] -
                                        input_levels[k_temp]) < 1e-6):
                output_data[time_index, k_out] = input_data[time_index, 0]
            elif (k_temp == k_max) and (abs(output_level_array[k_out] -
                                            input_levels[k_temp]) < 1e-6):
                output_data[time_index, k_out] = input_data[time_index, k_max]
            else:
                output_data[time_index, k_out] = np.nan
    return output_data
コード例 #54
0
np.multiply(a,b)


# In[141]:

np.divide(a,b)


# In[142]:

np.power(a,np.abs(b))


# In[143]:

np.copysign(a,b)


# In[144]:

np.greater(a,b)
#大于


# In[145]:

np.greater_equal(a,b)
#大于等于


# In[146]:
コード例 #55
0
def get_avoidance_velocity(agent, collider, t, dt):
    """Get the smallest relative change in velocity between agent and collider
    that will get them onto the boundary of each other's velocity obstacle
    (VO), and thus avert collision."""

    # This is a summary of the explanation from the AVO paper.
    #
    # The set of all relative velocities that will cause a collision within
    # time tau is called the velocity obstacle (VO). If the relative velocity
    # is outside of the VO, no collision will happen for at least tau time.
    #
    # The VO for two moving disks is a circularly truncated triangle
    # (spherically truncated cone in 3D), with an imaginary apex at the
    # origin. It can be described by a union of disks:
    #
    # Define an open disk centered at p with radius r:
    # D(p, r) := {q | ||q - p|| < r}        (1)
    #
    # Two disks will collide at time t iff ||x + vt|| < r, where x is the
    # displacement, v is the relative velocity, and r is the sum of their
    # radii.
    #
    # Divide by t:  ||x/t + v|| < r/t,
    # Rearrange: ||v - (-x/t)|| < r/t.
    #
    # By (1), this is a disk D(-x/t, r/t), and it is the set of all velocities
    # that will cause a collision at time t.
    #
    # We can now define the VO for time tau as the union of all such disks
    # D(-x/t, r/t) for 0 < t <= tau.
    #
    # Note that the displacement and radius scale _inversely_ proportionally
    # to t, generating a line of disks of increasing radius starting at -x/t.
    # This is what gives the VO its cone shape. The _closest_ velocity disk is
    # at D(-x/tau, r/tau), and this truncates the VO.

    x = -(agent.position - collider.position)
    v = agent.velocity - collider.velocity
    r = agent.radius + collider.radius

    x_len_sq = norm_sq(x)

    if x_len_sq >= r * r:
        # We need to decide whether to project onto the disk truncating the VO
        # or onto the sides.
        #
        # The center of the truncating disk doesn't mark the line between
        # projecting onto the sides or the disk, since the sides are not
        # parallel to the displacement. We need to bring it a bit closer. How
        # much closer can be worked out by similar triangles. It works out
        # that the new point is at x/t cos(theta)^2, where theta is the angle
        # of the aperture (so sin^2(theta) = (r/||x||)^2).
        adjusted_center = x / t * (1 - (r * r) / x_len_sq)

        if dot(v - adjusted_center, adjusted_center) < 0:
            # v lies in the front part of the cone
            # print("front")
            # print("front", adjusted_center, x_len_sq, r, x, t)
            w = v - x / t
            u = normalized(w) * r / t - w
            n = normalized(w)
        else:  # v lies in the rest of the cone
            # print("sides")
            # Rotate x in the direction of v, to make it a side of the cone.
            # Then project v onto that, and calculate the difference.
            leg_len = sqrt(x_len_sq - r * r)
            # The sign of the sine determines which side to project on.
            sine = copysign(r, det((v, x)))
            rot = array(((leg_len, sine), (-sine, leg_len)))
            rotated_x = rot.dot(x) / x_len_sq
            n = perp(rotated_x)
            if sine < 0:
                # Need to flip the direction of the line to make the
                # half-plane point out of the cone.
                n = -n
            # print("rotated_x=%s" % rotated_x)
            u = rotated_x * dot(v, rotated_x) - v
            # print("u=%s" % u)
    else:
        # We're already intersecting. Pick the closest velocity to our
        # velocity that will get us out of the collision within the next
        # timestep.
        # print("intersecting")
        w = v - x / dt
        u = normalized(w) * r / dt - w
        n = normalized(w)
    return u, n
コード例 #56
0
Z/1/1
Z<Z>Z
'''

# 28、以下表达式的结果是什么
'''
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)

答:
nan
0
[-2.14748365e+09]
'''

# 29、如何让一个浮点类型数组里面的值全部取整?

# uniform(下限,上限,输出样本数)
Z = np.random.uniform(-10, +10, 10)
# copysign(A,B) 把B的符号给A
# ceil(num) 计算大于等于num的最小整数
print(np.copysign(np.ceil(np.abs(Z)), Z))

# 30、如何在两个数组之间找到相同的值
Z1 = np.random.randint(0, 10, 10)
print(Z1)
Z2 = np.random.randint(0, 10, 10)
print(Z2)
print(np.intersect1d(Z1, Z2))
コード例 #57
0
    def draw_ellipsoid(self, numPoints=20, a_temp=[0, 0], draw_sfObs=False):
        if self.d == 2:
            theta = np.linspace(-pi, pi, num=numPoints)
            resolution = numPoints  # Resolution of drawing #points

        else:
            numPoints = [numPoints, ceil(numPoints / 2)]
            theta, phi = np.meshgrid(np.linspace(-pi, pi, num=numPoints[0]),
                                     np.linspace(-pi / 2,
                                                 pi / 2,
                                                 num=numPoints[1]))  #
            numPoints = numPoints[0] * numPoints[1]
            resolution = numPoints  # Resolution of drawing #points
            theta = theta.T
            phi = phi.T

        #print('a_temp', sum(a_temp))
        #if sum(a_temp) != 0:
        #print('Not saving figure internaly.')

        # For an arbitrary shap, the next two lines are used to find the shape segment
        if hasattr(self, 'partition'):
            warnings.warn('Warning - partition no finished implementing')
            for i in range(self.partition.shape[0]):
                ind[i, :] = self.theta >= (
                    self.partition[i, 1]) & self.theta <= (self.partition[i,
                                                                          1])
                [i, ind] = max(ind)
        else:
            ind = 0

        #a = obs[n].a[:,ind]
        #p = obs[n].p[:,ind]

        # TODO -- add partition index
        if sum(a_temp) == 0:
            a = self.a
        else:
            #            import pdb; pdb.set_trace() ## DEBUG ##
            a = a_temp

        p = self.p[:]

        R = np.array(self.rotMatrix)

        x_obs = np.zeros((self.d, numPoints))

        if self.d == 2:
            x_obs[0, :] = a[0] * np.cos(theta)
            x_obs[1, :] = np.copysign(
                a[1], theta) * (1 - np.cos(theta)**(2 * p[0]))**(1. /
                                                                 (2. * p[1]))
        else:
            x_obs[0, :] = (a[0] * np.cos(phi) * np.cos(theta)).reshape((1, -1))
            x_obs[1, :] = (
                a[1] * np.copysign(1, theta) * np.cos(phi) *
                (1 - np.cos(theta)**(2 * p[0]))**(1. / (2. * p[1]))).reshape(
                    (1, -1))
            x_obs[2, :] = (a[2] * np.copysign(1, phi) *
                           (1 - (np.copysign(1, theta) * np.cos(phi) *
                                 (1 - 0**(2 * p[2]) - np.cos(theta)**
                                  (2 * p[0]))**(1 / (2**p[1])))**(2 * p[1]) -
                            (np.cos(phi) * np.cos(theta))**(2 * p[0]))
                           **(1 / (2 * p[2]))).reshape((1, -1))

        # TODO for outside function - only sf is returned, remove x_obs to speed up
        x_obs_sf = np.zeros((self.d, numPoints))
        if not hasattr(self, 'sf'):
            self.sf = 1

        if type(self.sf) == int or type(self.sf) == float:
            x_obs_sf = R @ (self.sf * x_obs) + np.tile(
                np.array([self.x0]).T, (1, numPoints))
        else:
            x_obs_sf = R @ (x_obs * np.tile(self.sf,
                                            (1, numPoints))) + np.tile(
                                                self.x0, (numPoints, 1)).T

        x_obs = R @ x_obs + np.tile(np.array([self.x0]).T, (1, numPoints))

        if sum(a_temp) == 0:
            self.x_obs = x_obs.T.tolist()
            self.x_obs_sf = x_obs_sf.T.tolist()
        else:
            return x_obs_sf
コード例 #58
0
 def test_copysign_scalar(self):
     assert np.copysign(3 * u.m, 1.) == 3. * u.m
     assert np.copysign(3 * u.m, 1. * u.s) == 3. * u.m
     assert np.copysign(3 * u.m, -1.) == -3. * u.m
     assert np.copysign(3 * u.m, -1. * u.s) == -3. * u.m
コード例 #59
0
from numpy import *
print(sum(range(5),-1)) # prints 10 (sum iterating over last column of the range)

Z**Z # returns array of each element raised to the power of itself
2 << Z >> 2 # returns array of (2 shifted z digits left, bitwise) shifted 2 digits right, bitwise
Z <- Z # returns array of whether each element is nonnegative
1j*Z # returns array of each element multiplied by i
Z/1/1 # returns the original array
Z<Z>Z # invalid

np.array(0) / np.array(0) # returns nan because 0 divided by 0 is undefined
np.array(0) // np.array(0) # returns 0
np.array([np.nan]).astype(int).astype(float) # returns array([maximum negative number])

to_round = np.random.uniform(-10,10,(10,10))
rounded = np.copysign(np.ceil(np.abs(to_round)),to_round)

set_A = np.random.randint(-10,10,(10,10))
set_B = np.random.randint(-10,10,(10,10))
common_values = np.intersect1d(set_A,set_B)

defaults = np.seterr(all="ignore")
worst_settings_possible = np.seterr(**defaults)

np.sqrt(-1) == np.emath.sqrt(-1) # false

today = np.datetime64('today')
yesterday = today - 1
tomorrow = today + 1

dates_in_july_2016 = np.arange(np.datetime64('2016-07','D'),np.datetime64('2016-08'))
コード例 #60
0
ファイル: hillas.py プロジェクト: ohhPaaRa/ctapipe
def hillas_parameters_2(pix_x, pix_y, image, recalculate_pixels=True):
    """Compute Hillas parameters for a given shower image.

    Alternate implementation of `hillas_parameters` ...
    in the end we'll just keep one, but we're using Hillas parameter
    computation as an example for performance checks.

    Parameters
    ----------
    pix_x : array_like
        Pixel x-coordinate
    pix_y : array_like
        Pixel y-coordinate
    image : array_like
        Pixel values corresponding
    recalculate_pixels : Boolean (default True)
        Recalculate the pixel higher multiples (e.g., if pixels move (!) or pixel list changes between calls)

    Returns
    -------
    hillas_parameters : `MomentParameters`
    """

    if type(pix_x) == Quantity:
        unit = pix_x.unit
        assert pix_x.unit == pix_y.unit
    else:
        unit = 1.0

    pix_x = Quantity(np.asanyarray(pix_x, dtype=np.float64)).value
    pix_y = Quantity(np.asanyarray(pix_y, dtype=np.float64)).value
    image = np.asanyarray(image)

    assert pix_x.shape == image.shape
    assert pix_y.shape == image.shape

    size = image.sum()

    if size == 0.0:
        raise (HillasParameterizationError(
            "Empty pixels! Cannot calculate image parameters. Exiting..."))

    #call static_xy to initialize the "static variables"
    #actually, would be nice to just call this if we know the pixel positions have changed
    static_pix(pix_x, pix_y, recalculate_pixels)

    # Compute image moments (done in a bit faster way, but putting all
    # into one 2D array, where each row will be summed to calculate a
    # moment) However, this doesn't avoid a temporary created for the
    # 2D array

    # momdata = np.row_stack([pix_x,
    #                         pix_y,
    #                         pix_x * pix_x,
    #                         pix_y * pix_y,
    #                         pix_x * pix_y]) * image
    momdata = static_pix.pixdata * image
    moms = momdata.sum(axis=1) / size
    momdataHO = static_pix.pixdataHO * image
    momsHO = momdataHO.sum(axis=1) / size

    # give the moms values comprehensible names
    xm, ym, x2m, xym, y2m = moms
    x3m, x2ym, xy2m, y3m, x4m, x3ym, x2y2m, xy3m, y4m = momsHO

    # intermediate variables (could be avoided if compiler which understands powers, etc)
    xm2 = xm * xm
    ym2 = ym * ym
    xmym = xm * ym

    # calculate variances

    vx2 = x2m - xm2
    vy2 = y2m - ym2
    vxy = xym - xmym
    vx3 = x3m - 3.0 * xm * x2m + 2.0 * xm2 * xm
    vx2y = x2ym - x2m * ym - 2.0 * xym * xm + 2.0 * xm2 * ym
    vxy2 = xy2m - y2m * xm - 2.0 * xym * ym + 2.0 * xm * ym2
    vy3 = y3m - 3.0 * ym * y2m + 2.0 * ym2 * ym

    # polar coordinates of centroid

    rr = np.sqrt(xm2 +
                 ym2)  # could use hypot(xm, ym), but already have squares
    phi = np.arctan2(ym, xm) * u.rad

    # common factors:

    dd = vy2 - vx2
    zz = np.hypot(
        dd, 2.0 *
        vxy)  # for simpler formulae for length & width suggested CA 901019

    # shower shape parameters

    length = np.sqrt((vx2 + vy2 + zz) / 2.0)
    width = np.sqrt((vx2 + vy2 - zz) / 2.0)
    # azwidth = np.sqrt(x2m + y2m - zz) #Hillas Azwidth not used anymore
    # d = y2m - x2m
    # z = np.sqrt(d * d + 4 * xym * xym)
    # akwidth = np.sqrt((x2m + y2m - z) / 2.0) # Akerlof azwidth (910112) not used anymore either

    # miss, simpler formula for miss introduced CA, 901101; revised MP 910112

    uu = 1.0 + dd / zz
    vv = 2.0 - uu
    miss = np.sqrt((uu * xm2 + vv * ym2) / 2.0 - xmym * 2.0 * vxy / zz)
    # maybe for case zz = 0, put miss = dist?

    # rotation angle of ellipse relative to centroid
    tanpsi_numer = (dd + zz) * ym + (2.0 * vxy * xm)
    tanpsi_denom = (2.0 * vxy * ym) - (dd - zz) * xm

    psi = (np.arctan2(tanpsi_numer, tanpsi_denom)) * u.rad

    # -- Asymmetry and other higher moments
    if length != 0.0:
        vx4 = x4m - 4.0 * xm * x3m + 6.0 * xm2 * x2m - 3.0 * xm2 * xm2
        vx3y = x3ym - 3.0 * xm * x2ym  + 3.0 * xm2 * xym - x3m * ym \
                    + 3.0 * x2m * xmym - 3.0 * xm2 * xmym
        vx2y2 = x2y2m - 2.0 * ym * x2ym + x2m * ym2 \
                      - 2.0 * xm * xy2m + 4.0 * xym * xmym + xm2 * y2m - 3.0 * xm2 * ym2
        vxy3 = xy3m - 3.0 * ym * xy2m  + 3.0 * ym2 * xym - y3m * xm \
                    + 3.0 * y2m * xmym - 3.0 * ym2 * xmym
        vy4 = y4m - 4.0 * ym * y3m + 6.0 * ym2 * y2m - 3.0 * ym2 * ym2

        hyp = np.hypot(tanpsi_numer, tanpsi_denom)
        if hyp != 0.:
            cpsi = tanpsi_denom / hyp
            spsi = tanpsi_numer / hyp
        else:
            cpsi = 1.
            spsi = 0.

        cpsi2 = cpsi * cpsi
        spsi2 = spsi * spsi
        cspsi = cpsi * spsi
        sk3bylen3 = (vx3 * cpsi * cpsi2 + 3.0 * vx2y * cpsi2 * spsi +
                     3.0 * vxy2 * cpsi * spsi2 + vy3 * spsi * spsi2)
        asym = np.copysign(np.power(np.abs(sk3bylen3), 1. / 3.),
                           sk3bylen3) / length
        skewness = asym * asym * asym  # for MP's asym... (not for MAGIC asym!)
        # Kurtosis
        kurt = (vx4 * cpsi2 * cpsi2 + 4.0 * vx3y * cpsi2 * cspsi +
                6.0 * vx2y2 * cpsi2 * spsi2 + 4.0 * vxy3 * cspsi * spsi2 +
                vy4 * spsi2 * spsi2)
        kurtosis = kurt / (length * length * length * length)
    else:  # Skip Higher Moments
        psi = 0.0 * u.rad
        skewness = 0.0
        kurtosis = 0.0
        asym = 0.0

    return MomentParameters(size=size,
                            cen_x=xm * unit,
                            cen_y=ym * unit,
                            length=length * unit,
                            width=width * unit,
                            r=rr * unit,
                            phi=Angle(phi),
                            psi=Angle(psi),
                            miss=miss * unit,
                            skewness=skewness,
                            kurtosis=kurtosis)