Esempio n. 1
0
    def extend_byte_array(a, new_length):
        if len(a) < new_length:
            temp = Array.fill([], 0, new_length)
            Array.copy(a, 0, temp, 0, len(a))

            a = temp

        return a
Esempio n. 2
0
    def __init__(self, storage, shape = None, dtype = None, units = None, title = None, skip_flaws = False, signal = None):
        '''
        Constructor
        '''
        if title is None :
            if hasattr(storage, 'title') :
                title = storage.title
        if type(storage) is int or type(storage) is float or type(storage) is long or type(storage) is bool :
            storage = [storage]
        if isinstance(storage, Array) :
            self.storage = storage
#            self.name = name
            if signal :
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else :
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, 'none', storage.__iArray__)
            name = 'sd' + str(id(self.__iDataItem__))
            self.__iDataItem__.setShortName(name)
            if not units is None :
                self.__iDataItem__.setUnits(str(units))
        elif isinstance(storage, SimpleData) :
            name = storage.name
            self.storage = storage.storage
            if signal :
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else :
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, name, storage.__iArray__)
            if not units is None :
                self.__iDataItem__.setUnits(str(units))
        elif hasattr(storage, '__len__') :
            self.storage = Array(storage, shape, dtype)
            if signal :
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else :
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, 'none', self.storage.__iArray__)
            name = 'sd' + str(id(self.__iDataItem__))
            self.__iDataItem__.setShortName(name)
            if not units is None :
                self.__iDataItem__.setUnits(str(units))
        else :
            self.__iDataItem__ = storage
            self.storage = Array(storage.getData(skip_flaws))
            if not units is None :
                ounits = self.__iDataItem__.getUnits()
                if ounits is None or len(ounits) == 0 :
                    self.__iDataItem__.setUnits(str(units))
        if title is None :
            title = self.__iDataItem__.getTitle()
        if title is None :
            title = self.__iDataItem__.getShortName()
        self.__iDataItem__.setTitle(str(title))
        self.skip_flaws = skip_flaws
    def __init__(self, *dimension):
        """
        Creates a multi-dimensional array of elements organized into
        n-dimensions with each element initially set to None. The nu
        -mber of dimensions, which is specified by the number of arg
        -uments, must be greater than 1. The individual arguments, a
        -ll of which must be greater than zero, indicate the lengths
        of the corresponding array dimensions. The dimensions are sp
        -ecified from highest to lowest, where d_1 is the highest po
        -ssible dimension and d_n is the lowest.
        """
        assert len(
            dimension) > 1, "The multi array must have 2 or more dimensions."
        # The variable argument tuple contains the dim sizes.
        self._dims = dimension
        size = 1  # Reference to the total number of elements in the array.
        for d in dimension:
            assert d > 0, "Dimension must be > 0."
            size *= d

        # The 1-D array, which is actually created in the physical memory to
        # store the multi-dimensional array in row-major order.
        self._elements = Array(size)

        # The 1-D array that stores the factors which would be used to compute
        # the offset for each element.
        self._factors = Array(len(self._dims))

        # The _computeFactors() is a helper method to calculate the factors.
        self._computeFactors()
class TestArray(unittest.TestCase):

	def setUp(self):
		self.array = Array(10, 0)
		self.offarray = Array(5, 5)

	def test_init(self):
        # the length of the array should equal to the input
		self.assertEqual(len(self.array._data), 10)
		self.assertEqual(self.array._baseIndex, 0)
        # no negative length input is allowed
		self.assertRaises(AssertionError, Array, -10, 0)

	def test_copy(self):
		a = copy(self.array)
		self.assertEqual(len(a._data), 10)
		self.assertEqual(a._baseIndex, 0)
	
	def test_offset(self):
		self.assertEqual(self.array.getOffset(1), 1)
		# for array with the start index as 5
		self.assertEqual(self.offarray.getOffset(6), 1)
		self.assertRaises(IndexError, self.array.getOffset, -1)
		self.assertRaises(IndexError, self.array.getOffset, 11)
	
	def test_item(self):
		# test getitem
		for i in range(10):
			self.assertEqual(self.array[i], None)
		for i in range(10):
			self.array[i] = 10-i
		# test setitem
		for i in range(10):
			self.assertEqual(self.array[i], 10-i)

	def test_properties(self):
		self.assertEqual(self.array.data, self.array._data)
		self.assertEqual(self.array.baseIndex, self.array._baseIndex)
		self.array.baseIndex = 1
		self.assertEqual(1, self.array._baseIndex)
			
	def test_resizing(self):
		self.assertEqual(self.array.length, len(self.array._data))
		self.array.length = 5
		self.assertEqual(5, len(self.array._data))
		self.array.length = 15
		self.assertEqual(15, len(self.array._data))
Esempio n. 5
0
 def create_array():
     return Array('Q')
Esempio n. 6
0
def test_2d_var():
    '''
    Verifying that the variance of the array is returned correctly
    '''
    arr1 = Array((2, 2), 2, 2, 1, 1)
    assert arr1.variance() == 0.25
 def __init__(self, size):
     super(QueensBoard, self).__init__()
     self._board = Array(size)
     self._size = size
 def pins_on(self):
     """
     Set all pins high
     """
     self.f.write_data(Array('B', [0x01, 0xFF]))
Esempio n. 9
0
 def _do_epilog(self):
     self.log.debug('   epilog')
     cmd = Array('B', self._stop)
     self._ftdi.write_data(cmd)
     # be sure to purge the MPSSE reply
     self._ftdi.read_data_bytes(1, 1)
