test whether the image positions map back to the same source position
        :param kwargs_lens:
        :param kwargs_ps:
        :return: add penalty when solver does not find a solution
343291
def solver_penalty(self, kwargs_lens, kwargs_ps, kwargs_cosmo, tolerance):
        
        dist = self._param.check_solver(kwargs_lens, kwargs_ps, kwargs_cosmo)
        if dist > tolerance:
            return dist * 10**10
        return 0
1344439
def _update_camera_pos(self):
        

        # transform will be updated several times; do not update camera
        # transform until we are done.
        ch_em = self.events.transform_change
        with ch_em.blocker(self._update_transform):
            tr = self.transform
            tr.reset()

            up, forward, right = self._get_dim_vectors()

            # Create mapping so correct dim is up
            pp1 = np.array([(0, 0, 0), (0, 0, -1), (1, 0, 0), (0, 1, 0)])
            pp2 = np.array([(0, 0, 0), forward, right, up])
            tr.set_mapping(pp1, pp2)

            tr.translate(-self._actual_distance * forward)
            self._rotate_tr()
            tr.scale([1.0/a for a in self._flip_factors])
            tr.translate(np.array(self.center))
821623
def uncertaintyMap(self, psf, method='convolve', fitParams=None):
        '''
        
        '''

        #ignore background:
        #img[img<0]=0
        ###noise should not influence sharpness uncertainty:
        ##img = median_filter(img, 3)

        # decrease noise in order not to overestimate result:
        img = scaleSignal(self.img, fitParams=fitParams)

        if method == 'convolve':
            #print 'convolve'
            blurred = convolve2d(img, psf, 'same')
            m = abs(img-blurred) / abs(img + blurred)
            m = np.nan_to_num(m)
            m*=self.std**2
            m[m>1]=1
            self.blur_distortion = m
            np.save('blurred', blurred)
            return m
        else:
            restored = unsupervised_wiener(img, psf)[0]
            m = abs(img-restored) / abs(img + restored)
            m = np.nan_to_num(m)
            m*=self.std**2
            m[m>1]=1
            self.blur_distortion = m
            return m, restored
550395
def on_art_source(self, *args):
        
        if self.art_source:
            self.art_image = Image(source=self.art_source)
594314
def check_positive_flux(cls, kwargs_ps):
        
        pos_bool = True
        for kwargs in kwargs_ps:
            point_amp = kwargs['point_amp']
            for amp in point_amp:
                if amp < 0:
                    pos_bool = False
                    break
        return pos_bool
30613
def _validate_image_orientation(image_orientation):
    '''
    
    '''
    row_cosine, column_cosine, slice_cosine = _extract_cosines(image_orientation)

    if not _almost_zero(np.dot(row_cosine, column_cosine), 1e-4):
        raise DicomImportException("Non-orthogonal direction cosines: {}, {}".format(row_cosine, column_cosine))
    elif not _almost_zero(np.dot(row_cosine, column_cosine), 1e-8):
        logger.warning("Direction cosines aren't quite orthogonal: {}, {}".format(row_cosine, column_cosine))

    if not _almost_one(np.linalg.norm(row_cosine), 1e-4):
        raise DicomImportException("The row direction cosine's magnitude is not 1: {}".format(row_cosine))
    elif not _almost_one(np.linalg.norm(row_cosine), 1e-8):
        logger.warning("The row direction cosine's magnitude is not quite 1: {}".format(row_cosine))

    if not _almost_one(np.linalg.norm(column_cosine), 1e-4):
        raise DicomImportException("The column direction cosine's magnitude is not 1: {}".format(column_cosine))
    elif not _almost_one(np.linalg.norm(column_cosine), 1e-8):
        logger.warning("The column direction cosine's magnitude is not quite 1: {}".format(column_cosine))
1209022
def _likelihood(self, args):
        
        #generate image and computes likelihood
        kwargs_data = self.update_data(args)
        imageModel = class_creator.create_image_model(kwargs_data, self._kwargs_psf, self._kwargs_numerics, self._kwargs_model)
        logL = imageModel.likelihood_data_given_model(self._kwargs_lens, self._kwargs_source, self._kwargs_lens_light, self._kwargs_else, source_marg=self._source_marg)
        return logL, None
132319
public boolean process( List<AssociatedTriple> observations , TrifocalTensor solution ) {

		if( observations.size() < 7 )
			throw new IllegalArgumentException(
					"At least 7 correspondences must be provided. Found "+observations.size());

		// compute normalization to reduce numerical errors
		LowLevelMultiViewOps.computeNormalization(observations, N1, N2, N3);

		// compute solution in normalized pixel coordinates
		createLinearSystem(observations);

		// solve for the trifocal tensor
		solveLinearSystem();

		// enforce geometric constraints to improve solution
		extractEpipoles.setTensor(solutionN);
		extractEpipoles.extractEpipoles(e2,e3);
		enforce.process(e2,e3,A);
		enforce.extractSolution(solutionN);

		// undo normalization
		removeNormalization(solution);

		return true;
	}
448062
def half_light_radius_lens(self, kwargs_lens_light, center_x=0, center_y=0, model_bool_list=None, deltaPix=None, numPix=None):
        
        if model_bool_list is None:
            model_bool_list = [True] * len(kwargs_lens_light)
        if numPix is None:
            numPix = 1000
        if deltaPix is None:
            deltaPix = 0.05
        x_grid, y_grid = util.make_grid(numPix=numPix, deltapix=deltaPix)
        x_grid += center_x
        y_grid += center_y
        lens_light = self._lens_light_internal(x_grid, y_grid, kwargs_lens_light, model_bool_list=model_bool_list)
        R_h = analysis_util.half_light_radius(lens_light, x_grid, y_grid, center_x, center_y)
        return R_h
