Exemple #1
0
 def to_tree(cls, quantity, ctx):
     node = {}
     if isinstance(quantity, Quantity):
         node['value'] = custom_tree_to_tagged_tree(quantity.value, ctx)
         node['unit'] = custom_tree_to_tagged_tree(quantity.unit, ctx)
         return node
     raise TypeError("'{0}' is not a valid Quantity".format(quantity))
 def to_tree(cls, node, ctx): # to ASDF representation
     d = {}
     d['default'] = yamlutil.custom_tree_to_tagged_tree(node.default, ctx)
     extra_keys = node.keys()
     for key in extra_keys:
         d[key] = yamlutil.custom_tree_to_tagged_tree(getattr(node, key), ctx)
     return d
Exemple #3
0
    def _to_tree(cls, frame, ctx):

        node = {}

        node['name'] = frame.name

        # We want to check that it is exactly this type and not a subclass
        if type(frame) is CoordinateFrame:
            node['axes_type'] = frame.axes_type
            node['naxes'] = frame.naxes

        if frame.axes_order is not None:
            node['axes_order'] = list(frame.axes_order)

        if frame.axes_names is not None:
            node['axes_names'] = list(frame.axes_names)

        if frame.reference_frame is not None:
            node['reference_frame'] = yamlutil.custom_tree_to_tagged_tree(
                frame.reference_frame, ctx)

        if frame.unit is not None:
            node['unit'] = yamlutil.custom_tree_to_tagged_tree(
                list(frame.unit), ctx)

        if frame.axis_physical_types is not None:
            node['axis_physical_types'] = list(frame.axis_physical_types)

        return node
Exemple #4
0
    def _to_tree_base_transform_members(cls, model, node, ctx):
        if getattr(model, '_user_inverse', None) is not None:
            node['inverse'] = yamlutil.custom_tree_to_tagged_tree(
                model._user_inverse, ctx)

        if model.name is not None:
            node['name'] = model.name

        try:
            bb = model.bounding_box
        except NotImplementedError:
            bb = None

        if bb is not None:
            if model.n_inputs == 1:
                bb = list(bb)
            else:
                bb = [list(item) for item in model.bounding_box]
            node['bounding_box'] = yamlutil.custom_tree_to_tagged_tree(bb, ctx)
        if type(model.__class__.inputs) != property:
            node['inputs'] = model.inputs
            node['outputs'] = model.outputs

        # model / parameter constraints
        node['fixed'] = dict(model.fixed)
        node['bounds'] = dict(model.bounds)
Exemple #5
0
    def to_tree(cls, frame, ctx):
        import astropy.time

        node = {}

        node['name'] = frame.name

        node['axes_order'] = list(frame.axes_order)

        if frame.axes_names is not None:
            node['axes_names'] = list(frame.axes_names)

        if frame.reference_frame is not None:
            if frame.reference_frame is not astropy.time.Time:
                raise ValueError(
                    "Can not save reference_frame unless it's Time")

        if frame.reference_position is not None:
            node['reference_time'] = yamlutil.custom_tree_to_tagged_tree(
                frame.reference_position, ctx)

        if frame.unit is not None:
            node['unit'] = yamlutil.custom_tree_to_tagged_tree(
                list(frame.unit), ctx)

        return node
Exemple #6
0
    def _to_tree_from_model_tree(cls, tree, ctx):

        if not isinstance(tree.left, CompoundModel):
            left = yamlutil.custom_tree_to_tagged_tree(tree.left, ctx)
        else:
            left = cls._to_tree_from_model_tree(tree.left, ctx)

        if not isinstance(tree.right, CompoundModel):
            if isinstance(tree.right, dict):
                right = {
                    'keys': list(tree.right.keys()),
                    'values': list(tree.right.values())
                }
            else:
                right = yamlutil.custom_tree_to_tagged_tree(tree.right, ctx)
        else:
            right = cls._to_tree_from_model_tree(tree.right, ctx)

        node = {'forward': [left, right]}

        try:
            tag_name = 'transform/' + _operator_to_tag_mapping[tree.op]
        except KeyError:
            raise ValueError(f"Unknown operator '{tree.op}'")

        node = tagged.tag_object(cls.make_yaml_tag(tag_name), node, ctx=ctx)
        return node
Exemple #7
0
    def to_tree(cls, node, ctx):
        tree = {}

        if node.name is not None:
            tree["name"] = node.name

        inputs = []
        outputs = []
        for i, o, m in zip(node.inputs, node.outputs, node.mapping):
            input = {
                "name": i,
                "allow_dimensionless": node.input_units_allow_dimensionless[i],
            }
            if m[0] is not None:
                input["unit"] = yamlutil.custom_tree_to_tagged_tree(m[0], ctx)
            if node.input_units_equivalencies is not None and i in node.input_units_equivalencies:
                input["equivalencies"] = yamlutil.custom_tree_to_tagged_tree(
                    node.input_units_equivalencies[i], ctx)
            inputs.append(input)

            output = {
                "name": o,
            }
            if m[-1] is not None:
                output["unit"] = yamlutil.custom_tree_to_tagged_tree(
                    m[-1], ctx)
            outputs.append(output)

        tree["inputs"] = inputs
        tree["outputs"] = outputs

        return tree
