当前位置: 首页>>代码示例>>Python>>正文


Python units.s方法代码示例

本文整理汇总了Python中astropy.units.s方法的典型用法代码示例。如果您正苦于以下问题:Python units.s方法的具体用法?Python units.s怎么用?Python units.s使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在astropy.units的用法示例。


在下文中一共展示了units.s方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: outspec_compare

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def outspec_compare(self, outspec1, outspec2):
        r"""Compare two _outspec dictionaries.

        This is in service of the roundtrip comparison, test_roundtrip."""
        self.assertEqual(sorted(list(outspec1)), sorted(list(outspec2)))
        for k in outspec1:
            if isinstance(outspec1[k], list):
                # this happens for scienceInstrument and starlightSuppression,
                # which are lists of dictionaries
                for (d1, d2) in zip(outspec1[k], outspec2[k]):
                    for kk in d1:
                        if kk.split("_")[0] == 'koAngles':
                            self.assertEqual(d1[kk][0], d2[kk][0])
                            self.assertEqual(d1[kk][1], d2[kk][1])
                        else:
                            self.assertEqual(d1[kk], d2[kk])
            else:
                # these are strings or numbers, but not Quantity's,
                # because the outspec does not contain Quantity's
                self.assertEqual(outspec1[k], outspec2[k]) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:22,代码来源:test_OpticalSystem.py

示例2: test_roundtrip

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def test_roundtrip(self):
        r"""Test of initialization and __init__ -- round-trip parameter check.

        Method: Instantiate an OpticalSystem, use its resulting _outspec to
        instantiate another OpticalSystem.  Assert that all quantities in each
        dictionary are the same.  This checks that OpticalSystem objects are
        in fact reproducible from the _outspec alone.
        """
        optsys = self.fixture(**deepcopy(specs_simple))
        self.validate_basic(optsys, specs_simple)
        # save the _outspec
        outspec1 = optsys._outspec
        # recycle the _outspec into a new OpticalSystem
        optsys_next = self.fixture(**deepcopy(outspec1))
        # this is the new _outspec
        outspec2 = optsys_next._outspec
        # ensure the two _outspec's are the same
        self.outspec_compare(outspec1, outspec2) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:20,代码来源:test_OpticalSystem.py

示例3: hist

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def hist(self, nplan, xedges, yedges):
        """Returns completeness histogram for Monte Carlo simulation
        
        This function uses the inherited Planet Population module.
        
        Args:
            nplan (float):
                number of planets used
            xedges (float ndarray):
                x edge of 2d histogram (separation)
            yedges (float ndarray):
                y edge of 2d histogram (dMag)
        
        Returns:
            h (ndarray):
                2D numpy ndarray containing completeness histogram
        
        """
        
        s, dMag = self.genplans(nplan)
        # get histogram
        h, yedges, xedges = np.histogram2d(dMag, s.to('AU').value, bins=1000,
                range=[[yedges.min(), yedges.max()], [xedges.min(), xedges.max()]])
        
        return h, xedges, yedges 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:27,代码来源:SS_det_only.py

示例4: objfun

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def objfun(self,t,sInds,fZ):
        """
        Objective Function for SLSQP minimization. Purpose is to maximize summed completeness

        Args:
            t (ndarray):
                Integration times in days. NB: NOT an astropy quantity.
            sInds (ndarray):
                Target star indices (of same size as t)
            fZ (astropy Quantity):
                Surface brightness of local zodiacal light in units of 1/arcsec2
                Same size as t

        """
        good = t*u.d >= 0.1*u.s # inds that were not downselected by initial MIP

        comp = self.Completeness.comp_per_intTime(t[good]*u.d, self.TargetList, sInds[good], fZ[good], 
                self.ZodiacalLight.fEZ0, self.WAint[sInds][good], self.detmode)
        #self.vprint(-comp.sum()) # for verifying SLSQP output
        return -comp.sum() 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:22,代码来源:SLSQPScheduler.py

