示例#1
0
 def ComprobarLista2(self):
     if len(self.L_L_Goals) == 0:
         return
     with QtCore.QMutexLocker(self.mutex_bus):
         try:
             for x in range(0, len(self.L_L_Goals)):
                 with QtCore.QMutexLocker(self.mutex_goals):
                     m = self.L_L_Goals.pop(0)
                 for goal in m:
                     for x in self.motorParams:
                         if x.name == goal.name:
                             busId = x.busId
                             break
                     if x.invertedSign == "true":
                         goal.position = -goal.position
                     pos = np.ushort((goal.position + 2.618) * (1023 - 0) /
                                     (2.618 + 2.618))
                     vel = np.ushort(goal.maxSpeed)
                     dynamixel.set_velocity(self.bus,
                                            busId,
                                            vel,
                                            False,
                                            num_error_attempts=1)
                     dynamixel.set_position(self.bus,
                                            busId,
                                            pos,
                                            False,
                                            num_error_attempts=1)
                 dynamixel.send_action_packet(self.bus)
         except Ice.Exception, e:
             traceback.print_exc()
             print e
示例#2
0
def calc_checksum(data):
    """Calculates the checksum of a package as described in the Nortek
    integrators Section 10.2 verson Mar2016
    """
    hChecksum = np.ushort(0xb58c)
    for i in range(0,len(data),2):
        tmp = int.from_bytes(data[i:i+2], byteorder='little')
        hChecksum += tmp
        
    return np.ushort(hChecksum)
示例#3
0
def getpathintegers(m1, uptolength=7):
  '''returns a list of integers describing the paths for molecule m1.  This uses numpy 16 bit unsigned integers to reproduce the data in the Gobbi paper.  The returned list is sorted'''
  bondtypelookup = {}
  for b in m1.GetBonds():
    bondtypelookup[b.GetIdx()] = _BK_[b.GetBondType()], b.GetBeginAtom(), b.GetEndAtom()
  pathintegers = {}
  for a in m1.GetAtoms():
    idx = a.GetIdx()
    pathintegers[idx] = []
    #		for pathlength in range(1, uptolength+1):
    #			for path in rdmolops.FindAllPathsOfLengthN(m1, pathlength, rootedAtAtom=idx):
    for ipath, path in enumerate(
        FindAllPathsOfLengthMToN_Gobbi(m1, 1, uptolength, rootedAtAtom=idx, uniquepaths=False)):
      strpath = []
      currentidx = idx
      res = []
      for ip, p in enumerate(path):
        bk, a1, a2 = bondtypelookup[p]
        strpath.append(_BONDSYMBOL_[bk])
        if a1.GetIdx() == currentidx:
          a = a2
        else:
          a = a1
        ak = a.GetAtomicNum()
        if a.GetIsAromatic():
          ak += 108
#trying to get the same behaviour as the Gobbi test code - it looks like a circular path includes the bond, but not the closure atom - this fix works
        if a.GetIdx() == idx:
          ak = None
        if ak is not None:
          astr = a.GetSymbol()
          if a.GetIsAromatic():
            strpath.append(astr.lower())
          else:
            strpath.append(astr)
        res.append((bk, ak))
        currentidx = a.GetIdx()
      pathuniqueint = numpy.ushort(0)  # work with 16 bit unsigned integers and ignore overflow...
      for ires, (bi, ai) in enumerate(res):
        #use 16 bit unsigned integer arithmetic to reproduce the Gobbi ints
        #					pathuniqueint = ((pathuniqueint+bi)*_nAT_+ai)*_nBT_
        val1 = pathuniqueint + numpy.ushort(bi)
        val2 = val1 * numpy.ushort(_nAT_)
        #trying to get the same behaviour as the Gobbi test code - it looks like a circular path includes the bond, but not the closure atom - this fix works
        if ai is not None:
          val3 = val2 + numpy.ushort(ai)
          val4 = val3 * numpy.ushort(_nBT_)
        else:
          val4 = val2
        pathuniqueint = val4
      pathintegers[idx].append(pathuniqueint)
#sorted lists allow for a quicker comparison algorithm
  for p in pathintegers.values():
    p.sort()
  return pathintegers
示例#4
0
def build_land_mask(quality_flags, bits):
    """ Extand land mask to avoid detecting extreme values near the coast
    while detecting min and max values. """
    land_mask = numpy.zeros(quality_flags.shape, dtype='bool')
    land_bit = numpy.ushort(1 << bits['land'])
    coast_bit = numpy.ushort(1 << bits['coastline'])
    land_mask = (land_mask | (numpy.bitwise_and(quality_flags, land_bit) > 0) |
                 (numpy.bitwise_and(quality_flags, coast_bit) > 0))

    # Dilatation of land mask to remove coastal values
    dil_kern = numpy.ones((5, 5), dtype='bool')
    land_mask = binary_dilation(land_mask, structure=dil_kern)

    return land_mask
示例#5
0
 def test_numpy(self):
     """NumPy objects get serialized to readable JSON."""
     l = [
         np.float32(12.5),
         np.float64(2.0),
         np.float16(0.5),
         np.bool(True),
         np.bool(False),
         np.bool_(True),
         np.unicode_("hello"),
         np.byte(12),
         np.short(12),
         np.intc(-13),
         np.int_(0),
         np.longlong(100),
         np.intp(7),
         np.ubyte(12),
         np.ushort(12),
         np.uintc(13),
         np.ulonglong(100),
         np.uintp(7),
         np.int8(1),
         np.int16(3),
         np.int32(4),
         np.int64(5),
         np.uint8(1),
         np.uint16(3),
         np.uint32(4),
         np.uint64(5),
     ]
     l2 = [l, np.array([1, 2, 3])]
     roundtripped = loads(dumps(l2, cls=EliotJSONEncoder))
     self.assertEqual([l, [1, 2, 3]], roundtripped)
示例#6
0
 def test_numpy(self):
     """NumPy objects get serialized to readable JSON."""
     l = [
         np.float32(12.5),
         np.float64(2.0),
         np.float16(0.5),
         np.bool(True),
         np.bool(False),
         np.bool_(True),
         np.unicode_("hello"),
         np.byte(12),
         np.short(12),
         np.intc(-13),
         np.int_(0),
         np.longlong(100),
         np.intp(7),
         np.ubyte(12),
         np.ushort(12),
         np.uintc(13),
         np.ulonglong(100),
         np.uintp(7),
         np.int8(1),
         np.int16(3),
         np.int32(4),
         np.int64(5),
         np.uint8(1),
         np.uint16(3),
         np.uint32(4),
         np.uint64(5),
     ]
     l2 = [l, np.array([1, 2, 3])]
     roundtripped = loads(dumps(l2, cls=EliotJSONEncoder))
     self.assertEqual([l, [1, 2, 3]], roundtripped)
示例#7
0
    def from_s(value, idx):  # type: (np.float, np.float) -> str or np.nan
        if pd.isnull(value) or isinstance(value, string_types):
            return value
        value = np.ushort(value)
        name = (series.name if series.name in manycat2threecat else
                to_manycat_name(series.name))

        mapped = manycat2threecat.get(name)

        try:
            result = (value if mapped is None or len(mapped) < value else
                      mapped[4 if value == 5 else value])
        except IndexError:
            just = 20
            print(
                "mapped:".ljust(just),
                "{!r}\n".format(mapped),
                "value:".ljust(just),
                "{!r}\n".format(value),
                "idx:".ljust(just),
                "{!r}\n".format(idx),
                sep="",
            )
            print(series.index)
            raise
        return result
