Per-antenna UVW coordinate data source
172946
def uvw(self, context):
        

        # Hacky access of private member
        cube = context._cube

        # Create antenna1 source context
        a1_actual = cube.array("antenna1", reify=True)
        a1_ctx = SourceContext("antenna1", cube, context.cfg,
            context.iter_args, cube.array("antenna1"),
            a1_actual.shape, a1_actual.dtype)

        # Create antenna2 source context
        a2_actual = cube.array("antenna2", reify=True)
        a2_ctx = SourceContext("antenna2", cube, context.cfg,
            context.iter_args, cube.array("antenna2"),
            a2_actual.shape, a2_actual.dtype)

        # Get antenna1 and antenna2 data
        ant1 = self.antenna1(a1_ctx).ravel()
        ant2 = self.antenna2(a2_ctx).ravel()

        # Obtain per baseline UVW data
        lrow, urow = MS.uvw_row_extents(context)
        uvw = self._manager.ordered_uvw_table.getcol(MS.UVW,
                                                startrow=lrow,
                                                nrow=urow-lrow)

        # Perform the per-antenna UVW decomposition
        ntime, nbl = context.dim_extent_size('ntime', 'nbl')
        na = context.dim_global_size('na')
        chunks = np.repeat(nbl, ntime).astype(ant1.dtype)

        auvw = mbu.antenna_uvw(uvw, ant1, ant2, chunks, nr_of_antenna=na)

        return auvw.reshape(context.shape).astype(context.dtype)
1253333
def _match_channels_to_data(self, data):
        

        data = self._format_data(data)

        matched_channels = []
        for spectrum in data:
            match = self._overlapping_channels(spectrum.disp)
            if not match:
                # TODO: make this warning only appear once.
                logger.warn("No model spectra found matching data channel from "
                    "{0:.0f}-{1:.0f} Angstroms. These data will be ignored."\
                    .format(spectrum.disp[0], spectrum.disp[-1]))

            if len(match) > 1:
                raise ValueError("cannot match multiple channels for one spec")

            if len(match) == 0:
                match = [None]

            matched_channels.append(match[0])

        missing_channels = set(self.channel_names).difference(matched_channels)

        # Now which parameters should be ignored?
        ignore_parameters = []
        if missing_channels:
            for channel in missing_channels:
                ignore_parameters.extend(
                    set(self.parameters).intersection([_.format(channel) \
                        for _ in ("resolution_{}", "f_{}", "z_{}")]))
                
                ignore_parameters.extend(["continuum_{0}_{1}".format(channel, i)\
                    for i in range(self._configuration["model"].get("continuum",
                        {}).get(channel, -1) + 1)])

        if ignore_parameters:
            logger.warn("Ignoring the following model parameters because there "
                "are no data for that channel: {}".format(", ".join(
                    ignore_parameters)))

        return (matched_channels, missing_channels, ignore_parameters)