Esempio n. 10
0
    def test_sata(self):
        if self.drv is None:
            self.s.Fatal("Cannot Run Test when no device is found!")
            return
        self.drv.enable_sata_reset(True)
        self.s.Info("Reseting Hard Drive, sleeping for a half second...")
        time.sleep(0.5)
        self.drv.enable_sata_reset(False)
        self.s.Info("Hard Drive Reset, sleeping for a half second...")
        time.sleep(0.75)

        self.s.Info("Sata in reset: %s" % self.drv.is_sata_reset())
        #self.s.Info("Is reset in progress: %s" % self.drv.is_sata_reset_active())
        #self.s.Info("Command Layer Reset: %s" % self.drv.is_sata_command_layer_reset())
        self.s.Info("Is platform ready: %s" % self.drv.is_platform_ready())
        #self.s.Info("Is platform error: %s" % self.drv.is_platform_error())
        self.s.Important("linkup: %s" % self.drv.is_linkup())
        #self.s.Info("phy layer ready: %s" % self.drv.is_phy_ready())
        #self.s.Info("link layer ready: %s" % self.drv.is_link_layer_ready())
        #self.s.Info("sata busy: %s" % self.drv.is_sata_busy())
        #self.s.Info("is hard drive error: %s" % self.drv.is_hard_drive_error())
        #self.s.Info("PIO data ready: %s" % self.drv.is_pio_data_ready())
        #self.s.Info("RX COMM Init Detect: %s" % self.drv.get_rx_comm_init_detect())
        #self.s.Info("RX COMM Wake Detect: %s" % self.drv.get_rx_comm_wake_detect())
        #self.s.Info("TX OOB Complete: %s" % self.drv.get_tx_oob_complete())

        #self.s.Info("TX Comm Reset Detect: %s" % self.drv.get_tx_comm_reset())
        #self.s.Info("TX Comm Wake Detect: %s" % self.drv.get_tx_comm_wake())
        #self.s.Debug("OOB State: 0x%04X" % self.drv.get_oob_state())
        #self.s.Debug("Reset Count: 0x%08X" % self.drv.get_reset_count())
        #self.s.Debug("Debug Linkup Data: 0x%08X" % self.drv.get_debug_linkup_data())

        #self.s.Debug("Write to local buffer")
        self.s.Info("Local Buffer Test")
        values = Array('B')
        for i in range(2048 * 4):
            values.append(i % 256)

        self.drv.write_local_buffer(values)
        buf = self.drv.read_local_buffer()
        length_error = False
        if len(values) != len(buf):
            length_error = True
            self.s.Error(
                "Length of write does not match length of read! %d != %d" %
                (len(values), len(buf)))

        error_count = 0
        for i in range(len(values)):
            if error_count > 16:
                break
            if values[i] != buf[i]:
                error_count += 1
                self.s.Error("Error at Address 0x%04X: 0x%02X != 0x%02X" %
                             (i, values[i], buf[i]))

        if error_count > 0 or length_error:
            self.s.Error("Failed local buffer test")
        else:
            self.s.Important("Passed local buffer test!")

        #self.drv.get_hard_drive_size()
        ''' 
        rok_count = self.drv.get_r_ok_count()
        rok_count_before = rok_count
        rerr_count = self.drv.get_r_err_count()
        rerr_count_before = rerr_count

        print "ROK Test"
        self.s.Warning("ROK Count Before: %d" % rok_count)
        self.s.Warning("RERR Count Before: %d" % rerr_count)
        self.drv.hard_drive_idle()
        
        rok_count = self.drv.get_r_ok_count()
        rerr_count = self.drv.get_r_err_count()
        self.s.Warning("ROK Count After: %d" % rok_count)
        self.s.Warning("ROK Count Delta: %d" % (rok_count - rok_count_before))
        self.s.Warning("RERR Count After: %d" % rerr_count)
        self.s.Warning("RERR Count Delta: %d" % (rerr_count - rerr_count_before))
        '''
        self.s.Info("\tInitial Status of hard drive (Status): 0x%02X" %
                    self.drv.get_d2h_status())

        if (self.drv.get_d2h_status() & 0x0004) == 0:
            self.s.Info(
                "\tReceived 0 for status of hard drive, sending reset!")
            self.s.Info("Sending reset command to hard drive")
            self.drv.send_hard_drive_command(0x08)

            self.s.Info("\tInitial (Status): 0x%02X" %
                        self.drv.get_d2h_status())
            for i in range(32):
                self.drv.send_hard_drive_command(0xEC)
                if (self.drv.get_d2h_status() & 0x040) == 0:
                    print "Not Found..."
                else:
                    print "Found!"
            if (self.drv.get_d2h_status() & 0x040) == 0:
                self.s.Warning(
                    "Did not get a normal status response from the hard drive attempting soft reset"
                )
                time.sleep(0.1)
                self.drv.enable_sata_command_layer_reset(True)
                time.sleep(0.1)
                self.drv.enable_sata_command_layer_reset(False)

        self.s.Info("Put Hard Drive in IDLE state")
        self.drv.hard_drive_idle()
        #self.s.Info("\tIdle Result (Status): 0x%02X" % self.drv.get_d2h_status())
        if (self.drv.get_d2h_status() & 0x040) == 0:
            self.s.Error(
                "Did not get a normal status response from the hard drive")
            return

        native_size = self.drv.get_hard_drive_native_size()
        max_lba = self.drv.get_hard_drive_max_native_lba()
        print "Max Native LBA: %d" % max_lba
        self.s.Important("Native Size in gigabytes: %f" %
                         ((native_size * 1.0) * 0.000000001))

        print "Identify Device:"
        data = self.drv.identify_hard_drive()[0:512]
        #print "\tLength of read: %d" % len(data)
        #print "\tdata from hard drive: %s" % str(data)

        config = self.drv.get_config()
        print "Serial Number: %s" % config.serial_number()
        print "Max User Sectors: %d" % config.max_user_sectors()
        print "Max User Size (GB): %f" % (
            (config.max_user_sectors() * 512.0) * 0.000000001)
        #print "Max Sector Capacity: %d" % config.capacity_in_sectors()
        #print "Max Sector Capacity (GB): %f" % ((config.capacity_in_sectors() * 512.0) * 0.000000001)
        #print "Buffer size (bytes): %d" % config.hard_drive_buffer_size()
        #print "DMA Transfer Mode..."
        #config.dma_transfer_mode()
        #config.sata_enabled_features()

        values = Array('B')
        clear_values = Array('B')
        for i in range(2048 * 4):
            values.append(i % 256)
            clear_values.append(0)

        self.drv.set_local_buffer_write_size(128)
        self.drv.write_local_buffer(values)
        #self.drv.write_local_buffer(clear_values)
        #print "Ready Status (Before):0x%02X" % self.drv.get_din_fifo_status()
        #print "Sata Ready: %s" % self.drv.is_command_layer_ready()
        #print "Sata Busy: %s" % self.drv.is_sata_busy()

        self.drv.load_local_buffer()
        self.drv.load_local_buffer()
        self.s.Important("Before Write Start DMA Activate: %s" %
                         self.drv.is_dma_activate_en())
        #self.drv.hard_drive_write(0x0101, 16)
        #self.drv.hard_drive_write(0x0101, 1)
        self.drv.hard_drive_write(0x0000, 2)
        time.sleep(0.5)
        self.s.Important("After Write Start DMA Activate: %s" %
                         self.drv.is_dma_activate_en())
        #self.drv.load_local_buffer()
        #self.drv.load_local_buffer()
        self.drv.set_local_buffer_write_size(2048)
        #self.drv.load_local_buffer()

        #print "Ready Status (Before):0x%02X" % self.drv.get_din_fifo_status()
        #print "command state: %d" % self.drv.get_cmd_wr_state()
        #print "transport state: %d" % self.drv.get_transport_state()
        #print "link layer write state: %d" % self.drv.get_link_layer_write_state()

        #print ""
        #print "Ready Status (Before Read):0x%02X" % self.drv.get_din_fifo_status()
        #print "Sata Ready: %s" % self.drv.is_command_layer_ready()
        #print "Sata Busy: %s" % self.drv.is_sata_busy()
        #print "phy layer ready: %s" % self.drv.is_phy_ready()
        #print ""

        #if self.drv.is_command_layer_ready():
        #print "*** CAN READ NOW! ***"
        self.s.Info("Reading from Hard Drive...")
        self.drv.write_local_buffer(clear_values)

        #self.drv.hard_drive_read(0x0101, 2)
        self.drv.hard_drive_read(0x0400, 2)

        print "Read Result:"
        print "\tstatus: 0x%02X" % self.drv.get_d2h_status()
        print "\terror : 0x%02X" % self.drv.get_d2h_error()
        print "\tLBA: 0x%012X" % self.drv.get_hard_drive_lba()
        print "\tSector Count: 0x%04X" % self.drv.get_sector_count()

        data = self.drv.read_local_buffer()
        #print "\tdata from hard drive: %s" % str(data[0:1024])
        print "\tLength of read: %d" % len(data)
        print "\tdata from hard drive: %s" % str(data[0:1024])
        print "\tReady Status :0x%02X" % self.drv.get_din_fifo_status()

        self.drv.hard_drive_sleep()
from array import Array
from array import DynamicArray

# create instance of class Array
x = Array()

# create instance of subclass DynamicArray
y = DynamicArray()

# print method calls
print(x.__len__())
print(x.__getitem__(2))
print(y.append(2))
print(y.delete(0))
print(x.item)
print(y.__contains__(13))
print(y.reverse())
print(y.insert(1, 4))



 def program_low(self):
     pins = self.f.read_pins()
     pins &= ~(self.PROGRAM_PIN)
     self.f.write_data(Array('B', [0x00, pins]))
 def program_high(self):
     pins = self.f.read_pins()
     pins |= self.PROGRAM_PIN
     self.f.write_data(Array('B', [0x01, pins]))
 def soft_reset_low(self):
     pins = self.f.read_pins()
     pins &= ~(self.SOFT_RESET_PIN)
     self.f.write_data(Array('B', [0x00, pins]))
 def soft_reset_high(self):
     pins = self.f.read_pins()
     pins |= self.SOFT_RESET_PIN
     self.f.write_data(Array('B', [0x01, pins]))
 def pins_off(self):
     """
     Set all pins low
     """
     self.f.write_data(Array('B', [0x01, 0x00]))