示例#8
0
	def setPosition(self, goal):
		m = [x for x in self.motorParams if x.name == goal.name]
		if len(m)>0:
			position=(goal.position + 2.618) * (1023 - 0) / (2.618 + 2.618)
			pos=np.ushort(position)
			dynamixel.set_position(self.bus, (m[0].busId),pos)
			dynamixel.send_action_packet(self.bus)
示例#9
0
	def setVelocity(self, goal):
		m = [x for x in self.motorParams if x.name == goal.name]
		if len(m)>0:
			
			pos=np.ushort(goal.velocity)
			dynamixel.set_velocity(self.bus, (m[0].busId),pos)
			dynamixel.send_action_packet(self.bus)
示例#10
0
    def setVelocity(self, goal):
        m = [x for x in self.motorParams if x.name == goal.name]
        if len(m) > 0:

            pos = np.ushort(goal.velocity)
            dynamixel.set_velocity(self.bus, (m[0].busId), pos)
            dynamixel.send_action_packet(self.bus)
示例#11
0
def generate_old_series(patternparms):
    """ Generate a stripe series from the patternparms.

    patternparms is a list of tuples:  (pitch, angle, phase, wavelength),
    where pitch is in microns, and both the angle and phase are specified
    in radians.  
    """
    xindices = np.arange(512)
    yindices = np.arange(512)
    kk, ll = meshgrid(xindices, yindices)
    sequence = []
    mp2 = 1.5
    for realpitch, angle, phase, waves, wavelength in patternparms:
        pitch = realpitch / 15.0
        pattern = np.ushort(
            rint(
                (mp2 / pi) *
                (32767.5 + 32767.5 *
                 (mp2 / pi) * cos(phase + 2. * pi *
                                  (kk * cos(angle) + ll * sin(angle)) / pitch))
            ))
        # Scale to green LUT range
        pattern *= (16256. / 65536.)
        pattern += 49279
        sequence.append(pattern)
    return sequence
示例#12
0
 def setPosition(self, goal):
     m = [x for x in self.motorParams if x.name == goal.name]
     if len(m) > 0:
         position = (goal.position + 2.618) * (1023 - 0) / (2.618 + 2.618)
         pos = np.ushort(position)
         dynamixel.set_position(self.bus, (m[0].busId), pos)
         dynamixel.send_action_packet(self.bus)
示例#13
0
def writesufp(fpout, amp, hdr, scale=1):

    # fpout    = opened file to write the data to
    # amp      = matrix containing the amplitudes of the data
    # hdr      = header object containing the headers for the data
    # scale    = scale the header data from python format to SU format (=1) or not (=0)

    # Set global variables
    global vari
    global vari_bytes

    # Scale the data back to the SU format
    if scale == 1:
        scalel = hdr.scalel[0]
        scalco = hdr.scalco[0]

        if scalel < 0:
            scaledep = float(-1.0 / scalel)
        elif scalel == 0:
            scaledep = 1.0
        else:
            scaledep = float(scalel)

        if scalco < 0:
            scalepos = float(-1.0 / scalco)
        elif scalco == 0:
            scalepos = 1.0
        else:
            scalepos = float(scalco)
    else:
        scaledep = 1.0
        scalepos = 1.0

    # Get the size of the data to be written
    [nz, nx] = np.shape(amp)

    # Write out the data, check for the appropiate header format for every attribute
    for ix in range(nx):
        for ih in range(94):
            if ih < 80:
                if vari[ih] in vari[12:19]:
                    attrib = getattr(hdr, vari[ih]) / scaledep
                elif vari[ih] in vari[21:25]:
                    attrib = getattr(hdr, vari[ih]) / scalepos
                else:
                    attrib = getattr(hdr, vari[ih])
            if vari_bytes[ih] == 'i':
                fpout.write(struct.pack(vari_bytes[ih], int(attrib[ix])))
            elif vari_bytes[ih] == 'h' and ih < 80:
                fpout.write(struct.pack(vari_bytes[ih], np.short(attrib[ix])))
            elif vari_bytes[ih] == 'h' and ih > 79:
                fpout.write(struct.pack(vari_bytes[ih], np.short(0)))
            elif vari_bytes[ih] == 'H':
                fpout.write(struct.pack(vari_bytes[ih], np.ushort(attrib[ix])))
            elif vari_bytes[ih] == 'f':
                fpout.write(struct.pack(vari_bytes[ih], float(attrib[ix])))
        data = amp[:, ix]
        fpout.write(struct.pack('<%df' % len(data), *data))
示例#14
0
def process(var):
    global sym,symval
    if var in symval:
        return symval[var]
    if(var.isdigit()):
        return np.ushort(var)

    ins = sym[var]
    i = ins[0]
    if(i == 'x'):
        symval[var] = process(ins[1])
        return np.ushort(symval[var])
    elif(i == 'n'):
        symval[var] = ~process(ins[1])
        return np.ushort(symval[var])
    elif(i == 'a'):
        symval[var] = process(ins[1]) &  process(ins[2])
        return np.ushort(symval[var])
    elif(i == 'o'):
        symval[var] = process(ins[1]) | process(ins[2])
        return np.ushort(symval[var])
    elif(i == 'l'):
        symval[var] = process(ins[1]) << process(ins[2])
        return np.ushort(symval[var])
    elif(i == 'r'):
        symval[var] = process(ins[1]) >> process(ins[2])
        return np.ushort(symval[var])
示例#15
0
 def ComprobarLista(self):
     if len(self.lisPos) == 0:
         return
     try:
         m = self.lisPos.popleft()
         for x in self.motorParams:
             if x.name == m.name:
                 busId = x.busId
                 break
         pos = np.ushort(
             (m.position + 2.618) * (1023 - 0) / (2.618 + 2.618))
         vel = np.ushort(m.maxSpeed)
         dynamixel.set_velocity(self.bus, busId, vel)
         dynamixel.set_position(self.bus, busId, pos)
         dynamixel.send_action_packet(self.bus)
     except Ice.Exception, e:
         traceback.print_exc()
         print e
示例#16
0
	def ComprobarLista(self):	
		
		if len(self.lisPos) == 0:
			return
		try:
			m = self.lisPos.popleft()
			for x in self.motorParams:
				if x.name == m.name:
					busId = x.busId
					break
			pos = np.ushort((m.position + 2.618) * (1023 - 0) / (2.618 + 2.618))
			vel = np.ushort(m.maxSpeed)
			dynamixel.set_velocity(self.bus,busId, vel)
			dynamixel.set_position(self.bus, busId, pos)
			dynamixel.send_action_packet(self.bus)
		except Ice.Exception, e:
			traceback.print_exc()
			print e
