Get the beam energy in kev, based on typical biases: 
                itw (or ite bias) - bias15 - platform bias
                
            if get_error: fetch error in value, rather than value
352612
def beam_kev(self,get_error=False):
        
        
        # get epics pointer
        epics = self.epics
        
        # fetch stds
        if get_error:
            attr = 'std'
        else:
            attr = 'mean'
        
        # get inital beam energy in keV
        beam = getattr(epics.target_bias,attr)/1000.
            
        # get RB cell voltage
        bias15 = getattr(epics.bias15,attr)/1000.
        
        # get platform bias 
        if self.area == 'BNMR':
            platform = getattr(epics.nmr_bias,attr)
        elif self.area == 'BNQR':
            platform = getattr(epics.nqr_bias,attr)/1000.
        else:
            raise RuntimeError('Area not recognized')
        
        if get_error:
            return np.sqrt(np.sum(np.square((beam,bias15,platform)))) # keV
        else:
            return beam-bias15-platform
61604
def energy_data():
    
    cur = db.cursor().execute("""SELECT timestamp, current FROM Readings""")
    original = TimeSeries()
    original.initialize_from_sql_cursor(cur)
    original.normalize("day", fusionMethod = "sum")
    return itty.Response(json.dumps(original, cls=PycastEncoder), content_type='application/json')
1311368
def loadFromDisk(self, calculation):
        

        suffixes = {
            'Isotropic': 'iso',
            'Circular Dichroism (R-L)': 'cd',
            'Right Polarized (R)': 'r',
            'Left Polarized (L)': 'l',
            'Linear Dichroism (V-H)': 'ld',
            'Vertical Polarized (V)': 'v',
            'Horizontal Polarized (H)': 'h',
        }

        self.raw = list()
        for spectrumName in self.toPlot:
            suffix = suffixes[spectrumName]
            path = '{}_{}.spec'.format(calculation.baseName, suffix)

            try:
                data = np.loadtxt(path, skiprows=5)
            except (OSError, IOError) as e:
                raise e

            rows, columns = data.shape

            if calculation.experiment in ['XAS', 'XPS', 'XES']:

                xMin = calculation.xMin
                xMax = calculation.xMax
                xNPoints = calculation.xNPoints

                if calculation.experiment == 'XES':
                    x = np.linspace(xMin, xMax, xNPoints + 1)
                    x = x[::-1]
                    y = data[:, 2]
                    y = y / np.abs(y.max())
                else:
                    x = np.linspace(xMin, xMax, xNPoints + 1)
                    y = data[:, 2::2].flatten()

                spectrum = Spectrum1D(x, y)
                spectrum.name = spectrumName
                if len(suffix) > 2:
                    spectrum.shortName = suffix.title()
                else:
                    spectrum.shortName = suffix.upper()

                if calculation.experiment in ['XAS', ]:
                    spectrum.xLabel = 'Absorption Energy (eV)'
                elif calculation.experiment in ['XPS', ]:
                    spectrum.xLabel = 'Binding Energy (eV)'
                elif calculation.experiment in ['XES', ]:
                    spectrum.xLabel = 'Emission Energy (eV)'
                spectrum.yLabel = 'Intensity (a.u.)'

                self.broadenings = {'gaussian': (calculation.xGaussian, ), }
            else:
                xMin = calculation.xMin
                xMax = calculation.xMax
                xNPoints = calculation.xNPoints

                yMin = calculation.yMin
                yMax = calculation.yMax
                yNPoints = calculation.yNPoints

                x = np.linspace(xMin, xMax, xNPoints + 1)
                y = np.linspace(yMin, yMax, yNPoints + 1)
                z = data[:, 2::2]

                spectrum = Spectrum2D(x, y, z)
                spectrum.name = spectrumName
                if len(suffix) > 2:
                    spectrum.shortName = suffix.title()
                else:
                    spectrum.shortName = suffix.upper()

                spectrum.xLabel = 'Incident Energy (eV)'
                spectrum.yLabel = 'Energy Transfer (eV)'

                self.broadenings = {'gaussian': (calculation.xGaussian,
                                                 calculation.yGaussian), }

            self.raw.append(spectrum)

        # Process the spectra once they where read from disk.
        self.process()
1190207
def format_energy_results(energy):
    """"""
    if not energy:
        return {}
    result = {}
    cpuenergy = Decimal(0)
    for pkg, domains in energy.items():
        for domain, value in domains.items():
            if domain == DOMAIN_PACKAGE:
                cpuenergy += value
                result['cpuenergy-pkg{}'.format(pkg)] = value
            else:
                result['cpuenergy-pkg{}-{}'.format(pkg, domain)] = value
    result['cpuenergy'] = cpuenergy
    result = collections.OrderedDict(sorted(result.items()))
    return result