Esempio n. 17
0
    def read(self, read_all=False, to_python=False):
        # "to_python" cannot be set without "read_all"
        assert read_all or not to_python

        self._skip_whitespace()

        # None
        if self._skip_if_next('null'):
            return None

        # False
        if self._skip_if_next('false'):
            return False

        # True
        if self._skip_if_next('true'):
            return True

        # Number
        if self._peek() in '-0123456789':
            num = self._get()
            # Check sign
            if num == '-':
                num += self._get()
            # Read integer part
            if num[-1] != '0':
                while self._peek() in '0123456789':
                    num += self._get()
            # Read possible decimal part and convert to float
            if self._peek() == '.':
                self._get()
                num += '.' + self._get()
                if num[-1] not in '01234567890':
                    raise Exception(u'Expected digit after dot!')
                while self._peek() in '0123456789':
                    num += self._get()
                num = float(num)
            else:
                num = int(num)
            # Read possible exponent
            if self._peek() in 'eE':
                self._get()
                exp = self._get()
                exp_neg = False
                if exp == '-':
                    exp_neg = True
                    exp = self._get()
                elif exp == '+':
                    exp = self._get()
                while self._peek() in '0123456789':
                    exp += self._get()
                exp = int(exp)
                exp = 10 ** exp
                if exp_neg:
                    num = float(num) / exp
                else:
                    num *= exp
            return num

        # String
        if self._skip_if_next('"'):
            string = u''

            while True:
                c = self._get()

                if c == u'"':
                    break

                if c == u'\\':
                    c = self._get()
                    if c == u'"':
                        string += u'"'
                    elif c == u'\\':
                        string += u'\\'
                    elif c == u'/':
                        string += u'/'
                    elif c == u'b':
                        string += u'\b'
                    elif c == u'f':
                        string += u'\f'
                    elif c == u'n':
                        string += u'\n'
                    elif c == u'r':
                        string += u'\r'
                    elif c == u't':
                        string += u'\t'
                    elif c == u'u':
                        unicode_bytes = self._read(4)
                        string += ('\\u' + unicode_bytes).decode('unicode_escape')
                    else:
                        raise Exception(u'Unexpected {} in backslash encoding!'.format(c))

                else:
                    string += c

            return string

        # Array
        if self._peek() == '[':
            if to_python:
                array = Array(self, False)
                return array.to_python()
            else:
                return Array(self, read_all)

        # Object
        if self._peek() == '{':
            if to_python:
                obj = Object(self, False)
                return obj.to_python()
            else:
                return Object(self, read_all)

        raise Exception(u'Unexpected bytes!')
Esempio n. 18
0
class SimpleData:
 
    def __init__(self, storage, shape = None, dtype = None, units = None, title = None, skip_flaws = False, signal = None):
        '''
        Constructor
        '''
        if title is None :
            if hasattr(storage, 'title') :
                title = storage.title
        if type(storage) is int or type(storage) is float or type(storage) is long or type(storage) is bool :
            storage = [storage]
        if isinstance(storage, Array) :
            self.storage = storage
#            self.name = name
            if signal :
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else :
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, 'none', storage.__iArray__)
            name = 'sd' + str(id(self.__iDataItem__))
            self.__iDataItem__.setShortName(name)
            if not units is None :
                self.__iDataItem__.setUnits(str(units))
        elif isinstance(storage, SimpleData) :
            name = storage.name
            self.storage = storage.storage
            if signal :
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else :
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, name, storage.__iArray__)
            if not units is None :
                self.__iDataItem__.setUnits(str(units))
        elif hasattr(storage, '__len__') :
            self.storage = Array(storage, shape, dtype)
            if signal :
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else :
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, 'none', self.storage.__iArray__)
            name = 'sd' + str(id(self.__iDataItem__))
            self.__iDataItem__.setShortName(name)
            if not units is None :
                self.__iDataItem__.setUnits(str(units))
        else :
            self.__iDataItem__ = storage
            self.storage = Array(storage.getData(skip_flaws))
            if not units is None :
                ounits = self.__iDataItem__.getUnits()
                if ounits is None or len(ounits) == 0 :
                    self.__iDataItem__.setUnits(str(units))
        if title is None :
            title = self.__iDataItem__.getTitle()
        if title is None :
            title = self.__iDataItem__.getShortName()
        self.__iDataItem__.setTitle(str(title))
        self.skip_flaws = skip_flaws
#            self.name = iDataItem.getShortName()


#    def __add__(self, obj) :
#        arr1 = self.storage
#        arr2 = obj.storage
#        narr = arr1 + arr2
#        di = NcDataItem(self.__iDataItem__)
#        di.setCachedData(narr.__iArray__, 0)
#        nsd = SimpleData(di)
#        nsd.storage = narr
#        return nsd
    
#    def __mul__(self, object):
#        array1 = self.__iDataItem__.getData()
#        array2 = object.__iDataItem__.getData()
#        return SimpleData(array1.getArrayMath().toEltMultiply(array2).getArray())
    
        
#    def __repr__(self):
#        return self.__class__.__name__
    def __set_name__(self, name):
        self.__iDataItem__.setShortName(str(name))
        
    #####################################################################################
    #   Array indexing
    #####################################################################################
    def __getitem__(self, index):
        nst = self.storage[index]
        if isinstance(nst, Array) :
            return self.__new__(nst)
        else :
            return nst
            
    def get_slice(self, dim, index):
        return self.__new__(self.storage.get_slice(dim, index))
        
    
    def get_section(self, origin, shape, stride = None): 
        return self.__new__(self.storage.get_section(origin, shape, stride))
    
    def get_reduced(self, dim = None):
        return self.__new__(self.storage.get_reduced(dim))
        
    def section_iter(self, shape):
        return SimpledataSectionIter(self, shape)
        self.storage.section_iter(shape)
    
    def take(self, indices, axis=None, out=None, mode='raise'):
        return self.__new__(self.storage.take(indices, axis, out, mode))
#####################################################################################
# Array accessing
#####################################################################################    
    def get_value(self, index) :
        return self.storage.get_value(index)
    
    def __len__(self):
        return len(self.storage)
    
    def __getattr__(self, name):
        if name == 'name' :
            return self.__iDataItem__.getShortName()
        elif name == 'units' :
            return self.__iDataItem__.getUnits()
        elif name == 'title' :
            title = self.__iDataItem__.getTitle()
            if title is None :
                return self.name
            else :
                return title
        else :
            att = self.__iDataItem__.findAttributeIgnoreCase(name)
            if att:
                val = att.getValue()
                if val.getElementType() is String:
                    return str(val)
                else:
                    arr = Array(val)
                    if arr.size == 1 :
                        return arr[0]
        return getattr(self.storage, name)
    
    def get_attribute(self, name):
        att = self.__iDataItem__.findAttributeIgnoreCase(name)
        if att:
            val = att.getValue()
            if val.getElementType() is String:
                return str(val)
            else:
                arr = Array(val)
                if arr.size == 1 :
                    return arr[0]
        return None

    def __setattr__(self, name, value):
        if name == 'name' :
