示例#1
0
def serialize_Polygon(node, context):
    if node.geoColRef:
        return STC.Polygon[node.geoColRef]
    if node.vertices and _getDim(node.vertices[0]) != 2:
        raise common.STCValueError("Polygons are only available in 2D")
    return _makeBaseGeometry(STC.Polygon, node, context)[[
        STC.Vertex[STC.Position[_wrap2D(v)]] for v in node.vertices
    ]]
示例#2
0
def serialize_RefPos(node, context):
    try:
        return getattr(
            STC, node.standardOrigin
            or "UNKNOWNRefPos")[STC.PlanetaryEphem[node.planetaryEphemeris]]
    except AttributeError:
        raise common.STCValueError("No such standard origin: %s" %
                                   node.standardOrigin)
def _ensureSphericalFrame(coo):
    """raises an error if coo's frame is not suitable for holding spherical
	coordinates.
	XXX TODO: assert spatial and vel coos have the same frame, etc.
	"""
    if not coo.frame.isSpherical():
        raise common.STCValueError("%s is not a valid frame for transformable"
                                   " spherical coordinates." % (coo.frame))
示例#4
0
def serialize_Box(node, context):
    if node.geoColRef:
        return STC.Box[node.geoColRef]
    if _getDim(node.center) != 2:
        raise common.STCValueError("Boxes are only available in 2D")
    return _makeBaseGeometry(STC.Box, node,
                             context)[STC.Center[_wrap2D(node.center)],
                                      STC.Size[_wrap2D(node.boxsize)]]
示例#5
0
def getTransformFromScales(fromScale, toScale):
	if not fromScale or not toScale:
		return utils.identity

	try:
		toTT = timeConversions[fromScale][0]
		toTarget = timeConversions[toScale][1]
	except KeyError, key:
		raise common.STCValueError("Unknown timescale for transform: %s"%key)
示例#6
0
def serialize_Difference(node, context):
    if len(node.children) != 2:
        raise common.STCValueError(
            "Difference is only supported with two operands")
    op1 = _nodeToStan(node.children[0], context)
    op2 = _nodeToStan(node.children[1], context)
    # Banzai!  To save myself the trouble of having all those icky *2
    # elements around, I hack op2's name.
    op2.name_ = op2.name_ + "2"
    return STC.Difference[op1, op2]
示例#7
0
def _wiggleToCST(node, nDim):
	if node is None:
		return
	if isinstance(node, dm.CooWiggle):
		return node.values
	elif isinstance(node, dm.RadiusWiggle):
		return tuple((r,)*nDim for r in node.radii)
	else:
		raise common.STCValueError("Cannot serialize %s wiggles into STC-S"%
			node.__class__.__name__)
示例#8
0
	def asTriple(self):
		"""returns a triple defining the space frame for spherc's purposes.

		This is for the computation of coordinate transforms.  Since we only
		do coordinate transforms for spherical coordinate systems, this
		will, for now, raise STCValueErrors if everything but 2 or 3D SPHERICAL 
		flavours.  The other cases need more thought anyway.
		"""
		if self.flavor!="SPHERICAL" or (self.nDim!=2 and self.nDim!=3):
			raise common.STCValueError("Can only conform 2/3-spherical coordinates")
		return (self.refFrame, self.getEquinox(), self.refPos.standardOrigin)
示例#9
0
def serialize_Ellipse(node, context):
    if node.geoColRef:
        return STC.Ellipse[node.geoColRef]
    if _getDim(node.center) == 2:
        cls, wrap = STC.Ellipse, _wrap2D
    else:
        raise common.STCValueError("Ellipses are only defined in 2D")
    return _makeBaseGeometry(cls, node,
                             context)[STC.Center[wrap(node.center)],
                                      STC.SemiMajorAxis[node.smajAxis],
                                      STC.SemiMinorAxis[node.sminAxis],
                                      STC.PosAngle[node.posAngle], ]
示例#10
0
	def getASTItems(astRoot):
		areas, coo = getattr(astRoot, areaName), getattr(astRoot, cooName)
		if not areas and not coo:
			return None
		if len(areas)>1:
			raise common.STCValueError("STC-S does not support more than one area"
				" but %s has length %d"%(areaName, len(areas)))
		if areas:
			area = areas[0]
		else:
			area = None
		return coo, area
示例#11
0
def _serialize_Wiggle(node, serializer, wiggles):
    if node is None:
        return
    cooClass, radiusClass, matrixClass = wiggles
    if isinstance(node, dm.CooWiggle):
        return _wrapValues(cooClass, node.values, serializer),
    elif isinstance(node, dm.RadiusWiggle):
        return [radiusClass[strOrNull(r)] for r in node.radii]
    elif isinstance(node, dm.MatrixWiggle):
        return [matrixClass[_wrapMatrix(m, strOrNull)] for m in node.matrices]
    else:
        raise common.STCValueError("Cannot serialize %s errors to STC-X" %
                                   node.__class__.__name__)
