Create spectral parameters from 3FGL catalog columns.
429986
def spectral_pars_from_catalog(cat):
    """"""

    spectrum_type = cat['SpectrumType']
    pars = get_function_defaults(cat['SpectrumType'])
    par_idxs = {k: i for i, k in
                enumerate(get_function_par_names(cat['SpectrumType']))}

    for k in pars:
        pars[k]['value'] = cat['param_values'][par_idxs[k]]

    if spectrum_type == 'PowerLaw':

        pars['Index']['value'] *= -1.0
        pars['Index']['scale'] = -1.0
        pars['Scale']['scale'] = 1.0
        pars['Index']['max'] = max(5.0, pars['Index']['value'] + 1.0)
        pars['Index']['min'] = min(0.0, pars['Index']['value'] - 1.0)
        pars['Prefactor'] = make_parameter_dict(pars['Prefactor'])
        pars['Scale'] = make_parameter_dict(pars['Scale'], True, False)
        pars['Index'] = make_parameter_dict(pars['Index'], False, False)

    elif spectrum_type == 'LogParabola':

        pars['norm'] = make_parameter_dict(pars['norm'], False, True)
        pars['Eb'] = make_parameter_dict(pars['Eb'], True, False)
        pars['alpha'] = make_parameter_dict(pars['alpha'], False, False)
        pars['beta'] = make_parameter_dict(pars['beta'], False, False)

    elif spectrum_type == 'PLSuperExpCutoff':

        pars['Index1']['value'] *= -1.0
        pars['Index1']['scale'] = -1.0
        pars['Index2']['scale'] = 1.0
        pars['Prefactor'] = make_parameter_dict(pars['Prefactor'])
        pars['Scale'] = make_parameter_dict(pars['Scale'], True, False)
        pars['Index1'] = make_parameter_dict(pars['Index1'], False, False)
        pars['Index2'] = make_parameter_dict(pars['Index2'], False, False)
        pars['Cutoff'] = make_parameter_dict(pars['Cutoff'], False, True)

    elif spectrum_type == 'PLSuperExpCutoff2':

        pars['Index1']['value'] *= -1.0
        pars['Index1']['scale'] = -1.0
        pars['Index2']['scale'] = 1.0
        pars['Prefactor'] = make_parameter_dict(pars['Prefactor'])
        pars['Scale'] = make_parameter_dict(pars['Scale'], True, False)
        pars['Index1'] = make_parameter_dict(pars['Index1'], False, False)
        pars['Index2'] = make_parameter_dict(pars['Index2'], False, False)
        pars['Expfactor'] = make_parameter_dict(pars['Expfactor'], False, True)
    else:
        raise Exception('Unsupported spectral type:' + spectrum_type)

    return pars
856248
function createGLResources(gl, glConfig) {
  const resources = {
    gl,
    buffers: {},
    textures: {},
    framebuffers: {},
    programs: {},
  };
  const buffers = glConfig.resources.buffers || [];
  const textures = glConfig.resources.textures || [];
  const framebuffers = glConfig.resources.framebuffers || [];

  // Create Buffer
  buffers.forEach((buffer) => {
    const glBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW);
    resources.buffers[buffer.id] = glBuffer;
  });

  // Create Texture
  textures.forEach((texture) => {
    const glTexture = gl.createTexture();
    const pixelStore = texture.pixelStore || [];
    const texParameter = texture.texParameter || [];

    gl.bindTexture(gl.TEXTURE_2D, glTexture);

    pixelStore.forEach((option) => {
      gl.pixelStorei(gl[option[0]], option[1]);
    });

    texParameter.forEach((option) => {
      gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]);
    });

    resources.textures[texture.id] = glTexture;
  });

  // Create Framebuffer
  framebuffers.forEach((framebuffer) => {
    const glFramebuffer = gl.createFramebuffer();
    glFramebuffer.width = framebuffer.width;
    glFramebuffer.height = framebuffer.height;

    resources.framebuffers[framebuffer.id] = glFramebuffer;
  });

  // Create programs
  Object.keys(glConfig.programs).forEach((programName) => {
    buildShaderProgram(gl, programName, glConfig, resources);
  });

  // Add destroy function
  resources.destroy = () => {
    freeGLResources(resources);
  };

  return resources;
}
256933
def get_columns (fp):
    """"""
    if not is_tty(fp):
        return 80
    if os.name == 'nt':
        return colorama.get_console_size().X
    if has_curses:
        import curses
        try:
            curses.setupterm(os.environ.get("TERM"), fp.fileno())
            return curses.tigetnum("cols")
        except curses.error:
           pass
    return 80