示例5: objfun_deriv

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def objfun_deriv(self,t,sInds,fZ):
        """
        Jacobian of objective Function for SLSQP minimization. 

        Args:
            t (astropy Quantity):
                Integration times in days. NB: NOT an astropy quantity.
            sInds (ndarray):
                Target star indices (of same size as t)
            fZ (astropy Quantity):
                Surface brightness of local zodiacal light in units of 1/arcsec2
                Same size as t

        """
        good = t*u.d >= 0.1*u.s # inds that were not downselected by initial MIP

        tmp = self.Completeness.dcomp_dt(t[good]*u.d, self.TargetList, sInds[good], fZ[good], 
                self.ZodiacalLight.fEZ0, self.WAint[sInds][good], self.detmode).to("1/d").value

        jac = np.zeros(len(t))
        jac[good] = tmp
        return -jac 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:24,代码来源:SLSQPScheduler.py

示例6: __init__

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def __init__(self, occHIPs=[], **specs):
        
        SurveySimulation.__init__(self, **specs)

        self._outspec['occHIPs'] = occHIPs
        
        if occHIPs is not []:
            occHIPs_path = os.path.join(EXOSIMS.__path__[0],'Scripts',occHIPs)
            assert os.path.isfile(occHIPs_path), "%s is not a file."%occHIPs_path
            with open(occHIPs_path, 'r') as ofile:
                HIPsfile = ofile.read()
            self.occHIPs = HIPsfile.split(',')
            if len(self.occHIPs) <= 1:
                self.occHIPs = HIPsfile.split('\n')
        else:
            self.occHIPs = occHIPs 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:18,代码来源:SS_char_only2.py

示例7: tell

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def tell(self, unit=None):
        """Current offset in the file.

        Parameters
        ----------
        unit : `~astropy.units.Unit` or str, optional
            Time unit the offset should be returned in.  By default, no unit
            is used, i.e., an integer enumerating samples is returned. For the
            special string 'time', the absolute time is calculated.

        Returns
        -------
        offset : int, `~astropy.units.Quantity`, or `~astropy.time.Time`
             Offset in current file (or time at current position).
        """
        if unit is None:
            return self.offset

        # "isinstance" avoids costly comparisons of an actual unit with 'time'.
        if not isinstance(unit, u.UnitBase) and unit == 'time':
            return self.start_time + self.tell(unit=u.s)

        return (self.offset / self.sample_rate).to(unit) 
开发者ID:mhvk,项目名称:baseband,代码行数:25,代码来源:base.py

示例8: get_fh

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def get_fh(self, name, mode, kwargs={}):
        """Ensure name is a filehandle, opening it if necessary."""
        if mode == 'wb' and self.is_sequence(name):
            raise ValueError(f"{self.fmt} does not support writing to a "
                             f"sequence or template in binary mode.")

        if self.is_fh(name):
            return name

        if self.is_template(name):
            name = self.get_fns(name, mode, kwargs)

        open_kwargs = {'mode': (mode[0].replace('w', 'w+')
                                + mode[1].replace('s', 'b'))}
        if self.is_sequence(name):
            opener = sf.open
            if 'file_size' in kwargs:
                open_kwargs['file_size'] = kwargs.pop('file_size')

        else:
            opener = io.open

        return opener(name, **open_kwargs) 
开发者ID:mhvk,项目名称:baseband,代码行数:25,代码来源:base.py

示例9: test_corrupt_stream

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def test_corrupt_stream(self, tmpdir):
        corrupt_file = str(tmpdir.join('test.vdif'))
        with vdif.open(SAMPLE_FILE, 'rb') as fh, \
                open(corrupt_file, 'w+b') as s:
            frameset = fh.read_frameset()
            header0 = frameset.frames[0].header
            frameset.tofile(s)
            frameset = fh.read_frameset()
            frameset.tofile(s)
            # Now add lots of the final frame, i.e., with the wrong thread_id.
            fh.seek(-5032, 2)
            frame2 = fh.read_frame()
            for i in range(15):
                frame2.tofile(s)
            s.seek(0)
            with vdif.open(s, 'rs') as f2:
                assert f2.header0 == header0
                with pytest.raises(HeaderNotFoundError):
                    f2._last_header 