94063
def get_energy(self):
        
        value = self.box.homeautoswitch("getswitchenergy", self.actor_id)
        return int(value) if value.isdigit() else None
1306945
def nrows_expected(self):
        
        return np.prod([i.cvalues.shape[0] for i in self.index_axes])
1288312
def kl_error(self, input_data, targets, average=True,
                 cache=None, prediction=True):
        

        if cache is not None:
            activations = cache
        else:
            activations = \
              self.feed_forward(input_data, prediction=prediction)

        targets_non_nan = gpuarray.empty_like(targets)
        nan_to_zeros(targets, targets_non_nan)
        kl_error = gpuarray.sum(targets_non_nan *
                                (cumath.log(targets_non_nan + eps) -
                                 cumath.log(activations + eps)))
        if average:
            kl_error /= targets.shape[0]
        return kl_error.get()
150682
def explain(self, entry):
        
        d = self.get_explanation_dict(entry)
        print("The uncorrected value of the energy of %s is %f eV" %
              (entry.composition, d["uncorrected_energy"]))
        print("The following corrections / screening are applied for %s:\n" %
              d["compatibility"])
        for c in d["corrections"]:
            print("%s correction: %s\n" % (c["name"],
                                           c["description"]))
            print("For the entry, this correction has the value %f eV." % c[
                "value"])
            print("-" * 30)

        print("The final energy after corrections is %f" % d[
            "corrected_energy"])
372151
def _tl15(self, data, wavenumber):
        """"""

        return ((C2 * wavenumber) /
                xu.log((1.0 / data) * C1 * wavenumber ** 3 + 1.0))
732797
def get_interpolated_value(self, energy):
        
        f = {}
        for spin in self.densities.keys():
            f[spin] = get_linear_interpolated_value(self.energies,
                                                    self.densities[spin],
                                                    energy)
        return f
889501
def getskyimg(self,chip):
        
        sci_chip = self._image[self.scienceExt,chip]
        skyimg = np.ones(sci_chip.image_shape,dtype=sci_chip.image_dtype)*sci_chip.subtractedSky
        if sci_chip._conversionFactor != 1.0: # If units are not already ELECTRONS
            skyimg *= self.getexptimeimg(chip)
        return skyimg
970075
def twotheta(self) -> ErrorValue:
        """"""
        row, column = np.ogrid[0:self.shape[0], 0:self.shape[1]]
        rho = (((self.header.beamcentery - row) * self.header.pixelsizey) ** 2 +
               ((self.header.beamcenterx - column) * self.header.pixelsizex) ** 2) ** 0.5
        assert isinstance(self.header.pixelsizex, ErrorValue)
        assert isinstance(self.header.pixelsizey, ErrorValue)
        assert isinstance(rho, ErrorValue)
        return (rho / self.header.distance).arctan()
347876
def get_beam(secret_uuid):
    
    beam_dir = get_beam_cache_directory()
    beam_filename = os.path.join(beam_dir, secret_uuid)
    if os.path.isfile(beam_filename):
        with open(beam_filename, 'rb') as handle:
            beam = pickle.load(handle)
        return beam
    else:
        return None
283798
def getExpectedValue(distribution):
  
  k = np.array(distribution.possibleValues)
  return np.sum(k * distribution.pmf(k))
680720
def _iter_vals(key):
    
    for i in range(winreg.QueryInfoKey(key)[1]):
        yield winreg.EnumValue(key, i)
29677
def energy_value(h: List[Union[int, float]],
                 J: Dict[Tuple[int, int], Union[int, float]],
                 sol: List[int]) -> Union[int, float]:
    
    ener_ising = 0
    for elm in J.keys():
        if elm[0] == elm[1]:
            raise TypeError("""Interaction term must connect two different variables""")
        else:
            ener_ising += J[elm] * int(sol[elm[0]]) * int(sol[elm[1]])
    for i in range(len(h)):
        ener_ising += h[i] * int(sol[i])
    return ener_ising
1231179
def _energy_evaluation(self, operator):
        
        if self._quantum_state is not None:
            input_circuit = self._quantum_state
        else:
            input_circuit = [self.opt_circuit]
        if operator._paulis:
            mean_energy, std_energy = operator.evaluate_with_result(self._operator_mode, input_circuit,
                                                                    self._quantum_instance.backend, self.ret)
        else:
            mean_energy = 0.0
            std_energy = 0.0
        operator.disable_summarize_circuits()
        logger.debug('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean_energy)))
        return np.real(mean_energy), np.real(std_energy)