1363918
def _multitaper_spectrum(self, clm, k, convention='power', unit='per_l',
                             clat=None, clon=None, coord_degrees=True,
                             lmax=None, taper_wt=None):
        
        if lmax is None:
            lmax = clm.lmax

        if (clat is not None and clon is not None and clat == self.clat and
                clon == self.clon and coord_degrees is self.coord_degrees and
                k <= self.nwinrot):
            # use the already stored coeffs
            pass
        elif (clat is None and clon is None) and \
                (self.clat is not None and self.clon is not None and
                 k <= self.nwinrot):
            # use the already stored coeffs
            pass
        else:
            if clat is None:
                clat = self.clat
            if clon is None:
                clon = self.clon
            if (clat is None and clon is not None) or \
                    (clat is not None and clon is None):
                raise ValueError('clat and clon must both be input. ' +
                                 'clat = {:s}, clon = {:s}'
                                 .format(repr(clat), repr(clon)))
            if clat is None and clon is None:
                self.rotate(clat=90., clon=0., coord_degrees=True, nwinrot=k)
            else:
                self.rotate(clat=clat, clon=clon, coord_degrees=coord_degrees,
                            nwinrot=k)

        sh = clm.to_array(normalization='4pi', csphase=1, lmax=lmax)

        if taper_wt is None:
            mtse, sd = _shtools.SHMultiTaperMaskSE(sh, self.coeffs,
                                                   lmax=lmax, k=k)
        else:
            mtse, sd = _shtools.SHMultiTaperMaskSE(sh, self.coeffs, lmax=lmax,
                                                   k=k, taper_wt=taper_wt)

        if (unit == 'per_l'):
            pass
        elif (unit == 'per_lm'):
            degree_l = _np.arange(len(mtse))
            mtse /= (2.0 * degree_l + 1.0)
            sd /= (2.0 * degree_l + 1.0)
        else:
            raise ValueError(
                "unit must be 'per_l' or 'per_lm'." +
                "Input value was {:s}".format(repr(unit)))

        if (convention == 'power'):
            return mtse, sd
        elif (convention == 'energy'):
            return mtse * 4.0 * _np.pi, sd * 4.0 * _np.pi
        else:
            raise ValueError(
                "convention must be 'power' or 'energy'." +
                "Input value was {:s}".format(repr(convention)))