def build_mask_rgb(channels, quality_flags, tie_lat, lat_crop):
    """"""

    bits = {
        'coastline': 0,
        'ocean': 1,
        'tidal': 2,
        'land': 3,
        'inland_water': 4,
        'unfilled': 5,
        'spare': 6,
        'spare_': 7,
        'cosmetic': 8,
        'duplicate': 9,
        'day': 10,
        'twilight': 11,
        'sun_glint': 12,
        'snow': 13,
        'summary_cloud': 14,
        'summary_pointing': 15
    }

    # Invalidate if these flags are all off
    on_flags = numpy.ushort(0)
    on_flags = on_flags + numpy.ushort(1 << bits['day'])

    # Invalidate if any of these flags is on
    off_flags = numpy.ushort(0)
    off_flags = off_flags + numpy.ushort(1 << bits['coastline'])
    off_flags = off_flags + numpy.ushort(1 << bits['land'])
    off_flags = off_flags + numpy.ushort(1 << bits['snow'])

    # Intialize mask to compute histograms on selected valid values
    contrast_mask = numpy.zeros(quality_flags.shape, dtype='bool')

    # Initialize mask to remove invalid data
    data_mask = numpy.zeros(quality_flags.shape, dtype='bool')

    lat_mask = (numpy.abs(tie_lat) > lat_crop)
    contrast_mask = (contrast_mask | lat_mask)
    data_mask = (data_mask | lat_mask)

    # Mask data under sun_glint too
    off_flags = off_flags + numpy.uint32(1 << bits['sun_glint'])

    contrast_mask = (contrast_mask |
                     (numpy.bitwise_and(quality_flags, on_flags) <= 0) |
                     (numpy.bitwise_and(quality_flags, off_flags) > 0))

    # Granules containing only night/twilight data must be ignored.
    # Twilight data are only useful to improve the contrast when there is
    # at least some daily data.
    on_flags = numpy.ushort(0)
    on_flags |= 1 << bits['day']
    data_mask = (data_mask | (numpy.bitwise_and(quality_flags, on_flags) <= 0))
    if data_mask.all():
        raise OnlyNightData()

    return contrast_mask, data_mask
示例#18
0
    def write_smv(self, path: str, i: int) -> str:
        """Write the image+header with sequence number `i` to the directory
        `path` in SMV format.

        Returns the path to the written image.
        """
        img = self.data[i]
        h = self.headers[i]

        img = np.ushort(img)
        shape_x, shape_y = img.shape

        phi = self.start_angle + self.osc_angle * (i - 1)

        # TODO: Dials reads the beam_center from the first image and uses that for the whole range
        # For now, use the average beam center and consider it stationary, remove this line later
        mean_beam_center = self.mean_beam_center

        try:
            date = str(datetime.fromtimestamp(h['ImageGetTime']))
        except BaseException:
            date = '0'

        header = collections.OrderedDict()
        header['HEADER_BYTES'] = 512
        header['DIM'] = 2
        header['BYTE_ORDER'] = 'little_endian'
        header['TYPE'] = 'unsigned_short'
        header['SIZE1'] = shape_x
        header['SIZE2'] = shape_y
        header['PIXEL_SIZE'] = self.physical_pixelsize
        header['BIN'] = '1x1'
        header['BIN_TYPE'] = 'HW'
        header['ADC'] = 'fast'
        header['CREV'] = 1
        header['BEAMLINE'] = self.name  # special ID for DIALS
        header['DETECTOR_SN'] = 901  # special ID for DIALS
        header['DATE'] = date
        header['TIME'] = str(h['ImageExposureTime'])
        header['DISTANCE'] = f'{self.distance:.4f}'
        header['TWOTHETA'] = 0.00
        header['PHI'] = '{phi:.4f}'
        header['OSC_START'] = f'{phi:.4f}'
        header['OSC_RANGE'] = f'{self.osc_angle:.4f}'
        header['WAVELENGTH'] = f'{self.wavelength:.4f}'
        # reverse XY coordinates for XDS
        header['BEAM_CENTER_X'] = f'{mean_beam_center[1]:.4f}'
        header['BEAM_CENTER_Y'] = f'{mean_beam_center[0]:.4f}'
        header[
            'DENZO_X_BEAM'] = f'{mean_beam_center[0]*self.physical_pixelsize:.4f}'
        header[
            'DENZO_Y_BEAM'] = f'{mean_beam_center[1]*self.physical_pixelsize:.4f}'
        fn = path / f'{i:05d}.img'
        write_adsc(fn, img, header=header)
        return fn
示例#19
0
    def set_sim_sequence(self, angle_phase_wavelength):
        """ Generate a SIM sequence from a list of parameters.

        angle_phase_wavelength is a list where each element is a tuple of the 
        form (angle_number, phase_number, wavelength).
        """
        num_phases = 0
        num_angles = 0
        wavelengths = []
        for (angle, phase, wavelength) in angle_phase_wavelength:
            num_phases = max(num_phases, phase + 1)
            num_angles = max(num_angles, angle + 1)
            if wavelength not in wavelengths:
                wavelengths.append(wavelength)

        phases = [
            self.sim_phase_offset + n * TWO_PI / num_phases
            for n in xrange(num_phases)
        ]
        angles = [
            self.sim_angle_offset + n * TWO_PI / num_angles
            for n in xrange(num_angles)
        ]

        ## Calculate line pitches for each wavelength, once.
        # d  = m * wavelength / sin theta
        # 1/1000 since wavelength in nm, pixel pitch in microns.
        pitches = {
            w: w / (1000. * sin(self.sim_diffraction_angle * TWO_PI / 360.))
            for w in wavelengths
        }
        ## Figure out the LUTs we need for each wavelength, once.
        luts = {w: self.get_lut(w) for w in set(wavelengths)}

        # retardation for equal powers in 0 and combined +/-1 orders
        modulation = 65535 * 150. / 360.0

        sequence = []
        for (angle, phase, wavelength) in angle_phase_wavelength:
            pp = pitches[wavelength] / self.pixel_pitch
            th = angles[angle]
            ph = phases[phase]
            # Create a stripe 16-bit pattern
            pattern16 = numpy.ushort(
                rint((0.5 * modulation) + (0.5 * modulation) *
                     cos(ph + TWO_PI *
                         (cos(th) * self.kk + sin(th) * self.ll) / pp)))
            # Lose two LSBs and pass through the LUT for given wavelength.
            pattern = luts[wavelength][pattern16 / 4]
            # Append to the sequence.
            sequence.append(pattern)
        self.sequence_parameters = angle_phase_wavelength
        self.sequence = sequence
        self.load_sequence()
示例#20
0
 def __init__(self, id, events):
     self._events = dict()
     self._id = numpy.ushort(id)
     self._name = events.get("name").lower()
     if "events" in events.keys():
         self._parse_from_json(events.get("events"))
     elif self._name == "ump send":
         self._events[0] = make_trace_event("CHANNEL_SEND", 0, "ump send",
                                            self)
     elif self._name == "ump receive":
         self._events[0] = make_trace_event("CHANNEL_RECV", 0, "ump send",
                                            self)
