Пример #1
0
 def __init__(self,
              views: None | Sequence[T3DocView] = None,
              session: None | JDict = None):
     object.__setattr__(self, 'views', views)
     object.__setattr__(self, 'session',
                        ReadOnlyDict(session) if session else None)
     object.__setattr__(self, 'units',
                        set(v.unit for v in views) if views else set())
     object.__setattr__(self, 'extra', {})
Пример #2
0
def recursive_unfreeze(arg: ReadOnlyDict) -> dict:
    """
	Inverse of recursive_freeze
	"""
    if isinstance(arg, ReadOnlyDict):
        return dict({
            recursive_unfreeze(k): recursive_unfreeze(v)
            for k, v in arg.items()
        })

    if isinstance(arg, tuple):
        return list(map(recursive_unfreeze, arg))

    if isinstance(arg, frozenset):
        return set(arg)

    return arg
Пример #3
0
def recursive_freeze(arg: Any) -> Any:
    """
	Return an immutable shallow copy
	:param arg:
		dict: ReadOnlyDict is returned
		list: tuple is returned
		set: frozenset is returned
		otherwise: arg is returned 'as is'
	"""
    if isinstance(arg, dict):
        return ReadOnlyDict(
            {recursive_freeze(k): recursive_freeze(v)
             for k, v in arg.items()})

    if isinstance(arg, list):
        return tuple(map(recursive_freeze, arg))

    if isinstance(arg, set):
        return frozenset(arg)

    return arg
Пример #4
0
    def shape_alert_dict(d: dict[str, Any],
                         tag: None | Tag | list[Tag] = None) -> AmpelAlert:

        if d['prv_candidates']:

            dps: list[ReadOnlyDict] = [ReadOnlyDict(d['candidate'])]

            for el in d['prv_candidates']:

                # Upperlimit
                if el.get('candid') is None:

                    # rarely, meaningless upper limits with negativ
                    # diffmaglim are provided by IPAC
                    if el['diffmaglim'] < 0:
                        continue

                    ul = ReadOnlyDict(
                        jd=el['jd'],
                        fid=el['fid'],
                        pid=el['pid'],
                        diffmaglim=el['diffmaglim'],
                        programid=el['programid'],
                        pdiffimfilename=el.get('pdiffimfilename'))

                    dps.append(ul)

                # PhotoPoint
                else:
                    dps.append(ReadOnlyDict(el))

            return AmpelAlert(
                id=d['candid'],  # alert id
                stock=to_ampel_id(d['objectId']),  # internal ampel id
                datapoints=tuple(dps),
                extra=ReadOnlyDict({'name': d['objectId']}),  # ZTF name
                tag=tag)

        # No "previous candidate"
        return AmpelAlert(
            id=d['candid'],  # alert id
            stock=to_ampel_id(d['objectId']),  # internal ampel id
            datapoints=(ReadOnlyDict(d['candidate']), ),
            extra=ReadOnlyDict({'name': d['objectId']}),  # ZTF name
            tag=tag)