#            self.__iDataItem__.setShortName(str(value))
            raise AttributeError, 'name can not be set, try set the title instead'
        elif name == 'units' :
            self.__iDataItem__.setUnits(str(value))
        elif name == 'title' :
            self.__iDataItem__.setTitle(str(value))
        elif name == 'storage' :
            self.__dict__[name] = value
        elif name.startswith('__'):
            self.__dict__[name] = value
        else:
            self.__dict__[name] = value
    
    def set_attribute(self, name, value):
        if type(value) is str:
            self.__iDataItem__.addStringAttribute(name, value)
        else:
            arr = Array(value)
            att = nx_factory.createAttribute(name, arr.__iArray__)
            self.__iDataItem__.addOneAttribute(att)
        
        
    def __iter__(self):
        if (self.ndim > 1) :
            return SimpledataSliceIter(self)
        else :
            return self.item_iter()
        
    def item_iter(self):
        return self.storage.item_iter()
    
    def set_value(self, index, value):
        self.storage.set_value(index, value)
        
#********************************************************************************
#     Array math
#********************************************************************************
    
    def __eq__(self, obj) :
        if obj is None:
            return False
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        res = self.storage.__eq__(obj)
        if isinstance(res, Array) :
            return self.__new__(res)
        else :
            return res
    
    def __ne__(self, obj):
        if obj is None:
            return True
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        res = self.storage.__ne__(obj)
        if isinstance(res, Array) :
            return self.__new__(res)
        else :
            return res

    def __lt__(self, obj) :
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        res = self.storage.__lt__(obj)
        return self.__new__(res)

    def __gt__(self, obj) :
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        res = self.storage.__gt__(obj)
        return self.__new__(res)

    def __le__(self, obj) :
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        res = self.storage.__le__(obj)
        return self.__new__(res)

    def __ge__(self, obj) :
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        res = self.storage.__ge__(obj)
        return self.__new__(res)
        
    def __not__(self):
        raise ValueError, 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'

    def __add__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage + obj)

    def __iadd__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        self.storage.__iadd__(obj)
        return self

    def __radd__(self, obj):
        return self.__add__(obj)
            
    def __div__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage / obj)
    
    def __rdiv__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage.__rdiv__(obj))
    
    def __mul__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage * obj)
    
    def __rmul__(self, obj):
        return self.__mul__(obj)
        
    def __neg__(self):
        return self * -1
    
    def __sub__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage - obj)
    
    def __rsub__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage.__rsub__(obj))
    
    def __invert__(self):
        return self.__new__(self.storage.__invert__())
    
    def __pow__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage.__pow__(obj))

    def exp(self):
        return self.__new__(self.storage.exp())

    def log10(self):
        return self.__new__(self.storage.log10())
    
    def ln(self):
        return self.__new__(self.storage.ln())

    def sqrt(self):
        return self.__new__(self.storage.sqrt())
        
    def __rpow__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage.__rpow__(obj))
    
    def __mod__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage % obj)

    def __rmod__(self, obj):
        if isinstance(obj, SimpleData) :
            obj = obj.storage
        return self.__new__(self.storage.__rmod__(obj))

    def __sin__(self):
        return self.__new__(self.storage.__sin__())
    
    def __cos__(self):
        return self.__new__(self.storage.__cos__())
    
    def __tan__(self):
        return self.__new__(self.storage.__tan__())
    
    def __arcsin__(self):
        return self.__new__(self.storage.__arcsin__())
    
    def __arccos__(self):
        return self.__new__(self.storage.__arccos__())
    
    def __arctan__(self):
        return self.__new__(self.storage.__arctan__())
    
    def __exp__(self):
        return self.__new__(self.storage.__exp__())

    def __prod__(self, axis = None):
        return self.__new__(self.storage.__prod__(axis))
    
    def max(self, axis = None, out = None):
        if axis is None :
            return self.storage.max()
        else :
            if out is None :
                return self.__new__(self.storage.max(axis))
            else :
                if isinstance(out, SimpleData) :
                    obj = out.storage
                else :
                    obj = out
                self.storage.max(axis, obj)
                return out
    
    def min(self, axis = None, out = None):
        if axis is None :
            return self.storage.min()
        else :
            if out is None :
                return self.__new__(self.storage.min(axis))
            else :
                if isinstance(out, SimpleData) :
                    obj = out.storage
                else :
                    obj = out
                self.storage.min(axis, obj)
                return out
    
    def argmax(self, axis = None):
        return self.storage.argmax(axis)

    def argmin(self, axis = None):
        return self.storage.argmin(axis)
        
    def sum(self, axis = None, dtype = None, out = None):
        if axis is None :
            return self.storage.sum(dtype = dtype)
        else :
            if out is None :
                return self.__new__(self.storage.sum(axis, dtype))
            else :
                return self.storage.sum(axis, dtype, out)
            
    def transpose(self, axes = None):
        return self.__new__(self.storage.transpose(axes))
        
    def compress(self, condition, axis = None, out = None):
        return self.__new__(self.storage.compress(condition, axis, out))

    def clip(self, a_min, a_max, out = None):
        if out is None:
            return self.__new__(self.storage.clip(a_min, a_max))
        else :
            if hasattr(out, 'storage'):
                self.storage.clip(a_min, a_max, out.storage)
            else:
                self.storage.clip(a_min, a_max, out)
            return out
        
    def mean(self, axis = None, dtype = None, out = None):
        if axis is None :
            return self.storage.mean(dtype = dtype)
        else :
            if out is None :
                return self.__new__(self.storage.mean(axis, dtype))
            else :
                return self.storage.mean(axis, dtype, out)
#********************************************************************************
#     Array utilities
#********************************************************************************
    
    def __repr__(self, indent = ''):
        indent += '           '
        res = 'SimpleData(' + self.storage.__repr__(indent) + ', \n' \
                + indent + 'title=\'' + self.title + '\''
        if not self.units is None :
            res += ',\n' + indent + 'units=\'' + self.units + '\''
        res += ')'
        return res
    
    def __str__(self, indent = ''):
        if self.dtype is str :
            return indent + self.storage.__str__(indent)
        res = 'title: ' + self.title + '\n' + indent
        if not self.units is None and len(self.units) > 0:
            res += 'units: ' + self.units + '\n' + indent
        res += 'storage: ' + self.storage.__str__(indent + ' ' * 9) 
        return res
    
    def tolist(self):
        return self.storage.tolist()
            
#####################################################################################
#   Array modification
#####################################################################################    

    def __setitem__(self, index, value):
        if isinstance(value, SimpleData) :
            value = value.storage
        self.storage[index] = value
    
    def copy_from(self, value, length = -1):
        if isinstance(value, SimpleData) :
            value = value.storage
        self.storage.copy_from(value, length)
                    
    def fill(self, val):
        self.storage.fill(val)
            
    def put(self, indices, values, mode='raise') :
        self.storage.put(indices, values, mode)
        