示例#21
0
def build_cloud_mask(raw_cloud_flags, cloud_bits):
    """ Construct a cloud mask from the raw flags in the SLSTR flag mask. Bits
    to consider in the mask have been selected to filter as much cloud as
    possible without removing frontal structures."""
    bits_to_mask = (
        'visible',
        'threshold',
        'small_histogram1.6',
        # 'large_histogram1.6',
        'small_histogram2.25',
        'gross_cloud',
        'thin_cirrus',
        'medium_high',
        'fog_low_stratus',
        # '3.7_11_view_difference',
        '11_12_view_difference')
    mask_ref = numpy.ushort(0)
    # Enable selected mask bits
    for mask_name in bits_to_mask:
        mask_ref = mask_ref + (1 << cloud_bits[mask_name])

    # Apply spatial coherence only if thermal histogram is flagged to
    # avoid masking fronts
    # 1 - Compute thermal_histogram mask
    unmask_ref = numpy.ushort(0)
    unmask_ref = unmask_ref + (1 << cloud_bits['thermal_histogram'])
    # 2 - Compute spatial coherence mask
    spatial = numpy.ushort(0)
    spatial = spatial + (1 << cloud_bits['spatial_coherence'])
    # 3 - Combine masks
    spatial_mask = ((numpy.bitwise_and(raw_cloud_flags, unmask_ref) > 0) &
                    (numpy.bitwise_and(raw_cloud_flags, spatial) > 0))

    # Build cloud mask
    cloud_mask = numpy.zeros(shape=raw_cloud_flags.shape, dtype='bool')
    cloud_mask = (cloud_mask | spatial_mask |
                  (numpy.bitwise_and(raw_cloud_flags, mask_ref) > 1))

    return cloud_mask
示例#22
0
	def ComprobarLista2(self):
		if len(self.L_L_Goals) == 0:
			return
		with QtCore.QMutexLocker(self.mutex_bus):
			try:
				for x in range(0, len(self.L_L_Goals)):
					m = self.L_L_Goals.pop(0)
					for goal in m:
						for x in self.motorParams:
							if x.name == goal.name:
								busId = x.busId
								break
						if x.invertedSign == "true":
							goal.position = -goal.position
						pos = np.ushort((goal.position + 2.618) * (1023 - 0) / (2.618 + 2.618))
						vel = np.ushort(goal.maxSpeed)
						dynamixel.set_velocity(self.bus, busId, vel, False, num_error_attempts=1)
						dynamixel.set_position(self.bus, busId, pos, False, num_error_attempts=1)
					dynamixel.send_action_packet(self.bus)
			except Ice.Exception, e:
				traceback.print_exc()
				print e
示例#23
0
    def set_sim_sequence(self, angle_phase_wavelength):
        """ Generate a SIM sequence from a list of parameters.

        angle_phase_wavelength is a list where each element is a tuple of the 
        form (angle_number, phase_number, wavelength).
        """
        num_phases = 0
        num_angles = 0
        wavelengths = []
        for (angle, phase, wavelength) in angle_phase_wavelength:
            num_phases = max(num_phases, phase + 1)
            num_angles = max(num_angles, angle + 1)
            if wavelength not in wavelengths:
                wavelengths.append(wavelength)

        phases = [self.sim_phase_offset + n * TWO_PI / num_phases
                    for n in xrange(num_phases)]
        angles = [self.sim_angle_offset + n * TWO_PI / num_angles
                    for n in xrange(num_angles)]

        ## Calculate line pitches for each wavelength, once.
        # d  = m * wavelength / sin theta
        # 1/1000 since wavelength in nm, pixel pitch in microns.
        pitches = {w: w / (1000. * sin(self.sim_diffraction_angle * TWO_PI / 360.))
                     for w in wavelengths}
        ## Figure out the LUTs we need for each wavelength, once.
        luts = {w: self.get_lut(w) for w in set(wavelengths)}

        # retardation for equal powers in 0 and combined +/-1 orders
        modulation = 65535 * 150. / 360.0

        sequence = []
        for (angle, phase, wavelength) in angle_phase_wavelength:
            pp = pitches[wavelength] / self.pixel_pitch
            th = angles[angle]
            ph = phases[phase]
            # Create a stripe 16-bit pattern
            pattern16 = numpy.ushort(
                rint(
                    (0.5 * modulation) + (0.5 * modulation) * cos(
                        ph + TWO_PI * (cos(th) * self.kk + sin(th) * self.ll)
                        / pp)
                    ))              
            # Lose two LSBs and pass through the LUT for given wavelength.
            pattern = luts[wavelength][pattern16 / 4]
            # Append to the sequence.
            sequence.append(pattern)
        self.sequence_parameters = angle_phase_wavelength
        self.sequence = sequence
        self.load_sequence()
示例#24
0
def testread(path):  
    image,label=decode_from_tfrecords(path)  
    images, sparse_labels=get_batch(image, label, 1)
    init=tf.global_variables_initializer()
    with tf.Session() as session:  
        session.run(init)  
        coord = tf.train.Coordinator()  
        threads = tf.train.start_queue_runners(sess=session)  
        for l in range(10):
            images_np,batch_label_np=session.run([images,sparse_labels])  
            print images_np.shape  
            print batch_label_np.shape
            img=np.ushort((np.reshape(images_np, (224,224,3))*255+127))
            print img.shape
            plt.figure()
            plt.imshow(img)
            plt.show()
                     
        coord.request_stop()
        coord.join(threads)
示例#25
0
def calculate_checksum(crc_accum, packet):

    crc_table = [
        0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011, 0x8033,
        0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022, 0x8063, 0x0066,
        0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072, 0x0050, 0x8055, 0x805F,
        0x005A, 0x804B, 0x004E, 0x0044, 0x8041, 0x80C3, 0x00C6, 0x00CC, 0x80C9,
        0x00D8, 0x80DD, 0x80D7, 0x00D2, 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB,
        0x00EE, 0x00E4, 0x80E1, 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE,
        0x00B4, 0x80B1, 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087,
        0x0082, 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
        0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1, 0x01E0,
        0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1, 0x81D3, 0x01D6,
        0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2, 0x0140, 0x8145, 0x814F,
        0x014A, 0x815B, 0x015E, 0x0154, 0x8151, 0x8173, 0x0176, 0x017C, 0x8179,
        0x0168, 0x816D, 0x8167, 0x0162, 0x8123, 0x0126, 0x012C, 0x8129, 0x0138,
        0x813D, 0x8137, 0x0132, 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E,
        0x0104, 0x8101, 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317,
        0x0312, 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
        0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371, 0x8353,
        0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342, 0x03C0, 0x83C5,
        0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1, 0x83F3, 0x03F6, 0x03FC,
        0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2, 0x83A3, 0x03A6, 0x03AC, 0x83A9,
        0x03B8, 0x83BD, 0x83B7, 0x03B2, 0x0390, 0x8395, 0x839F, 0x039A, 0x838B,
        0x038E, 0x0384, 0x8381, 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E,
        0x0294, 0x8291, 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7,
        0x02A2, 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
        0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1, 0x8243,
        0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252, 0x0270, 0x8275,
        0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261, 0x0220, 0x8225, 0x822F,
        0x022A, 0x823B, 0x023E, 0x0234, 0x8231, 0x8213, 0x0216, 0x021C, 0x8219,
        0x0208, 0x820D, 0x8207, 0x0202
    ]
    for d in packet:
        i = (numpy.ushort(crc_accum >> 8) ^ d) & 0xff

        crc_accum = (crc_accum << 8) ^ crc_table[i]
        crc_accum &= 0xffffff

    return crc_accum & 0xffff
