Add an entry into the models table for a source based on L-band and
    C-band flux densities.
768717
def add_from_vla_obs (src, Lband, Cband):
    
    if src in models:
        raise PKError ('already have a model for ' + src)

    fL = np.log10 (1425)
    fC = np.log10 (4860)

    lL = np.log10 (Lband)
    lC = np.log10 (Cband)

    A = (lL - lC) / (fL - fC)
    B = lL - A * fL

    def fluxdens (freq_mhz):
        return 10. ** (A * np.log10 (freq_mhz) + B)

    def spindex (freq_mhz):
        return A

    models[src] = fluxdens
    spindexes[src] = spindex
1074687
def add(self, model):
        """"""
        def foo(m, p, i):
            if m[i][0].name == model.name:
                raise ValueError("Model already exists")
            return
        # checks if already existing
        self.foreach(foo)
        
        self.append((model,))
        return
1195356
def import_model(self, source):
        """"""
        source = self._resolve_source(source)
        self._context = FilePathContext(source)
        with self._context.open() as f:
            self._reader = self._open_reader(f)

        return self._reader.create_model()
1358383
def add_columns(self, model, **fields):
        """"""
        for name, field in fields.items():
            model._meta.add_field(name, field)
            self.ops.append(self.migrator.add_column(
                model._meta.table_name, field.column_name, field))
            if field.unique:
                self.ops.append(self.migrator.add_index(
                    model._meta.table_name, (field.column_name,), unique=True))
        return model
52647
def addSPI(fitsname_alpha=None, fitsname_alpha_error=None, lsmname=None,
           outfile=None,freq0=None, beam=None, spitol=(-10,10)):
    
#    import pylab as plt
    if beam is None:
        raise RuntimeError("the beam option must be specified")

    print "INFO: Getting fits info from: %s, %s" %(fitsname_alpha, fitsname_alpha_error)

    fits_alpha = fitsInfo(fitsname_alpha)    # Get fits info
    image_alpha = fits_alpha['image']     # get image data

    if fitsname_alpha_error:
        fits_alpha_error = fitsInfo(fitsname_alpha_error)
        image_alpha_error = fits_alpha_error['image']
    else:
        fits_alpha_error = fitsInfo(fitsname_alpha)
        image_alpha_error = fits_alpha_error['image']
        image_alpha_error[...] = 1.0

    # may supply FITS file for freq0, in which case just pull ref frequency from FITS file,
    # else explicit frequency, else get frequency from alpha image
    if type(freq0) is str:
        freq0 = fitsInfo(freq0)['freq0']
    else:
        freq0 = freq0 or fits_alpha['freq0']

    model = Tigger.load(lsmname)    # load output sky model
    rad = lambda a: a*(180/np.pi) # convert radians to degrees

    for src in model.sources:
        ra = rad(src.pos.ra)
        dec = rad(src.pos.dec)

        # Cater for point sources and assume source extent equal to the
        # Gaussian major axis along both ra and dec axis
        dra = rad(src.shape.ex) if src.shape  else beam[0]
        ddec = rad(src.shape.ey) if src.shape  else beam[1]
        pa = rad(src.shape.pa) if src.shape  else beam[2]

        emin, emaj = sorted([dra, ddec])
        # Determine region of interest
        rgn = sky2px(fits_alpha["wcs"],ra,dec,dra,ddec,fits_alpha["dra"], beam[1])
        imslice = slice(rgn[2], rgn[3]), slice(rgn[0], rgn[3])
        alpha = image_alpha[imslice]
        xpix, ypix = alpha.shape
        xx, yy = np.ogrid[-xpix:xpix, -ypix:ypix]

        emajPix = emaj/fits_alpha["dra"]
        eminPix = emin/fits_alpha["dra"]
        # Create elliptcal mask which has same shape as source
        mask = ((xx/emajPix)**2 + (yy/eminPix)**2 <= 1)[xpix*2-xpix:xpix*2+xpix, ypix*2-ypix:ypix*2+ypix]
        mask = ndimage.rotate(mask, angle=pa, order=0, reshape=False)
        
        draPix = dra/fits_alpha["dra"]
        ddPix = ddec/fits_alpha["ddec"]

        alpha *= mask
        alpha_error = image_alpha_error[imslice]*mask
        good = np.where( np.logical_and(alpha!=0, alpha!=np.nan))
        alpha = alpha[good]
        alpha_error = alpha_error[good]
        good = np.where( np.logical_and(alpha_error!=np.nan, alpha_error!=np.inf))

        alpha = alpha[good]
        alpha_error = alpha_error[good]

        subIm_weight = 1/alpha_error
        subIm_weighted = alpha*subIm_weight

        if len(subIm_weighted)>0:
            subIm_normalization = np.sum(subIm_weight)
            spi = float(np.sum(subIm_weighted)/subIm_normalization)
            spi_error = 1/float(subIm_normalization)
            if spi > spitol[0] or spi < spitol[-1]:
                sys.stdout.write("INFO: Adding spi: %.3f (at %.3g MHz) to source %s" % (
                                 spi, freq0/1e6, src.name))
                src.spectrum = Tigger.Models.ModelClasses.SpectralIndex(spi, freq0)
                src.setAttribute('spi_error', spi_error)
        else:
            sys.stdout.write("ALERT: no spi info found in %s for source %s" % (
                             fitsname_alpha, src.name))

    model.save(outfile)