示例#12
0
def _getFromSTC(elName, itemDesc):
    """returns the STC element elName or raises an STCValueError if
	it does not exist.

	itemDesc is used in the error message.  This is a helper for
	concise notation of reference frames.
	"""
    if elName is None:
        elName = "UNKNOWNFrame"
    try:
        return getattr(STC, elName)
    except AttributeError:
        raise common.STCValueError("No such %s: %s" % (itemDesc, elName))
示例#13
0
def serialize_Circle(node, context):
    # would you believe that the sequence of center and radius is swapped
    # in sphere and circle?  Oh boy.
    if node.geoColRef:
        return STC.Circle[node.geoColRef]
    nDim = _getDim(node.center)
    if nDim == 2:
        return _makeBaseGeometry(STC.Circle, node,
                                 context)[STC.Center[_wrap2D(node.center)],
                                          STC.Radius[node.radius], ]
    elif nDim == 3:
        return _makeBaseGeometry(STC.Sphere, node,
                                 context)[STC.Radius[node.radius],
                                          STC.Center[_wrap3D(node.center)], ]
    else:
        raise common.STCValueError("Spheres are only defined in 2 and 3D")
示例#14
0
def fromPgSphere(refFrame, pgGeom):
	"""Returns an AST for a pgsphere object as defined in utils.pgsphere.

	This interprets the pgSphere box as a coordinate interval, which is wrong
	but probably what most VO protocols expect.
	"""
	frame = SpaceFrame(refFrame=refFrame)

	if isinstance(pgGeom, SpaceCoo.pgClass):
		return STCSpec(place=SpaceCoo.fromPg(frame, pgGeom))

	for stcGeo in [Circle, SpaceInterval, Polygon]:
		if isinstance(pgGeom, stcGeo.pgClass):
			return STCSpec(areas=[stcGeo.fromPg(frame, pgGeom)])
	
	raise common.STCValueError("Unknown pgSphere object %r"%pgGeom)
示例#15
0
	def getEquinox(self):
		"""returns a datetime.datetime instance for the frame's equinox.

		It will return None if no equinox is given, and it may raise an
		STCValueError if an invalid equinox string has been set.
		"""
		if self.equinox is None:
			return None
		mat = re.match("([B|J])([0-9.]+)", self.equinox)
		if not mat:
			raise common.STCValueError("Equinoxes must be [BJ]<float>, but %s isn't"%(
				self.equinox))
		if mat.group(1)=='B':
			return times.bYearToDateTime(float(mat.group(2)))
		else:
			return times.jYearToDateTime(float(mat.group(2)))
示例#16
0
def _flattenValue(val, node=None):
	"""returns a sensible STC-S string representation for many sorts of
	values, dispatched on their type.

	This function can be used as a flattener.
	"""
	if val is None:
		return ""
	elif isinstance(val, basestring):
		return str(val)
	elif isinstance(val, (int, float)):
		return str(val)
	elif isinstance(val, (list, tuple)):
		return " ".join(_flattenValue(v) for v in val)
	elif isinstance(val, datetime.datetime):
		return val.isoformat()
	elif isinstance(val, common.ColRef):
		return '"%s"'%val.dest
	else:
		raise common.STCValueError("Cannot serialize %r to STC-S"%val)
示例#17
0
def _yallopToSv(yallop6, yallopK, rvAndPrlx):
    """returns a 6-Vector from a yallop-6 vector.

	rvAndPrlx is the third item of the return value of _svToYallop.
	"""
    rv, prlx = rvAndPrlx
    x, y, z, xd, yd, zd = yallop6
    rxy2 = x**2 + y**2
    r = math.sqrt(z**2 + rxy2)
    if rxy2 == 0:
        raise common.STCValueError("No spherical proper motion on poles.")
    alpha = math.atan2(y, x)
    if alpha < 0:
        alpha += 2 * math.pi
    delta = math.atan2(z, math.sqrt(rxy2))
    pma = (x * yd - y * xd) / rxy2
    pmd = (zd * rxy2 - z * (x * xd + y * yd)) / r / r / math.sqrt(rxy2)
    if abs(prlx) > 1 / sphermath.defaultDistance:
        rv = numpy.dot(yallop6[:3], yallop6[3:]) / yallopK / prlx / r
        prlx = prlx / r
    return _yallopSVConverter.to6((alpha, delta, prlx), (pma, pmd, rv))
