Performs magnetometer calibration. Assumes mag_samples contains samples
        in order [+x, -x, +y, -y, +z, -z]. Calculates per-axis scale/offset values
770581
def calculate_mag_calibration(self, mag_samples):
        """"""

        max_vals = [mag_samples[0][0], mag_samples[2][1], mag_samples[3][2]]
        min_vals = [mag_samples[1][0], mag_samples[3][1], mag_samples[5][2]]

        magbiases = [int((max_vals[i] + min_vals[i]) / 2.0) for i in range(3)]
        magscalings = [(max_vals[i] - min_vals[i]) / 2.0 for i in range(3)]
        avg_rads = sum(magscalings) / 3.0
        magscalings = [avg_rads / magscalings[i] for i in range(3)]

        data = self.calibration_data[self.current_imuid]

        data[self.MAGX_OFFSET] = str(int(magbiases[0]))
        data[self.MAGY_OFFSET] = str(int(magbiases[1]))
        data[self.MAGZ_OFFSET] = str(int(magbiases[2]))
        
        data[self.MAGX_SCALE] = str(magscalings[0])
        data[self.MAGY_SCALE] = str(magscalings[1])
        data[self.MAGZ_SCALE] = str(magscalings[2])

        data[self.MAG_TIMESTAMP] = datetime.now().isoformat()

        self.write_calibration_data()
        self.update_data_display(self.calibration_data[self.current_imuid])
        self.calibration_state = self.CAL_NONE
743193
def sample_gradient(x, y)
      d0 = sample_distance x, y - 1
      d1 = sample_distance x - 1, y
      d2 = sample_distance x + 1, y
      d3 = sample_distance x, y + 1

      [(d2 - d1) / @scale, (d3 - d0) / @scale]
    end
921753
def magfit(logfile):
    ''''''

    print("Processing log %s" % filename)

    # open the log file
    mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps)

    data = []
    mag = None
    offsets = Vector3(0,0,0)

    # now gather all the data
    while True:
        # get the next MAVLink message in the log
        m = mlog.recv_match(condition=args.condition)
        if m is None:
            break
        if m.get_type() == "SENSOR_OFFSETS":
            # update offsets that were used during this flight
            offsets = Vector3(m.mag_ofs_x, m.mag_ofs_y, m.mag_ofs_z)
        if m.get_type() == "RAW_IMU" and offsets != None:
            # extract one mag vector, removing the offsets that were
            # used during that flight to get the raw sensor values
            mag = Vector3(m.xmag, m.ymag, m.zmag) - offsets
            data.append(mag)

    print("Extracted %u data points" % len(data))
    print("Current offsets: %s" % offsets)

    # run the fitting algorithm
    ofs = offsets
    ofs = Vector3(0,0,0)
    for r in range(args.repeat):
        ofs = find_offsets(data, ofs)
        print('Loop %u offsets %s' % (r, ofs))
        sys.stdout.flush()
    print("New offsets: %s" % ofs)
283581
def parse_magmoms(self, data, lattice=None):
        
        if lattice is None:
            raise Exception(
                'Magmoms given in terms of crystal axes in magCIF spec.')
        try:
            magmoms = {
                data["_atom_site_moment_label"][i]:
                    np.array(
                        [str2float(data["_atom_site_moment_crystalaxis_x"][i]),
                         str2float(data["_atom_site_moment_crystalaxis_y"][i]),
                         str2float(data["_atom_site_moment_crystalaxis_z"][i])]
                    )
                for i in range(len(data["_atom_site_moment_label"]))
            }
        except (ValueError, KeyError):
            return None
        return magmoms