404191
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs):
    
    # If the user provides an illuminant_override numpy array, use it.
    if illuminant_override:
        reference_illum = illuminant_override
    else:
        # Otherwise, look up the illuminant from known standards based
        # on the value of 'illuminant' pulled from the SpectralColor object.
        try:
            reference_illum = spectral_constants.REF_ILLUM_TABLE[cobj.illuminant]
        except KeyError:
            raise InvalidIlluminantError(cobj.illuminant)

    # Get the spectral distribution of the selected standard observer.
    if cobj.observer == '10':
        std_obs_x = spectral_constants.STDOBSERV_X10
        std_obs_y = spectral_constants.STDOBSERV_Y10
        std_obs_z = spectral_constants.STDOBSERV_Z10
    else:
        # Assume 2 degree, since it is theoretically the only other possibility.
        std_obs_x = spectral_constants.STDOBSERV_X2
        std_obs_y = spectral_constants.STDOBSERV_Y2
        std_obs_z = spectral_constants.STDOBSERV_Z2

    # This is a NumPy array containing the spectral distribution of the color.
    sample = cobj.get_numpy_array()

    # The denominator is constant throughout the entire calculation for X,
    # Y, and Z coordinates. Calculate it once and re-use.
    denom = std_obs_y * reference_illum

    # This is also a common element in the calculation whereby the sample
    # NumPy array is multiplied by the reference illuminant's power distribution
    # (which is also a NumPy array).
    sample_by_ref_illum = sample * reference_illum

    # Calculate the numerator of the equation to find X.
    x_numerator = sample_by_ref_illum * std_obs_x
    y_numerator = sample_by_ref_illum * std_obs_y
    z_numerator = sample_by_ref_illum * std_obs_z

    xyz_x = x_numerator.sum() / denom.sum()
    xyz_y = y_numerator.sum() / denom.sum()
    xyz_z = z_numerator.sum() / denom.sum()

    return XYZColor(
        xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
766462
def _create_filefunction(self, name, spectrum_pars):
        """"""

        spectrum_pars = {} if spectrum_pars is None else spectrum_pars

        if 'loge' in spectrum_pars:
            loge = spectrum_pars.get('loge')
        else:
            ebinsz = (self.log_energies[-1] -
                      self.log_energies[0]) / self.enumbins
            loge = utils.extend_array(self.log_energies, ebinsz, 0.5, 6.5)

        # Get the values
        dnde = np.zeros(len(loge))
        if 'dnde' in spectrum_pars:
            dnde = spectrum_pars.get('dnde')
        else:
            dnde = np.array([self.like[name].spectrum()(pyLike.dArg(10 ** egy))
                             for egy in loge])

        filename = \
            os.path.join(self.workdir,
                         '%s_filespectrum.txt' % (name.lower().replace(' ', '_')))

        # Create file spectrum txt file
        np.savetxt(filename, np.vstack((10**loge, dnde)).T)
        self.like.setSpectrum(name, str('FileFunction'))

        self.roi[name]['Spectrum_Filename'] = filename
        # Update
        for c in self.components:
            src = c.like.logLike.getSource(str(name))
            spectrum = src.spectrum()

            spectrum.getParam(str('Normalization')).setBounds(1E-3, 1E3)

            file_function = pyLike.FileFunction_cast(spectrum)
            file_function.readFunction(str(filename))
            c.roi[name]['Spectrum_Filename'] = filename
99075
def create_model_name(src):
    
    o = ''
    spatial_type = src['SpatialModel'].lower()
    o += spatial_type

    if spatial_type == 'gaussian':
        o += '_s%04.2f' % src['SpatialWidth']

    if src['SpectrumType'] == 'PowerLaw':
        o += '_powerlaw_%04.2f' % float(src.spectral_pars['Index']['value'])
    else:
        o += '_%s' % (src['SpectrumType'].lower())

    return o
646293
def loadings(self):
        """"""
        loadings = self.v[:, : self.keep] * np.sqrt(self.eigenvalues)
        cols = ["PC%s" % i for i in range(1, self.keep + 1)]
        loadings = pd.DataFrame(
            loadings, columns=cols, index=self.feature_names
        )
        return loadings
410863
def glsfit(psr,renormalize=True):
    """"""
    
    mask = psr.deleted == 0
    res, err = psr.residuals(removemean=False)[mask], psr.toaerrs[mask]
    M = psr.designmatrix(updatebats=False,fixunits=True,fixsigns=True)[mask,:]
        
    C = numpy.diag((err * 1e-6)**2)
    
    if renormalize:
        norm = numpy.sqrt(numpy.sum(M**2,axis=0))
        M /= norm
    else:
        norm = np.ones_like(M[0,:])
    
    mtcm = numpy.dot(M.T,numpy.dot(numpy.linalg.inv(C),M))
    mtcy = numpy.dot(M.T,numpy.dot(numpy.linalg.inv(C),res))
    
    xvar = numpy.linalg.inv(mtcm)
        
    c = scipy.linalg.cho_factor(mtcm)
    xhat = scipy.linalg.cho_solve(c,mtcy)

    sol = psr.vals()
    psr.vals(sol + xhat[1:] / norm[1:])
    psr.errs(numpy.sqrt(numpy.diag(xvar)[1:]) / norm[1:])
    
    return chisq(psr)
220760
def get_psms(self):
        """"""
        self.header = actions.create_header(self.oldheader, self.spectracol)
        self.psms = actions.generate_psms_spectradata(self.lookup, self.fn,
                                                      self.oldheader)
36256
def get_spectral_index(src, egy):
    """"""
    delta = 1E-5
    f0 = src.spectrum()(pyLike.dArg(egy * (1 - delta)))
    f1 = src.spectrum()(pyLike.dArg(egy * (1 + delta)))

    if f0 > 0 and f1 > 0:
        gamma = np.log10(f0 / f1) / np.log10((1 - delta) / (1 + delta))
    else:
        gamma = np.nan

    return gamma
462962
def map_columns(col):
    
    if col.startswith('7'):
        # spectral data
        try:
            return VARIABLE_MAP[col]
        except KeyError:
            return col
    try:
        variable_name = VARIABLE_MAP[col[:3]]
        variable_number = col[3:]
        return variable_name + '_' + variable_number
    except KeyError:
        return col
387780
def make_from_catalogue(cls, catalogue, spacing, dilate):
        '''
        
        '''
        new = cls()
        cat_bbox = get_catalogue_bounding_polygon(catalogue)

        if dilate > 0:
            cat_bbox = cat_bbox.dilate(dilate)

        # Define Grid spacing
        new.update({'xmin': np.min(cat_bbox.lons),
                    'xmax': np.max(cat_bbox.lons),
                    'xspc': spacing,
                    'ymin': np.min(cat_bbox.lats),
                    'ymax': np.max(cat_bbox.lats),
                    'yspc': spacing,
                    'zmin': 0.,
                    'zmax': np.max(catalogue.data['depth']),
                    'zspc': np.max(catalogue.data['depth'])})

        if new['zmin'] == new['zmax'] == new['zspc'] == 0:
            new['zmax'] = new['zspc'] = 1

        return new
671744
def T(u, dfs_data):
    """"""
    return list(set([w for v in S_star(u, dfs_data) for w in A(v, dfs_data)]))
1019929
def get_bgcolor(self, index):
        """"""
        if index.column() == 0:
            color = QColor(Qt.lightGray)
            color.setAlphaF(.05)
        elif index.column() < 3:
            color = QColor(Qt.lightGray)
            color.setAlphaF(.2)
        else:
            color = QColor(Qt.lightGray)
            color.setAlphaF(.3)
        return color
1310686
def process(self, frames, eod, spec_range=120.0):
        

        samples = frames[:, 0]
        nsamples = len(frames[:, 0])
        if nsamples != self.blocksize:
            self.window = self.window_function(nsamples)
        samples *= self.window

        while nsamples > self.fft_size:
            self.fft_size = 2 * self.fft_size

        zeros_p = numpy.zeros(self.fft_size / 2 - int(nsamples / 2))
        if nsamples % 2:
            zeros_n = numpy.zeros(self.fft_size / 2 - int(nsamples / 2) - 1)
        else:
            zeros_n = numpy.zeros(self.fft_size / 2 - int(nsamples / 2))
        samples = numpy.concatenate((zeros_p, samples, zeros_n), axis=0)

        fft = numpy.fft.fft(samples)
        # normalized abs(FFT) between 0 and 1
        spectrum = numpy.abs(fft[:fft.shape[0] / 2 + 1]) / float(nsamples)
        length = numpy.float64(spectrum.shape[0])

        # scale the db spectrum from [- spec_range db ... 0 db] > [0..1]
        db_spectrum = ((20 * (numpy.log10(spectrum + 1e-30)))
                       .clip(-spec_range, 0.0) + spec_range) / spec_range
        energy = spectrum.sum()
        spectral_centroid = 0

        if energy > 1e-20:
            # calculate the spectral centroid
            if self.spectrum_range is None:
                self.spectrum_range = numpy.arange(length)
            spectral_centroid = (spectrum * self.spectrum_range).sum() / \
                (energy * (length - 1)) * \
                self.samplerate * 0.5
            # clip > log10 > scale between 0 and 1
            spectral_centroid = (math.log10(self.clip(spectral_centroid,
                                                      self.lower,
                                                      self.higher)) -
                                 self.lower_log) / (self.higher_log -
                                                    self.lower_log)

        return (spectral_centroid, db_spectrum)
121048
def prepare_values(self, raw, offset=0):
        """"""
        from pygal.graph.map import BaseMap
        from pygal import Histogram

        if self.zero == 0 and isinstance(self, BaseMap):
            self.zero = 1

        if self.x_label_rotation:
            self.x_label_rotation %= 360

        if self.y_label_rotation:
            self.y_label_rotation %= 360

        for key in ('x_labels', 'y_labels'):
            if getattr(self, key):
                setattr(self, key, list(getattr(self, key)))
        if not raw:
            return

        adapters = list(self._adapters) or [lambda x: x]
        if self.logarithmic:
            for fun in not_zero, positive:
                if fun in adapters:
                    adapters.remove(fun)
            adapters = adapters + [positive, not_zero]
        adapters = adapters + [decimal_to_float]

        self._adapt = reduce(compose, adapters) if not self.strict else ident
        self._x_adapt = reduce(
            compose, self._x_adapters
        ) if not self.strict and getattr(self, '_x_adapters', None) else ident

        series = []

        raw = [(
            list(raw_values) if not isinstance(raw_values, dict) else
            raw_values, serie_config_kwargs
        ) for raw_values, serie_config_kwargs in raw]

        width = max([len(values)
                     for values, _ in raw] + [len(self.x_labels or [])])

        for raw_values, serie_config_kwargs in raw:
            metadata = {}
            values = []
            if isinstance(raw_values, dict):
                if isinstance(self, BaseMap):
                    raw_values = list(raw_values.items())
                else:
                    value_list = [None] * width
                    for k, v in raw_values.items():
                        if k in (self.x_labels or []):
                            value_list[self.x_labels.index(k)] = v
                    raw_values = value_list

            for index, raw_value in enumerate(raw_values + (
                (width - len(raw_values)) * [None]  # aligning values
                    if len(raw_values) < width else [])):
                if isinstance(raw_value, dict):
                    raw_value = dict(raw_value)
                    value = raw_value.pop('value', None)
                    metadata[index] = raw_value
                else:
                    value = raw_value

                # Fix this by doing this in charts class methods
                if isinstance(self, Histogram):
                    if value is None:
                        value = (None, None, None)
                    elif not is_list_like(value):
                        value = (value, self.zero, self.zero)
                    elif len(value) == 2:
                        value = (1, value[0], value[1])
                    value = list(map(self._adapt, value))
                elif self._dual:
                    if value is None:
                        value = (None, None)
                    elif not is_list_like(value):
                        value = (value, self.zero)
                    if self._x_adapt:
                        value = (
                            self._x_adapt(value[0]), self._adapt(value[1])
                        )
                    if isinstance(self, BaseMap):
                        value = (self._adapt(value[0]), value[1])
                    else:
                        value = list(map(self._adapt, value))
                else:
                    value = self._adapt(value)

                values.append(value)
            serie_config = SerieConfig()
            serie_config(
                **dict((k, v) for k, v in self.state.__dict__.items()
                       if k in dir(serie_config))
            )
            serie_config(**serie_config_kwargs)
            series.append(
                Serie(offset + len(series), values, serie_config, metadata)
            )
        return series