1318778
def calibrate(self, data, calibration):
        """"""
        tic = datetime.now()
        channel_name = self.channel_name

        if calibration == 'counts':
            res = data
        elif calibration in ['radiance', 'reflectance', 'brightness_temperature']:
            # Choose calibration coefficients
            # a) Internal: Nominal or GSICS?
            band_idx = self.mda['spectral_channel_id'] - 1
            if self.calib_mode != 'GSICS' or self.channel_name in VIS_CHANNELS:
                # you cant apply GSICS values to the VIS channels
                coefs = self.prologue["RadiometricProcessing"]["Level15ImageCalibration"]
                int_gain = coefs['CalSlope'][band_idx]
                int_offset = coefs['CalOffset'][band_idx]
            else:
                coefs = self.prologue["RadiometricProcessing"]['MPEFCalFeedback']
                int_gain = coefs['GSICSCalCoeff'][band_idx]
                int_offset = coefs['GSICSOffsetCount'][band_idx]

            # b) Internal or external? External takes precedence.
            gain = self.ext_calib_coefs.get(self.channel_name, {}).get('gain', int_gain)
            offset = self.ext_calib_coefs.get(self.channel_name, {}).get('offset', int_offset)

            # Convert to radiance
            data = data.where(data > 0)
            res = self._convert_to_radiance(data.astype(np.float32), gain, offset)
            line_mask = self.mda['image_segment_line_quality']['line_validity'] >= 2
            line_mask &= self.mda['image_segment_line_quality']['line_validity'] <= 3
            line_mask &= self.mda['image_segment_line_quality']['line_radiometric_quality'] == 4
            line_mask &= self.mda['image_segment_line_quality']['line_geometric_quality'] == 4
            res *= np.choose(line_mask, [1, np.nan])[:, np.newaxis].astype(np.float32)

        if calibration == 'reflectance':
            solar_irradiance = CALIB[self.platform_id][channel_name]["F"]
            res = self._vis_calibrate(res, solar_irradiance)

        elif calibration == 'brightness_temperature':
            cal_type = self.prologue['ImageDescription'][
                'Level15ImageProduction']['PlannedChanProcessing'][self.mda['spectral_channel_id']]
            res = self._ir_calibrate(res, channel_name, cal_type)

        logger.debug("Calibration time " + str(datetime.now() - tic))
        return res