开发者ID:mhvk,项目名称:baseband,代码行数:21,代码来源:test_vdif.py

示例10: __init__

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def __init__(self, fh_raw, squeeze=True, subset=(), verify=True):
        fh_raw = DADAFileReader(fh_raw)
        header0 = fh_raw.read_header()
        super().__init__(fh_raw, header0, squeeze=squeeze, subset=subset,
                         verify=verify)
        # Store number of frames, for finding last header.
        with self.fh_raw.temporary_offset() as fh_raw:
            self._raw_file_size = fh_raw.seek(0, 2)
            self._nframes, partial_frame_nbytes = divmod(
                self._raw_file_size, self.header0.frame_nbytes)
            # If there is a partial last frame.
            if partial_frame_nbytes > 0:
                # If partial last frame contains payload bytes.
                if partial_frame_nbytes > self.header0.nbytes:
                    self._nframes += 1
                    # If there's only one frame and it's incomplete.
                    if self._nframes == 1:
                        self._header0 = self._last_header
                        self._samples_per_frame = (
                            self._last_header.samples_per_frame)
                # Otherwise, ignore the partial frame unless it's the only
                # frame, in which case raise an EOFError.
                elif self._nframes == 0:
                    raise EOFError('file (of {0} bytes) appears to end without'
                                   'any payload.'.format(partial_frame_nbytes)) 
开发者ID:mhvk,项目名称:baseband,代码行数:27,代码来源:base.py

示例11: i8_mag15s

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def i8_mag15s(starttime, endtime):
    identifier = 'I8_15SEC_MAG'
    units = OrderedDict([('N_of_points', u.dimensionless_unscaled),
                         ('SourceFlag', u.dimensionless_unscaled),
                         ('|B|', u.nT),
                         ('Bx gse', u.nT), ('By gse', u.nT),
                         ('Bz gse', u.nT), ('By gsm', u.nT),
                         ('Bz gsm', u.nT), ('Bxx gse', u.nT**2),
                         ('Byy gse', u.nT**2), ('Bzz gse', u.nT**2),
                         ('Byx gse', u.nT**2), ('Bzx gse', u.nT**2),
                         ('Bzy gse', u.nT**2), ('Time shift', u.s),
                         ('SW_flag', u.dimensionless_unscaled)])
    for coord in ['GSE', 'GSET', 'GSM', 'GSMT']:
        for i in range(3):
            units[f'SC_Pos_{coord}_{i}'] = u.earthRad
    return _imp8(starttime, endtime, identifier, units=units) 
开发者ID:heliopython,项目名称:heliopy,代码行数:18,代码来源:imp.py

示例12: load_local_file

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def load_local_file(self, interval):
        # Read in data
        headings = ['probe', 'year', 'doy', 'hour', 'minute', 'second',
                    'naverage', 'Bx', 'By', 'Bz', '|B|',
                    'sigma_Bx', 'sigma_By', 'sigma_Bz']

        colspecs = [(1, 2), (2, 4), (4, 7), (7, 9), (9, 11), (11, 13),
                    (13, 15), (15, 22), (22, 29), (29, 36), (36, 42), (42, 48),
                    (48, 54), (54, 60)]
        data = pd.read_fwf(self.local_path(interval), names=headings,
                           header=None, colspecs=colspecs)

        # Process data
        data['year'] += 1900
        # Convert date info to datetime
        data['Time'] = pd.to_datetime(data['year'], format='%Y') + \
            pd.to_timedelta(data['doy'] - 1, unit='d') + \
            pd.to_timedelta(data['hour'], unit='h') + \
            pd.to_timedelta(data['minute'], unit='m') + \
            pd.to_timedelta(data['second'], unit='s')
        data = data.drop(['year', 'doy', 'hour', 'minute', 'second'], axis=1)
        data = data.set_index('Time', drop=False)
        return data 
开发者ID:heliopython,项目名称:heliopy,代码行数:25,代码来源:helios.py

