r"""
    Alternative implementation of the `cosine` distance measure.
    
    Notes
    -----
    Under development.
556573
def cosine_alt(h1, h2): # 17 us @array, 42 us @list \w 100 bins
    
    """
    h1, h2 = __prepare_histogram(h1, h2)
    return -1 * float(scipy.sum(h1 * h2)) / (scipy.sum(scipy.power(h1, 2)) * scipy.sum(scipy.power(h2, 2)))
916744
def distance_matrix(lons, lats, diameter=2*EARTH_RADIUS):
    
    m = len(lons)
    assert m == len(lats), (m, len(lats))
    lons = numpy.radians(lons)
    lats = numpy.radians(lats)
    cos_lats = numpy.cos(lats)
    result = numpy.zeros((m, m))
    for i in range(len(lons)):
        a = numpy.sin((lats[i] - lats) / 2.0)
        b = numpy.sin((lons[i] - lons) / 2.0)
        result[i, :] = numpy.arcsin(
            numpy.sqrt(a * a + cos_lats[i] * cos_lats * b * b)) * diameter
    return numpy.matrix(result, copy=False)
1065017
def generateDistanceMatrix(width, height):
	
	
	# Determine the coordinates of the exact centre of the window
	originX = width / 2
	originY = height / 2
	
	# Generate the distance matrix
	distances = zerosFactory((height,width), dtype=np.float)
	for index, val in np.ndenumerate(distances):
		y,x = index
		distances[(y,x)] = math.sqrt( math.pow(x - originX, 2) + math.pow(y - originY, 2) )
	
	return distances
989980
def _dcorr(y, n2, A, dcov2_xx):
    
    # Pairwise Euclidean distances
    b = squareform(pdist(y, metric='euclidean'))
    # Double centering
    B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()
    # Compute squared distance covariances
    dcov2_yy = np.vdot(B, B) / n2
    dcov2_xy = np.vdot(A, B) / n2
    return np.sqrt(dcov2_xy) / np.sqrt(np.sqrt(dcov2_xx) * np.sqrt(dcov2_yy))
181109
function normalizeCoords(dispObj, coords) {
    var focalAngleRad = dispObj.rotation * Math.PI / 180;
    var oppositeRad = (Math.PI - focalAngleRad) / 2;

    // Distance from register point to coords
    var relX = coords.x - dispObj.regX;
    var relY = dispObj.regY - coords.y; // opposite of cartesian
    var distFromFocal = Math.sqrt(Math.pow(relX, 2) +
                        Math.pow(relY, 2));
    if(relX < 0) distFromFocal = -distFromFocal;

    // Distance between the relative and normalized point
    var pointDistance;
    if(oppositeRad !== 0)
        pointDistance = distFromFocal * Math.sin(focalAngleRad) /
                        Math.sin(oppositeRad);
    else
        pointDistance =  distFromFocal * 2;

    var totalRelativeRad = 0;
    if(distFromFocal !== 0)
        totalRelativeRad = Math.asin(relY / distFromFocal);

    var xRad = (Math.PI / 2) - focalAngleRad - oppositeRad +
                            totalRelativeRad;

    var x = Math.sin(xRad) * pointDistance +
            coords.x - dispObj.regX + dispObj.x;
    var y = Math.cos(xRad) * pointDistance +
            coords.y - dispObj.regY + dispObj.y;

    var rotation = coords.rotation || 0;
    rotation += dispObj.rotation;

    return {
        x: x,
        y: y,
        rotation: rotation
    };
}
343002
def cluster_row_and_col(net, dist_type='cosine', linkage_type='average',
                        dendro=True, run_clustering=True, run_rank=True,
                        ignore_cat=False, calc_cat_pval=False, links=False):
  '''  '''

  import scipy
  from copy import deepcopy
  from scipy.spatial.distance import pdist
  from . import categories, make_viz, cat_pval

  dm = {}
  for inst_rc in ['row', 'col']:

    tmp_mat = deepcopy(net.dat['mat'])
    dm[inst_rc] = calc_distance_matrix(tmp_mat, inst_rc, dist_type)

    # save directly to dat structure
    node_info = net.dat['node_info'][inst_rc]

    node_info['ini'] = list(range( len(net.dat['nodes'][inst_rc]), -1, -1))

    # cluster
    if run_clustering is True:
      node_info['clust'], node_info['group'] = \
          clust_and_group(net, dm[inst_rc], linkage_type=linkage_type)
    else:
      dendro = False
      node_info['clust'] = node_info['ini']

    # sorting
    if run_rank is True:
      node_info['rank'] = sort_rank_nodes(net, inst_rc, 'sum')
      node_info['rankvar'] = sort_rank_nodes(net, inst_rc, 'var')
    else:
      node_info['rank'] = node_info['ini']
      node_info['rankvar'] = node_info['ini']

    ##################################
    if ignore_cat is False:
      categories.calc_cat_clust_order(net, inst_rc)

  if calc_cat_pval is True:
    cat_pval.main(net)

  # make the visualization json
  make_viz.viz_json(net, dendro, links)

  return dm