Exemple #8
0
 def to_tree(cls, spec_coord, ctx):
     node = {}
     if isinstance(spec_coord, SpectralCoord):
         node['value'] = custom_tree_to_tagged_tree(spec_coord.value, ctx)
         node['unit'] = custom_tree_to_tagged_tree(spec_coord.unit, ctx)
         return node
     raise TypeError(f"'{spec_coord}' is not a valid SpectralCoord")
Exemple #9
0
 def to_tree(cls, node, ctx):  # to ASDF representation
     d = {}
     d['sci'] = yamlutil.custom_tree_to_tagged_tree(node.sci, ctx)
     d['wcs'] = yamlutil.custom_tree_to_tagged_tree(node.wcs, ctx)
     if node.obsinfo is not None:
         d['obsinfo'] = yamlutil.custom_tree_to_tagged_tree(
             node.obsinfo, ctx)
     if node.dq is not None:
         d['dq'] = yamlutil.custom_tree_to_tagged_tree(node.dq, ctx)
     if node.err is not None:
         d['err'] = yamlutil.custom_tree_to_tagged_tree(node.err, ctx)
     if node.aperture is not None:
         d['aperture'] = yamlutil.custom_tree_to_tagged_tree(
             node.aperture, ctx)
     if node.target_id is not None:
         d['target_id'] = yamlutil.custom_tree_to_tagged_tree(
             node.target_id, ctx)
     if node.background_corrected is not None:
         d['background_corrected'] = yamlutil.custom_tree_to_tagged_tree(
             node.background_corrected, ctx)
     if node.background_apertures is not None:
         d['background_apertures'] = yamlutil.custom_tree_to_tagged_tree(
             node.background_apertures, ctx)
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
Exemple #10
0
 def to_tree(cls, quantity, ctx):
     node = {}
     if isinstance(quantity, Quantity):
         node['value'] = custom_tree_to_tagged_tree(quantity.value, ctx)
         node['unit'] = custom_tree_to_tagged_tree(quantity.unit, ctx)
         return node
     raise TypeError(f"'{quantity}' is not a valid Quantity")
Exemple #11
0
 def to_tree(cls, node, ctx): # to ASDF representation
     d = {}
     d['fields'] = yamlutil.custom_tree_to_tagged_tree(node.fields, ctx)
     d['field_separator'] = node.field_separator
     d['datasets'] = yamlutil.custom_tree_to_tagged_tree(node.datasets, ctx)
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
 def to_tree(cls, node, ctx):  # to ASDF representation
     d = {}
     d['center'] = yamlutil.custom_tree_to_tagged_tree(node.center, ctx)
     d['footprint'] = yamlutil.custom_tree_to_tagged_tree(
         node.footprint, ctx)
     d['aperture_id'] = node.aperture_id
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
Exemple #13
0
 def to_tree(cls, node, ctx): # to ASDF representation
     d = {}
     d['proposal_id'] = node.id
     if node.proposers is not None:
         d['proposers'] = yamlutil.custom_tree_to_tagged_tree(node.proposers, ctx)
     if node.title is not None:
         d['proposal_title'] = node.title
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
Exemple #14
0
 def to_tree(cls, node, ctx): # to ASDF representation
     d = {}
     d['solar_system_body'] = node.solar_system_body
     d['latitude'] = yamlutil.custom_tree_to_tagged_tree(node.latitude, ctx)
     d['longitude'] = yamlutil.custom_tree_to_tagged_tree(node.longitude, ctx)
     if node.altitude is not None:
         d['altitude'] = yamlutil.custom_tree_to_tagged_tree(node.altitude, ctx)
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
Exemple #15
0
    def to_tree(cls, node, ctx):
        fmt = node.format

        if fmt == 'byear':
            node = time.Time(node, format='byear_str')

        elif fmt == 'jyear':
            node = time.Time(node, format='jyear_str')

        elif fmt in ('fits', 'datetime', 'plot_date'):
            node = time.Time(node, format='isot')

        fmt = node.format

        fmt = _astropy_format_to_asdf_format.get(fmt, fmt)

        guessable_format = fmt in _guessable_formats

        if node.scale == 'utc' and guessable_format and node.isscalar:
            return node.value

        d = {'value': yamlutil.custom_tree_to_tagged_tree(node.value, ctx)}

        if not guessable_format:
            d['format'] = fmt

        if node.scale != 'utc':
            d['scale'] = node.scale

        if node.location is not None:
            x, y, z = node.location.x, node.location.y, node.location.z
            # Preserve backwards compatibility for writing the old schema
            # This allows WCS to test backwards compatibility with old frames
            # This code does get tested in CI, but we don't run a coverage test
            if cls.version == '1.0.0': # pragma: no cover
                unit = node.location.unit
                d['location'] = {
                    'x': x.value,
                    'y': y.value,
                    'z': z.value,
                    'unit': yamlutil.custom_tree_to_tagged_tree(unit, ctx)
                }
            else:
                d['location'] = {
                    # It seems like EarthLocations can be represented either in
                    # terms of Cartesian coordinates or latitude and longitude, so
                    # we rather arbitrarily choose the former for our representation
                    'x': yamlutil.custom_tree_to_tagged_tree(x, ctx),
                    'y': yamlutil.custom_tree_to_tagged_tree(y, ctx),
                    'z': yamlutil.custom_tree_to_tagged_tree(z, ctx)
                }

        return d