示例#26
0
    def __init__(self):
        NT = namedtuple('NT', tuple('abc'))

        self.values = [
                np.longlong(-1), np.int_(-1), np.intc(-1), np.short(-1), np.byte(-1),
                np.ubyte(1), np.ushort(1), np.uintc(1), np.uint(1), np.ulonglong(1),
                np.half(1.0), np.single(1.0), np.float_(1.0), np.longfloat(1.0),
                np.csingle(1.0j), np.complex_(1.0j), np.clongfloat(1.0j),
                np.bool_(0), np.str_('1'), np.unicode_('1'), np.void(1),
                np.object(), np.datetime64('NaT'), np.timedelta64('NaT'), np.nan,
                12, 12.0, True, None, float('NaN'), object(), (1, 2, 3),
                NT(1, 2, 3), datetime.date(2020, 12, 31), datetime.timedelta(14),
        ]

        # Datetime & Timedelta
        for precision in ['ns', 'us', 'ms', 's', 'm', 'h', 'D', 'M', 'Y']:
            for kind, ctor in (('m', np.timedelta64), ('M', np.datetime64)):
                self.values.append(ctor(12, precision))

        for size in (1, 8, 16, 32, 64, 128, 256, 512):
            self.values.append(bytes(size))
            self.values.append('x' * size)
示例#27
0
def generate_stripe_series(patternparms):
    """ Generate a stripe series from the patternparms.

    patternparms is a list of tuples:  (pitch, angle, phase, wavelength),
    where pitch is in microns, and both the angle and phase are specified
    in radians.  
    """
    xindices = np.arange(512)
    yindices = np.arange(512)
    kk, ll = meshgrid(xindices, yindices)
    sequence = []
    for realpitch, angle, phase, waves, wavelength in patternparms:
        pitch = realpitch / 15.0
        modulation = waves * (2**16)
        lut = LUTS[whichLUT(wavelength)]
        pattern16 = np.ushort(
            rint(32768. + (modulation / 2) *
                 cos(phase + 2 * pi *
                     (kk * cos(angle) + ll * sin(angle)) / pitch)))
        pattern = lut[pattern16 / 4]
        sequence.append(pattern)
    return sequence
示例#28
0
 def __init__(self, speed_mhz=0):
     self.clock = CPU.Clock(speed_mhz=speed_mhz)
     self.pc = ushort()  # Program counter
     self.sp = ubyte()  # Stack pointer
     self.acc = ubyte()  # Accumulator
     self.idx = ubyte()  # Index Register X
     self.idy = ubyte()  # Index Register Y
     # Processor status bits
     self.ps = {
         'carry_flag': bool(),
         'zero_flag': bool(),
         'interrupt_flag': bool(),
         'decimal_flag': bool(),
         'break_flag': bool(),
         'reserved': bool(),
         'overflow_flag': bool(),
         'negative_flag': bool()
     }
     self.memory = None
     self.io = None
     self.instructions = cpu6502.instructions.instructions.Instructions(self, filepath=os.path.join(
         os.path.dirname(os.path.abspath(cpu6502.__file__)), '6502_instructions.json'))
示例#29
0
def generate_stripe_series(patternparms):
    """ Generate a stripe series from the patternparms.

    patternparms is a list of tuples:  (pitch, angle, phase, wavelength),
    where pitch is in microns, and both the angle and phase are specified
    in radians.  
    """
    sequence = []
    xindices = np.arange(512)
    yindices = np.arange(512)
    kk, ll = meshgrid(xindices, yindices)
    for realpitch, angle, phase, wavelength in patternparms:
        pitch = realpitch / 15.0
        # Factor to balance m=0,+/-1 orders.
        mp2 = 1.5 
        pattern = np.ushort(
                rint((mp2 / pi) * 32767.5 + 32767.5 * cos(phase +
                2 * pi * (cos(angle) * kk + sin(angle) * ll) / pitch)))
        # Scale to green LUT range
        pattern *= 16256. / 65535.
        pattern += 49279.
        sequence.append(pattern)
    return sequence
示例#30
0
class TestNumpyJSONEncoder(unittest.TestCase):
    @parameterized.expand(
        [(numpy.bool_(1), True), (numpy.bool8(1), True), (numpy.byte(1), 1),
         (numpy.int8(1), 1), (numpy.ubyte(1), 1), (numpy.uint8(1), 1),
         (numpy.short(1), 1), (numpy.int16(1), 1), (numpy.ushort(1), 1),
         (numpy.uint16(1), 1), (numpy.intc(1), 1), (numpy.int32(1), 1),
         (numpy.uintc(1), 1), (numpy.uint32(1), 1), (numpy.int_(1), 1),
         (numpy.int32(1), 1), (numpy.uint(1), 1), (numpy.uint32(1), 1),
         (numpy.longlong(1), 1), (numpy.int64(1), 1), (numpy.ulonglong(1), 1),
         (numpy.uint64(1), 1), (numpy.half(1.0), 1.0),
         (numpy.float16(1.0), 1.0), (numpy.single(1.0), 1.0),
         (numpy.float32(1.0), 1.0), (numpy.double(1.0), 1.0),
         (numpy.float64(1.0), 1.0), (numpy.longdouble(1.0), 1.0)] + ([
             (numpy.float128(1.0), 1.0)  # unavailable on windows
         ] if hasattr(numpy, 'float128') else []))
    def test_numpy_primary_type_encode(self, np_val, py_val):
        self.assertEqual(json.dumps(py_val),
                         json.dumps(np_val, cls=NumpyEncoder))

    @parameterized.expand([
        (numpy.array([1, 2, 3], dtype=numpy.int), [1, 2, 3]),
        (numpy.array([[1], [2], [3]], dtype=numpy.double), [[1.0], [2.0],
                                                            [3.0]]),
        (numpy.zeros((2, 2), dtype=numpy.bool_), [[False, False],
                                                  [False, False]]),
        (numpy.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],
                     dtype=[('name', 'U10'), ('age', 'i4'),
                            ('weight', 'f4')]), [['Rex', 9, 81.0],
                                                 ['Fido', 3, 27.0]]),
        (numpy.rec.array([(1, 2., 'Hello'), (2, 3., "World")],
                         dtype=[('foo', 'i4'), ('bar', 'f4'),
                                ('baz', 'U10')]), [[1, 2.0, "Hello"],
                                                   [2, 3.0, "World"]])
    ])
    def test_numpy_array_encode(self, np_val, py_val):
        self.assertEqual(json.dumps(py_val),
                         json.dumps(np_val, cls=NumpyEncoder))
示例#31
0
def generate_stripe_series(patternparms):
    """ Generate a stripe series from the patternparms.

    patternparms is a list of tuples:  (pitch, angle, phase, wavelength),
    where pitch is in microns, and both the angle and phase are specified
    in radians.  
    """
    sequence = []
    xindices = np.arange(512)
    yindices = np.arange(512)
    kk, ll = meshgrid(xindices, yindices)
    for realpitch, angle, phase, wavelength in patternparms:
        pitch = realpitch / 15.0
        # Factor to balance m=0,+/-1 orders.
        mp2 = 1.5
        pattern = np.ushort(
            rint((mp2 / pi) * 32767.5 +
                 32767.5 * cos(phase + 2 * pi *
                               (cos(angle) * kk + sin(angle) * ll) / pitch)))
        # Scale to green LUT range
        pattern *= 16256. / 65535.
        pattern += 49279.
        sequence.append(pattern)
    return sequence