498999
def recalculate_current_specimen_interpreatations(self):
        
        self.initialize_CART_rot(self.s)
        if str(self.s) in self.pmag_results_data['specimens']:
            for fit in self.pmag_results_data['specimens'][self.s]:
                if fit.get('specimen') and 'calculation_type' in fit.get('specimen'):
                    fit.put(self.s, 'specimen', self.get_PCA_parameters(
                        self.s, fit, fit.tmin, fit.tmax, 'specimen', fit.get('specimen')['calculation_type']))
                if len(self.Data[self.s]['zijdblock_geo']) > 0 and fit.get('geographic') and 'calculation_type' in fit.get('geographic'):
                    fit.put(self.s, 'geographic', self.get_PCA_parameters(
                        self.s, fit, fit.tmin, fit.tmax, 'geographic', fit.get('geographic')['calculation_type']))
                if len(self.Data[self.s]['zijdblock_tilt']) > 0 and fit.get('tilt-corrected') and 'calculation_type' in fit.get('tilt-corrected'):
                    fit.put(self.s, 'tilt-corrected', self.get_PCA_parameters(self.s, fit, fit.tmin,
                                                                              fit.tmax, 'tilt-corrected', fit.get('tilt-corrected')['calculation_type']))
1098594
def offset(self, mjd, new_scale, eop):
        

        delta = 0
        for one, two in self.steps(new_scale):
            one = one.name.lower()
            two = two.name.lower()
            # find the operation
            oper = "_scale_{}_minus_{}".format(two, one)
            # find the reverse operation
            roper = "_scale_{}_minus_{}".format(one, two)
            if hasattr(self, oper):
                delta += getattr(self, oper)(mjd, eop)
            elif hasattr(self, roper):
                delta -= getattr(self, roper)(mjd, eop)
            else:  # pragma: no cover
                raise DateError("Unknown convertion {} => {}".format(one, two))

        return delta
531724
def mag_yaw(RAW_IMU, inclination, declination):
    ''''''
    m = mag_rotation(RAW_IMU, inclination, declination)
    (r, p, y) = m.to_euler()
    y = degrees(y)
    if y < 0:
        y += 360
    return y
1031989
def _compute_sigma_b(self, C, mag, vs30measured):
        
        sigma_0 = self._compute_sigma_0(C, mag, vs30measured)
        sigma_amp = self.CONSTS['sigma_amp']

        return np.sqrt(sigma_0 ** 2 - sigma_amp ** 2)