示例13: make_interpolant

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def make_interpolant(self, param, value, unit):
        """Make an interpolating function."""

        # the generic quadratic function we have used to test
        # always positive, reaches a maximum of 1.0 at x=0.5
        quadratic = lambda x: 0.25 + 3.0 * (1-x) * x

        if isinstance(value, (numbers.Number, np.ndarray)):
            if param == 'QE':
                return lambda lam: value*unit
            elif param in ('core_thruput', 'core_contrast', 'PSF'):
                # for PSF, will be an ndarray
                return lambda lam, WA: value*unit
        elif isinstance(value, basestring):
            # for most ty
            if param == 'QE':
                return lambda lam: quadratic(lam)*unit
            elif param in ('core_thruput', 'core_contrast'):
                return lambda lam, WA: quadratic(WA)*unit
            elif param == 'PSF':
                # this rather messy construct uses a value like
                # "psf_5x5.fits" to recover a PSF matrix to use, else,
                # it uses a fixed value.  The pattern matches
                # psf_NNNxMMM.fits where NNN and MMM are digit sequences.
                m = re.search("psf_(\d+)x(\d+)\.fits", value)
                if m is None:
                    # use a fixed value, we won't need it anyway
                    a_value = np.array([1])
                else:
                    # this is the size, like [5,5]
                    s = [int(n) for n in m.groups()]
                    # this is the value, which is always a progression
                    # from 0...prod(s)-1, reshaped to be the size asked for
                    a_value = np.arange(np.prod(s)).reshape(s)
                return lambda lam, WA: a_value*unit
        else:
            assert False, "unknown interpolant needed" 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:39,代码来源:test_OpticalSystem.py

示例14: compare_interpolants

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def compare_interpolants(self, f1, f2, param, msg=''):
        r"""Compare two interpolants f1 and f2 by probing them randomly."""
        # Find out the number of input arguments expected
        f1_info = inspect.getargspec(f1)
        f2_info = inspect.getargspec(f2)
        # this is the number of formal arguments MINUS the number of defaults
        # (EXOSIMS uses defaults to provide functional closure, though it's unneeded)
        nargin1 = len(f1_info.args) - (0 if not f1_info.defaults else len(f1_info.defaults))
        nargin2 = len(f2_info.args) - (0 if not f2_info.defaults else len(f2_info.defaults))
        if nargin1 != nargin2:
            raise self.failureException(msg + '-- functions have different arity (arg lengths)')
        # make a few random probes of the interpolant on the interval (0,1)
        for count in range(10):
            # obtain a vector of length nargin1
            arg_in = np.random.random(nargin1)
            # the result can be a float (for contrast),
            # a numpy array (for PSF), or a Quantity (for QE)
            if  param in ('core_thruput', 'core_contrast'):
                out_1 = f1(arg_in[0]*u.nm,arg_in[1]*u.arcsec)
            else:
                out_1 = f1(*arg_in)
            out_2 = f2(*arg_in)
            diff = out_1 - out_2
            # if it's a quantity, unbox the difference
            if isinstance(diff, u.quantity.Quantity):
                diff = diff.value
            if np.any(np.abs(diff) > 1e-5):
                errmsg = msg + '-- function mismatch: %r != %r' % (out_1, out_2)
                raise self.failureException(errmsg) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:31,代码来源:test_OpticalSystem.py

示例15: compare_lists

# 需要导入模块: from astropy import units [as 别名]
# 或者: from astropy.units import s [as 别名]
def compare_lists(self, list1, list2, msg=''):
        r"""Compare two lists-of-dicts f1 and f2 to ensure f2 attributes are in f1."""
        if len(list1) != len(list2):
            raise self.failureException(msg +
                                        ' -- list length mismatch: %d vs %d' % (len(f1), len(f2)))
        for d1, d2 in zip(list1, list2):
            if type(d1) != type(d2):
                raise self.failureException(msg +
                                            ' -- type mismatch: %d vs %d' % (type(d1), type(d2)))
            assert isinstance(d2, dict), msg + " -- compare_lists expects lists-of-dicts"
            # note: we need d2 to be a subset of d1
            for k in d2:
                self.assertEqual(d1[k], d2[k], msg + ' -- key %s mismatch' % k) 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:15,代码来源:test_OpticalSystem.py


注:本文中的astropy.units.s方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。