Exemple #16
0
    def to_tree(cls, node, ctx):
        format = node.format

        if format == 'byear':
            node = time.Time(node, format='byear_str')

        elif format == 'jyear':
            node = time.Time(node, format='jyear_str')

        elif format in ('fits', 'datetime', 'plot_date'):
            node = time.Time(node, format='isot')

        format = node.format

        format = _astropy_format_to_asdf_format.get(format, format)

        guessable_format = format in _guessable_formats

        if node.scale == 'utc' and guessable_format:
            if node.isscalar:
                return node.value
            else:
                return yamlutil.custom_tree_to_tagged_tree(
                    node.value, ctx)

        d = {'value': yamlutil.custom_tree_to_tagged_tree(node.value, ctx)}

        if not guessable_format:
            d['format'] = format

        if node.scale != 'utc':
            d['scale'] = node.scale

        if node.location is not None:
            x, y, z = node.location.x, node.location.y, node.location.z
            # Preserve backwards compatibility for writing the old schema
            # This allows WCS to test backwards compatibility with old frames
            # This code does get tested in CI, but we don't run a coverage test
            if cls.version == '1.0.0': # pragma: no cover
                unit = node.location.unit
                d['location'] = { 'x': x, 'y': y, 'z': z, 'unit': unit }
            else:
                d['location'] = {
                    # It seems like EarthLocations can be represented either in
                    # terms of Cartesian coordinates or latitude and longitude, so
                    # we rather arbitrarily choose the former for our representation
                    'x': yamlutil.custom_tree_to_tagged_tree(x, ctx),
                    'y': yamlutil.custom_tree_to_tagged_tree(y, ctx),
                    'z': yamlutil.custom_tree_to_tagged_tree(z, ctx)
                }

        return d
Exemple #17
0
 def to_tree(cls, node, ctx):  # to ASDF representation
     d = {}
     d['name'] = node.name
     d['size'] = node.size
     if node.binning is not None:
         d['binning'] = yamlutil.custom_tree_to_tagged_tree(
             node.binning, ctx)
     if node.subarray is not None:
         d['subarray'] = yamlutil.custom_tree_to_tagged_tree(
             node.subarray, ctx)
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
 def to_tree(cls, node, ctx):  # to ASDF representation
     d = {}
     d['id'] = node.id
     d['coordinates'] = yamlutil.custom_tree_to_tagged_tree(
         node.coordinates, ctx)
     if node.name is not None:
         d['name'] = yamlutil.custom_tree_to_tagged_tree(node.name, ctx)
     if node.aliases is not None:
         d['aliases'] = yamlutil.custom_tree_to_tagged_tree(
             node.aliases, ctx)
     if node.meta is not None:
         d['meta'] = yamlutil.custom_tree_to_tagged_tree(node.meta, ctx)
     return d
Exemple #19
0
    def to_tree(cls, data, ctx):
        node = {
            'data': yamlutil.custom_tree_to_tagged_tree(data.data, ctx),
            'name': data.name
        }
        if data.description:
            node['description'] = data.description
        if data.unit:
            node['unit'] = yamlutil.custom_tree_to_tagged_tree(data.unit, ctx)
        if data.meta:
            node['meta'] = data.meta

        return node
Exemple #20
0
    def to_tree(cls, data, ctx):
        node = {
            'data': yamlutil.custom_tree_to_tagged_tree(
                data.data, ctx),
            'name': data.name
        }
        if data.description:
            node['description'] = data.description
        if data.unit:
            node['unit'] = yamlutil.custom_tree_to_tagged_tree(
                data.unit, ctx)
        if data.meta:
            node['meta'] = data.meta

        return node