#####################################################################################
#   Reinterpreting arrays
#####################################################################################    
    def reshape(self, shape): 
        return self.__new__(self.storage.reshape(shape))
    
    def flatten(self) :
        return self.__new__(self.storage.flatten())

    def view_1d(self):
        return self.__new__(self.storage.view_1d())
    
    def __copy__(self):
        return self.__new__(self.storage.__copy__())

    def __deepcopy__(self):
        return self.__new__(self.storage.__deepcopy__())
    
    def float_copy(self):
        return self.__new__(self.storage.float_copy())

    def positive_float_copy(self):
        return self.__new__(self.storage.positive_float_copy())

    def __new__(self, storage, units = None, parent = None, title = None):
        name = self.name
        if units is None :
            units = self.units
        if title is None :
            title = self.title
        sd = new(storage, name, units, parent, title)
        for att in self.__iDataItem__.getAttributeList():
            sd.__iDataItem__.addOneAttribute(att)
        return sd

    def __dir__(self):
        dirs = self.storage.__dir__()
        dirs.append('name')
        dirs.append('storage')
        dirs.append('title')
        dirs.append('units')
        return sorted(dirs)
        
    def all(self):
        return self.storage.all()
    
    def any(self):
        return self.storage.any()

    def get_flawed_indices(self):
        return self.__iDataItem__.getFlawedIndexList()
     
    def delete_slice(self, indices):
        slices = []
        if type(indices) is int :
            slices = [indices]
        elif hasattr(indices, '__len__') :
            slices = indices
        else :
            raise AttributeError, 'indices must be either integer value or integer list'
        if len(slices) > 0 :
            narr = array.delete(self.storage, slices, 0)
            oname = self.__iDataItem__.getShortName()
            self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, oname, narr.__iArray__)
            self.storage = narr
    
    def intg(self, axis = None, out = None, keepdims = False):
        if axis is None :
            return self.storage.intg()
        else :
            if out is None :
                return self.__new__(self.storage.intg(axis, out, keepdims))
            else :
                return self.storage.intg(axis, out, keepdims)
Esempio n. 19
0
 def __init__(self,
              storage,
              shape=None,
              dtype=None,
              units=None,
              title=None,
              skip_flaws=False,
              signal=None):
     '''
     Constructor
     '''
     if title is None:
         if hasattr(storage, 'title'):
             title = storage.title
     if type(storage) is int or type(storage) is float or type(
             storage) is long or type(storage) is bool:
         storage = [storage]
     if isinstance(storage, Array):
         self.storage = storage
         #            self.name = name
         if signal:
             self.__iDataItem__ = nx_factory.\
                         createNXsignal(None, 'none', storage.__iArray__)
         else:
             self.__iDataItem__ = nx_factory.\
                         createNXDataItem(None, 'none', storage.__iArray__)
         name = 'sd' + str(id(self.__iDataItem__))
         self.__iDataItem__.setShortName(name)
         if not units is None:
             self.__iDataItem__.setUnits(str(units))
     elif isinstance(storage, SimpleData):
         name = storage.name
         self.storage = storage.storage
         if signal:
             self.__iDataItem__ = nx_factory.\
                         createNXsignal(None, 'none', storage.__iArray__)
         else:
             self.__iDataItem__ = nx_factory.\
                         createNXDataItem(None, name, storage.__iArray__)
         if not units is None:
             self.__iDataItem__.setUnits(str(units))
     elif hasattr(storage, '__len__'):
         self.storage = Array(storage, shape, dtype)
         if signal:
             self.__iDataItem__ = nx_factory.\
                         createNXsignal(None, 'none', storage.__iArray__)
         else:
             self.__iDataItem__ = nx_factory.\
                         createNXDataItem(None, 'none', self.storage.__iArray__)
         name = 'sd' + str(id(self.__iDataItem__))
         self.__iDataItem__.setShortName(name)
         if not units is None:
             self.__iDataItem__.setUnits(str(units))
     else:
         self.__iDataItem__ = storage
         self.storage = Array(storage.getData(skip_flaws))
         if not units is None:
             ounits = self.__iDataItem__.getUnits()
             if ounits is None or len(ounits) == 0:
                 self.__iDataItem__.setUnits(str(units))
     if title is None:
         title = self.__iDataItem__.getTitle()
     if title is None:
         title = self.__iDataItem__.getShortName()
     self.__iDataItem__.setTitle(str(title))
     self.skip_flaws = skip_flaws
Esempio n. 20
0
 def _make_buffer(self, regaddr, out=None):
     data = Array('B')
     data.extend(spack('%s%s' % (self._endian, self._format), regaddr))
     if out:
         data.extend(out)
     return data.tobytes()
Esempio n. 21
0
 def test_write_memory(self):
     address = 0x00
     data = Array('B', [0x00, 0x01, 0x02, 0x03, 0x04])
     self.simple_dev.write_memory(address, data)
Esempio n. 22
0
class SimpleData:
    def __init__(self,
                 storage,
                 shape=None,
                 dtype=None,
                 units=None,
                 title=None,
                 skip_flaws=False,
                 signal=None):
        '''
        Constructor
        '''
        if title is None:
            if hasattr(storage, 'title'):
                title = storage.title
        if type(storage) is int or type(storage) is float or type(
                storage) is long or type(storage) is bool:
            storage = [storage]
        if isinstance(storage, Array):
            self.storage = storage
            #            self.name = name
            if signal:
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else:
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, 'none', storage.__iArray__)
            name = 'sd' + str(id(self.__iDataItem__))
            self.__iDataItem__.setShortName(name)
            if not units is None:
                self.__iDataItem__.setUnits(str(units))
        elif isinstance(storage, SimpleData):
            name = storage.name
            self.storage = storage.storage
            if signal:
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else:
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, name, storage.__iArray__)
            if not units is None:
                self.__iDataItem__.setUnits(str(units))
        elif hasattr(storage, '__len__'):
            self.storage = Array(storage, shape, dtype)
            if signal:
                self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, 'none', storage.__iArray__)
            else:
                self.__iDataItem__ = nx_factory.\
                            createNXDataItem(None, 'none', self.storage.__iArray__)
            name = 'sd' + str(id(self.__iDataItem__))
            self.__iDataItem__.setShortName(name)
            if not units is None:
                self.__iDataItem__.setUnits(str(units))
        else:
            self.__iDataItem__ = storage
            self.storage = Array(storage.getData(skip_flaws))
            if not units is None:
                ounits = self.__iDataItem__.getUnits()
                if ounits is None or len(ounits) == 0:
                    self.__iDataItem__.setUnits(str(units))
        if title is None:
            title = self.__iDataItem__.getTitle()
        if title is None:
            title = self.__iDataItem__.getShortName()
        self.__iDataItem__.setTitle(str(title))
        self.skip_flaws = skip_flaws
#            self.name = iDataItem.getShortName()

#    def __add__(self, obj) :
#        arr1 = self.storage
#        arr2 = obj.storage
#        narr = arr1 + arr2
#        di = NcDataItem(self.__iDataItem__)
#        di.setCachedData(narr.__iArray__, 0)
#        nsd = SimpleData(di)
#        nsd.storage = narr
#        return nsd

#    def __mul__(self, object):
#        array1 = self.__iDataItem__.getData()
#        array2 = object.__iDataItem__.getData()
#        return SimpleData(array1.getArrayMath().toEltMultiply(array2).getArray())

#    def __repr__(self):
#        return self.__class__.__name__

    def __set_name__(self, name):
        self.__iDataItem__.setShortName(str(name))

    #####################################################################################
    #   Array indexing
    #####################################################################################
    def __getitem__(self, index):
        nst = self.storage[index]
        if isinstance(nst, Array):
            return self.__new__(nst)
        else:
            return nst

    def get_slice(self, dim, index):
        return self.__new__(self.storage.get_slice(dim, index))

    def get_section(self, origin, shape, stride=None):
        return self.__new__(self.storage.get_section(origin, shape, stride))

    def get_reduced(self, dim=None):
        return self.__new__(self.storage.get_reduced(dim))

    def section_iter(self, shape):
        return SimpledataSectionIter(self, shape)
        self.storage.section_iter(shape)

    def take(self, indices, axis=None, out=None, mode='raise'):
        return self.__new__(self.storage.take(indices, axis, out, mode))