示例#32
0
    def __processNormalMap(self, img_path, final_w, final_h):
        image = cv2.imread(img_path)
        image = self.__bootstrap(image, self.bootstrap_type)

        rows = image.shape[0]
        cols = image.shape[1]
        chan = image.shape[2]

        aspect = float(cols) / float(rows)
        aspect_need = float(final_w) / float(final_h)

        new_w = cols
        new_h = rows
        cols_offset = 0
        rows_offset = 0

        if aspect_need != aspect:
            if aspect > aspect_need:
                new_w = rows
                cols_offset = int((cols - new_w) / 2)
            elif aspect < aspect_need:
                new_h = cols
                rows_offset = int((rows - new_h) / 2)

        image_c = image[rows_offset:rows_offset + new_h,
                        cols_offset:cols_offset + new_w, :]
        image_resized = cv2.resize(image_c, (final_h, final_w))

        normal_map = estimateNormalMap(image_resized, 3, 25)
        normal_map = normal_map * 65355

        #cv2.imshow("normal_map", normal_map)
        #cv2.moveWindow("normal_map", 380, 100)
        #cv2.waitKey(1)

        return np.ushort(normal_map)
示例#33
0
reveal_type(np.bool8())  # E: numpy.bool_
reveal_type(np.bytes0())  # E: numpy.bytes_
reveal_type(np.string_())  # E: numpy.bytes_
reveal_type(np.object0())  # E: numpy.object_
reveal_type(np.void0(0))  # E: numpy.void

reveal_type(np.byte())  # E: {byte}
reveal_type(np.short())  # E: {short}
reveal_type(np.intc())  # E: {intc}
reveal_type(np.intp())  # E: {intp}
reveal_type(np.int0())  # E: {intp}
reveal_type(np.int_())  # E: {int_}
reveal_type(np.longlong())  # E: {longlong}

reveal_type(np.ubyte())  # E: {ubyte}
reveal_type(np.ushort())  # E: {ushort}
reveal_type(np.uintc())  # E: {uintc}
reveal_type(np.uintp())  # E: {uintp}
reveal_type(np.uint0())  # E: {uintp}
reveal_type(np.uint())  # E: {uint}
reveal_type(np.ulonglong())  # E: {ulonglong}

reveal_type(np.half())  # E: {half}
reveal_type(np.single())  # E: {single}
reveal_type(np.double())  # E: {double}
reveal_type(np.float_())  # E: {double}
reveal_type(np.longdouble())  # E: {longdouble}
reveal_type(np.longfloat())  # E: {longdouble}

reveal_type(np.csingle())  # E: {csingle}
reveal_type(np.singlecomplex())  # E: {csingle}
# This is an example for the initialization of a linear kernel on word (2byte)
# data.

from tools.load import LoadMatrix
from numpy import ushort

lm = LoadMatrix()
traindat = ushort(lm.load_numbers("../data/fm_train_word.dat"))
testdat = ushort(lm.load_numbers("../data/fm_test_word.dat"))

parameter_list = [[traindat, testdat, 1.2], [traindat, testdat, 1.2]]


def kernel_linear_word_modular(fm_train_word=traindat, fm_test_word=testdat, scale=1.2):

    from shogun.Kernel import LinearKernel, AvgDiagKernelNormalizer
    from shogun.Features import WordFeatures

    feats_train = WordFeatures(fm_train_word)
    feats_test = WordFeatures(fm_test_word)

    kernel = LinearKernel(feats_train, feats_train)
    kernel.set_normalizer(AvgDiagKernelNormalizer(scale))
    kernel.init(feats_train, feats_train)

    km_train = kernel.get_kernel_matrix()
    kernel.init(feats_train, feats_test)
    km_test = kernel.get_kernel_matrix()
    return kernel

示例#35
0
from tools.load import LoadMatrix
from numpy import ushort
from sg import sg

lm = LoadMatrix()

trainword = ushort(lm.load_numbers('../data/fm_test_word.dat'))
testword = ushort(lm.load_numbers('../data/fm_test_word.dat'))
parameter_list = [[trainword, testword, 10, 1.4],
                  [trainword, testword, 11, 1.5]]


def kernel_linearword(fm_train_word=trainword,
                      fm_test_word=testword,
                      size_cache=10,
                      scale=1.4):
    sg('set_features', 'TRAIN', fm_train_word)
    sg('set_features', 'TEST', fm_test_word)
    sg('set_kernel', 'LINEAR', 'WORD', size_cache, scale)
    km = sg('get_kernel_matrix', 'TRAIN')
    km = sg('get_kernel_matrix', 'TEST')
    return km


if __name__ == '__main__':
    print 'LinearWord'
    kernel_linearword(*parameter_list[0])
示例#36
0
文件: scalars.py 项目: nanbo99/numpy
np.bool8()
np.bytes0()
np.string_()
np.object0()
np.void0(0)

np.byte()
np.short()
np.intc()
np.intp()
np.int0()
np.int_()
np.longlong()

np.ubyte()
np.ushort()
np.uintc()
np.uintp()
np.uint0()
np.uint()
np.ulonglong()

np.half()
np.single()
np.double()
np.float_()
np.longdouble()
np.longfloat()

np.csingle()
np.singlecomplex()
示例#37
0
    ppl.plot(list(range(nfrms)), vel[ptnum, :])
    ppl.xlabel('Frame')
    ppl.ylabel('Mean luminal velocity [mm/s]')
    ppl.title('Velocity in vessel')
    fig.canvas.draw()

print('Close the figure to continue...')
ppl.show(32)

# save the mask as a Nifti image
pchdr = pcimgs.header
pixel_size = pchdr.get_zooms()
print('get_zooms(): ', pixel_size)

nibimg = nib.Nifti1Image(np.ushort(masksum), None, pchdr)
hdr = nibimg.header
hdr.set_xyzt_units('mm', 'sec')
# print(hdr)
nib.save(nibimg, os.path.join(imgpath, 'mask2d_rs18.nii.gz'))

# here is how to save it as a 3D with it replicated nfrms times
mask3d = np.zeros((nrows, ncols, 1, nfrms))
for i in range(nfrms):
    mask3d[:, :, 0, i] = masksum

