Replace the distortion model in a current WCS with a new model
        Start by creating linear WCS, then run
493926
def replace_model(refwcs, newcoeffs):
    
    print('WARNING:')
    print('    Replacing existing distortion model with one')
    print('    not necessarily matched to the observation!')
    # create linear version of WCS to be updated by new model
    wcslin = stwcs.distortion.utils.undistortWCS(refwcs)
    outwcs = refwcs.deepcopy()
    outwcs.wcs.cd = wcslin.wcs.cd
    outwcs.wcs.set()
    outwcs.setOrient()
    outwcs.setPscale()
    # add new model to updated WCS object
    add_model(outwcs,newcoeffs)
    # Update CD matrix with new model
    apply_model(outwcs)

    # replace original input WCS with newly updated WCS
    refwcs = outwcs.deepcopy()
821722
public static void rotateCW( InterleavedS64 input , InterleavedS64 output ) {
		if( input.width != output.height || input.height != output.width || input.numBands != output.numBands )
			throw new IllegalArgumentException("Incompatible shapes");

		int h = input.height-1;

		for( int y = 0; y < input.height; y++ ) {
			int indexSrc = input.startIndex + y*input.stride;
			for (int x = 0; x < input.width; x++) {
				int indexDst = output.getIndex(h-y,x);

				int end = indexSrc + input.numBands;
				while( indexSrc != end ) {
					output.data[indexDst++] = input.data[indexSrc++];
				}
			}
		}
	}
303397
def add_transform_chain(self, tc):
        """"""
        # Generate the transforms snippet.
        for t in tc.gpu_transforms:
            if isinstance(t, Clip):
                # Set the varying value in the vertex shader.
                self.insert_vert('v_temp_pos_tr = temp_pos_tr;')
                continue
            self.insert_vert(t.glsl('temp_pos_tr'))
        # Clipping.
        clip = tc.get('Clip')
        if clip:
            self.insert_frag(clip.glsl('v_temp_pos_tr'), 'before_transforms')
645697
def updateWCS(self, pixel_scale=None, orient=None,refpos=None,refval=None,size=None):
        
        # Set up parameters necessary for updating WCS
        # Check to see if new value is provided,
        # If not, fall back on old value as the default

        _updateCD = no
        if orient is not None and orient != self.orient:
            pa = DEGTORAD(orient)
            self.orient = orient
            self._orient_lin = orient
            _updateCD = yes
        else:
            # In case only pixel_scale was specified
            pa = DEGTORAD(self.orient)

        if pixel_scale is not None and pixel_scale != self.pscale:
            _ratio = pixel_scale / self.pscale
            self.pscale = pixel_scale
            _updateCD = yes
        else:
            # In case, only orient was specified
            pixel_scale = self.pscale
            _ratio = None

        # If a new plate scale was given,
        # the default size should be revised accordingly
        # along with the default reference pixel position.
        # Added 31 Mar 03, WJH.
        if _ratio is not None:
            self.naxis1 /= _ratio
            self.naxis2 /= _ratio
            self.crpix1 = self.naxis1/2.
            self.crpix2 = self.naxis2/2.

        # However, if the user provides a given size,
        # set it to use that no matter what.
        if size is not None:
            self.naxis1 = size[0]
            self.naxis2 = size[1]

        # Insure that naxis1,2 always return as integer values.
        self.naxis1 = int(self.naxis1)
        self.naxis2 = int(self.naxis2)

        if refpos is not None:
            self.crpix1 = refpos[0]
            self.crpix2 = refpos[1]
        if self.crpix1 is None:
            self.crpix1 = self.naxis1/2.
            self.crpix2 = self.naxis2/2.

        if refval is not None:
            self.crval1 = refval[0]
            self.crval2 = refval[1]

        # Reset WCS info now...
        if _updateCD:
            # Only update this should the pscale or orientation change...
            pscale = pixel_scale / 3600.

            self.cd11 = -pscale * N.cos(pa)
            self.cd12 = pscale * N.sin(pa)
            self.cd21 = self.cd12
            self.cd22 = -self.cd11

        # Now make sure that all derived values are really up-to-date based
        # on these changes
        self.update()
471668
def GenerateDSW(dswfile, source, env):
    """"""

    version_num = 6.0
    if 'MSVS_VERSION' in env:
        version_num, suite = msvs_parse_version(env['MSVS_VERSION'])
    if version_num >= 7.0:
        g = _GenerateV7DSW(dswfile, source, env)
        g.Build()
    else:
        g = _GenerateV6DSW(dswfile, source, env)
        g.Build()
651293
def copy(self):
        
        copied_model = GPModel(kernel = self.model.kern.copy(),
                            noise_var=self.noise_var,
                            exact_feval=self.exact_feval,
                            optimizer=self.optimizer,
                            max_iters=self.max_iters,
                            optimize_restarts=self.optimize_restarts,
                            verbose=self.verbose,
                            ARD=self.ARD)

        copied_model._create_model(self.model.X,self.model.Y)
        copied_model.updateModel(self.model.X,self.model.Y, None, None)
        return copied_model