Пример #5
0
    def __next__(self) -> AmpelAlertProtocol:
        """
		:raises StopIteration: when alert_loader dries out.
		:raises AttributeError: if alert_loader was not set properly before this method is called
		"""

        fpath = next(self.alert_loader)  # type: ignore
        with open(fpath, "r") as f:  # type: ignore
            li = iter(f)
            for l in li:
                if "# Requested input R.A." in l:
                    ra = float(l.split("=")[1].split(" ")[1])
                    dec = float(next(li).split("=")[1].split(" ")[1])
                    break

        # basename("/usr/local/auth.AAA.BBB.py").split(".")[1:-1] -> ['AAA', 'BBB']
        tags = basename(fpath).split(".")[1:-1] or None  # type: ignore
        sn_name = basename(fpath).split(".")[0]  # type: ignore

        df = pd.DataFrame()
        fig = plt.figure()
        d = get_baseline(fpath, write_lc=df, make_plot=fig)
        if 't_peak' not in d:
            print(sn_name)
            print(d)
            return self.__next__()

        t_min = d['t_peak'] - 40
        t_max = d['t_peak'] + 150
        all_ids = b""
        pps = []

        for index, row in df.iterrows():

            pp = {
                k: dcast[k](v) if (k in dcast and v is not None) else v
                for k, v in row.items()
            }

            if (pp['jd'] < t_min or pp['jd'] > t_max or
                (self.excl_poor_conditions and pp['poor_conditions'] == 1)
                    or pp[self.flux_key] < self.flux_threshold):
                continue

            pp_hash = blake2b(encode(pp), digest_size=7).digest()
            pp['candid'] = int.from_bytes(pp_hash, byteorder=sys.byteorder)
            pp['fid'] = ZTF_FILTER_MAP[pp['passband']]
            pp['ra'] = ra
            pp['dec'] = dec

            # Convert jansky to flux
            pp['flux'] = pp[self.flux_key] * 2.75406

            # Opionally scale uncertainties
            pp['flux_unc'] = pp[
                self.flux_unc_key] * 2.75406 * self.flux_unc_scale[
                    pp['passband']]

            # Enforce error floor
            if pp['flux_unc'] / pp['flux'] < self.flux_unc_floor:
                if tags is None:
                    tags = ['FLOOR']
                else:
                    tags.append('FLOOR')
                pp['flux_unc'] = pp['flux'] * self.flux_unc_floor

            all_ids += pp_hash
            pps.append(ReadOnlyDict(pp))

        if not pps:
            return self.__next__()

        pa = AmpelAlert(
            id=int.from_bytes(  # alert id
                blake2b(all_ids, digest_size=7).digest(),
                byteorder=sys.byteorder),
            stock=to_ampel_id(sn_name),  # internal ampel id
            datapoints=tuple(pps),
            extra=ReadOnlyDict({
                'name': sn_name,
                'stock': {
                    'ret':
                    d,
                    'plot':
                    mplfig_to_svg_dict1(fig,
                                        self.plot_props,
                                        logger=self.logger,
                                        extra={"sn_name": sn_name})
                }
            }),
            tag=tags)

        plt.close('all')
        return pa
def test_pickle():
    d = ReadOnlyDict({'a': 1})
    assert pickle.loads(pickle.dumps(d)) == d
Пример #7
0
 def add_session_info(self, d: JDict) -> None:
     if self.session:
         object.__setattr__(self, 'session', ReadOnlyDict(self.session | d))
     else:
         object.__setattr__(self, 'session', ReadOnlyDict(d))
Пример #8
0
            pp_hash = blake2b(encode(pp), digest_size=7).digest()
            if self.counter:
                pp['candid'] = self.counter
                self.counter += 1
            else:
                pp['candid'] = int.from_bytes(pp_hash, byteorder=sys.byteorder)
            pp['magpsf'] = -2.5 * log10(pp['ampl']) + pp['magzp']
            # 2.5/log(10) = 1.0857362047581294
            pp['sigmapsf'] = 1.0857362047581294 * pp['ampl.err'] / pp['ampl']
            pp['fid'] = pp.pop('filterid')
            pp['jd'] = pp.pop('obsmjd') + 2400000.5
            pp['programid'] = 1
            pp['sigma_err'] = pp.pop('sigma.err')
            pp['ampl_err'] = pp.pop('ampl.err')
            pp['ra'] = float(cdict['ra'])
            pp['dec'] = float(cdict['dec'])
            all_ids += pp_hash
            pps.append(ReadOnlyDict(pp))

        if not pps:
            return self.__next__()

        return AmpelAlert(
            id=int.from_bytes(  # alert id
                blake2b(all_ids, digest_size=7).digest(),
                byteorder=sys.byteorder),
            stock=to_ampel_id(cdict['name']),  # internal ampel id
            datapoints=tuple(pps),
            extra={'name': cdict['name']},
            tag=tags)