Exemple #21
0
    def to_tree_transform(cls, model, ctx):
        typeindex = cls.types.index(model.__class__)
        poly_type = cls.invtypemap[int(typeindex/2)*2]
        ndim = (typeindex % 2) + 1
        if ndim == 1:
            coefficients = np.array(model.parameters)
        else:
            coefficients = np.zeros((model.x_degree + 1, model.y_degree + 1))
            for i in range(model.x_degree + 1):
                for j in range(model.y_degree + 1):
                    name = f'c{i}_{j}'
                    coefficients[i, j] = getattr(model, name).value
        node = {'polynomial_type': poly_type, 'coefficients': coefficients}
        if ndim == 1:
            if model.domain is not None:
                node['domain'] = model.domain
            if model.window is not None:
                node['window'] = model.window
        else:
            if model.x_domain or model.y_domain is not None:
                node['domain'] = (model.x_domain, model.y_domain)
            if model.x_window or model.y_window is not None:
                node['window'] = (model.x_window, model.y_window)

        return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #22
0
    def to_tree_transform(cls, model, ctx):
        if isinstance(model, modeling.models.Polynomial1D):
            coefficients = np.array(model.parameters)
        elif isinstance(model, modeling.models.Polynomial2D):
            degree = model.degree
            coefficients = np.zeros((degree + 1, degree + 1))
            for i in range(degree + 1):
                for j in range(degree + 1):
                    if i + j < degree + 1:
                        name = 'c' + str(i) + '_' + str(j)
                        coefficients[i, j] = getattr(model, name).value
        node = {'coefficients': coefficients}
        typeindex = cls.types.index(model.__class__)
        ndim = (typeindex % 2) + 1
        if ndim == 1:
            if model.domain is not None:
                node['domain'] = model.domain
            if model.window is not None:
                node['window'] = model.window
        else:
            if model.x_domain or model.y_domain is not None:
                node['domain'] = (model.x_domain, model.y_domain)
            if model.x_window or model.y_window is not None:
                node['window'] = (model.x_window, model.y_window)

        return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #23
0
    def to_tree_tagged(cls, frame, ctx):
        if type(frame) not in frame_transform_graph.frame_set:
            raise ValueError("Can only save frames that are registered with the "
                             "transformation graph.")

        node = {}
        if frame.has_data:
            node['data'] = custom_tree_to_tagged_tree(frame.data, ctx)
        frame_attributes = {}
        for attr in frame.frame_attributes.keys():
            value = getattr(frame, attr, None)
            if value is not None:
                frame_attributes[attr] = value
        node['frame_attributes'] = custom_tree_to_tagged_tree(frame_attributes, ctx)

        return tagged.tag_object(cls._frame_name_to_tag(frame.name), node, ctx=ctx)
Exemple #24
0
    def to_tree_transform(cls, model, ctx):
        if isinstance(model, modeling.models.Polynomial1D):
            coefficients = np.array(model.parameters)
        elif isinstance(model, modeling.models.Polynomial2D):
            degree = model.degree
            coefficients = np.zeros((degree + 1, degree + 1))
            for i in range(degree + 1):
                for j in range(degree + 1):
                    if i + j < degree + 1:
                        name = 'c' + str(i) + '_' + str(j)
                        coefficients[i, j] = getattr(model, name).value
        node = {'coefficients': coefficients}
        typeindex = cls.types.index(model.__class__)
        ndim = (typeindex % 2) + 1

        if cls.version >= PolynomialTypeBase.DOMAIN_WINDOW_MIN_VERSION:
            # Schema versions prior to 1.2 included an unrelated "domain"
            # property.  We can't serialize the new domain values with those
            # versions because they don't validate.
            if ndim == 1:
                if model.domain is not None:
                    node['domain'] = model.domain
                if model.window is not None:
                    node['window'] = model.window
            else:
                if model.x_domain or model.y_domain is not None:
                    node['domain'] = (model.x_domain, model.y_domain)
                if model.x_window or model.y_window is not None:
                    node['window'] = (model.x_window, model.y_window)

        return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #25
0
    def to_tree_tagged(cls, frame, ctx):
        if type(frame) not in frame_transform_graph.frame_set:
            raise ValueError("Can only save frames that are registered with the "
                             "transformation graph.")

        node = {}
        if frame.has_data:
            node['data'] = custom_tree_to_tagged_tree(frame.data, ctx)
        frame_attributes = {}
        for attr in frame.frame_attributes.keys():
            value = getattr(frame, attr, None)
            if value is not None:
                frame_attributes[attr] = value
        node['frame_attributes'] = custom_tree_to_tagged_tree(frame_attributes, ctx)

        return tagged.tag_object(cls._frame_name_to_tag(frame.name), node, ctx=ctx)
Exemple #26
0
    def to_tree(cls, obj, ctx):
        """
        Converts Spectrum1D object into tree used for YAML representation
        """
        node = {}
        node['flux'] = custom_tree_to_tagged_tree(obj.flux, ctx)
        node['spectral_axis'] = custom_tree_to_tagged_tree(obj.spectral_axis,
                                                           ctx)
        if obj.uncertainty is not None:
            node['uncertainty'] = {}
            node['uncertainty'][
                'uncertainty_type'] = obj.uncertainty.uncertainty_type
            data = custom_tree_to_tagged_tree(obj.uncertainty.array, ctx)
            node['uncertainty']['data'] = data

        return node