915673
def _build_model(self):
        """"""

        with tf.variable_scope("init"):
            x = self._conv("init_conv", self._images, 3, 3, 16,
                           self._stride_arr(1))

        strides = [1, 2, 2]
        activate_before_residual = [True, False, False]
        if self.hps.use_bottleneck:
            res_func = self._bottleneck_residual
            filters = [16, 64, 128, 256]
        else:
            res_func = self._residual
            filters = [16, 16, 32, 64]

        with tf.variable_scope("unit_1_0"):
            x = res_func(x, filters[0], filters[1], self._stride_arr(
                strides[0]), activate_before_residual[0])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_1_%d" % i):
                x = res_func(x, filters[1], filters[1], self._stride_arr(1),
                             False)

        with tf.variable_scope("unit_2_0"):
            x = res_func(x, filters[1], filters[2], self._stride_arr(
                strides[1]), activate_before_residual[1])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_2_%d" % i):
                x = res_func(x, filters[2], filters[2], self._stride_arr(1),
                             False)

        with tf.variable_scope("unit_3_0"):
            x = res_func(x, filters[2], filters[3], self._stride_arr(
                strides[2]), activate_before_residual[2])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_3_%d" % i):
                x = res_func(x, filters[3], filters[3], self._stride_arr(1),
                             False)
        with tf.variable_scope("unit_last"):
            x = self._batch_norm("final_bn", x)
            x = self._relu(x, self.hps.relu_leakiness)
            x = self._global_avg_pool(x)

        with tf.variable_scope("logit"):
            logits = self._fully_connected(x, self.hps.num_classes)
            self.predictions = tf.nn.softmax(logits)

        with tf.variable_scope("costs"):
            xent = tf.nn.softmax_cross_entropy_with_logits(
                logits=logits, labels=self.labels)
            self.cost = tf.reduce_mean(xent, name="xent")
            self.cost += self._decay()

            if self.mode == "eval":
                tf.summary.scalar("cost", self.cost)
1334783
def _process_input_wcs_single(fname, wcskey, updatewcs):
    
    if wcskey in ['', ' ', 'INDEF', None]:
        if updatewcs:
            uw.updatewcs(fname, checkfiles=False)
    else:
        numext = fileutil.countExtn(fname)
        extlist = []
        for extn in range(1, numext + 1):
            extlist.append(('SCI', extn))
        if wcskey in string.ascii_uppercase:
            wkey = wcskey
            wname = ' '
        else:
            wname = wcskey
            wkey = ' '
        altwcs.restoreWCS(fname, extlist, wcskey=wkey, wcsname=wname)
    # make an asn table at the end
    # Make sure there is a WCSCORR table for each input image
    if wcskey not in ['', ' ', 'INDEF', None] or updatewcs:
        wcscorr.init_wcscorr(fname)
1171227
def construct_model(images,
                    actions=None,
                    context_frames=2,
                    hparams=None,
                    is_training=True):
  """"""

  pred_depth = 20

  enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [], [], [], []

  lstm_states = [None] * (pred_depth + 2)

  enc_out = encoder_vgg(
      images[0], hparams.enc_size, False, scope_prefix='timestep/',
      hparams=hparams, is_training=is_training)
  enc_out = tf.identity(enc_out, 'enc_out')
  enc_out_all.append(enc_out)

  num_timesteps = len(actions) - 1
  sum_freq = int(num_timesteps / 4 + 1)

  reuse = False
  for timestep, action in zip(range(len(actions) - 1), actions[:-1]):
    done_warm_start = timestep > context_frames - 1

    with tf.variable_scope('timestep', reuse=reuse):
      if done_warm_start:
        pred_input = pred_out_all[-1]
      else:
        pred_input = enc_out_all[-1]
      pred_out = predictor(
          pred_input, action, lstm_states, pred_depth, False, hparams=hparams)
      pred_out = tf.identity(pred_out, 'pred_out')
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('pred_out', pred_out)
      pred_out_all.append(pred_out)

      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('lstm_state', lstm_states[0])
      van_out, _, _ = van(
          enc_out_all[0],
          images[0],
          pred_out,
          images[timestep + 1],
          tf.AUTO_REUSE,
          hparams=hparams)
      van_out = tf.identity(van_out, 'van_out')
      van_out_all.append(van_out)

      enc_out = encoder_vgg(
          images[timestep + 1], hparams.enc_size, True, hparams=hparams,
          is_training=is_training)
      enc_out = tf.identity(enc_out, 'enc_out')
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('enc_out', enc_out)
      enc_out_all.append(enc_out)

      van_input = images[0]
      enc_noise = tf.zeros_like(enc_out)
      if timestep % sum_freq == 0:  # and not hparams.use_tpu:
        tf.summary.histogram('enc_noise', enc_noise)
      van_on_enc, _, _ = van(
          enc_out_all[0],
          van_input,
          enc_out + enc_noise,
          images[timestep + 1],
          tf.AUTO_REUSE,
          hparams=hparams)
      van_on_enc = tf.identity(van_on_enc, 'van_on_enc')
      van_on_enc_all.append(van_on_enc)

      reuse = True

  return enc_out_all, pred_out_all, van_out_all, van_on_enc_all