print('pchdr.shape = ', pcdata.shape)
print('mask2.shape = ', mask2.shape)
print('masksum.shape = ', masksum.shape)
print('mask3d.shape = ', mask3d.shape)
示例#38
0
    def demo(self, image):

        self.time2store = self.gen_datetime()
        # self.time2store = datetime.now()
        # print('min_side: {min_side}\nmax_side: {max_side}'.format(
            # min_side=self.min_side4train, max_side=self.max_side4train))
        # copy to draw on
        draw = image.copy()

        # preprocess image for network
        image = preprocess_image(image)
        # cv2.imshow('ss22', image)
        image, scale = resize_image(
            image, min_side=self.min_side4train, max_side=self.max_side4train)

        time_ = self.time2store
        # time_ = datetime.now()

        image_id = time_.strftime('%Y%m-%d%H-%M%S-') + str(uuid4())

        # process image
        start = time.time()
        boxes, scores, labels = self.model.predict_on_batch(
            np.expand_dims(image, axis=0))
        processing_time = time.time() - start
        # print("processing time: ", processing_time)

        img4elas, scale4elas = resize_image(
            draw, min_side=self.min_side4elas, max_side=self.max_side4elas)

        # correct for image scale
        boxes /= scale

        found_ = {}

        main_body = {'image_id': image_id, 'time_': time_}
        # visualize detections
        print('es_mode: {}\nstatus: {}'.format(self.es_mode, self.es_status))
        temp_data = []
        index = 1
        for box, score, label in zip(boxes[0], scores[0], labels[0]):
            # scores are sorted so we can break
            # print(index, box, score, self.labels_to_names[label])
            if score < self.confThreshold:
                break

            color = label_color(label)

            b = box.astype(int)

            draw_box(draw, b, color=color)

            caption = "{} {:.3f}".format(
                self.labels_to_names[label], score)
            # print(caption)
            draw_caption(draw, b, caption)
            temp_data.append([self.labels_to_names[label],
                              score, b, processing_time])

            box = [np.ushort(x).item() for x in box]

            # cv2.imshow(str(self.model_is), draw )
            # cv2.waitKey()
            #  if self.es_mode and self.es_status:
            #     self.es.elas_record(label=label, score=np.float32(score).item(), box=box, image_id=image_id, time_=time_)

            if self.es_mode and self.es_status and self.labels_to_names[label] == 'pigeon':
                # print('{tag}\n\n{data}\n\n{tag}'.format(
                #     tag='#'*20,
                #     data='label: {label}\nscore: {score}'.format(
                #         label=self.labels_to_names[label], score=score)
                # ))
                cv2.waitKey(4)
                self.es.elas_record(label=label, score=np.float32(
                    score).item(), box=box, **main_body)
            index += 1

            try:
                found_[self.labels_to_names[label]] += 1
            except:
                found_[self.labels_to_names[label]] = 1
        # os.makedirs("data4eval/non-pigeon/result/{}".format(self.model_is), exist_ok=True)

        # cv2.imwrite("data4eval/non-pigeon/result/{}/{}-{}.jpg".format(self.model_is, self.model_is,  datetime.now(), image_id), draw)
        # scheduler = BackgroundScheduler(timezone=get_localzone())
        # scheduler.add_job(task_deley, 'interval', seconds=sec_per_frame)
        # scheduler.add_job(stopTurret, 'interval', seconds=20)
        # scheduler.start()    

        try:
            if found_['pigeon'] > 0:
                self.silen_.alert()
                if self.es_mode and self.es_status:
                    print('{tag}\n\n{data}\n\n{tag}'.format(
                        tag='#'*50,
                        data='id: {id}\nbird count: {found}'.format(
                            id=image_id, found=found_)))
                    self.es.elas_image(image=img4elas, scale=scale, found_=found_,
                                    processing_time=processing_time, **main_body)
                    # self.es.elas_date(**main_body)
        except Exception as e:
            print(e)

        return draw
示例#39
0

# Generate test images from TIFFs.
images = []
test_files = os.listdir(TEST_PATH)
print "Loading test files:"
for f in test_files:
    print "  %s" % f
    images.append(dev.read_tiff(f))


# Numerically-generated test images.
ind = np.arange(512)
kk, ll = np.meshgrid(ind, ind)
ndarray_images = []
ndarray_images.append(np.ushort(32767 + ((kk % 32) > 15) * 65535/2))
ndarray_images.append(np.ushort(32767 + (((kk + ll) % 48) > 23 )* 65535/2))
ndarray_images.append(np.ushort(32767 + ((ll % 32) > 15) * 65535/2))


# Show a single TIFF-derived image for five seconds.
print "Single image from TIFF."
dev.write_image(images[0])
dev.power = True
sleep(5)

# Run the TIFF-derived cycle for five seconds.
print "TIFF series"
dev.load_sequence(images)
dev.start_sequence()
sleep(5)
    def execute(self):
        for kk,file_name in enumerate(self.file_list):
            print file_name
            reader=vtk.vtkPolyDataReader()
            reader.SetFileName(file_name)
            reader.Update()

            poly = self.compute_radius(reader.GetOutput(),spacing_list[kk])
            if self.use_field_data == False:
                poly.GetPointData().\
                    SetNormals(poly.GetPointData().\
                               GetArray(self.normal_map[self.feature_type]))
            else:
                poly.GetPointData().\
                    SetNormals(poly.GetFieldData().\
                               GetArray(self.normal_map[self.feature_type]))

            glypher=self.create_glyphs(poly)
            if len(self.color_list) <= kk:
                color=[]
            else:
                color=self.color_list[kk]
            if len(self.opacity_list) <= kk:
                opacity=1
            else:
                opacity=self.opacity_list[kk]
            self.create_actor(glypher,color=color,opacity=opacity)

            # Adds the box interaction mechanism

            self.boxWidgetParticles.SetInteractor(self.iren)
            self.boxWidgetParticles.SetPlaceFactor(1.25)
            self.boxWidgetParticles.SetInput(glypher.GetOutput())
            self.boxWidgetParticles.PlaceWidget()
            self.boxWidgetParticles.AddObserver("EndInteractionEvent", self.SelectPolygons)
            self.boxWidgetParticles.EnabledOff()

            ## The SelectPolygons function is slow as hell - therefore it is only updated when it is released
            # self.boxWidgetParticles.AddObserver("StartInteractionEvent", self.StartInteraction)
            # self.boxWidgetParticles.AddObserver("InteractionEvent", self.SelectPolygons)
            # self.boxWidgetParticles.AddObserver("EndInteractionEvent", self.EndInteraction)



        if len(self.lung)>0:
            ## Generate a transfer function - the phantom is in the range -400, -200


            # Converts the nrrd into a vtk volume
            readdata, options = nrrd.read(self.lung)
            print options


            ## This is to be changed!! FIXME - the minimum value does not need to be of interest - find the min val of HUs
            readdata = readdata.transpose([2,1,0])   # yup, nrrd and axes

            minval = readdata.min()
            print minval
            print readdata.max()


            tfun = vtk.vtkPiecewiseFunction()
            # tfun.AddPoint(100, 0);
            # tfun.AddPoint(600, 1.0);
            # tfun.AddPoint(700, 1.0);
            # tfun.AddPoint(500, 0.0);
            # tfun.AddPoint(1000, 0);

            tfun.AddPoint(-minval-2000, 0);
            tfun.AddPoint(-minval-1000, 0.0);
            tfun.AddPoint(-minval-300, 1.0);
            tfun.AddPoint(-minval-100, 1.0);
            tfun.AddPoint(-minval-80, 0);
            readdata = np.ushort(readdata - minval)
            print readdata.min()
            print readdata.max()


            # tfun.AddPoint(-1000, 0.0);
            # tfun.AddPoint(- 800, 0.0);
            # tfun.AddPoint(- 400, 1.0);
            # tfun.AddPoint(- 200, 1.0);
            # tfun.AddPoint(- 180, 0.0);
            # tfun.AddPoint(  100, 0.0);
            # tfun.AddPoint(  300, 0.0);
            # tfun.AddPoint(  800, 0.0);
            # tfun.AddPoint( 1070, 0.0);

            sz = readdata.shape
            dataSpacing = options.get('space directions')   # scale of the image
            dataSpacing = [dataSpacing[0][0], dataSpacing[1][1], dataSpacing[2][2]]
            dataOrigin = options.get('space origin')
            dataImporter = vtk.vtkImageImport()
            data_string = readdata.tostring()
            dataImporter.CopyImportVoidPointer(data_string, len(data_string))

            dataImporter.SetDataScalarTypeToUnsignedShort()
            dataImporter.SetNumberOfScalarComponents(1)   # it is a bw image
            dataImporter.SetDataOrigin(dataOrigin) # location of the image
            dataImporter.SetDataSpacing(dataSpacing)
            dataImporter.SetDataExtent(0, sz[2]-1, 0, sz[1]-1, 0, sz[0]-1)
            dataImporter.SetWholeExtent(0, sz[2]-1, 0, sz[1]-1, 0, sz[0]-1)
            self.volume_size = [sz[2]-1, sz[1]-1, sz[0]-1]
            dataImporter.Update()

            print dataImporter.GetDataScalarTypeAsString()

            volumeProperty = vtk.vtkVolumeProperty()
            volumeProperty.SetScalarOpacity(tfun)
            volumeProperty.SetInterpolationTypeToLinear()


            # How is the volume going to be rendered?
            compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
            self.volumeMapper.SetVolumeRayCastFunction(compositeFunction)
            self.volumeMapper.SetInputConnection(dataImporter.GetOutputPort())

            # Finally generate the volume
            self.volumeActor.SetMapper(self.volumeMapper)
            self.volumeActor.SetProperty(volumeProperty)

            # Add the new actors to the rendering pipeline
            self.ren.AddVolume(self.volumeActor)
            self.volume_added_to_renderer = True
            self.volume_loaded = True

            # Adds the box interaction mechanism
            self.boxWidgetVolume.SetInteractor(self.iren)
            self.boxWidgetVolume.SetPlaceFactor(1.0)

            self.boxWidgetVolume.SetInput(dataImporter.GetOutput())

            self.boxWidgetVolume.PlaceWidget()
            self.boxWidgetVolume.InsideOutOn()
            self.boxWidgetVolume.AddObserver("StartInteractionEvent", self.StartInteraction)
            self.boxWidgetVolume.AddObserver("InteractionEvent", self.ClipVolumeRender)
            self.boxWidgetVolume.AddObserver("EndInteractionEvent", self.EndInteraction)

            outlineProperty = self.boxWidgetVolume.GetOutlineProperty()
            outlineProperty.SetRepresentationToWireframe()
            outlineProperty.SetAmbient(1.0)
            outlineProperty.SetAmbientColor(1, 1, 1)
            outlineProperty.SetLineWidth(3)

            selectedOutlineProperty = self.boxWidgetVolume.GetSelectedOutlineProperty()
            selectedOutlineProperty.SetRepresentationToWireframe()
            selectedOutlineProperty.SetAmbient(1.0)
            selectedOutlineProperty.SetAmbientColor(1, 0, 0)
            selectedOutlineProperty.SetLineWidth(3)

            # picker = vtk.vtkCellPicker()
            # picker.SetTolerance(0.005)

            # Adds the plane interactors
            self.planeWidgetX.DisplayTextOn()
            self.planeWidgetY.DisplayTextOn()
            self.planeWidgetY.DisplayTextOn()
            self.planeWidgetX.SetInput(dataImporter.GetOutput())
            self.planeWidgetY.SetInput(dataImporter.GetOutput())
            self.planeWidgetZ.SetInput(dataImporter.GetOutput())
            self.planeWidgetX.SetPlaneOrientationToXAxes()
            self.planeWidgetY.SetPlaneOrientationToYAxes()
            self.planeWidgetZ.SetPlaneOrientationToZAxes()
            self.planeWidgetX.SetSliceIndex(1)
            self.planeWidgetY.SetSliceIndex(1)
            self.planeWidgetZ.SetSliceIndex(1)

            self.planeWidgetX.SetInteractor(self.iren)
            self.planeWidgetY.SetInteractor(self.iren)
            self.planeWidgetZ.SetInteractor(self.iren)



        self.ren.SetBackground(0, 0, 0)
        self.add_color_bar()
        self.render()