#####################################################################################
# Array accessing
#####################################################################################

    def get_value(self, index):
        return self.storage.get_value(index)

    def __len__(self):
        return len(self.storage)

    def __getattr__(self, name):
        if name == 'name':
            return self.__iDataItem__.getShortName()
        elif name == 'units':
            return self.__iDataItem__.getUnits()
        elif name == 'title':
            title = self.__iDataItem__.getTitle()
            if title is None:
                return self.name
            else:
                return title
        else:
            att = self.__iDataItem__.findAttributeIgnoreCase(name)
            if att:
                val = att.getValue()
                if val.getElementType() is String:
                    return str(val)
                else:
                    arr = Array(val)
                    if arr.size == 1:
                        return arr[0]
        return getattr(self.storage, name)

    def get_attribute(self, name):
        att = self.__iDataItem__.findAttributeIgnoreCase(name)
        if att:
            val = att.getValue()
            if val.getElementType() is String:
                return str(val)
            else:
                arr = Array(val)
                if arr.size == 1:
                    return arr[0]
        return None

    def __setattr__(self, name, value):
        if name == 'name':
            #            self.__iDataItem__.setShortName(str(value))
            raise AttributeError, 'name can not be set, try set the title instead'
        elif name == 'units':
            self.__iDataItem__.setUnits(str(value))
        elif name == 'title':
            self.__iDataItem__.setTitle(str(value))
        elif name == 'storage':
            self.__dict__[name] = value
        elif name.startswith('__'):
            self.__dict__[name] = value
        else:
            self.__dict__[name] = value

    def set_attribute(self, name, value):
        if type(value) is str:
            self.__iDataItem__.addStringAttribute(name, value)
        else:
            arr = Array(value)
            att = nx_factory.createAttribute(name, arr.__iArray__)
            self.__iDataItem__.addOneAttribute(att)

    def __iter__(self):
        if (self.ndim > 1):
            return SimpledataSliceIter(self)
        else:
            return self.item_iter()

    def item_iter(self):
        return self.storage.item_iter()

    def set_value(self, index, value):
        self.storage.set_value(index, value)

#********************************************************************************
#     Array math
#********************************************************************************

    def __eq__(self, obj):
        if obj is None:
            return False
        if isinstance(obj, SimpleData):
            obj = obj.storage
        res = self.storage.__eq__(obj)
        if isinstance(res, Array):
            return self.__new__(res)
        else:
            return res

    def __ne__(self, obj):
        if obj is None:
            return True
        if isinstance(obj, SimpleData):
            obj = obj.storage
        res = self.storage.__ne__(obj)
        if isinstance(res, Array):
            return self.__new__(res)
        else:
            return res

    def __lt__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        res = self.storage.__lt__(obj)
        return self.__new__(res)

    def __gt__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        res = self.storage.__gt__(obj)
        return self.__new__(res)

    def __le__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        res = self.storage.__le__(obj)
        return self.__new__(res)

    def __ge__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        res = self.storage.__ge__(obj)
        return self.__new__(res)

    def __not__(self):
        raise ValueError, 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'

    def __add__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage + obj)

    def __iadd__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        self.storage.__iadd__(obj)
        return self

    def __radd__(self, obj):
        return self.__add__(obj)

    def __div__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage / obj)

    def __rdiv__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage.__rdiv__(obj))

    def __mul__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage * obj)

    def __rmul__(self, obj):
        return self.__mul__(obj)

    def __neg__(self):
        return self * -1

    def __sub__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage - obj)

    def __rsub__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage.__rsub__(obj))

    def __invert__(self):
        return self.__new__(self.storage.__invert__())

    def __pow__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage.__pow__(obj))

    def exp(self):
        return self.__new__(self.storage.exp())

    def log10(self):
        return self.__new__(self.storage.log10())

    def ln(self):
        return self.__new__(self.storage.ln())

    def sqrt(self):
        return self.__new__(self.storage.sqrt())

    def __rpow__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage.__rpow__(obj))

    def __mod__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage % obj)

    def __rmod__(self, obj):
        if isinstance(obj, SimpleData):
            obj = obj.storage
        return self.__new__(self.storage.__rmod__(obj))

    def __sin__(self):
        return self.__new__(self.storage.__sin__())

    def __cos__(self):
        return self.__new__(self.storage.__cos__())

    def __tan__(self):
        return self.__new__(self.storage.__tan__())

    def __arcsin__(self):
        return self.__new__(self.storage.__arcsin__())

    def __arccos__(self):
        return self.__new__(self.storage.__arccos__())

    def __arctan__(self):
        return self.__new__(self.storage.__arctan__())

    def __exp__(self):
        return self.__new__(self.storage.__exp__())

    def __prod__(self, axis=None):
        return self.__new__(self.storage.__prod__(axis))

    def max(self, axis=None, out=None):
        if axis is None:
            return self.storage.max()
        else:
            if out is None:
                return self.__new__(self.storage.max(axis))
            else:
                if isinstance(out, SimpleData):
                    obj = out.storage
                else:
                    obj = out
                self.storage.max(axis, obj)
                return out

    def min(self, axis=None, out=None):
        if axis is None:
            return self.storage.min()
        else:
            if out is None:
                return self.__new__(self.storage.min(axis))
            else:
                if isinstance(out, SimpleData):
                    obj = out.storage
                else:
                    obj = out
                self.storage.min(axis, obj)
                return out

    def argmax(self, axis=None):
        return self.storage.argmax(axis)

    def argmin(self, axis=None):
        return self.storage.argmin(axis)

    def sum(self, axis=None, dtype=None, out=None):
        if axis is None:
            return self.storage.sum(dtype=dtype)
        else:
            if out is None:
                return self.__new__(self.storage.sum(axis, dtype))
            else:
                return self.storage.sum(axis, dtype, out)

    def transpose(self, axes=None):
        return self.__new__(self.storage.transpose(axes))

    def compress(self, condition, axis=None, out=None):
        return self.__new__(self.storage.compress(condition, axis, out))

    def clip(self, a_min, a_max, out=None):
        if out is None:
            return self.__new__(self.storage.clip(a_min, a_max))
        else:
            if hasattr(out, 'storage'):
                self.storage.clip(a_min, a_max, out.storage)
            else:
                self.storage.clip(a_min, a_max, out)
            return out

    def mean(self, axis=None, dtype=None, out=None):
        if axis is None:
            return self.storage.mean(dtype=dtype)
        else:
            if out is None:
                return self.__new__(self.storage.mean(axis, dtype))
            else:
                return self.storage.mean(axis, dtype, out)
#********************************************************************************
#     Array utilities
#********************************************************************************

    def __repr__(self, indent='', skip=True):
        indent += '           '
        res = 'SimpleData(' + self.storage.__repr__(indent, skip) + ', \n' \
                + indent + 'title=\'' + self.title + '\''
        if not self.units is None:
            res += ',\n' + indent + 'units=\'' + self.units + '\''
        res += ')'
        return res

    def __str__(self, indent='', skip=True):
        if self.dtype is str:
            return indent + self.storage.__str__(indent, skip)
        res = 'title: ' + self.title + '\n' + indent
        if not self.units is None and len(self.units) > 0:
            res += 'units: ' + self.units + '\n' + indent
        res += 'storage: ' + self.storage.__str__(indent + ' ' * 9)
        return res

    def tolist(self):
        return self.storage.tolist()

#####################################################################################
#   Array modification
#####################################################################################

    def __setitem__(self, index, value):
        if isinstance(value, SimpleData):
            value = value.storage
        self.storage[index] = value

    def copy_from(self, value, length=-1):
        if isinstance(value, SimpleData):
            value = value.storage
        self.storage.copy_from(value, length)

    def fill(self, val):
        self.storage.fill(val)

    def put(self, indices, values, mode='raise'):
        self.storage.put(indices, values, mode)