991305
private void recomputeLoadSums() {
        loadsHaveChanged.set(false);
        for (int d = 0; d < nbDims; d++) {
            int sli = 0;
            int sls = 0;
            for (int b = 0; b < nbBins; b++) {
                sli += loads[d][b].getLB();
                sls += loads[d][b].getUB();
            }
            this.sumLoadInf[d].set(sli);
            this.sumLoadSup[d].set(sls);
        }
    }
1087359
def convertWCS(inwcs,drizwcs):
    
    drizwcs[0] = inwcs.crpix[0]
    drizwcs[1] = inwcs.crval[0]
    drizwcs[2] = inwcs.crpix[1]
    drizwcs[3] = inwcs.crval[1]
    drizwcs[4] = inwcs.cd[0][0]
    drizwcs[5] = inwcs.cd[1][0]
    drizwcs[6] = inwcs.cd[0][1]
    drizwcs[7] = inwcs.cd[1][1]

    return drizwcs
923686
def transform(self, X):
        
        iclustup = []
        dims = self.n_components
        if hasattr(self, 'isort1'):
            if X.shape[1] == self.v.shape[0]:
                # reduce dimensionality of X
                X = X @ self.v
                nclust = self.n_X
                AtS = self.A.T @ self.S
                vnorm   = np.sum(self.S * (self.A @ AtS), axis=0)[np.newaxis,:]
                cv      = X @ AtS
                cmap    = np.maximum(0., cv)**2 / vnorm
                iclustup, cmax = upsample(np.sqrt(cmap), dims, nclust, 10)
            else:
                print('ERROR: new points do not have as many features as original data')
        else:
            print('ERROR: need to fit model first before you can embed new points')
        if iclustup.ndim > 1:
            iclustup = iclustup.T
        else:
            iclustup = iclustup.flatten()
        return iclustup
11022
def start_bundle(self, element=None):
    """"""
    import tensorflow as tf
    from trainer import feature_transforms

    g = tf.Graph()
    session = tf.Session(graph=g)

    # Build the transformation graph
    with g.as_default():
      transformed_features, _, placeholders = (
          feature_transforms.build_csv_serving_tensors_for_transform_step(
              analysis_path=self._analysis_output_dir, 
              features=self._features, 
              schema=self._schema,
              stats=self._stats,
              keep_target=True))
      session.run(tf.tables_initializer())
    
    self._session = session
    self._transformed_features = transformed_features
    self._input_placeholder_tensor = placeholders['csv_example']
1251747
def undistortWCS(refwcs):
    
    wcslin = stwcs.distortion.utils.output_wcs([refwcs])

    outwcs = stwcs.wcsutil.HSTWCS()
    outwcs.wcs = wcslin.wcs
    outwcs.wcs.set()
    outwcs.setPscale()
    outwcs.setOrient()
    outwcs.sip = None

    # Update instrument specific keywords
    outwcs.inst_kw = refwcs.inst_kw
    for kw in refwcs.inst_kw:
        outwcs.__dict__[kw] = refwcs.__dict__[kw]
    outwcs.pixel_shape = wcslin.pixel_shape

    return outwcs
507033
public void setOriginToCurrent() {
		IT currToWorld = (IT)worldToCurr.invert(null);
		IT oldWorldToNewWorld = (IT) worldToInit.concat(currToWorld,null);

		PixelTransform<Point2D_F32> newToOld = converter.convertPixel(oldWorldToNewWorld,null);

		// fill in the background color
		GImageMiscOps.fill(workImage, 0);
		// render the transform
		distorter.setModel(newToOld);
		distorter.apply(stitchedImage, workImage);

		// swap the two images
		I s = workImage;
		workImage = stitchedImage;
		stitchedImage = s;

		// have motion estimates be relative to this frame
		motion.setToFirst();
		first = true;

		computeCurrToInit_PixelTran();
	}
526360
def updateModel(self, X_all, Y_all, X_new, Y_new):
        
        if self.model is None:
            self._create_model(X_all, Y_all)
        else:
            self.model.set_XY(X_all, Y_all)

        # WARNING: Even if self.max_iters=0, the hyperparameters are bit modified...
        if self.max_iters > 0:
            # --- update the model maximizing the marginal likelihood.
            if self.optimize_restarts==1:
                self.model.optimize(optimizer=self.optimizer, max_iters = self.max_iters, messages=False, ipython_notebook=False)
            else:
                self.model.optimize_restarts(num_restarts=self.optimize_restarts, optimizer=self.optimizer, max_iters = self.max_iters, verbose=self.verbose)
569797
def convert_flatten(builder, layer, input_names, output_names, keras_layer):
    
    input_name, output_name = (input_names[0], output_names[0])

    # blob_order == 0 if the input blob needs not be rearranged
    # blob_order == 1 if the input blob needs to be rearranged
    blob_order = 0

    # using keras_layer.input.shape have a "?" (Dimension[None] at the front),
    # making a 3D tensor with unknown batch size 4D
    if len(keras_layer.input.shape) == 4:
        blob_order = 1

    builder.add_flatten(name=layer, mode=blob_order, input_name=input_name, output_name=output_name)