File: quantity.py

package info (click to toggle)
python-astropy 1.3-8~bpo8%2B2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 44,292 kB
  • sloc: ansic: 160,360; python: 137,322; sh: 11,493; lex: 7,638; yacc: 4,956; xml: 1,796; makefile: 474; cpp: 364
file content (1585 lines) | stat: -rw-r--r-- 63,924 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module defines the `Quantity` object, which represents a number with some
associated units. `Quantity` objects support operations like ordinary numbers,
but will deal with unit conversions internally.
"""

from __future__ import (absolute_import, unicode_literals, division,
                        print_function)

# Standard library
import re
import numbers
from fractions import Fraction
import warnings

import numpy as np

# AstroPy
from ..extern import six
from ..extern.six.moves import zip
from .core import (Unit, dimensionless_unscaled, get_current_unit_registry,
                   UnitBase, UnitsError, UnitConversionError, UnitTypeError)
from .format.latex import Latex
from ..utils.compat import NUMPY_LT_1_8, NUMPY_LT_1_9
from ..utils.compat.misc import override__dir__
from ..utils.misc import isiterable, InheritDocstrings
from ..utils.data_info import ParentDtypeInfo
from .. import config as _config


__all__ = ["Quantity", "SpecificTypeQuantity"]


# We don't want to run doctests in the docstrings we inherit from Numpy
__doctest_skip__ = ['Quantity.*']


_UNIT_NOT_INITIALISED = "(Unit not initialised)"
_UFUNCS_FILTER_WARNINGS = {np.arcsin, np.arccos, np.arccosh, np.arctanh}

class Conf(_config.ConfigNamespace):
    """
    Configuration parameters for Quantity
    """
    latex_array_threshold = _config.ConfigItem(100,
        'The maximum size an array Quantity can be before its LaTeX '
        'representation for IPython gets "summarized" (meaning only the first '
        'and last few elements are shown with "..." between). Setting this to a '
        'negative number means that the value will instead be whatever numpy '
        'gets from get_printoptions.')
conf = Conf()


def _can_have_arbitrary_unit(value):
    """Test whether the items in value can have arbitrary units

    Numbers whose value does not change upon a unit change, i.e.,
    zero, infinity, or not-a-number

    Parameters
    ----------
    value : number or array

    Returns
    -------
    `True` if each member is either zero or not finite, `False` otherwise
    """
    return np.all(np.logical_or(np.equal(value, 0.), ~np.isfinite(value)))


class QuantityIterator(object):
    """
    Flat iterator object to iterate over Quantities

    A `QuantityIterator` iterator is returned by ``q.flat`` for any Quantity
    ``q``.  It allows iterating over the array as if it were a 1-D array,
    either in a for-loop or by calling its `next` method.

    Iteration is done in C-contiguous style, with the last index varying the
    fastest. The iterator can also be indexed using basic slicing or
    advanced indexing.

    See Also
    --------
    Quantity.flatten : Returns a flattened copy of an array.

    Notes
    -----
    `QuantityIterator` is inspired by `~numpy.ma.core.MaskedIterator`.  It
    is not exported by the `~astropy.units` module.  Instead of
    instantiating a `QuantityIterator` directly, use `Quantity.flat`.
    """
    def __init__(self, q):
        self._quantity = q
        self._dataiter = q.view(np.ndarray).flat

    def __iter__(self):
        return self

    def __getitem__(self, indx):
        out = self._dataiter.__getitem__(indx)
        # For single elements, ndarray.flat.__getitem__ returns scalars; these
        # need a new view as a Quantity.
        if isinstance(out, type(self._quantity)):
            return out
        else:
            return self._quantity._new_view(out)

    def __setitem__(self, index, value):
        self._dataiter[index] = self._quantity._to_own_unit(value)

    def __next__(self):
        """
        Return the next value, or raise StopIteration.
        """
        out = next(self._dataiter)
        # ndarray.flat._dataiter returns scalars, so need a view as a Quantity.
        return self._quantity._new_view(out)

    next = __next__


class QuantityInfo(ParentDtypeInfo):
    """
    Container for meta information like name, description, format.  This is
    required when the object is used as a mixin column within a table, but can
    be used as a general way to store meta information.
    """
    attrs_from_parent = set(['dtype', 'unit'])  # dtype and unit taken from parent
    _supports_indexing = True
    _represent_as_dict_attrs = ('value', 'unit')

    @staticmethod
    def default_format(val):
        return '{0.value:}'.format(val)

    @staticmethod
    def possible_string_format_functions(format_):
        """Iterate through possible string-derived format functions.

        A string can either be a format specifier for the format built-in,
        a new-style format string, or an old-style format string.

        This method is overridden in order to suppress printing the unit
        in each row since it is already at the top in the column header.
        """
        yield lambda format_, val: format(val.value, format_)
        yield lambda format_, val: format_.format(val.value)
        yield lambda format_, val: format_ % val.value

    def _construct_from_dict(self, map):
        # Need to pop value because different Quantity subclasses use
        # different first arg name for the value.  :-(
        value = map.pop('value')
        return self._parent_cls(value, **map)


@six.add_metaclass(InheritDocstrings)
class Quantity(np.ndarray):
    """A `~astropy.units.Quantity` represents a number with some associated unit.

    Parameters
    ----------
    value : number, `~numpy.ndarray`, `Quantity` object (sequence), str
        The numerical value of this quantity in the units given by unit.  If a
        `Quantity` or sequence of them (or any other valid object with a
        ``unit`` attribute), creates a new `Quantity` object, converting to
        `unit` units as needed.  If a string, it is converted to a number or
        `Quantity`, depending on whether a unit is present.

    unit : `~astropy.units.UnitBase` instance, str
        An object that represents the unit associated with the input value.
        Must be an `~astropy.units.UnitBase` object or a string parseable by
        the :mod:`~astropy.units` package.

    dtype : ~numpy.dtype, optional
        The dtype of the resulting Numpy array or scalar that will
        hold the value.  If not provided, it is determined from the input,
        except that any input that cannot represent float (integer and bool)
        is converted to float.

    copy : bool, optional
        If `True` (default), then the value is copied.  Otherwise, a copy will
        only be made if ``__array__`` returns a copy, if value is a nested
        sequence, or if a copy is needed to satisfy an explicitly given
        ``dtype``.  (The `False` option is intended mostly for internal use,
        to speed up initialization where a copy is known to have been made.
        Use with care.)

    order : {'C', 'F', 'A'}, optional
        Specify the order of the array.  As in `~numpy.array`.  This parameter
        is ignored if the input is a `Quantity` and ``copy=False``.

    subok : bool, optional
        If `False` (default), the returned array will be forced to be a
        `Quantity`.  Otherwise, `Quantity` subclasses will be passed through.

    ndmin : int, optional
        Specifies the minimum number of dimensions that the resulting array
        should have.  Ones will be pre-pended to the shape as needed to meet
        this requirement.  This parameter is ignored if the input is a
        `Quantity` and ``copy=False``.

    Raises
    ------
    TypeError
        If the value provided is not a Python numeric type.
    TypeError
        If the unit provided is not either a :class:`~astropy.units.Unit`
        object or a parseable string unit.

    Notes
    -----
    Quantities can also be created by multiplying a number or array with a
    :class:`~astropy.units.Unit`. See http://docs.astropy.org/en/latest/units/

    """
    # Need to set a class-level default for _equivalencies, or
    # Constants can not initialize properly
    _equivalencies = []

    # Default unit for initialization; can be overridden by subclasses,
    # possibly to `None` to indicate there is no default unit.
    _default_unit = dimensionless_unscaled

    # Ensures views have an undefined unit.
    _unit = None

    __array_priority__ = 10000

    def __new__(cls, value, unit=None, dtype=None, copy=True, order=None,
                subok=False, ndmin=0):

        if unit is not None:
            # convert unit first, to avoid multiple string->unit conversions
            unit = Unit(unit)

        # optimize speed for Quantity with no dtype given, copy=False
        if isinstance(value, Quantity):
            if unit is not None and unit is not value.unit:
                value = value.to(unit)
                # the above already makes a copy (with float dtype)
                copy = False

            if type(value) is not cls and not (subok and
                                               isinstance(value, cls)):
                value = value.view(cls)

            if dtype is None:
                if not copy:
                    return value

                if not np.can_cast(np.float32, value.dtype):
                    dtype = np.float

            return np.array(value, dtype=dtype, copy=copy, order=order,
                            subok=True, ndmin=ndmin)

        # Maybe str, or list/tuple of Quantity? If so, this may set value_unit.
        # To ensure array remains fast, we short-circuit it.
        value_unit = None
        if not isinstance(value, np.ndarray):
            if isinstance(value, six.string_types):
                # The first part of the regex string matches any integer/float;
                # the second parts adds possible trailing .+-, which will break
                # the float function below and ensure things like 1.2.3deg
                # will not work.
                v = re.match(r'\s*[+-]?((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+)?'
                             r'[.+-]?', value)
                try:
                    value = float(v.group())
                except Exception:
                    raise TypeError('Cannot parse "{0}" as a {1}. It does not '
                                    'start with a number.'
                                    .format(value, cls.__name__))
                unit_string = v.string[v.end():].strip()
                if unit_string:
                    value_unit = Unit(unit_string)
                    if unit is None:
                        unit = value_unit  # signal no conversion needed below.

            elif (isiterable(value) and len(value) > 0 and
                  all(isinstance(v, Quantity) for v in value)):
                # Convert all quantities to the same unit.
                if unit is None:
                    unit = value[0].unit
                value = [q.to(unit).value for q in value]
                value_unit = unit  # signal below that conversion has been done

        if value_unit is None:
            # If the value has a `unit` attribute and if not None
            # (for Columns with uninitialized unit), treat it like a quantity.
            value_unit = getattr(value, 'unit', None)
            if value_unit is None:
                # Default to dimensionless for no (initialized) unit attribute.
                if unit is None:
                    unit = cls._default_unit
                value_unit = unit  # signal below that no conversion is needed
            else:
                try:
                    value_unit = Unit(value_unit)
                except Exception as exc:
                    raise TypeError("The unit attribute {0} of the input could "
                                    "not be parsed as an astropy Unit, raising "
                                    "the following exception:\n{1}"
                                    .format(repr(value.unit), exc))

                if unit is None:
                    unit = value_unit
                elif unit is not value_unit:
                    copy = False  # copy will be made in conversion at end

        value = np.array(value, dtype=dtype, copy=copy, order=order,
                         subok=False, ndmin=ndmin)

        # check that array contains numbers or long int objects
        if (value.dtype.kind in 'OSU' and
            not (value.dtype.kind == 'O' and
                 isinstance(value.item(() if value.ndim == 0 else 0),
                            numbers.Number))):
            raise TypeError("The value must be a valid Python or "
                            "Numpy numeric type.")

        # by default, cast any integer, boolean, etc., to float
        if dtype is None and (not np.can_cast(np.float32, value.dtype)
                              or value.dtype.kind == 'O'):
            value = value.astype(np.float)

        value = value.view(cls)
        value._set_unit(value_unit)
        if unit is value_unit:
            return value
        else:
            # here we had non-Quantity input that had a "unit" attribute
            # with a unit different from the desired one.  So, convert.
            return value.to(unit)

    def __array_finalize__(self, obj):
        # If our unit is not set and obj has a valid one, use it.
        if self._unit is None:
            unit = getattr(obj, '_unit', None)
            if unit is not None:
                self._set_unit(unit)

        # Copy info if the original had `info` defined.  Because of the way the
        # DataInfo works, `'info' in obj.__dict__` is False until the
        # `info` attribute is accessed or set.  Note that `obj` can be an
        # ndarray which doesn't have a `__dict__`.
        if 'info' in getattr(obj, '__dict__', ()):
            self.info = obj.info

    def __array_prepare__(self, obj, context=None):
        # This method gets called by Numpy whenever a ufunc is called on the
        # array. The object passed in ``obj`` is an empty version of the
        # output array which we can e.g. change to an array sub-class, add
        # attributes to, etc. After this is called, then the ufunc is called
        # and the values in this empty array are set.

        # If no context is set, just return the input
        if context is None:
            return obj

        # Find out which ufunc is being used
        function = context[0]

        from .quantity_helper import UNSUPPORTED_UFUNCS, UFUNC_HELPERS

        # Check whether we even support this ufunc
        if function in UNSUPPORTED_UFUNCS:
            raise TypeError("Cannot use function '{0}' with quantities"
                            .format(function.__name__))

        # Now find out what arguments were passed to the ufunc, usually, this
        # will include at least the present object, and another, which could
        # be a Quantity, or a Numpy array, etc. when using two-argument ufuncs.
        args = context[1][:function.nin]
        units = [getattr(arg, 'unit', None) for arg in args]

        # If the ufunc is supported, then we call a helper function (defined
        # in quantity_helper.py) which returns the scale by which the inputs
        # should be multiplied before being passed to the ufunc, as well as
        # the unit the output from the ufunc will have.
        if function in UFUNC_HELPERS:
            converters, result_unit = UFUNC_HELPERS[function](function, *units)
        else:
            raise TypeError("Unknown ufunc {0}.  Please raise issue on "
                            "https://github.com/astropy/astropy"
                            .format(function.__name__))

        if any(converter is False for converter in converters):
            # for two-argument ufuncs with a quantity and a non-quantity,
            # the quantity normally needs to be dimensionless, *except*
            # if the non-quantity can have arbitrary unit, i.e., when it
            # is all zero, infinity or NaN.  In that case, the non-quantity
            # can just have the unit of the quantity
            # (this allows, e.g., `q > 0.` independent of unit)
            maybe_arbitrary_arg = args[converters.index(False)]
            try:
                if _can_have_arbitrary_unit(maybe_arbitrary_arg):
                    converters = [None, None]
                else:
                    raise UnitsError("Can only apply '{0}' function to "
                                     "dimensionless quantities when other "
                                     "argument is not a quantity (unless the "
                                     "latter is all zero/infinity/nan)"
                                     .format(function.__name__))
            except TypeError:
                # _can_have_arbitrary_unit failed: arg could not be compared
                # with zero or checked to be finite.  Then, ufunc will fail too.
                raise TypeError("Unsupported operand type(s) for ufunc {0}: "
                                "'{1}' and '{2}'"
                                .format(function.__name__,
                                        args[0].__class__.__name__,
                                        args[1].__class__.__name__))

        # In the case of np.power and np.float_power, the unit itself needs to
        # be modified by an amount that depends on one of the input values,
        # so we need to treat this as a special case.
        # TODO: find a better way to deal with this.
        if result_unit is False:
            if units[0] is None or units[0] == dimensionless_unscaled:
                result_unit = dimensionless_unscaled
            else:
                if units[1] is None:
                    p = args[1]
                else:
                    p = args[1].to(dimensionless_unscaled).value

                try:
                    result_unit = units[0] ** p
                except ValueError as exc:
                    # Changing the unit does not work for, e.g., array-shaped
                    # power, but this is OK if we're (scaled) dimensionless.
                    try:
                        converters[0] = units[0]._get_converter(
                            dimensionless_unscaled)
                    except UnitConversionError:
                        raise exc
                    else:
                        result_unit = dimensionless_unscaled

        # We now prepare the output object
        if self is obj:

            # this happens if the output object is self, which happens
            # for in-place operations such as q1 += q2

            # In some cases, the result of a ufunc should be a plain Numpy
            # array, which we can't do if we are doing an in-place operation.
            if result_unit is None:
                raise TypeError("Cannot store non-quantity output from {0} "
                                "function in {1} instance"
                                .format(function.__name__, type(self)))

            if self.__quantity_subclass__(result_unit)[0] is not type(self):
                raise UnitTypeError(
                    "Cannot store output with unit '{0}' from {1} function "
                    "in {2} instance.  Use {3} instance instead."
                    .format(result_unit, function.__name__, type(self),
                            self.__quantity_subclass__(result_unit)[0]))

            # If the Quantity has an integer dtype, in-place operations are
            # dangerous because in some cases the quantity will be e.g.
            # decomposed, which involves being scaled by a float, but since
            # the array is an integer the output then gets converted to an int
            # and truncated.
            result_dtype = np.result_type(*((args + (float,))
                                            if any(converters) else args))
            if not np.can_cast(result_dtype, obj.dtype, casting='same_kind'):
                raise TypeError("Arguments cannot be cast safely to inplace "
                                "output with dtype={0}".format(self.dtype))

            result = self  # no view needed since we return the object itself

            # in principle, if self is also an argument, it could be rescaled
            # here, since it won't be needed anymore.  But maybe not change
            # inputs before the calculation even if they will get destroyed

        else:  # normal case: set up output as a Quantity

            result = self._new_view(obj, result_unit)

        # We now need to treat the case where the inputs have to be scaled -
        # the issue is that we can't actually scale the inputs since that
        # would be changing the objects passed to the ufunc, which would not
        # be expected by the user.
        if any(converters):

            # If self is both output and input (which happens for in-place
            # operations), input will get overwritten with junk. To avoid
            # that, hide it in a new object
            if self is obj and any(self is arg for arg in args):
                # but with two outputs it would become unhidden too soon
                # [ie., np.modf(q1, q1, other)].  Bail.
                if context[2] < function.nout - 1:
                    raise TypeError("Cannot apply multi-output {0} function "
                                    "to quantities with in-place replacement "
                                    "of an input by any but the last output."
                                    .format(function.__name__))

                # If self is already contiguous, we don't need to do
                # an additional copy back into the original array, so
                # we store it in `result._result`.  Otherwise, we
                # store it in `result._contiguous`.  `__array_wrap__`
                # knows how to handle putting either form back into
                # the original array.
                if self.flags['C_CONTIGUOUS']:
                    result = self.copy()
                    result._result = self
                else:
                    result._contiguous = self.copy()

            # ensure we remember the scales we need
            result._converters = converters

            if function in _UFUNCS_FILTER_WARNINGS:
                # Filter out RuntimeWarning's caused by the ufunc being called on
                # the unscaled quantity first (e.g., np.arcsin(15*u.pc/u.kpc))
                self._catch_warnings = warnings.catch_warnings()
                self._catch_warnings.__enter__()
                warnings.filterwarnings('ignore',
                                        message='invalid value encountered in',
                                        category=RuntimeWarning)

        # unit output will get (setting _unit could prematurely change input
        # if obj is self, which happens for in-place operations; see above)
        result._result_unit = result_unit

        return result

    def __array_wrap__(self, obj, context=None):

        if context is None:
            # Methods like .squeeze() created a new `ndarray` and then call
            # __array_wrap__ to turn the array into self's subclass.
            return self._new_view(obj)

        else:
            # with context defined, we are continuing after a ufunc evaluation.
            if hasattr(obj, '_result_unit'):
                result_unit = obj._result_unit
                del obj._result_unit
            else:
                result_unit = None

            # We now need to re-calculate quantities for which the input
            # needed to be scaled.
            if hasattr(obj, '_converters'):

                converters = obj._converters
                del obj._converters

                if hasattr(self, '_catch_warnings'):
                    self._catch_warnings.__exit__()
                    del self._catch_warnings

                # For in-place operations, input will get overwritten with
                # junk. To avoid that, we hid it in a new object in
                # __array_prepare__ and retrieve it here.
                if hasattr(obj, '_result'):
                    obj = obj._result
                elif hasattr(obj, '_contiguous'):
                    obj[()] = obj._contiguous
                    del obj._contiguous

                # take array view to which output can be written without
                # getting back here
                obj_array = obj.view(np.ndarray)

                # Find out which ufunc was called and with which inputs
                function = context[0]
                args = context[1][:function.nin]

                # Set the inputs, rescaling as necessary
                inputs = []
                for arg, converter in zip(args, converters):
                    if converter:
                        inputs.append(converter(arg.value))
                    else:  # with no conversion, input can be non-Quantity.
                        inputs.append(getattr(arg, 'value', arg))

                # For output arrays that require scaling, we can reuse the
                # output array to perform the scaling in place, as long as the
                # array is not integral. Here, we set the obj_array to `None`
                # when it cannot be used to store the scaled result.
                # Use a try/except, since np.result_type can fail, which would
                # break the wrapping #4770.
                try:
                    tmp_dtype = np.result_type(*inputs)
                # Catch the appropriate exceptions: TypeError or ValueError in
                # case the result_type raised an Exception, i.e. inputs is list
                except (TypeError, ValueError):
                    obj_array = None
                else:
                    # Explicitly check if it can store the result.
                    if not (result_unit is None or
                            np.can_cast(tmp_dtype, obj_array.dtype)):
                        obj_array = None

                # Re-compute the output using the ufunc
                if function.nin == 1:
                    if function.nout == 1:
                        out = function(inputs[0], obj_array)
                    else:  # 2-output function (np.modf, np.frexp); 1 input
                        if context[2] == 0:
                            out, _ = function(inputs[0], obj_array, None)
                        else:
                            _, out = function(inputs[0], None, obj_array)
                else:
                    out = function(inputs[0], inputs[1], obj_array)

                if obj_array is None:
                    obj = self._new_view(out, result_unit)

            if result_unit is None:  # return a plain array
                return obj.view(np.ndarray)
            elif obj is self:  # all OK now, so set unit.
                obj._set_unit(result_unit)
                return obj
            else:
                return obj

    def __deepcopy__(self, memo):
        # If we don't define this, ``copy.deepcopy(quantity)`` will
        # return a bare Numpy array.
        return self.copy()

    def __quantity_subclass__(self, unit):
        """
        Overridden by subclasses to change what kind of view is
        created based on the output unit of an operation.

        Parameters
        ----------
        unit : UnitBase
            The unit for which the appropriate class should be returned

        Returns
        -------
        tuple :
            - `Quantity` subclass
            - bool: True is subclasses of the given class are ok
        """
        return Quantity, True

    def _new_view(self, obj=None, unit=None):
        """
        Create a Quantity view of some array-like input, and set the unit

        By default, return a view of ``obj`` of the same class as ``self`` and
        with the same unit.  Subclasses can override the type of class for a
        given unit using ``__quantity_subclass__``, and can ensure properties
        other than the unit are copied using ``__array_finalize__``.

        If the given unit defines a ``_quantity_class`` of which ``self``
        is not an instance, a view using this class is taken.

        Parameters
        ----------
        obj : ndarray or scalar, optional
            The array to create a view of.  If obj is a numpy or python scalar,
            it will be converted to an array scalar.  By default, ``self``
            is converted.

        unit : `UnitBase`, or anything convertible to a :class:`~astropy.units.Unit`, optional
            The unit of the resulting object.  It is used to select a
            subclass, and explicitly assigned to the view if given.
            If not given, the subclass and unit will be that of ``self``.

        Returns
        -------
        view : Quantity subclass
        """
        # Determine the unit and quantity subclass that we need for the view.
        if unit is None:
            unit = self.unit
            quantity_subclass = self.__class__
        else:
            unit = Unit(unit)
            quantity_subclass = getattr(unit, '_quantity_class', Quantity)
            if isinstance(self, quantity_subclass):
                quantity_subclass, subok = self.__quantity_subclass__(unit)
                if subok:
                    quantity_subclass = self.__class__

        # We only want to propagate information from ``self`` to our new view,
        # so obj should be a regular array.  By using ``np.array``, we also
        # convert python and numpy scalars, which cannot be viewed as arrays
        # and thus not as Quantity either, to zero-dimensional arrays.
        # (These are turned back into scalar in `.value`)
        if obj is None:
            obj = self.view(np.ndarray)
        else:
            obj = np.array(obj, copy=False)

        # Take the view, set the unit, and update possible other properties
        # such as ``info``, ``wrap_angle`` in `Longitude`, etc.
        view = obj.view(quantity_subclass)
        view._set_unit(unit)
        view.__array_finalize__(self)
        return view

    def _set_unit(self, unit):
        """Set the unit.

        This is used anywhere the unit is set or modified, i.e., in the
        initilizer, in ``__imul__`` and ``__itruediv__`` for in-place
        multiplication and division by another unit, as well as in
        ``__array_finalize__`` for wrapping up views.  For Quantity, it just
        sets the unit, but subclasses can override it to check that, e.g.,
        a unit is consistent.
        """
        if not isinstance(unit, UnitBase):
            # Trying to go through a string ensures that, e.g., Magnitudes with
            # dimensionless physical unit become Quantity with units of mag.
            unit = Unit(str(unit), parse_strict='silent')
            if not isinstance(unit, UnitBase):
                raise UnitTypeError(
                    "{0} instances require {1} units, not {2} instances."
                    .format(type(self).__name__, UnitBase, type(unit)))

        self._unit = unit

    def __reduce__(self):
        # patch to pickle Quantity objects (ndarray subclasses), see
        # http://www.mail-archive.com/numpy-discussion@scipy.org/msg02446.html

        object_state = list(super(Quantity, self).__reduce__())
        object_state[2] = (object_state[2], self.__dict__)
        return tuple(object_state)

    def __setstate__(self, state):
        # patch to unpickle Quantity objects (ndarray subclasses), see
        # http://www.mail-archive.com/numpy-discussion@scipy.org/msg02446.html

        nd_state, own_state = state
        super(Quantity, self).__setstate__(nd_state)
        self.__dict__.update(own_state)

    def to(self, unit, equivalencies=[]):
        """
        Returns a new `~astropy.units.Quantity` object with the specified
        units.

        Parameters
        ----------
        unit : `~astropy.units.UnitBase` instance, str
            An object that represents the unit to convert to. Must be
            an `~astropy.units.UnitBase` object or a string parseable
            by the `~astropy.units` package.

        equivalencies : list of equivalence pairs, optional
            A list of equivalence pairs to try if the units are not
            directly convertible.  See :ref:`unit_equivalencies`.
            If not provided or ``[]``, class default equivalencies will be used
            (none for `~astropy.units.Quantity`, but may be set for subclasses)
            If `None`, no equivalencies will be applied at all, not even any
            set globally or within a context.
        """
        if equivalencies == []:
            equivalencies = self._equivalencies
        unit = Unit(unit)
        new_val = self.unit.to(unit, self.view(np.ndarray),
                               equivalencies=equivalencies)
        return self._new_view(new_val, unit)

    info = QuantityInfo()

    @property
    def value(self):
        """ The numerical value of this quantity. """
        value = self.view(np.ndarray)
        if self.shape:
            return value
        else:
            return value.item()

    @property
    def unit(self):
        """
        A `~astropy.units.UnitBase` object representing the unit of this
        quantity.
        """

        return self._unit

    @property
    def equivalencies(self):
        """
        A list of equivalencies that will be applied by default during
        unit conversions.
        """

        return self._equivalencies

    @property
    def si(self):
        """
        Returns a copy of the current `Quantity` instance with SI units. The
        value of the resulting object will be scaled.
        """
        si_unit = self.unit.si
        return self._new_view(self.value * si_unit.scale,
                              si_unit / si_unit.scale)

    @property
    def cgs(self):
        """
        Returns a copy of the current `Quantity` instance with CGS units. The
        value of the resulting object will be scaled.
        """
        cgs_unit = self.unit.cgs
        return self._new_view(self.value * cgs_unit.scale,
                              cgs_unit / cgs_unit.scale)

    @property
    def isscalar(self):
        """
        True if the `value` of this quantity is a scalar, or False if it
        is an array-like object.

        .. note::
            This is subtly different from `numpy.isscalar` in that
            `numpy.isscalar` returns False for a zero-dimensional array
            (e.g. ``np.array(1)``), while this is True for quantities,
            since quantities cannot represent true numpy scalars.
        """
        return not self.shape

    # This flag controls whether convenience conversion members, such
    # as `q.m` equivalent to `q.to(u.m).value` are available.  This is
    # not turned on on Quantity itself, but is on some subclasses of
    # Quantity, such as `astropy.coordinates.Angle`.
    _include_easy_conversion_members = False

    @override__dir__
    def __dir__(self):
        """
        Quantities are able to directly convert to other units that
        have the same physical type.  This function is implemented in
        order to make autocompletion still work correctly in IPython.
        """
        if not self._include_easy_conversion_members:
            return []
        extra_members = set()
        equivalencies = Unit._normalize_equivalencies(self.equivalencies)
        for equivalent in self.unit._get_units_with_same_physical_type(
                equivalencies):
            extra_members.update(equivalent.names)
        return extra_members

    def __getattr__(self, attr):
        """
        Quantities are able to directly convert to other units that
        have the same physical type.
        """
        if not self._include_easy_conversion_members:
            raise AttributeError(
                "'{0}' object has no '{1}' member".format(
                    self.__class__.__name__,
                    attr))

        def get_virtual_unit_attribute():
            registry = get_current_unit_registry().registry
            to_unit = registry.get(attr, None)
            if to_unit is None:
                return None

            try:
                return self.unit.to(
                    to_unit, self.value, equivalencies=self.equivalencies)
            except UnitsError:
                return None

        value = get_virtual_unit_attribute()

        if value is None:
            raise AttributeError(
                "{0} instance has no attribute '{1}'".format(
                    self.__class__.__name__, attr))
        else:
            return value

    if not NUMPY_LT_1_9:
        # Equality (return False if units do not match) needs to be handled
        # explicitly for numpy >=1.9, since it no longer traps errors.
        def __eq__(self, other):
            try:
                try:
                    return super(Quantity, self).__eq__(other)
                except DeprecationWarning:
                    # We treat the DeprecationWarning separately, since it may
                    # mask another Exception.  But we do not want to just use
                    # np.equal, since super's __eq__ treats recarrays correctly.
                    return np.equal(self, other)
            except UnitsError:
                return False
            except TypeError:
                return NotImplemented

        def __ne__(self, other):
            try:
                try:
                    return super(Quantity, self).__ne__(other)
                except DeprecationWarning:
                    return np.not_equal(self, other)
            except UnitsError:
                return True
            except TypeError:
                return NotImplemented

    # Arithmetic operations
    def __mul__(self, other):
        """ Multiplication between `Quantity` objects and other objects."""

        if isinstance(other, (UnitBase, six.string_types)):
            try:
                return self._new_view(self.copy(), other * self.unit)
            except UnitsError:  # let other try to deal with it
                return NotImplemented

        return super(Quantity, self).__mul__(other)

    def __imul__(self, other):
        """In-place multiplication between `Quantity` objects and others."""

        if isinstance(other, (UnitBase, six.string_types)):
            self._set_unit(other * self.unit)
            return self

        return super(Quantity, self).__imul__(other)

    def __rmul__(self, other):
        """ Right Multiplication between `Quantity` objects and other
        objects.
        """

        return self.__mul__(other)

    def __truediv__(self, other):
        """ Division between `Quantity` objects and other objects."""

        if isinstance(other, (UnitBase, six.string_types)):
            try:
                return self._new_view(self.copy(), self.unit / other)
            except UnitsError:  # let other try to deal with it
                return NotImplemented

        return super(Quantity, self).__truediv__(other)

    def __itruediv__(self, other):
        """Inplace division between `Quantity` objects and other objects."""

        if isinstance(other, (UnitBase, six.string_types)):
            self._set_unit(self.unit / other)
            return self

        return super(Quantity, self).__itruediv__(other)

    def __rtruediv__(self, other):
        """ Right Division between `Quantity` objects and other objects."""

        if isinstance(other, (UnitBase, six.string_types)):
            return self._new_view(1. / self.value, other / self.unit)

        return super(Quantity, self).__rtruediv__(other)

    def __div__(self, other):
        """ Division between `Quantity` objects. """
        return self.__truediv__(other)

    def __idiv__(self, other):
        """ Division between `Quantity` objects. """
        return self.__itruediv__(other)

    def __rdiv__(self, other):
        """ Division between `Quantity` objects. """
        return self.__rtruediv__(other)

    def __divmod__(self, other):
        other_value = self._to_own_unit(other)
        result_tuple = divmod(self.value, other_value)

        return (self._new_view(result_tuple[0], dimensionless_unscaled),
                self._new_view(result_tuple[1]))

    def __pow__(self, other):
        if isinstance(other, Fraction):
            # Avoid getting object arrays by raising the value to a Fraction.
            return self._new_view(self.value ** float(other),
                                  self.unit ** other)

        return super(Quantity, self).__pow__(other)

    def __pos__(self):
        """
        Plus the quantity. This is implemented in case users use +q where q is
        a quantity.  (Required for scalar case.)
        """
        return self.copy()

    # other overrides of special functions
    def __hash__(self):
        return hash(self.value) ^ hash(self.unit)

    def __iter__(self):
        if self.isscalar:
            raise TypeError(
                "'{cls}' object with a scalar value is not iterable"
                .format(cls=self.__class__.__name__))

        # Otherwise return a generator
        def quantity_iter():
            for val in self.value:
                yield self._new_view(val)

        return quantity_iter()

    def __getitem__(self, key):
        try:
            out = super(Quantity, self).__getitem__(key)
        except IndexError:
            # We want zero-dimensional Quantity objects to behave like scalars,
            # so they should raise a TypeError rather than an IndexError.
            if self.isscalar:
                raise TypeError(
                    "'{cls}' object with a scalar value does not support "
                    "indexing".format(cls=self.__class__.__name__))
            else:
                raise
        # For single elements, ndarray.__getitem__ returns scalars; these
        # need a new view as a Quantity.
        if type(out) is not type(self):
            out = self._new_view(out)
        return out

    def __setitem__(self, i, value):
        # update indices
        if not self.isscalar:
            self.info.adjust_indices(i, value, len(self))
        self.view(np.ndarray).__setitem__(i, self._to_own_unit(value))

    def __setslice__(self, i, j, value):
        # update indices
        if not self.isscalar:
            self.info.adjust_indices(slice(i, j), value, len(self))
        self.view(np.ndarray).__setslice__(i, j, self._to_own_unit(value))

    # __contains__ is OK

    def __nonzero__(self):
        """Quantities should always be treated as non-False; there is too much
        potential for ambiguity otherwise.
        """
        return True
    if not six.PY2:
        __bool__ = __nonzero__

    def __len__(self):
        if self.isscalar:
            raise TypeError("'{cls}' object with a scalar value has no "
                            "len()".format(cls=self.__class__.__name__))
        else:
            return len(self.value)

    # Numerical types
    def __float__(self):
        try:
            return float(self.to(dimensionless_unscaled).value)
        except (UnitsError, TypeError):
            raise TypeError('Only dimensionless scalar quantities can be '
                            'converted to Python scalars')

    def __int__(self):
        try:
            return int(self.to(dimensionless_unscaled).value)
        except (UnitsError, TypeError):
            raise TypeError('Only dimensionless scalar quantities can be '
                            'converted to Python scalars')

    def __index__(self):
        # for indices, we do not want to mess around with scaling at all,
        # so unlike for float, int, we insist here on unscaled dimensionless
        try:
            assert self.unit.is_unity()
            return self.value.__index__()
        except Exception:
            raise TypeError('Only integer dimensionless scalar quantities '
                            'can be converted to a Python index')

    if six.PY2:
        def __long__(self):
            try:
                return long(self.to(dimensionless_unscaled).value)
            except (UnitsError, TypeError):
                raise TypeError('Only dimensionless scalar quantities can be '
                                'converted to Python scalars')

    @property
    def _unitstr(self):
        if self.unit is None:
            unitstr = _UNIT_NOT_INITIALISED
        else:
            unitstr = str(self.unit)

        if unitstr:
            unitstr = ' ' + unitstr

        return unitstr

    # Display
    # TODO: we may want to add a hook for dimensionless quantities?
    def __str__(self):
        return '{0}{1:s}'.format(self.value, self._unitstr)

    def __repr__(self):
        prefixstr = '<' + self.__class__.__name__ + ' '
        arrstr = np.array2string(self.view(np.ndarray), separator=',',
                                 prefix=prefixstr)
        return '{0}{1}{2:s}>'.format(prefixstr, arrstr, self._unitstr)

    def _repr_latex_(self):
        """
        Generate a latex representation of the quantity and its unit.

        The behavior of this function can be altered via the
        `numpy.set_printoptions` function and its various keywords.  The
        exception to this is the ``threshold`` keyword, which is controlled via
        the ``[units.quantity]`` configuration item ``latex_array_threshold``.
        This is treated separately because the numpy default of 1000 is too big
        for most browsers to handle.

        Returns
        -------
        lstr
            A LaTeX string with the contents of this Quantity
        """
        # need to do try/finally because "threshold" cannot be overridden
        # with array2string
        pops = np.get_printoptions()
        try:
            formatter = {'float_kind': Latex.format_exponential_notation}
            if conf.latex_array_threshold > -1:
                np.set_printoptions(threshold=conf.latex_array_threshold,
                                    formatter=formatter)

            # the view is needed for the scalar case - value might be float
            latex_value = np.array2string(
                self.view(np.ndarray),
                style=(Latex.format_exponential_notation
                       if self.dtype.kind == 'f' else repr),
                max_line_width=np.inf, separator=',~')
            latex_value = latex_value.replace('...', r'\dots')
        finally:
            np.set_printoptions(**pops)

        # Format unit
        # [1:-1] strips the '$' on either side needed for math mode
        latex_unit = (self.unit._repr_latex_()[1:-1]  # note this is unicode
                      if self.unit is not None
                      else _UNIT_NOT_INITIALISED)

        return '${0} \; {1}$'.format(latex_value, latex_unit)

    def __format__(self, format_spec):
        """
        Format quantities using the new-style python formatting codes
        as specifiers for the number.

        If the format specifier correctly applies itself to the value,
        then it is used to format only the value. If it cannot be
        applied to the value, then it is applied to the whole string.

        """
        try:
            value = format(self.value, format_spec)
            full_format_spec = "s"
        except ValueError:
            value = self.value
            full_format_spec = format_spec

        return format("{0}{1:s}".format(value, self._unitstr),
                      full_format_spec)

    def decompose(self, bases=[]):
        """
        Generates a new `Quantity` with the units
        decomposed. Decomposed units have only irreducible units in
        them (see `astropy.units.UnitBase.decompose`).

        Parameters
        ----------
        bases : sequence of UnitBase, optional
            The bases to decompose into.  When not provided,
            decomposes down to any irreducible units.  When provided,
            the decomposed result will only contain the given units.
            This will raises a `~astropy.units.UnitsError` if it's not possible
            to do so.

        Returns
        -------
        newq : `~astropy.units.Quantity`
            A new object equal to this quantity with units decomposed.
        """
        return self._decompose(False, bases=bases)

    def _decompose(self, allowscaledunits=False, bases=[]):
        """
        Generates a new `Quantity` with the units decomposed. Decomposed
        units have only irreducible units in them (see
        `astropy.units.UnitBase.decompose`).

        Parameters
        ----------
        allowscaledunits : bool
            If True, the resulting `Quantity` may have a scale factor
            associated with it.  If False, any scaling in the unit will
            be subsumed into the value of the resulting `Quantity`

        bases : sequence of UnitBase, optional
            The bases to decompose into.  When not provided,
            decomposes down to any irreducible units.  When provided,
            the decomposed result will only contain the given units.
            This will raises a `~astropy.units.UnitsError` if it's not possible
            to do so.

        Returns
        -------
        newq : `~astropy.units.Quantity`
            A new object equal to this quantity with units decomposed.

        """

        new_unit = self.unit.decompose(bases=bases)

        # Be careful here because self.value usually is a view of self;
        # be sure that the original value is not being modified.
        if not allowscaledunits and hasattr(new_unit, 'scale'):
            new_value = self.value * new_unit.scale
            new_unit = new_unit / new_unit.scale
            return self._new_view(new_value, new_unit)
        else:
            return self._new_view(self.copy(), new_unit)

    # These functions need to be overridden to take into account the units
    # Array conversion
    # http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html#array-conversion

    def item(self, *args):
        return self._new_view(super(Quantity, self).item(*args))

    def tolist(self):
        raise NotImplementedError("cannot make a list of Quantities.  Get "
                                  "list of values with q.value.list()")

    def _to_own_unit(self, value, check_precision=True):
        try:
            # for speed, "unit.to(...)" instead of "value.to(self.unit).value
            _value = value.unit.to(self.unit, value.value)
        except AttributeError:
            try:
                _value = dimensionless_unscaled.to(self.unit, value)
            except UnitsError as exc:
                if _can_have_arbitrary_unit(value):
                    _value = value
                else:
                    raise exc

        if check_precision:
            value_dtype = getattr(value, 'dtype', None)
            if self.dtype != value_dtype:
                self_dtype_array = np.array(_value, self.dtype)
                value_dtype_array = np.array(_value, dtype=value_dtype,
                                             copy=False)
                if not np.all(np.logical_or(self_dtype_array ==
                                            value_dtype_array,
                                            np.isnan(value_dtype_array))):
                    raise TypeError("cannot convert value type to array type "
                                    "without precision loss")
        return _value

    def itemset(self, *args):
        if len(args) == 0:
            raise ValueError("itemset must have at least one argument")

        self.view(np.ndarray).itemset(*(args[:-1] +
                                        (self._to_own_unit(args[-1]),)))

    def tostring(self, order='C'):
        raise NotImplementedError("cannot write Quantities to string.  Write "
                                  "array with q.value.tostring(...).")

    def tofile(self, fid, sep="", format="%s"):
        raise NotImplementedError("cannot write Quantities to file.  Write "
                                  "array with q.value.tofile(...)")

    def dump(self, file):
        raise NotImplementedError("cannot dump Quantities to file.  Write "
                                  "array with q.value.dump()")

    def dumps(self):
        raise NotImplementedError("cannot dump Quantities to string.  Write "
                                  "array with q.value.dumps()")

    # astype, byteswap, copy, view, getfield, setflags OK as is

    def fill(self, value):
        self.view(np.ndarray).fill(self._to_own_unit(value))

    # Shape manipulation: resize cannot be done (does not own data), but
    # shape, transpose, swapaxes, flatten, ravel, squeeze all OK.  Only
    # the flat iterator needs to be overwritten, otherwise single items are
    # returned as numbers.
    @property
    def flat(self):
        """A 1-D iterator over the Quantity array.

        This returns a ``QuantityIterator`` instance, which behaves the same
        as the `~numpy.flatiter` instance returned by `~numpy.ndarray.flat`,
        and is similar to, but not a subclass of, Python's built-in iterator
        object.
        """
        return QuantityIterator(self)

    @flat.setter
    def flat(self, value):
        y = self.ravel()
        y[:] = value

    # Item selection and manipulation
    # take, repeat, sort, compress, diagonal OK
    def put(self, indices, values, mode='raise'):
        self.view(np.ndarray).put(indices, self._to_own_unit(values), mode)

    def choose(self, choices, out=None, mode='raise'):
        raise NotImplementedError("cannot choose based on quantity.  Choose "
                                  "using array with q.value.choose(...)")

    # ensure we do not return indices as quantities
    def argsort(self, axis=-1, kind='quicksort', order=None):
        return self.view(np.ndarray).argsort(axis=axis, kind=kind, order=order)

    def searchsorted(self, v, *args, **kwargs):
        return np.searchsorted(np.array(self),
                               self._to_own_unit(v, check_precision=False),
                               *args, **kwargs)  # avoid numpy 1.6 problem

    def argmax(self, axis=None, out=None):
        return self.view(np.ndarray).argmax(axis, out=out)

    def argmin(self, axis=None, out=None):
        return self.view(np.ndarray).argmin(axis, out=out)

    # Calculation -- override ndarray methods to take into account units.
    # We use the corresponding numpy functions to evaluate the results, since
    # the methods do not always allow calling with keyword arguments.
    # For instance, np.array([0.,2.]).clip(a_min=0., a_max=1.) gives
    # TypeError: 'a_max' is an invalid keyword argument for this function
    def _wrap_function(self, function, *args, **kwargs):
        """Wrap a numpy function, returning a Quantity with the proper unit

        Parameters
        ----------
        function : callable
            numpy function to wrap
        args : positional arguments
            any positional arguments to the function.
        kwargs : keyword arguments
            Keyword arguments to the function.

        If present, the following arguments are treated specially:

        unit : `~astropy.units.Unit` or `None`
            unit of the output result.  If not given or `None` (default),
            the unit of `self`.
        out : `~astropy.units.Quantity`
            A Quantity instance in which to store the output.

        Notes
        -----
        Output should always be assigned via a keyword argument.

        Returns
        -------
        out : `~astropy.units.Quantity`
            Result of the function call, with the unit set properly.
        """

        unit = kwargs.pop('unit', None)
        out = kwargs.get('out', None)
        if out is not None:
            if unit is None:
                unit = self.unit

            if (isinstance(out, Quantity) and
                out.__quantity_subclass__(unit)[0] is type(out)):
                # Set out to ndarray view to prevent calling __array_prepare__.
                kwargs['out'] = out.view(np.ndarray)
            else:
                ok_class =  (out.__quantity_subclass__(out, unit)[0]
                             if isinstance(out, Quantity) else Quantity)
                raise UnitTypeError("out cannot be assigned to a {0} instance; "
                                    "use a {1} instance instead.".format(
                                        out.__class__, ok_class))

        value = function(self.view(np.ndarray), *args, **kwargs)
        if out is None:
            return self._new_view(value, unit)
        else:
            out._set_unit(unit)
            return out

    def clip(self, a_min, a_max, out=None):
        return self._wrap_function(np.clip, self._to_own_unit(a_min),
                                   self._to_own_unit(a_max), out=out)

    def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
        return self._wrap_function(np.trace, offset, axis1, axis2, dtype,
                                   out=out)

    def var(self, axis=None, dtype=None, out=None, ddof=0):
        return self._wrap_function(np.var, axis, dtype,
                                   out=out, ddof=ddof, unit=self.unit**2)

    def std(self, axis=None, dtype=None, out=None, ddof=0):
        return self._wrap_function(np.std, axis, dtype, out=out, ddof=ddof)

    def mean(self, axis=None, dtype=None, out=None):
        return self._wrap_function(np.mean, axis, dtype, out=out)

    def ptp(self, axis=None, out=None):
        return self._wrap_function(np.ptp, axis, out=out)

    def round(self, decimals=0, out=None):
        return self._wrap_function(np.round, decimals, out=out)

    def max(self, axis=None, out=None, keepdims=False):
        return self._wrap_function(np.max, axis, out=out, keepdims=keepdims)

    def min(self, axis=None, out=None, keepdims=False):
        return self._wrap_function(np.min, axis, out=out, keepdims=keepdims)

    def sum(self, axis=None, dtype=None, out=None, keepdims=False):
        return self._wrap_function(np.sum, axis, dtype, out=out,
                                   keepdims=keepdims)

    def prod(self, axis=None, dtype=None, out=None, keepdims=False):
        if not self.unit.is_unity():
            raise ValueError("cannot use prod on scaled or "
                             "non-dimensionless Quantity arrays")
        return self._wrap_function(np.prod, axis, dtype, out=out,
                                   keepdims=keepdims)

    def dot(self, b, out=None):
        result_unit = self.unit * getattr(b, 'unit', dimensionless_unscaled)
        return self._wrap_function(np.dot, b, out=out, unit=result_unit)

    def cumsum(self, axis=None, dtype=None, out=None):
        return self._wrap_function(np.cumsum, axis, dtype, out=out)

    def cumprod(self, axis=None, dtype=None, out=None):
        if not self.unit.is_unity():
            raise ValueError("cannot use cumprod on scaled or "
                             "non-dimensionless Quantity arrays")
        return self._wrap_function(np.cumprod, axis, dtype, out=out)

    # Calculation: override methods that do not make sense.

    def all(self, axis=None, out=None):
        raise NotImplementedError("cannot evaluate truth value of quantities. "
                                  "Evaluate array with q.value.all(...)")

    def any(self, axis=None, out=None):
        raise NotImplementedError("cannot evaluate truth value of quantities. "
                                  "Evaluate array with q.value.any(...)")

    # Calculation --numpy functions that can be overridden with methods

    def diff(self, n=1, axis=-1):
        return self._wrap_function(np.diff, n, axis)

    def ediff1d(self, to_end=None, to_begin=None):
        return self._wrap_function(np.ediff1d, to_end, to_begin)

    if NUMPY_LT_1_8:
        def nansum(self, axis=None):
            return self._wrap_function(np.nansum, axis)
    else:
        def nansum(self, axis=None, out=None, keepdims=False):
            return self._wrap_function(np.nansum, axis,
                                       out=out, keepdims=keepdims)

    def insert(self, obj, values, axis=None):
        """
        Insert values along the given axis before the given indices and return
        a new `~astropy.units.Quantity` object.

        This is a thin wrapper around the `numpy.insert` function.

        Parameters
        ----------
        obj : int, slice or sequence of ints
            Object that defines the index or indices before which ``values`` is
            inserted.
        values : array-like
            Values to insert.  If the type of ``values`` is different
            from that of quantity, ``values`` is converted to the matching type.
            ``values`` should be shaped so that it can be broadcast appropriately
            The unit of ``values`` must be consistent with this quantity.
        axis : int, optional
            Axis along which to insert ``values``.  If ``axis`` is None then
            the quantity array is flattened before insertion.

        Returns
        -------
        out : `~astropy.units.Quantity`
            A copy of quantity with ``values`` inserted.  Note that the
            insertion does not occur in-place: a new quantity array is returned.

        Examples
        --------
        >>> import astropy.units as u
        >>> q = [1, 2] * u.m
        >>> q.insert(0, 50 * u.cm)
        <Quantity [ 0.5,  1.,  2.] m>

        >>> q = [[1, 2], [3, 4]] * u.m
        >>> q.insert(1, [10, 20] * u.m, axis=0)
        <Quantity [[  1.,  2.],
                   [ 10., 20.],
                   [  3.,  4.]] m>

        >>> q.insert(1, 10 * u.m, axis=1)
        <Quantity [[  1., 10.,  2.],
                   [  3., 10.,  4.]] m>

        """
        out_array = np.insert(self.value, obj, self._to_own_unit(values), axis)
        return self._new_view(out_array)


class SpecificTypeQuantity(Quantity):
    """Superclass for Quantities of specific physical type.

    Subclasses of these work just like :class:`~astropy.units.Quantity`, except
    that they are for specific physical types (and may have methods that are
    only appropriate for that type).  Astropy examples are
    :class:`~astropy.coordinates.Angle` and
    :class:`~astropy.coordinates.Distance`

    At a minimum, subclasses should set ``_equivalent_unit`` to the unit
    associated with the physical type.
    """
    # The unit for the specific physical type.  Instances can only be created
    # with units that are equivalent to this.
    _equivalent_unit = None

    # The default unit used for views.  Even with `None`, views of arrays
    # without units are possible, but will have an uninitalized unit.
    _unit = None

    # Default unit for initialization through the constructor.
    _default_unit = None

    # ensure that we get precedence over our superclass.
    __array_priority__ = Quantity.__array_priority__ + 10

    def __quantity_subclass__(self, unit):
        if unit.is_equivalent(self._equivalent_unit):
            return type(self), True
        else:
            return super(SpecificTypeQuantity,
                         self).__quantity_subclass__(unit)[0], False

    def _set_unit(self, unit):
        if unit is None or not unit.is_equivalent(self._equivalent_unit):
            raise UnitTypeError(
                "{0} instances require units equivalent to '{1}'"
                .format(type(self).__name__, self._equivalent_unit) +
                (", but no unit was given." if unit is None else
                 ", so cannot set it to '{0}'.".format(unit)))

        super(SpecificTypeQuantity, self)._set_unit(unit)