Exemple #27
0
def test_validator_visit_repeat_nodes():
    ctx = asdf.AsdfFile()
    node = asdf.tags.core.Software(name="Minesweeper")
    tree = yamlutil.custom_tree_to_tagged_tree(
        {
            "node": node,
            "other_node": node,
            "nested": {
                "node": node
            }
        }, ctx)

    visited_nodes = []

    def _test_validator(validator, value, instance, schema):
        visited_nodes.append(instance)

    validator = schema.get_validator(
        ctx=ctx, validators=util.HashableDict(type=_test_validator))
    validator.validate(tree)
    assert len(visited_nodes) == 1

    visited_nodes.clear()
    validator = schema.get_validator(
        validators=util.HashableDict(type=_test_validator),
        _visit_repeat_nodes=True)
    validator.validate(tree)
    assert len(visited_nodes) == 3
Exemple #28
0
 def to_tree_transform(cls, model, ctx):
     node = {
         'condition': model.condition,
         'compareto': model.compareto,
         'value': model.value
     }
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #29
0
def _check_value(value, schema):
    """
    Perform the actual validation.
    """
    if value is None:
        if schema.get('fits_required'):
            name = schema.get("fits_keyword") or schema.get("fits_hdu")
            raise jsonschema.ValidationError("%s is a required value"
                                              % name)
    else:
        validator_context = AsdfFile()
        validator_resolver = validator_context.resolver

        temp_schema = {
            '$schema':
            'http://stsci.edu/schemas/asdf-schema/0.1.0/asdf-schema'}
        temp_schema.update(schema)
        validator = asdf_schema.get_validator(temp_schema,
                                              validator_context,
                                              validator_callbacks,
                                              validator_resolver)

        value = yamlutil.custom_tree_to_tagged_tree(value, validator_context)
        validator.validate(value, _schema=temp_schema)
        validator_context.close()
Exemple #30
0
 def to_tree_transform(cls, model, ctx):
     node = {
         'beta_zero': model.beta_zero.value,
         'beta_del': model.beta_del.value,
         'channel': model.channel.value
     }
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #31
0
    def to_tree_transform(cls, model, ctx):
        node = OrderedDict()
        node['no_label'] = model.no_label
        if model.inputs_mapping is not None:
            node['inputs_mapping'] = model.inputs_mapping

        if isinstance(model, LabelMapperArray):
            node['mapper'] = model.mapper
        elif isinstance(model, LabelMapper):
            node['mapper'] = model.mapper
            node['inputs'] = list(model.inputs)
        elif isinstance(model, (LabelMapperDict, LabelMapperRange)):
            if hasattr(model, 'atol'):
                node['atol'] = model.atol
            mapper = OrderedDict()
            labels = list(model.mapper)

            transforms = []
            for k in labels:
                transforms.append(model.mapper[k])
            if isiterable(labels[0]):
                labels = [list(l) for l in labels]
            mapper['labels'] = labels
            mapper['models'] = transforms
            node['mapper'] = mapper
            node['inputs'] = list(model.inputs)
        else:
            raise TypeError("Unrecognized type of LabelMapper - {0}".format(model))

        return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #32
0
    def to_tree(cls, hdulist, ctx):
        units = []
        for hdu in hdulist:
            header_list = []
            for card in hdu.header.cards:
                if card.comment:
                    new_card = [card.keyword, card.value, card.comment]
                else:
                    if card.value:
                        new_card = [card.keyword, card.value]
                    else:
                        if card.keyword:
                            new_card = [card.keyword]
                        else:
                            new_card = []
                header_list.append(new_card)

            hdu_dict = {}
            hdu_dict['header'] = header_list
            if hdu.data is not None:
                if hdu.data.dtype.names is not None:
                    data = table.Table(hdu.data)
                else:
                    data = hdu.data
                hdu_dict['data'] = yamlutil.custom_tree_to_tagged_tree(
                    data, ctx)

            units.append(hdu_dict)

        return units
Exemple #33
0
    def to_tree_transform(cls, model, ctx):
        node = OrderedDict()
        node['no_label'] = model.no_label
        if model.inputs_mapping is not None:
            node['inputs_mapping'] = model.inputs_mapping

        if isinstance(model, LabelMapperArray):
            node['mapper'] = model.mapper
        elif isinstance(model, LabelMapper):
            node['mapper'] = model.mapper
            node['inputs'] = list(model.inputs)
        elif isinstance(model, (LabelMapperDict, LabelMapperRange)):
            if hasattr(model, 'atol'):
                node['atol'] = model.atol
            mapper = OrderedDict()
            labels = list(model.mapper)

            transforms = []
            for k in labels:
                transforms.append(model.mapper[k])
            if isiterable(labels[0]):
                labels = [list(l) for l in labels]
            mapper['labels'] = labels
            mapper['models'] = transforms
            node['mapper'] = mapper
            node['inputs'] = list(model.inputs)
        else:
            raise TypeError("Unrecognized type of LabelMapper - {0}".format(model))

        return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #34