823299
def _build_model(self):
        

        if "input_dim" not in self.settings:
            raise ValueError("Model parameter input_dim cannot be None.")

        self.sparse_linear = SparseLinear(
            self.settings["input_dim"], self.cardinality, self.settings["bias"]
        )
809297
def AddBookkeepingOperators(model):
    
    # Print basically prints out the content of the blob. to_file=1 routes the
    # printed output to a file. The file is going to be stored under
    #     root_folder/[blob name]
    model.Print('accuracy', [], to_file=1)
    model.Print('loss', [], to_file=1)
    # Summarizes the parameters. Different from Print, Summarize gives some
    # statistics of the parameter, such as mean, std, min and max.
    for param in model.params:
        model.Summarize(param, [], to_file=1)
        model.Summarize(model.param_to_grad[param], [], to_file=1)
600133
def model_mag(self, pardict, use_cache=True):
        
        if pardict == self._cache_key and use_cache:
            #print('{}: using cached'.format(self))
            return self._cache_val

        #print('{}: calculating'.format(self))
        self._cache_key = pardict


        # Generate appropriate parameter vector from dictionary
        p = []
        for l in self.leaf_labels:
            p.extend(pardict[l])

        assert len(p) == self.n_params

        tot = np.inf
        #print('Building {} mag for {}:'.format(self.band, self))
        for i,m in enumerate(self.leaves):
            mag = m.evaluate(p[i*5:(i+1)*5], self.band)
            # logging.debug('{}: mag={}'.format(self,mag))
            #print('{}: {}({}) = {}'.format(m,self.band,p[i*5:(i+1)*5],mag))
            tot = addmags(tot, mag)

        self._cache_val = tot
        return tot
569499
def get_model(self, sm_id):
        
        sm = self.source_models[sm_id]
        if self.source_model_lt.num_samples:
            self.source_model_lt.num_samples = sm.samples
        new = self.__class__(self.gsim_lt, self.source_model_lt, [sm],
                             self.optimize_same_id)
        new.sm_id = sm_id
        return new
1218651
private static void addSetOpenEngSBModelTail(CtClass clazz) throws CannotCompileException, NotFoundException {
        CtClass[] params = generateClassField(List.class);
        CtMethod method = new CtMethod(CtClass.voidType, "setOpenEngSBModelTail", params, clazz);
        StringBuilder builder = new StringBuilder();
        builder.append(createTrace("Called setOpenEngSBModelTail"))
            .append("if($1 != null) {for(int i = 0; i < $1.size(); i++) {")
            .append("OpenEngSBModelEntry entry = (OpenEngSBModelEntry) $1.get(i);")
            .append(String.format("%s.put(entry.getKey(), entry); } }", TAIL_FIELD));
        method.setBody(createMethodBody(builder.toString()));
        clazz.addMethod(method);
    }