示例#18
0
def getTrafoFunction(srcTriple, dstTriple, sixTrans):
    """returns a function that transforms 6-vectors from the system
	described by srcTriple to the one described by dstTriple.

	The triples consist of (system, equinox, refpoint).

	If no transformation function can be produced, the function raises
	an STCValueError.

	sixTrans is a sphermath.SVConverter instance, used here for communication
	of input details and user preferences.
	"""
    # special case the identity since it's indistingishable from a failed
    # search otherwise
    if srcTriple == dstTriple:
        return nullTransform
    trafoPath = _simplifyPath(_findTransformsPath(srcTriple, dstTriple))
    if trafoPath is None:
        raise common.STCValueError("Cannot find a transform from %s to %s" %
                                   (srcTriple, dstTriple))
    return _pathToFunction(trafoPath, sixTrans)
示例#19
0
def _makeSpatialUnits(nDim, *unitSources):
    """returns a units value from unitSources.

	The tuple has length nDim, unitSources are arguments that are either
	None, strings, or tuples.  The first non-None-one wins, strings and 1-tuples
	are expanded to length nDim.
	"""
    for unit in unitSources:
        if not unit:
            continue
        if isinstance(unit, (tuple, list)):
            if len(unit) == 1:
                return tuple(unit * nDim)
            elif len(unit) == nDim:
                return tuple(unit)
            else:
                raise common.STCValueError(
                    "Cannot construct %d-dimensional units from"
                    " %s." % (nDim, repr(unit)))
        else:  # a string or something similar
            return (unit, ) * nDim
    return None
示例#20
0
def computeTransMatrixFromPole(poleCoo, longZeroCoo, changeHands=False):
    """returns a transformation matrix to transform from the reference
	system into a rotated system.

	The rotated system is defined by its pole, the spherical coordinates
	at which it has longitude zero and whether or not it is right handed.

	All angles are in rad.
	"""
    # when moving from numpy here, replace this with the like-named
    # function from utils.mathtricks.
    x = spherToCart(*longZeroCoo)
    z = spherToCart(*poleCoo)
    if abs(numpy.dot(x, z)) > 1e-5:
        raise common.STCValueError(
            "%s and %s are not valid pole/zero points for"
            " a rotated coordinate system" % (poleCoo, longZeroCoo))
    y = (z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2],
         z[0] * x[1] - z[1] * x[0])
    if changeHands:
        y = (-y[0], -y[1], -y[2])
    return numpy.array([x, y, z])
示例#21
0
def _validateCoos(values, nDim, minItems, maxItems):
    """makes sure values is valid a source of between minItems and maxItems
	nDim-dimensional tuples.

	minItems and maxItems may both be None to signify no limit.
	"""
    if isinstance(values, common.GeometryColRef):
        values.expectedLength = nDim
    numItems = len(values) / nDim
    if numItems * nDim != len(values):
        # special case: a *single* ColRef is good for anything (could be
        # an array or something)
        if len(values) == 1 and isinstance(values[0], common.ColRef):
            return
        raise common.STCSParseError(
            "%s is not valid input to create %d-dimensional"
            " coordinates" % (values, nDim))
    if minItems is not None and numItems < minItems:
        raise common.STCSParseError("Expected at least %d coordinates in %s." %
                                    (minItems, values))
    if maxItems is not None and numItems > maxItems:
        raise common.STCValueError(
            "Expected not more than %d coordinates in %s." %
            (maxItems, values))
示例#22
0
	def _setupNode(self):
		if self.unit and not self.velTimeUnit:
			raise common.STCValueError("Invalid units for Redshift: %s/%s."%(
				repr(self.unit), repr(self.velTimeUnit)))
		self._setupNodeNext(_RedshiftMixin)
示例#23
0
	def _setupNode(self):
		if self.unit:
			if not self.velTimeUnit or len(self.unit)!=len(self.velTimeUnit):
				raise common.STCValueError("Invalid units for Velocity: %s/%s."%(
					repr(self.unit), repr(self.velTimeUnit)))
		self._setupNodeNext(_VelocityMixin)
示例#24
0
	def adaptValuesWith(self, unitConverter):
		raise common.STCValueError("Matrix wiggles cannot be transformed.")
示例#25
0
def _getEulersFor(frame):
	if not frame in TRANSFORMS:
		raise common.STCValueError("Unknown reference frame: %s"%frame)
	return TRANSFORMS[frame]
示例#26
0
def _computeFlavor(node):
	try:
		return stcsFlavors[(node.nDim, node.flavor)]
	except KeyError:
		raise common.STCValueError("Coordinate Frame %s cannot"
			" be represented it STC-S"%node)
示例#27
0
def serialize_Not(node, context):
    if len(node.children) != 1:
        raise common.STCValueError("Not is only supported with one operand")
    return STC.Negation[_nodeToStan(node.children[0], context)]