0
    def to_tree(cls, hdulist, ctx):
        units = []
        for hdu in hdulist:
            header_list = []
            for card in hdu.header.cards:
                if card.comment:
                    new_card = [card.keyword, card.value, card.comment]
                else:
                    if card.value:
                        new_card = [card.keyword, card.value]
                    else:
                        if card.keyword:
                            new_card = [card.keyword]
                        else:
                            new_card = []
                header_list.append(new_card)

            hdu_dict = {}
            hdu_dict['header'] = header_list
            if hdu.data is not None:
                if hdu.data.dtype.names is not None:
                    data = table.Table(hdu.data)
                else:
                    data = hdu.data
                hdu_dict['data'] = yamlutil.custom_tree_to_tagged_tree(data, ctx)

            units.append(hdu_dict)

        return units
def _check_value(value, schema):
    """
    Perform the actual validation.
    """
    if value is None:
        if schema.get('fits_required'):
            name = schema.get("fits_keyword") or schema.get("fits_hdu")
            raise jsonschema.ValidationError("%s is a required value"
                                              % name)
    else:
        validator_context = AsdfFile()
        validator_resolver = validator_context.resolver

        temp_schema = {
            '$schema':
            'http://stsci.edu/schemas/asdf-schema/0.1.0/asdf-schema'}
        temp_schema.update(schema)
        validator = asdf_schema.get_validator(temp_schema,
                                              validator_context,
                                              validator_callbacks,
                                              validator_resolver)

        value = yamlutil.custom_tree_to_tagged_tree(value, validator_context)
        validator.validate(value, _schema=temp_schema)
        validator_context.close()
Exemple #36
0
    def to_tree_transform(cls, model, ctx):
        if isinstance(model, modeling.rotations.RotateNative2Celestial):
            try:
                node = {"phi": _parameter_to_value(model.lon),
                        "theta": _parameter_to_value(model.lat),
                        "psi": _parameter_to_value(model.lon_pole),
                        "direction": "native2celestial"
                        }
            except AttributeError:
                node = {"phi": model.lon,
                        "theta": model.lat,
                        "psi": model.lon_pole,
                        "direction": "native2celestial"
                        }
        elif isinstance(model, modeling.rotations.RotateCelestial2Native):
            try:
                node = {"phi": _parameter_to_value(model.lon),
                        "theta": _parameter_to_value(model.lat),
                        "psi": _parameter_to_value(model.lon_pole),
                        "direction": "celestial2native"
                        }
            except AttributeError:
                node = {"phi": model.lon,
                        "theta": model.lat,
                        "psi": model.lon_pole,
                        "direction": "celestial2native"
                        }
        else:
            node = {"phi": _parameter_to_value(model.phi),
                    "theta": _parameter_to_value(model.theta),
                    "psi": _parameter_to_value(model.psi),
                    "direction": model.axes_order
                    }

        return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #37
0
 def to_tree_transform(cls, model, ctx):
     node = {'orders': list(model.orders),
             'lmodels': list(model.lmodels),
             'xmodels': list(model.xmodels),
             'ymodels': list(model.ymodels),
             'class_name': type(model).name
             }
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #38
0
def test_isot(tmpdir):
    tree = {'time': time.Time('2000-01-01T00:00:00.000')}

    helpers.assert_roundtrip_tree(tree, tmpdir)

    ff = asdf.AsdfFile(tree)
    tree = yamlutil.custom_tree_to_tagged_tree(ff.tree, ff)
    assert isinstance(tree['time'], str)
Exemple #39
0
 def to_tree_transform(cls, model, ctx):
     node = {
         'v2ref': model.v2ref.value,
         'v3ref': model.v3ref.value,
         'roll': model.roll.value,
         'matrix': model.matrix.value.tolist(),
         'shift': model.shift.value.tolist()
     }
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #40
0
 def to_tree_transform(cls, model, ctx):
     slits = []
     models = []
     for s, m in model.models.iteritems():
         slits.append(s)
         models.append(m)
     node = {'slits': slits,
             'models': models}
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #41
0
 def to_tree_transform(cls, model, ctx):
     node = {}
     node["fill_value"] = model.fill_value
     node["lookup_table"] = model.lookup_table
     node["points"] = [p for p in model.points]
     node["method"] = str(model.method)
     node["bounds_error"] = model.bounds_error
     node["name"] = model.name
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #42
0
 def to_tree_transform(cls, model, ctx):
     if isinstance(model, DirCos2Unitless):
         model_type = 'directional2unitless'
     elif isinstance(model, Unitless2DirCos):
         model_type = 'unitless2directional'
     else:
         raise TypeError("Model of type {0} i snot supported."
                         .format(model.__class__))
     node = {'model_type': model_type}
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #43
0
    def _to_tree_base_transform_members(cls, model, node, ctx):
        if getattr(model, '_user_inverse', None) is not None:
            node['inverse'] = yamlutil.custom_tree_to_tagged_tree(
            model._user_inverse, ctx)

        if model.name is not None:
            node['name'] = model.name

        try:
            bb = model.bounding_box
        except NotImplementedError:
            bb = None

        if bb is not None:
            if model.n_inputs == 1:
                bb = list(bb)
            else:
                bb = [list(item) for item in model.bounding_box]
            node['bounding_box'] = yamlutil.custom_tree_to_tagged_tree(bb, ctx)