259889
def to_gmfs(shakemap, spatialcorr, crosscorr, site_effects, trunclevel,
            num_gmfs, seed, imts=None):
    
    N = len(shakemap)  # number of sites
    std = shakemap['std']
    if imts is None or len(imts) == 0:
        imts = std.dtype.names
    else:
        imts = [imt for imt in imts if imt in std.dtype.names]
    val = {imt: numpy.log(shakemap['val'][imt]) - std[imt] ** 2 / 2.
           for imt in imts}
    imts_ = [imt.from_string(name) for name in imts]
    M = len(imts_)
    cross_corr = cross_correlation_matrix(imts_, crosscorr)
    mu = numpy.array([numpy.ones(num_gmfs) * val[str(imt)][j]
                      for imt in imts_ for j in range(N)])
    dmatrix = geo.geodetic.distance_matrix(
        shakemap['lon'], shakemap['lat'])
    spatial_corr = spatial_correlation_array(dmatrix, imts_, spatialcorr)
    stddev = [std[str(imt)] for imt in imts_]
    for im, std in zip(imts_, stddev):
        if std.sum() == 0:
            raise ValueError('Cannot decompose the spatial covariance '
                             'because stddev==0 for IMT=%s' % im)
    spatial_cov = spatial_covariance_array(stddev, spatial_corr)
    L = cholesky(spatial_cov, cross_corr)  # shape (M * N, M * N)
    if trunclevel:
        Z = truncnorm.rvs(-trunclevel, trunclevel, loc=0, scale=1,
                          size=(M * N, num_gmfs), random_state=seed)
    else:
        Z = norm.rvs(loc=0, scale=1, size=(M * N, num_gmfs), random_state=seed)
    # Z has shape (M * N, E)
    gmfs = numpy.exp(numpy.dot(L, Z) + mu) / PCTG
    if site_effects:
        gmfs = amplify_gmfs(imts_, shakemap['vs30'], gmfs)
    if gmfs.max() > MAX_GMV:
        logging.warning('There suspiciously large GMVs of %.2fg', gmfs.max())
    return imts, gmfs.reshape((M, N, num_gmfs)).transpose(1, 2, 0)
1031016
def metop20kmto1km(lons20km, lats20km):
    
    cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047])
    cols1km = np.arange(2048)
    lines = lons20km.shape[0]
    rows20km = np.arange(lines)
    rows1km = np.arange(lines)

    along_track_order = 1
    cross_track_order = 3

    satint = SatelliteInterpolator((lons20km, lats20km),
                                   (rows20km, cols20km),
                                   (rows1km, cols1km),
                                   along_track_order,
                                   cross_track_order)
    return satint.interpolate()
1158273
def small_phi_ces_distance(C1, C2):
    """"""
    return sum(c.phi for c in C1) - sum(c.phi for c in C2)
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))
1093004
def _friends_bootstrap_radius(args):
    """"""

    # Unzipping.
    points, ftype = args
    rstate = np.random

    # Resampling.
    npoints, ndim = points.shape
    idxs = rstate.randint(npoints, size=npoints)  # resample
    idx_in = np.unique(idxs)  # selected objects
    sel = np.ones(npoints, dtype='bool')
    sel[idx_in] = False
    idx_out = np.where(sel)[0]  # "missing" objects
    if len(idx_out) < 2:  # edge case
        idx_out = np.append(idx_out, [0, 1])
    points_in, points_out = points[idx_in], points[idx_out]

    # Construct KDTree to enable quick nearest-neighbor lookup for
    # our resampled objects.
    kdtree = spatial.KDTree(points_in)

    if ftype == 'balls':
        # Compute distances from our "missing" points its closest neighbor
        # among the resampled points using the Euclidean norm
        # (i.e. "radius" of n-sphere).
        dists, ids = kdtree.query(points_out, k=1, eps=0, p=2)
    elif ftype == 'cubes':
        # Compute distances from our "missing" points its closest neighbor
        # among the resampled points using the Euclidean norm
        # (i.e. "half-side-length" of n-cube).
        dists, ids = kdtree.query(points_out, k=1, eps=0, p=np.inf)

    # Conservative upper-bound on radius.
    dist = max(dists)

    return dist