#####################################################################################
#   Reinterpreting arrays
#####################################################################################

    def reshape(self, shape):
        return self.__new__(self.storage.reshape(shape))

    def flatten(self):
        return self.__new__(self.storage.flatten())

    def view_1d(self):
        return self.__new__(self.storage.view_1d())

    def __copy__(self):
        return self.__new__(self.storage.__copy__())

    def __deepcopy__(self):
        return self.__new__(self.storage.__deepcopy__())

    def float_copy(self):
        return self.__new__(self.storage.float_copy())

    def positive_float_copy(self):
        return self.__new__(self.storage.positive_float_copy())

    def __new__(self, storage, units=None, parent=None, title=None):
        name = self.name
        if units is None:
            units = self.units
        if title is None:
            title = self.title
        sd = new(storage, name, units, parent, title)
        for att in self.__iDataItem__.getAttributeList():
            sd.__iDataItem__.addOneAttribute(att)
        return sd

    def __dir__(self):
        dirs = self.storage.__dir__()
        dirs.append('name')
        dirs.append('storage')
        dirs.append('title')
        dirs.append('units')
        return sorted(dirs)

    def all(self):
        return self.storage.all()

    def any(self):
        return self.storage.any()

    def get_flawed_indices(self):
        return self.__iDataItem__.getFlawedIndexList()

    def delete_slice(self, indices):
        slices = []
        if type(indices) is int:
            slices = [indices]
        elif hasattr(indices, '__len__'):
            slices = indices
        else:
            raise AttributeError, 'indices must be either integer value or integer list'
        if len(slices) > 0:
            narr = array.delete(self.storage, slices, 0)
            oname = self.__iDataItem__.getShortName()
            self.__iDataItem__ = nx_factory.\
                            createNXsignal(None, oname, narr.__iArray__)
            self.storage = narr

    def intg(self, axis=None, out=None, keepdims=False):
        if axis is None:
            return self.storage.intg()
        else:
            if out is None:
                return self.__new__(self.storage.intg(axis, out, keepdims))
            else:
                return self.storage.intg(axis, out, keepdims)
Esempio n. 23
0
if __name__ == '__main__':
    # Create an array for the counters and initialize each element to 0.
    from array import Array
    theCounters = Array(127)

    # Open the text file for reading and extract each line from the file
    # and iterate over each character in the line.
    theFile = open("C:/temp/atextfile.txt", 'r')
    for line in theFile:
        for letter in line:
            code = ord(letter)
            theCounters[code] += 1
    # Close the file
    theFile.close()

    # Print the results. The uppercase letters have ASCII values in the
    # range 65..90 and the lowercase letters are in the range 97..122.
    for i in range(26):
        print("%c - %4d %c - %4d" % (chr(65 + i), theCounters[65 + i],
                                     chr(97 + i), theCounters[97 + i]))
Esempio n. 24
0
 def test_write(self):
     address = 0x20
     data = Array('B', [0x00, 0x01, 0x02, 0x03])
     disable_auto_increment = False
     self.simple_dev.write(address, data, disable_auto_increment)
 def __init__(self):
     self._capacity = _INITIAL_CAPACITY_
     self._head = None
     self._tail = None
     self._array = Array(_INITIAL_CAPACITY_)
    def __init__(self, numLevels):
        self._qSize = 0
        self._qLevels = Array(numLevels)

        for i in range(numLevels):
            self._qLevels[i] = Queue()
Esempio n. 27
0
 def jedec2int(cls, jedec, maxlength=3):
     return tuple(Array('B', jedec[:maxlength]))
Esempio n. 28
0
def test_2d_is_equal():
    '''
    Verifying that comparing a 1d-array element-wise
    to another array through is equal returns what
    it’s supposed to - which should be a boolean 
    array.
    '''
    arr1 = Array((2, 2), 2, 1, 1, 1)
    assert str(arr1.is_equal(1)) == \
        "[[False, True]\n [True, True]]"

    arr1 = Array((2, 2), 2, 1, 1, 1)
    arr2 = Array((2, 2), 2, 1, 1, 1)
    assert str(arr1.is_equal(arr2)) == \
        "[[True, True]\n [True, True]]"

    arr1 = Array((2, 2), 2, 1, 1, 1)
    arr2 = Array((2, 2), 2, 2, 1, 1)
    assert str(arr1.is_equal(arr2)) == \
        "[[True, False]\n [True, True]]"
Esempio n. 29
0
 def _read_hi_speed(self, address, length):
     read_cmd = Array('B', (self.CMD_READ_HI_SPEED, (address >> 16) & 0xff,
                            (address >> 8) & 0xff, address & 0xff, 0))
     return self._spi.exchange(read_cmd, length)
Esempio n. 30
0
def test_nd_var():
    '''
    Verifying that the variance of the array is returned correctly
    '''
    arr1 = Array((3, 2, 1), 1, 2, 3, 4, 5, 6)
    assert arr1.variance() == 2.9166666666666665
Esempio n. 31
0
 def _read_status(self):
     read_cmd = Array('B', (self.CMD_READ_STATUS, ))
     data = self._spi.exchange(read_cmd, 1)
     if len(data) != 1:
         raise SerialFlashTimeout("Unable to retrieve flash status")
     return data[0]