Exemple #44
0
def test_isot(tmpdir):
    tree = {
        'time': time.Time('2000-01-01T00:00:00.000')
    }

    helpers.assert_roundtrip_tree(tree, tmpdir)

    ff = asdf.AsdfFile(tree)
    tree = yamlutil.custom_tree_to_tagged_tree(ff.tree, ff)
    assert isinstance(tree['time'], str)
Exemple #45
0
def test_time_tag():
    schema = asdf_schema.load_schema(
        'http://stsci.edu/schemas/asdf/time/time-1.1.0',
        resolve_references=True)
    schema = _flatten_combiners(schema)

    date = time.Time(datetime.datetime.now())
    tree = {'date': date}
    asdf = AsdfFile(tree=tree)
    instance = yamlutil.custom_tree_to_tagged_tree(tree['date'], asdf)

    asdf_schema.validate(instance, schema=schema)

    tag = 'tag:stsci.edu:asdf/time/time-1.1.0'
    date = tagged.tag_object(tag, date)
    tree = {'date': date}
    asdf = AsdfFile(tree=tree)
    instance = yamlutil.custom_tree_to_tagged_tree(tree['date'], asdf)

    asdf_schema.validate(instance, schema=schema)
Exemple #46
0
 def to_tree_transform(cls, model, ctx):
     node = {'order': model.order.value,
             'groove_density': model.groove_density.value
             }
     if isinstance(model, AngleFromGratingEquation):
         node['output'] = 'angle'
     elif isinstance(model, WavelengthFromGratingEquation):
         node['output'] = 'wavelength'
     else:
         raise TypeError("Can't serialize an instance of {0}".format(model.__class__.__name__))
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #47
0
 def to_tree_transform(cls, model, ctx):
     node = {'prism_angle': model.prism_angle,
             'kcoef': model.kcoef.tolist(),
             'lcoef': model.lcoef.tolist(),
             'tcoef': model.tcoef.tolist(),
             'ref_temp': model.tref,
             'ref_pressure': model.pref,
             'temp': model.temp,
             'pressure': model.pressure
             }
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #48
0
 def to_tree_transform(cls, model, ctx):
     xll=[list(m) for m in model.xmodels]
     yll=[list(m) for m in model.ymodels]
     node = {'orders': list(model.orders),
             'xmodels': xll,
             'ymodels': yll,
             'lmodels': list(model.lmodels),
             'theta': model.theta,
             'model_type': type(model).name
             }
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #49
0
 def to_tree_transform(cls, model, ctx):
     if isinstance(model, NRSZCoord):
         model_type = 'nrszcoord'
     elif isinstance(model, DirCos2Unitless):
         model_type = 'from_dircos'
     elif isinstance(model, Unitless2DirCos):
         model_type = 'to_dircos'
     else:
         raise TypeError("Model of type {0} i snot supported.".format(model.__class__))
     node = {'model_type': model_type}
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #50
0
    def to_tree(cls, data, ctx):
        columns = []
        for name in data.colnames:
            column = yamlutil.custom_tree_to_tagged_tree(
                data.columns[name], ctx)
            columns.append(column)

        node = {'columns': columns}
        if data.meta:
            node['meta'] = data.meta

        return node
Exemple #51
0
    def _to_tree(cls, frame, ctx):
        import numpy as np
        from astropy.coordinates import CartesianDifferential
        from astropy.coordinates import CartesianRepresentation
        from astropy.io.misc.asdf.tags.unit.quantity import QuantityType

        node = {}

        node['name'] = frame.name

        if frame.axes_order != (0, 1):
            node['axes_order'] = list(frame.axes_order)

        if frame.axes_names is not None:
            node['axes_names'] = list(frame.axes_names)

        if frame.reference_frame is not None:
            reference_frame = {}
            reference_frame['type'] = cls._get_inverse_reference_frame_mapping()[
                type(frame.reference_frame)]

            for name in frame.reference_frame.get_frame_attr_names().keys():
                frameval = getattr(frame.reference_frame, name)
                # CartesianRepresentation becomes a flat list of x,y,z
                # coordinates with associated units
                if isinstance(frameval, CartesianRepresentation):
                    value = [frameval.x, frameval.y, frameval.z]
                    frameval = value
                elif isinstance(frameval, CartesianDifferential):
                    value = [frameval.d_x, frameval.d_y, frameval.d_z]
                    frameval = value
                yamlval = yamlutil.custom_tree_to_tagged_tree(frameval, ctx)
                reference_frame[name] = yamlval

            node['reference_frame'] = reference_frame

        if frame.unit is not None:
            node['unit'] = yamlutil.custom_tree_to_tagged_tree(
                list(frame.unit), ctx)
        return node