1288689
def add_model(refwcs, newcoeffs):
    
    # Update refwcs with distortion model
    for kw in model_attrs:
        if newcoeffs.__dict__[key] is not None:
            refwcs.__dict__[key] = newcoeffs.__dict__[key]
448697
def addRnaQuantificationSet(self):
        
        self._openRepo()
        dataset = self._repo.getDatasetByName(self._args.datasetName)
        if self._args.name is None:
            name = getNameFromPath(self._args.filePath)
        else:
            name = self._args.name
        rnaQuantificationSet = rna_quantification.SqliteRnaQuantificationSet(
            dataset, name)
        referenceSetName = self._args.referenceSetName
        if referenceSetName is None:
            raise exceptions.RepoManagerException(
                "A reference set name must be provided")
        referenceSet = self._repo.getReferenceSetByName(referenceSetName)
        rnaQuantificationSet.setReferenceSet(referenceSet)
        rnaQuantificationSet.populateFromFile(self._args.filePath)
        rnaQuantificationSet.setAttributes(json.loads(self._args.attributes))
        self._updateRepo(
            self._repo.insertRnaQuantificationSet, rnaQuantificationSet)
689464
def gen_source_models(self, gsim_lt):
        
        num_gsim_paths = 1 if self.num_samples else gsim_lt.get_num_paths()
        for i, rlz in enumerate(self):
            yield LtSourceModel(
                rlz.value, rlz.weight, ('b1',), [], num_gsim_paths, i, 1)
1333495
def add_population(self,pop):
        
        if pop.model in self.modelnames:
            raise ValueError('%s model already in PopulationSet.' % pop.model)
        self.modelnames.append(pop.model)
        self.shortmodelnames.append(pop.modelshort)
        self.poplist.append(pop)
841486
private void addModels(final Key<Model>[] newModels) {
    int before = leaderboard().getModelCount();
    leaderboard().addModels(newModels);
    int after = leaderboard().getModelCount();
    modelCount.addAndGet(after - before);
  }
182598
void addDistribution(Stream.Builder<WavefrontMetricLineData> metrics, Meter.Id id,
                         List<WavefrontHistogramImpl.Distribution> distributions) {
        String name = getConventionName(id);
        String source = config.source();
        Map<String, String> tags = getTagsAsMap(id);

        for (WavefrontHistogramImpl.Distribution distribution : distributions) {
            try {
                String lineData = Utils.histogramToLineData(name, distribution.centroids,
                    histogramGranularities, distribution.timestamp, source, tags, "unknown");
                metrics.add(new WavefrontMetricLineData(lineData, true));
            } catch (IllegalArgumentException e) {
                logger.error("failed to convert distribution to Wavefront format: " + id.getName(), e);
            }
        }
    }
361958
def set_fluxinfo(self):
        

        knowncals = ['3C286', '3C48', '3C147', '3C138']

        # find scans with knowncals in the name
        sourcenames = [self.sources[source]['source'] for source in self.sources]
        calsources = [cal for src in sourcenames for cal in knowncals if cal in src]
        calsources_full = [src for src in sourcenames for cal in knowncals if cal in src]
        if len(calsources):
            # if cal found, set band name from first spw
            self.band = self.sdm['Receiver'][0].frequencyBand.split('_')[1]

            if len(calsources) > 1:
                print 'Found multiple flux calibrators:', calsources
            self.fluxname = calsources[0]
            self.fluxname_full = calsources_full[0]
            print 'Set flux calibrator to %s and band to %s.' % (self.fluxname_full, self.band)
        else:
            self.fluxname = ''
            self.fluxname_full = ''
            self.band = ''