1037641
def _loglr(self):
        
        """
        # calculate <d-h|d-h> = <h|h> - 2<h|d> + <d|d> up to a constant
        p = self.current_params.copy()
        p.update(self.static_params)

        if self.time is None:
            self.time = p['tc']

        shloglr = hhloglr = 0
        for ifo in self.sh:
            fp, fc = self.det[ifo].antenna_pattern(p['ra'], p['dec'],
                                                   p['polarization'],
                                                   self.time)
            dt = self.det[ifo].time_delay_from_earth_center(p['ra'],
                                                            p['dec'],
                                                            self.time)
            ip = numpy.cos(p['inclination'])
            ic = 0.5 * (1.0 + ip * ip)
            htf = (fp * ip + 1.0j * fc * ic) / p['distance']

            sh = self.sh[ifo].at_time(p['tc'] + dt) * htf
            shloglr += sh
            hhloglr += self.hh[ifo] * abs(htf) ** 2.0

        vloglr = numpy.log(scipy.special.i0e(abs(shloglr)))
        vloglr += abs(shloglr) + hhloglr

        return float(vloglr)
1253441
def calcdelay(self, ant1, ant2, skyfreq, pol):
        

        select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]]

        ind1 = n.where(ant1 == self.antnum[select])
        ind2 = n.where(ant2 == self.antnum[select])
        d1 = self.delay[select][ind1]
        d2 = self.delay[select][ind2]
        if len(d1-d2) > 0:
            return d1-d2
        else:
            return n.array([0])
298946
def get_data (self, datakind, integnum):
        """"""

        if integnum < 0 or integnum >= self.n_integrations:
            raise ValueError ('illegal integration number %d' % integnum)

        size = self.sizeinfo.get (datakind)
        if size is None:
            raise ValueError ('unrecognized data kind "%s"' % datakind)

        dtype = _datatypes[datakind]
        offset = self.headsize + integnum * self.intsize
        dslice = self.mmdata[offset:offset+size]
        data = np.fromstring (dslice, dtype=dtype)

        if datakind == 'crossData.bin':
            data = data.reshape ((self.n_baselines, self.n_channels, len (self.crosspols)))
        elif datakind == 'autoData.bin':
            data = data.reshape ((self.n_antennas, self.n_channels, 2))
        elif datakind == 'flags.bin':
            data = data.reshape ((self.n_baselines + self.n_antennas, self.n_channels,
                                  len (self.crosspols)))

        return data
1220974
def _get_area_def_uniform_sampling(self, lon0, channel):
        """"""
        logger.debug('Computing area definition')

        if lon0 is not None:
            # Define proj4 projection parameters
            proj_dict = {'a': EQUATOR_RADIUS,
                         'b': POLE_RADIUS,
                         'lon_0': lon0,
                         'h': ALTITUDE,
                         'proj': 'geos',
                         'units': 'm'}

            # Calculate maximum scanning angles
            xmax, ymax = get_geostationary_angle_extent(
                namedtuple('area', ['proj_dict'])(proj_dict))

            # Derive area extent using small angle approximation (maximum
            # scanning angle is ~8.6 degrees)
            llx, lly, urx, ury = ALTITUDE * np.array([-xmax, -ymax, xmax, ymax])
            area_extent = [llx, lly, urx, ury]

            # Original image is oversampled. Create pyresample area definition
            # with uniform sampling in N-S and E-W direction
            if self._is_vis(channel):
                sampling = SAMPLING_NS_VIS
            else:
                sampling = SAMPLING_NS_IR
            pix_size = ALTITUDE * sampling
            area_def = pyresample.geometry.AreaDefinition(
                'goes_geos_uniform',
                '{} geostationary projection (uniform sampling)'.format(self.platform_name),
                'goes_geos_uniform',
                proj_dict,
                np.rint((urx - llx) / pix_size).astype(int),
                np.rint((ury - lly) / pix_size).astype(int),
                area_extent)

            return area_def
        else:
            return None
1364189
def from_arrays(cls, name, verts, normals, n_verts=3):

        """"""

        # Put header in string
        wavefront_str = "o {name}\n".format(name=name)

        # Write Vertex data from vert_dict
        for vert in verts:
            wavefront_str += "v {0} {1} {2}\n".format(*vert)

        # Write (false) UV Texture data
        wavefront_str += "vt 1.0 1.0\n"

        for norm in normals:
            wavefront_str += "vn {0} {1} {2}\n".format(*norm)


        # Write Face Indices (1-indexed)
        for wall_idx, vert_indices in enumerate(grouper(n_verts, range(1, len(verts) + 1))):
            face_str = 'f '
            for idx in vert_indices:
                face_str += "{v}/1/{n} ".format(v=idx, n=wall_idx + 1)
            wavefront_str += face_str + '\n'

        return WavefrontWriter(string=wavefront_str)
1182559
def det2lab_xds(
        pixels_coord, frame_number,
        starting_frame, starting_angle, oscillation_angle,
        rotation_axis,
        wavelength, wavevector,
        NX, NY, pixelsize_x, pixelsize_y,
        distance_to_detector, x_center, y_center,
        detector_x, detector_y, detector_normal, **kwargs):
    """"""

    array_shape = (1, 3)

    if detector_x.shape == array_shape:
        detector_x = detector_x.T
        detector_y = detector_y.T
        detector_normal = detector_normal.T
    if wavevector.shape == array_shape:
        wavevector = wavevector.T
    if rotation_axis.shape == array_shape:
        rotation_axis = rotation_axis.T
    xmm = (pixels_coord[:, [0]] - x_center) * pixelsize_x
    ymm = (pixels_coord[:, [1]] - y_center) * pixelsize_y
    # find scattering vector of each pixel
    scattering_vector_mm = np.outer(xmm, detector_x) + \
                           np.outer(ymm, detector_y) + \
                           distance_to_detector * np.outer(np.ones(shape=xmm.shape),
                                                           detector_normal)
    scattering_vector_mm = scattering_vector_mm.T
    phi = (frame_number - starting_frame) * oscillation_angle + \
          starting_angle
    # calculating norm for each column
    norms = np.sum(scattering_vector_mm ** 2., axis=0) ** (1. / 2)
    #deviding scattering vector by its own norm
    unit_scattering_vector = scattering_vector_mm / norms
    #subtracting incident beam vector

    h = unit_scattering_vector / wavelength - \
        np.tile(wavevector, (unit_scattering_vector.shape[1], 1)).T
    #rotating
    if phi.size == 1:
        h = np.dot(rotvec2mat(rotation_axis.T, -2 * np.pi * phi / 360), h)
    else:
        for i in range(phi.size):
            h[:, [i]] = np.dot(
                rotvec2mat(rotation_axis.T, -2 * np.pi * phi[i] / 360), h[:, [i]])

    return h, scattering_vector_mm, unit_scattering_vector
919966
def _load_data(self, band):
        
        d = bandpass_data_fits('sw' + self._band_map[band] + '_20041120v106.arf')[1].data

        # note:
        #   data.WAVE_MIN[i] < data.WAVE_MIN[i+1], but
        #   data.WAVE_MIN[i] > data.WAVE_MAX[i] (!)
        #   data.WAVE_MIN[i] = data.WAVE_MAX[i+1] (!)

        wmid = 0.5 * (d.WAVE_MIN + d.WAVE_MAX) # in Ångström
        df = pd.DataFrame({'wlen': wmid, 'resp': d.SPECRESP,
                           'wlo': d.WAVE_MAX, 'whi': d.WAVE_MIN})
        return df
473475
def expected_magz(RAW_IMU, ATTITUDE, inclination, declination):
    ''''''
    v = expected_mag(RAW_IMU, ATTITUDE, inclination, declination)
    return v.z
1355495
def _antenna_uvw(uvw, antenna1, antenna2, chunks, nr_of_antenna):
    

    if antenna1.ndim != 1:
        raise ValueError("antenna1 shape should be (row,)")

    if antenna2.ndim != 1:
        raise ValueError("antenna2 shape should be (row,)")

    if uvw.ndim != 2 or uvw.shape[1] != 3:
        raise ValueError("uvw shape should be (row, 3)")

    if not (uvw.shape[0] == antenna1.shape[0] == antenna2.shape[0]):
        raise ValueError("First dimension of uvw, antenna1 "
                         "and antenna2 do not match")

    if chunks.ndim != 1:
        raise ValueError("chunks shape should be (utime,)")

    if nr_of_antenna < 1:
        raise ValueError("nr_of_antenna < 1")

    ant_uvw_shape = (chunks.shape[0], nr_of_antenna, 3)
    antenna_uvw = np.full(ant_uvw_shape, np.nan, dtype=uvw.dtype)

    start = 0

    for ci, chunk in enumerate(chunks):
        end = start + chunk

        # one pass should be enough!
        _antenna_uvw_loop(uvw, antenna1, antenna2, antenna_uvw, ci, start, end)

        start = end

    return antenna_uvw
1182791
def default_antenna2(self, context):
    
    ant1, ant2 = default_base_ant_pairs(self, context)
    (tl, tu), (bl, bu) = context.dim_extents('ntime', 'nbl')
    ant2_result = np.empty(context.shape, context.dtype)
    ant2_result[:,:] = ant2[np.newaxis,bl:bu]
    return ant2_result
276525
def updated_dimensions(self):
        
        return [("ntime", args.ntime),      # Timesteps
                ("nchan", args.nchan),      # Channels
                ("na", args.na),            # Antenna
                ("npsrc", len(lm_coords))]
1327222
def cmd_antenna(self, args):
        ''''''
        if len(args) != 2:
            if self.gcs_location is None:
                print("GCS location not set")
            else:
                print("GCS location %s" % str(self.gcs_location))
            return
        self.gcs_location = (float(args[0]), float(args[1]))
407007
def frequent_antennas(positions, percentage=0.8):
    
    location_count = Counter(list(map(str, positions)))

    target = math.ceil(sum(location_count.values()) * percentage)
    location_sort = sorted(list(location_count.keys()),
                           key=lambda x: location_count[x])

    while target > 0 and len(location_sort) > 0:
        location_id = location_sort.pop()
        target -= location_count[location_id]

    return len(location_count) - len(location_sort)
1335694
def rectwidth(self):
        
        mywaveunits = self.waveunits.name
        self.convert('angstroms')

        wave = self.wave
        thru = self.throughput
        self.convert(mywaveunits)

        num = self.trapezoidIntegration(wave, thru)
        den = thru.max()

        if 0.0 in (num, den):
            return 0.0
        else:
            return num/den