Exemple #52
0
 def to_tree_transform(cls, model, ctx):
     if isinstance(model, modeling.models.Polynomial1D):
         coefficients = np.array(model.parameters)
     elif isinstance(model, modeling.models.Polynomial2D):
         degree = model.degree
         coefficients = np.zeros((degree + 1, degree + 1))
         for i in range(degree + 1):
             for j in range(degree + 1):
                 if i + j < degree + 1:
                     name = 'c' + str(i) + '_' +str(j)
                     coefficients[i, j] = getattr(model, name).value
     node = {'coefficients': coefficients}
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #53
0
    def to_tree(cls, smap, ctx):
        node = {}
        node['data'] = np.asarray(smap.data)
        node['meta'] = dict(smap.meta)
        node['shift'] = u.Quantity(smap.shifted_value)
        node['mask'] = smap.mask
        node['uncertainty'] = smap.uncertainty
        node['unit'] = smap.unit

        # TODO: Save some or all of plot_settings
        # node['plot_settings'] = smap.plot_settings

        return custom_tree_to_tagged_tree(node, ctx)
Exemple #54
0
 def get_item_as_json_value(self, key):
     """
     Equivalent to __getitem__, except returns the value as a JSON
     basic type, rather than an arbitrary Python type.
     """
     assert isinstance(key, six.string_types)
     meta = self
     parts = key.split('.')
     for part in parts:
         try:
             meta = getattr(meta, part)
         except AttributeError:
             raise KeyError(repr(key))
     return yamlutil.custom_tree_to_tagged_tree(meta, self._instance)
Exemple #55
0
    def to_tree(cls, equiv, ctx):
        node = {}
        if not isinstance(equiv, Equivalency):
            raise TypeError("'{0}' is not a valid Equivalency".format(equiv))

        eqs = []
        for e, kwargs in zip(equiv.name, equiv.kwargs):
            kwarg_names = list(kwargs.keys())
            kwarg_values = list(kwargs.values())
            kwarg_values = [custom_tree_to_tagged_tree(val, ctx) if isinstance(val, Quantity)
                            else val for val in kwarg_values]
            eq = {'name': e, 'kwargs_names': kwarg_names, 'kwargs_values': kwarg_values}
            eqs.append(eq)
        return eqs
Exemple #56
0
 def to_tree_transform(cls, model, ctx):
     selector = OrderedDict()
     node = OrderedDict()
     labels = list(model.selector)
     values = []
     for l in labels:
         values.append(model.selector[l])
     selector['labels'] = labels
     selector['transforms'] = values
     node['inputs'] = list(model.inputs)
     node['outputs'] = list(model.outputs)
     node['selector'] = selector
     node['label_mapper'] = model.label_mapper
     node['undefined_transform_value'] = model.undefined_transform_value
     return yamlutil.custom_tree_to_tagged_tree(node, ctx)
Exemple #57
0
    def to_tree(cls, representation, ctx):
        comps = representation.components
        components = {}
        for c in comps:
            value = getattr(representation, '_' + c, None)
            if value is not None:
                components[c] = value

        t = type(representation)

        node = {}
        node['type'] = t.__name__
        node['components'] = custom_tree_to_tagged_tree(components, ctx)

        return node
Exemple #58
0
    def _to_tree_from_model_tree(cls, tree, ctx):
        if tree.left.isleaf:
            left = yamlutil.custom_tree_to_tagged_tree(
                tree.left.value, ctx)
        else:
            left = cls._to_tree_from_model_tree(tree.left, ctx)

        if tree.right.isleaf:
            right = yamlutil.custom_tree_to_tagged_tree(
                tree.right.value, ctx)
        else:
            right = cls._to_tree_from_model_tree(tree.right, ctx)

        node = {
            'forward': [left, right]
        }

        try:
            tag_name = 'transform/' + _operator_to_tag_mapping[tree.value]
        except KeyError:
            raise ValueError("Unknown operator '{0}'".format(tree.value))

        node = tagged.tag_object(cls.make_yaml_tag(tag_name), node, ctx=ctx)
        return node
Exemple #59
0
    def to_tree(cls, frame, ctx):
        node = {}

        wrap_angle = Quantity(frame.ra.wrap_angle)
        node['ra'] = {
            'value': frame.ra.value,
            'unit': frame.ra.unit.to_string(),
            'wrap_angle': custom_tree_to_tagged_tree(wrap_angle, ctx)
        }
        node['dec'] = {
            'value': frame.dec.value,
            'unit': frame.dec.unit.to_string()
        }

        return node