from tools.load import LoadMatrix
from numpy import ushort
from sg import sg
lm=LoadMatrix()

trainword=ushort(lm.load_numbers('../data/fm_test_word.dat'))
testword=ushort(lm.load_numbers('../data/fm_test_word.dat'))
parameter_list=[[trainword,testword,10,1.4],
	       [trainword,testword,11,1.5]]

def kernel_linearword (fm_train_word=trainword,fm_test_word=testword,
		       size_cache=10, scale=1.4):
	sg('set_features', 'TRAIN', fm_train_word)
	sg('set_features', 'TEST', fm_test_word)
	sg('set_kernel', 'LINEAR', 'WORD', size_cache, scale)
	km=sg('get_kernel_matrix', 'TRAIN')
	km=sg('get_kernel_matrix', 'TEST')
	return km

if __name__=='__main__':
	print('LinearWord')
	kernel_linearword(*parameter_list[0])
def VolumeRenderingRayCast(inVolume, scale=[1, 1, 1], lowerThreshold=0, upperThreshold=None):
    """
    Recieve a numpy volume and render it with RayCast method. This method employs CPU raycast
    and will subject to upgrades of using GPUVolumeMapper in the future. The method returns
    a vtkVolume actor which can be added to a vtkRenderer

    :param inVolume:        numpy volume
    :param scale:           scale [x, y, z] of the slice/voxel spacing to real spacing
    :param lowerThreshold:  lower Threshold for raycast. Default = 0
    :param upperThreshold:  upper Threshold for raycast. Default = inVolume.max()
    :return: vtk.vtkVolume
    """
    inVolume = np.ushort(inVolume)
    inVolumeString = inVolume.tostring()

    # Color map related
    if upperThreshold == None:
        upperThreshold = inVolume.max()

    if upperThreshold <= lowerThreshold:
        raise ValueError("Upper Threshold must be larger than lower Threshold.")

    centerThreshold = (upperThreshold - lowerThreshold) / 2.0 + lowerThreshold
    lowerQuardThreshold = (centerThreshold - lowerThreshold) / 2.0 + lowerThreshold
    upperQuardThreshold = (upperThreshold - centerThreshold) / 2.0 + centerThreshold

    dataImporter = vtk.vtkImageImport()
    dataImporter.CopyImportVoidPointer(inVolumeString, len(inVolumeString))
    dataImporter.SetDataScalarTypeToUnsignedShort()
    dataImporter.SetNumberOfScalarComponents(1)
    dataImporter.SetDataExtent(0, inVolume.shape[2] - 1, 0, inVolume.shape[1] - 1, 0, inVolume.shape[0] - 1)
    dataImporter.SetWholeExtent(0, inVolume.shape[2] - 1, 0, inVolume.shape[1] - 1, 0, inVolume.shape[0] - 1)

    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(lowerThreshold, 0)
    alphaChannelFunc.AddPoint(lowerQuardThreshold, 0.05)
    alphaChannelFunc.AddPoint(centerThreshold, 0.4)
    alphaChannelFunc.AddPoint(upperQuardThreshold, 0.05)
    alphaChannelFunc.AddPoint(upperThreshold, 0)

    colorFunc = vtk.vtkColorTransferFunction()
    colorFunc.AddRGBPoint(lowerThreshold, 0, 0, 0)
    colorFunc.AddRGBPoint(centerThreshold, 0.5, 0.5, 0.5)
    colorFunc.AddRGBPoint(upperThreshold, 0.8, 0.8, 0.8)

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)

    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
    volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetInputConnection(dataImporter.GetOutputPort())

    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)
    volume.SetScale(scale)

    # Volume is returned for further rendering
    return volume