635361
def par_y1step(i):
    
    """

    global mp_Y1
    grpind = slice(mp_grp[i], mp_grp[i+1])
    XU1 = mp_X[grpind] + 1/mp_alpha*mp_U1[grpind]
    if mp_wl1.shape[mp_axisM] is 1:
        gamma = mp_lmbda/(mp_alpha**2*mp_rho)*mp_wl1
    else:
        gamma = mp_lmbda/(mp_alpha**2*mp_rho)*mp_wl1[grpind]
    Y1 = sp.prox_l1(XU1, gamma)
    if mp_NonNegCoef:
        Y1[Y1 < 0.0] = 0.0
    if mp_NoBndryCross:
        for n in range(len(mp_Nv)):
            Y1[(slice(None),) + (slice(None),)*n +
               (slice(1-mp_Dshp[n], None),)] = 0.0
    mp_Y1[mp_grp[i]:mp_grp[i+1]] = Y1
315021
def get_magsymops(self, data):
        
        magsymmops = []

        # check to see if magCIF file explicitly contains magnetic symmetry operations
        if data.data.get("_space_group_symop_magn_operation.xyz"):

            xyzt = data.data.get("_space_group_symop_magn_operation.xyz")
            if isinstance(xyzt, str):
                xyzt = [xyzt]
            magsymmops = [MagSymmOp.from_xyzt_string(s) for s in xyzt]

            if data.data.get("_space_group_symop_magn_centering.xyz"):

                xyzt = data.data.get("_space_group_symop_magn_centering.xyz")
                if isinstance(xyzt, str):
                    xyzt = [xyzt]
                centering_symops = [MagSymmOp.from_xyzt_string(s) for s in xyzt]

                all_ops = []
                for op in magsymmops:
                    for centering_op in centering_symops:
                        new_translation = [i - np.floor(i) for i
                                           in
                                           op.translation_vector + centering_op.translation_vector]
                        new_time_reversal = op.time_reversal * centering_op.time_reversal
                        all_ops.append(
                            MagSymmOp.from_rotation_and_translation_and_time_reversal(
                                rotation_matrix=op.rotation_matrix,
                                translation_vec=new_translation,
                                time_reversal=new_time_reversal))
                magsymmops = all_ops

        # else check to see if it specifies a magnetic space group
        elif data.data.get("_space_group_magn.name_BNS") or data.data.get(
                "_space_group_magn.number_BNS"):

            if data.data.get("_space_group_magn.name_BNS"):
                # get BNS label for MagneticSpaceGroup()
                id = data.data.get("_space_group_magn.name_BNS")
            else:
                # get BNS number for MagneticSpaceGroup()
                # by converting string to list of ints
                id = list(map(int, (
                data.data.get("_space_group_magn.number_BNS").split("."))))

            msg = MagneticSpaceGroup(id)

            if data.data.get("_space_group_magn.transform_BNS_Pp_abc"):
                if data.data.get(
                        "_space_group_magn.transform_BNS_Pp_abc") != "a,b,c;0,0,0":
                    return NotImplementedError(
                        "Non-standard settings not currently supported.")
            elif data.data.get("_space_group_magn.transform_BNS_Pp"):
                return NotImplementedError(
                    "Incomplete specification to implement.")

            magsymmops = msg.symmetry_ops

        if not magsymmops:
            msg = "No magnetic symmetry detected, using primitive symmetry."
            warnings.warn(msg)
            self.errors.append(msg)
            magsymmops = [MagSymmOp.from_xyzt_string("x, y, z, 1")]

        return magsymmops
1006800
def get_calibration(self, name, shape, chunks=None):
        """"""
        data_items = self.root.findall(".//calibrationVector")
        data, low_res_coords = self.read_xml_array(data_items, name)
        return self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks)
545059
def starmodel_props(self):
        
        props = {}
        mags = self.mags
        mag_errs = self.mag_errs
        for b in mags.keys():
            if np.size(mags[b])==2:
                props[b] = mags[b]
            elif np.size(mags[b])==1:
                mag = mags[b]
                try:
                    e_mag = mag_errs[b]
                except:
                    e_mag = 0.05
                props[b] = (mag, e_mag)

        if self.Teff is not None:
            props['Teff'] = self.Teff
        if self.logg is not None:
            props['logg'] = self.logg
        if self.feh is not None:
            props['feh'] = self.feh

        return props
337641
def stash_calibration(self, attenuations, freqs, frange, calname):
        """"""
        self.calibration_vector = attenuations
        self.calibration_freqs = freqs
        self.calibration_frange = frange
        self.calname = calname
1137344
def cylindrical(cls, mag, theta, z=0):
        ''''''
        return cls(
            mag * math.cos(theta),  # X
            mag * math.sin(theta),  # Y
            z  # Z
        )
830005
def completeness(self, mags, method='step'):
        
        if method == 'step':
            func = lambda x: (x < self.mask_roi_unique[:,np.newaxis]).astype(float)
        elif method == 'erf':
            # Trust the ERD???
            # 95% completeness: 
            def func(x):
                # Efficiency at bright end (assumed to be 100%)
                e = 1.0
                # SDSS EDR says full width is ~0.5 mag
                width = 0.2 
                # This should be the halfway point in the curve
                maglim = self.mask_roi_unique[:,np.newaxis]
                return (e/2.0)*(1/np.sqrt(2*width))*(np.sqrt(2*width)-scipy.special.erf((x-maglim)))
        else:
            raise Exception('...')

        return func(mags)
1207498
def addmags(*mags):
    
    tot = 0
    uncs = []
    for mag in mags:
        try:
            tot += 10**(-0.4*mag)
        except:
            m, dm = mag
            f = 10**(-0.4*m)
            tot += f
            unc = f * (1 - 10**(-0.4*dm))
            uncs.append(unc)

    totmag = -2.5*np.log10(tot)
    if len(uncs) > 0:
        f_unc = np.sqrt(np.array([u**2 for u in uncs]).sum())
        return totmag, -2.5*np.log10(1 - f_unc/tot)
    else:
        return totmag
987080
def get_data():
    

    # pretend we're measuring a noisy resonance at zero
    y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1

    # and that it takes time to do so
    _t.sleep(0.1)

    # return mag phase
    return abs(y), _n.angle(y, True)