class MultiArray:
    """
    A multi-dimensional array consists of a collection of elements
organized into multiple dimensions. Individual elements are re
    -ferenced by specifying an n-tuple or a subscript of multiple
    components, (i_1, i_2, ... , i_n), one for each dimension of th
    -e array.

    In most programming languages, a multi-dimensional array is ac
    -tually created and stored in memory as a one-dimension array.
    With this organization, a multi-dimensional array is simply
    an abstract view of a physical one-dimensional data structure.

    The elements can be stored in row-major order or column-major
    order, and in this MultiArray ADT, we use the row-major order
    storagement.

    """

    def __init__(self, *dimension):
        """
        Creates a multi-dimensional array of elements organized into
        n-dimensions with each element initially set to None. The nu
        -mber of dimensions, which is specified by the number of arg
        -uments, must be greater than 1. The individual arguments, a
        -ll of which must be greater than zero, indicate the lengths
        of the corresponding array dimensions. The dimensions are sp
        -ecified from highest to lowest, where d_1 is the highest po
        -ssible dimension and d_n is the lowest.
        """
        assert len(
            dimension) > 1, "The multi array must have 2 or more dimensions."
        # The variable argument tuple contains the dim sizes.
        self._dims = dimension
        size = 1  # Reference to the total number of elements in the array.
        for d in dimension:
            assert d > 0, "Dimension must be > 0."
            size *= d

        # The 1-D array, which is actually created in the physical memory to
        # store the multi-dimensional array in row-major order.
        self._elements = Array(size)

        # The 1-D array that stores the factors which would be used to compute
        # the offset for each element.
        self._factors = Array(len(self._dims))

        # The _computeFactors() is a helper method to calculate the factors.
        self._computeFactors()

    def numDims(self):
        """
        Returns the number of dimensions in the multi-dimensional array.
        """
        return len(self._dims)

    def length(self, dim):
        """
        Returns the length of the given array dimension. The individual
        dimensions are numbered starting from 1, where 1 represents the
        first, or highest, dimension possible in the array. Thus in an a
        -rray of three dimensions, 1 indicates the number of tables in t
        -he box, 2 is the number of rows, and 3 is number of columns.
        """
        assert dim > 1 and dim < len(self._dims),\
            "Dimension component out of range."
        return self._dims[dim - 1]

    def clear(self, value):
        self._elements.clear(value)

    def __getitem__(self, ndxTuple):
        """
        Returns the value stored in the array at the element position
        indicated by the n-tuple(i_1, i_2, ..., i_n). All of the spec
        -ified indices must be given and they must be within the valid
        range of the corresponding array dimensions. Accessed using th
        -e element operator: y = x[1, 2].
        """
        assert len(ndxTuple) == self.numDims(), \
            "Invalid # of array subscripts."
        index = self._computeIndex(ndxTuple)
        assert index is not None, "Array subscript out of range."
        return self._elements[index]

    def __setitem__(self, ndxTuple, value):
        """
        Modifies the contents of the specified array element to contain
        the given value. The element if specified by the n-tuple (i_1,
        i_2, ..., i_n). All of the subscript components must be given a
        -nd they must be within the valid range of the corresponding ar
        -ray dimensions. Accessed using the lement operator: x[1, 2] = y.
        """
        assert len(ndxTuple) == self.numDims(), \
            "Invalid # of array subscripts."

        # The _computeIndex() is a helper method which defined protected and used to
        # calculate the offset of each element given by position (i_1,
        # i_2,...,i_n).
        index = self._computeIndex(ndxTuple)

        assert index is not None, "Array subscript out of range."
        self._elements[index] = value

    def _computeIndex(self, idx):
        """
        The _computIndex() is a helper method defined to compute the offset of
        each element given by position (i_1, i_2, ..., i_n).

        The parameter idx which receives a tuple, and then used to check the
        index given as each dimension, if idx[j] (represents the index of jth
        dimension) small than 0 or greater than the length of jth dimension,
        the function returns None, representing out of range. Otherwise, com
        -pute the offset using the equation:

        +--------------------------------------------------------------------+
                index(i_1, i_2, i_3,...,i_n) = i_1 * f_1 + i_2 * f_2
                                                                                i_n-1 * f_n-1 + i_n * 1
        +--------------------------------------------------------------------+

        """
        offset = 0
        for j in range(len(idx)):
            if idx[j] < 0 or idx[j] >= self._dims[j]:
                return None
            else:
                offset += idx[j] * self._factors[j]
        return offset

    def _computeFactors(self):
        """
        This is the second helper method defined to compute the factores before
        excute the _computeIndex() method(actually it's excuted in __init__ met
        -hod at the head of the ADT).

        Since the size of a multi-dimensional array is fixed at the time it's cr
        -eated and cannot change during execution, the factors(represented as f_1,
        f_2,..., f_i,...,f_n above) will not change either. This can be used to
        our advantage to reduce the number of multiplications required to compute
        the element offsets:
                Instead of computing the factors every time an element is accessed, we
                can compute and store the factors and simply plug them into the equati
                -on when needed.

        Here is another trick, since the equation to compute the factors as follo
        -ws:
        +-------------------------------------------------------------------------+
                f_n = 1 and f_j = d_j+1 * d_j+2 * ... * d_n-1 * d_n
        +-------------------------------------------------------------------------+

        which can be turned into the forms as follows:

        +-------------------------------------------------------------------------+
                f_n = 1 and f_j = d_j+1 * f_j+1
        +-------------------------------------------------------------------------+

        much like a fibonacci equation, so that we can first calculate the f_n and
        cache it, then use the result of f_n to calculate the f_n-1,then f_n-2...
        so on. Everytime we compute the ith factor, the (i+1)th is already known.In
        addition, the sequence of d is given at the moment of initializing, d_1,d_2
        ...,d_i to d_n is also already known.

        It's much efficient than using the first equation.


        """
        max_idx = len(self._factors) - 1
        self._factors[max_idx] = 1

        for i in range(max_idx, 0, -1):
            self._factors[i - 1] = self._dims[i] * self._factors[i]
Esempio n. 33
0
 def _enable_write(self):
     wren_cmd = Array('B', (self.CMD_WRITE_ENABLE, ))
     self._spi.exchange(wren_cmd)
Esempio n. 34
0
 def _disable_write(self):
     wrdi_cmd = Array('B', (self.CMD_WRITE_DISABLE, ))
     self._spi.exchange(wrdi_cmd)
Esempio n. 35
0
 def __init__(self, maxSize):
     self.size = 0
     self.front = 0
     self.back = 0
     self.items = Array(maxSize)
#Count the number of occurrences of each letter in a text file.
from array import Array

# Create an array for the counters and initialize each element to 0.
theCounters = Array( 127 )
theCounters.clear( 0 )

# Open the text file for reading and extract each line from the file
# and iterate over each character in the line.
theFile = open( 'atextfile.txt', 'r' )
for line in theFile :
    for letter in line :
        code = ord( letter )
        theCounters[code] += 1

# Close the file
theFile.close()

# Print the results. The uppercase letters have ASCII values in the
# range 65..90 and the lowercase letters are in the range 97..122.
for i in range( 26 ) :
    print( "%c - %4d %c - %4d" % \
    (chr(65+i), theCounters[65+i], chr(97+i), theCounters[97+i]) )
j = 0
for i in theCounters:
    print "%3d %d" % (j, i)
    j += 1

Esempio n. 37
0
def test_memory(dyn, dev_index):
    print "testing memory @ %d" % dev_index
    mem_bus = dyn.is_memory_device(dev_index)
    if mem_bus:
        print "Memory is on Memory bus"
    else:
        print "Memory is on Peripheral bus"

    print "Testing short write"
    data_out = Array('B', [0xAA, 0xBB, 0xCC, 0xDD, 0x55, 0x66, 0x77, 0x88])
    print "out data: %s" % str(data_out)
    print "hex: "
    for i in range(0, len(data_out)):
        print str(hex(data_out[i])) + ", ",
    print " "

    dyn.write_memory(0, data_out)

    print "Testing short read"
    data_in = dyn.read_memory(0, 2)
    print "mem data: %s" % str(data_in)
    print "hex: "
    for i in range(0, len(data_in)):
        print str(hex(data_in[i])) + ", ",
    print " "

    print "Testing a write/read at the end of memory"
    dev_size = dyn.get_device_size(dev_index)
    print "writing to memory location 0x%08X" % (dev_size - 8)
    dyn.write_memory(dev_size - 8, data_out)
    print "reading from memory location 0x%08X" % (dev_size - 8)
    data_in = dyn.read_memory(dev_size - 8, 2)

    print "mem data: %s" % str(data_in)
    print "hex: "
    for i in range(0, len(data_in)):
        print str(hex(data_in[i])) + ", ",
    print " "

    dev_size = (dyn.get_device_size(dev_index) / 4)
    print "Memory size: 0x%X" % (dyn.get_device_size(dev_index))

    data_out = Array('B')
    num = 0
    try:
        for i in range(0, 4 * dev_size):
            num = (i) % 255
            if (i / 256) % 2 == 1:
                data_out.append(255 - (num))
            else:
                data_out.append(num)

    except OverflowError as err:
        print "Overflow Error: %d >= 256" % num
        sys.exit(1)

    print "Writing %d bytes of data" % (len(data_out))
    dyn.write_memory(0, data_out)
    #dyn.write(dev_index, 0, data_out, mem_bus)
    print "Reading %d bytes of data" % (len(data_out))
    data_in = dyn.read_memory(0, len(data_out) / 4)
    #data_in = dyn.read(dev_index, 0, len(data_out) / 4, mem_bus)

    print "Comparing values"
    fail = False
    fail_count = 0
    if len(data_out) != len(data_in):
        print "data_in length not equal to data_out length:"
        print "\totugoing: %d incomming: %d" % (len(data_out), len(data_in))
        fail = True

    else:
        for i in range(0, len(data_out)):
            if data_in[i] != data_out[i]:
                fail = True
                #print "Mismatch at %d: READ DATA %d != WRITE DATA %d" % (i, data_in[i], data_out[i])
                fail_count += 1

    if not fail:
        print "Memory test passed!"
    elif (fail_count == 0):
        print "Data length of data_in and data_out do not match"
    else:
        print "Failed: %d mismatches" % fail_count
	def setUp(self):
		self.array = Array(10, 0)
		self.offarray = Array(5, 5)
Esempio n. 39
0
 def __init__(self, numRows, numCols):
     self._numCols = numCols
     self._listOfRows = Array(numRows)