507618
def distance_to_edge(geom, skydir):
    """"""

    # FIXME: We should add a pixel_size property in gammapy.maps
    # FIXME: We should make this into a MapGeom method 
    
    xpix, ypix = skydir.to_pixel(geom.wcs, origin=0)
    deltax = np.array((xpix - geom.center_pix[0]) * geom._cdelt[0],
                      ndmin=1)
    deltay = np.array((ypix - geom.center_pix[1]) * geom._cdelt[1],
                      ndmin=1)

    deltax = np.abs(deltax) - 0.5 * geom.width[0]
    deltay = np.abs(deltay) - 0.5 * geom.width[1]

    m0 = (deltax < 0) & (deltay < 0)
    m1 = (deltax > 0) & (deltay < 0)
    m2 = (deltax < 0) & (deltay > 0)
    m3 = (deltax > 0) & (deltay > 0)
    mx = np.abs(deltax) <= np.abs(deltay)
    my = np.abs(deltay) < np.abs(deltax)

    delta = np.zeros(len(deltax))
    delta[(m0 & mx) | (m3 & my) | m1] = deltax[(m0 & mx) | (m3 & my) | m1]
    delta[(m0 & my) | (m3 & mx) | m2] = deltay[(m0 & my) | (m3 & mx) | m2]
    return delta
169378
function findSquaredDistanceBetweenSegments(segmentA, segmentB) {
  findClosestPointsFromSegmentToSegment(_segmentDistance_tmpVecA, _segmentDistance_tmpVecB,
      segmentA, segmentB);
  return vec3.squaredDistance(_segmentDistance_tmpVecA, _segmentDistance_tmpVecB);
}
382423
def __surface_distances(result, reference, voxelspacing=None, connectivity=1):
    
    result = numpy.atleast_1d(result.astype(numpy.bool))
    reference = numpy.atleast_1d(reference.astype(numpy.bool))
    if voxelspacing is not None:
        voxelspacing = _ni_support._normalize_sequence(voxelspacing, result.ndim)
        voxelspacing = numpy.asarray(voxelspacing, dtype=numpy.float64)
        if not voxelspacing.flags.contiguous:
            voxelspacing = voxelspacing.copy()
            
    # binary structure
    footprint = generate_binary_structure(result.ndim, connectivity)
    
    # test for emptiness
    if 0 == numpy.count_nonzero(result): 
        raise RuntimeError('The first supplied array does not contain any binary object.')
    if 0 == numpy.count_nonzero(reference): 
        raise RuntimeError('The second supplied array does not contain any binary object.')    
            
    # extract only 1-pixel border line of objects
    result_border = result ^ binary_erosion(result, structure=footprint, iterations=1)
    reference_border = reference ^ binary_erosion(reference, structure=footprint, iterations=1)
    
    # compute average surface distance        
    # Note: scipys distance transform is calculated only inside the borders of the
    #       foreground objects, therefore the input has to be reversed
    dt = distance_transform_edt(~reference_border, sampling=voxelspacing)
    sds = dt[result_border]
    
    return sds
1262481
def cluster(self, dist_type='cosine', run_clustering=True,
                 dendro=True, views=['N_row_sum', 'N_row_var'],
                 linkage_type='average', sim_mat=False, filter_sim=0.1,
                 calc_cat_pval=False, run_enrichr=None, enrichrgram=None):
    '''
    
    '''
    initialize_net.viz(self)

    make_clust_fun.make_clust(self, dist_type=dist_type, run_clustering=run_clustering,
                                   dendro=dendro,
                                   requested_views=views,
                                   linkage_type=linkage_type,
                                   sim_mat=sim_mat,
                                   filter_sim=filter_sim,
                                   calc_cat_pval=calc_cat_pval,
                                   run_enrichr=run_enrichr,
                                   enrichrgram=enrichrgram)
1038426
function distanceFrom(Centroids) {
                var distances = [];

                for(var i = 1; i <= this.Observations.rows(); i++) {
                    var distance = [];

                    for(var j = 1; j <= Centroids.rows(); j++) {
                        distance.push(this.Observations.row(i).distanceFrom(Centroids.row(j)));
                    }

                    distances.push(distance);
                }

                return $M(distances);
            }
1266311
def _compute_distance_term(self, C, mag, rrup):
        
        term1 = C['b'] * rrup
        term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag))

        return term1 + term2