457888
def multi_gaussian_lens(self, kwargs_lens, model_bool_list=None, e1=0, e2=0, n_comp=20):
        
        if 'center_x' in kwargs_lens[0]:
            center_x = kwargs_lens[0]['center_x']
            center_y = kwargs_lens[0]['center_y']
        else:
            raise ValueError('no keyword center_x defined!')
        theta_E = self._lensModelExtensions.effective_einstein_radius(kwargs_lens)
        r_array = np.logspace(-4, 2, 200) * theta_E
        x_coords, y_coords = param_util.transform_e1e2(r_array, np.zeros_like(r_array), e1=-e1, e2=-e2)
        x_coords += center_x
        y_coords += center_y
        #r_array = np.logspace(-2, 1, 50) * theta_E
        if model_bool_list is None:
            model_bool_list = [True] * len(kwargs_lens)
        kappa_s = np.zeros_like(r_array)
        for i in range(len(kwargs_lens)):
            if model_bool_list[i] is True:
                kappa_s += self.LensModel.kappa(x_coords, y_coords, kwargs_lens, k=i)
        amplitudes, sigmas, norm = mge.mge_1d(r_array, kappa_s, N=n_comp)
        return amplitudes, sigmas, center_x, center_y
699812
def error_response(self, kwargs_lens, kwargs_ps):
        
        model_error = self.error_map(kwargs_lens, kwargs_ps)
        error_map_1d = self.ImageNumerics.image2array(model_error)
        C_D_response = self.ImageNumerics.C_D_response + error_map_1d
        return C_D_response, model_error
866349
def bss_eval_images(reference_sources, estimated_sources,
                    compute_permutation=True):
    
    return bss_eval(
        reference_sources, estimated_sources,
        window=np.inf, hop=np.inf,
        compute_permutation=compute_permutation, filters_len=512,
        framewise_filters=True,
        bsseval_sources_version=False)
247633
def image_amplitude(self, kwargs_ps, kwargs_lens, k=None):
        
        amp_list = []
        for i, model in enumerate(self._point_source_list):
            if k is None or k == i:
                amp_list.append(model.image_amplitude(kwargs_ps=kwargs_ps[i], kwargs_lens=kwargs_lens, min_distance=self._min_distance,
                                                        search_window=self._search_window,
                                                        precision_limit=self._precision_limit,
                                                        num_iter_max=self._num_iter_max, x_center=self._x_center,
                                                        y_center=self._y_center))
        return amp_list
55767
def camera_position(self, pose=None):
        '''
        
        '''
        if pose is None:
            pose = self.pose()
        t, r = pose
        return -np.matrix(cv2.Rodrigues(r)[0]).T * np.matrix(t)
1186199
def _lens_light_internal(self, x_grid, y_grid, kwargs_lens_light, model_bool_list=None):
        
        if model_bool_list is None:
            model_bool_list = [True] * len(kwargs_lens_light)
        lens_light = np.zeros_like(x_grid)
        for i, bool in enumerate(model_bool_list):
            if bool is True:
                lens_light_i = self.LensLightModel.surface_brightness(x_grid, y_grid, kwargs_lens_light, k=i)
                lens_light += lens_light_i
        return lens_light
452436
def fake_lens_path_set(lens_path, value, obj):
    
    segment = head(lens_path)
    obj_copy = copy.copy(obj)

    def set_array_index(i, v, l):
        # Fill the array with None up to the given index and set the index to v
        try:
            l[i] = v
        except IndexError:
            for _ in range(i - len(l) + 1):
                l.append(None)
            l[i] = v

    if not (length(lens_path) - 1):
        # Done
        new_value = value
    else:
        # Find the value at the path or create a {} or [] at obj[segment]
        found_or_created = item_path_or(
            if_else(
                lambda segment: segment.isnumeric(),
                always([]),
                always({})
            )(head(tail(lens_path))),
            segment,
            obj
        )
        # Recurse on the rest of the path
        new_value = fake_lens_path_set(tail(lens_path), value, found_or_created)

    # Set or replace
    if segment.isnumeric():
        set_array_index(int(segment), new_value, obj_copy)
    else:
        obj_copy[segment] = new_value
    return obj_copy
1221651
def validate_orientation(dicoms):
    
    first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3]
    first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6]
    for dicom_ in dicoms:
        # Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)
        image_orient1 = numpy.array(dicom_.ImageOrientationPatient)[0:3]
        image_orient2 = numpy.array(dicom_.ImageOrientationPatient)[3:6]
        if not numpy.allclose(image_orient1, first_image_orient1, rtol=0.001, atol=0.001) \
                or not numpy.allclose(image_orient2, first_image_orient2, rtol=0.001, atol=0.001):
            logger.warning('Image orientations not consistent through all slices')
            logger.warning('---------------------------------------------------------')
            logger.warning('%s %s' % (image_orient1, first_image_orient1))
            logger.warning('%s %s' % (image_orient2, first_image_orient2))
            logger.warning('---------------------------------------------------------')
            raise ConversionValidationError('IMAGE_ORIENTATION_INCONSISTENT')