Takes in a list of attribute values for a field,
    evaluates the centroid using the comparator,
    & returns the centroid (i.e. the 'best' value for the field)
325924
def getCentroid(attribute_variants, comparator):
    

    n = len(attribute_variants)

    distance_matrix = numpy.zeros([n, n])

    # populate distance matrix by looping through elements of matrix triangle
    for i in range(0, n):
        for j in range(0, i):
            distance = comparator(attribute_variants[i], attribute_variants[j])
            distance_matrix[i, j] = distance_matrix[j, i] = distance

    average_distance = distance_matrix.mean(0)

    # there can be ties for minimum, average distance string
    min_dist_indices = numpy.where(
        average_distance == average_distance.min())[0]

    if len(min_dist_indices) > 1:
        centroid = breakCentroidTie(attribute_variants, min_dist_indices)
    else:
        centroid_index = min_dist_indices[0]
        centroid = attribute_variants[centroid_index]

    return centroid
415651
private List<Object> getValues(PivotField field, Map<Integer, Object> filter) {
//		long start = System.currentTimeMillis();
		List<Object> values = new ArrayList<Object>();
		int fieldIndex = field.getIndex();
		for (int i = 0; i < dataSource.getRowCount(); i++) {
			if (filter.isEmpty()) {
				values.add(dataSource.getValueAt(i, fieldIndex));
			} else {
				if (acceptValue(i, filter)) {
					values.add(dataSource.getValueAt(i, fieldIndex));
				}
			}
		}
//		long stop = System.currentTimeMillis();
//		System.out.println("getValues in " + (stop - start));
		
		return values;
	}
460634
def select(data, field_name):
    
    if isinstance(data, Cube):
        return data._select(_normalize_selects(field_name))

    if isinstance(data, PartFlatList):
        return data.select(field_name)

    if isinstance(data, UniqueIndex):
        data = (
            data._data.values()
        )  # THE SELECT ROUTINE REQUIRES dicts, NOT Data WHILE ITERATING

    if is_data(data):
        return select_one(data, field_name)

    if is_data(field_name):
        field_name = wrap(field_name)
        if field_name.value in ["*", "."]:
            return data

        if field_name.value:
            # SIMPLIFY {"value":value} AS STRING
            field_name = field_name.value

    # SIMPLE PYTHON ITERABLE ASSUMED
    if is_text(field_name):
        path = split_field(field_name)
        if len(path) == 1:
            return FlatList([d[field_name] for d in data])
        else:
            output = FlatList()
            flat_list._select1(data, path, 0, output)
            return output
    elif is_list(field_name):
        keys = [_select_a_field(wrap(f)) for f in field_name]
        return _select(Data(), unwrap(data), keys, 0)
    else:
        keys = [_select_a_field(field_name)]
        return _select(Data(), unwrap(data), keys, 0)
125644
Object getValue(int fieldNum)
    {
        String attributeName = getAttributeName(fieldNum);
        ClassDescriptor cld = broker.getClassDescriptor(pc.getClass());
        
        // field could be a primitive typed attribute...
        AttributeDescriptorBase fld = cld.getFieldDescriptorByName(attributeName);
        // field could be a reference attribute...
        if (fld == null) 
        {
			fld = cld.getObjectReferenceDescriptorByName(attributeName);
		}
		// or it could be a collection attribute:
        if (fld == null) 
        {
			fld = cld.getCollectionDescriptorByName(attributeName);
		}        
        Object value = fld.getPersistentField().get(pc);
        return value;
    }
261996
public int compareTo(Field field)
    {
        if (field instanceof BaseField) if (!this.isSameType((BaseField)field))
            return super.compareTo(field);
        short short1 = Short.MIN_VALUE, short2 = Short.MAX_VALUE;
        Short tempShort = (Short)this.getData();    // Get the physical data
        if (tempShort != null)
            short1 = tempShort.shortValue();
        tempShort = (Short)field.getData();   // Get the physical data
        if (tempShort != null)
            short2 = tempShort.shortValue();
        if (short1 == short2)
            return 0;
        if (short1 < short2)
            return -1;
        else
            return 1;
    }
1196002
private LinkedHashMap<Integer, Coordinate> getCoordinate( int nStaz, SimpleFeatureCollection collection, String idField )
            throws Exception {
        LinkedHashMap<Integer, Coordinate> id2CoordinatesMap = new LinkedHashMap<Integer, Coordinate>();
        FeatureIterator<SimpleFeature> iterator = collection.features();
        Coordinate coordinate = null;
        try {
            while( iterator.hasNext() ) {
                SimpleFeature feature = iterator.next();
                int name = ((Number) feature.getAttribute(idField)).intValue();
                coordinate = ((Geometry) feature.getDefaultGeometry()).getCentroid().getCoordinate();
                double z = 0;
                if (fPointZ != null) {
                    try {
                        z = ((Number) feature.getAttribute(fPointZ)).doubleValue();
                    } catch (NullPointerException e) {
                        pm.errorMessage(msg.message("kriging.noPointZ"));
                        throw new Exception(msg.message("kriging.noPointZ"));
                    }
                }
                coordinate.z = z;
                id2CoordinatesMap.put(name, coordinate);
            }
        } finally {
            iterator.close();
        }

        return id2CoordinatesMap;
    }
197424
def _closest_centroid(self, x):
        
        closest_centroid = 0
        distance = 10^9

        for i in range(self.n_clusters):
            current_distance = linalg.norm(x - self.centroids[i])
            if current_distance < distance:
                closest_centroid = i
                distance = current_distance

        return closest_centroid
294731
def field2choices(self, field, **kwargs):
        
        attributes = {}

        comparable = [
            validator.comparable
            for validator in field.validators
            if hasattr(validator, "comparable")
        ]
        if comparable:
            attributes["enum"] = comparable
        else:
            choices = [
                OrderedSet(validator.choices)
                for validator in field.validators
                if hasattr(validator, "choices")
            ]
            if choices:
                attributes["enum"] = list(functools.reduce(operator.and_, choices))

        return attributes
865707
function getDotValue(obj, field) {
  var fieldParts = typeof field === 'string' ? field.split('.') : field,
    i,
    objs;

  if (!obj) {
    return undefined;
  } // field cannot be empty so that means we should return undefined so that nothing can match

  if (fieldParts.length === 0) {
    return obj;
  }

  if (fieldParts.length === 1) {
    return obj[fieldParts[0]];
  }

  if (util.isArray(obj[fieldParts[0]])) {
    // If the next field is an integer, return only this item of the array
    i = parseInt(fieldParts[1], 10);
    if (typeof i === 'number' && !isNaN(i)) {
      return getDotValue(obj[fieldParts[0]][i], fieldParts.slice(2));
    }

    // Return the array of values
    objs = new Array();
    for (i = 0; i < obj[fieldParts[0]].length; i += 1) {
      objs.push(getDotValue(obj[fieldParts[0]][i], fieldParts.slice(1)));
    }
    return objs;
  } else {
    return getDotValue(obj[fieldParts[0]], fieldParts.slice(1));
  }
}
1133448
function centroidOf(points, dimension) {
    var centroid = new Float32Array(dimension);
    for (var i = 0; i < centroid.length; i++) {
      var sum = 0;
      var count = 0;
      for (var pointIndex = 0; pointIndex < points.length; pointIndex++) {
        var p = points[pointIndex];
        var point = p.getPoint();
        var val = point.getValue(i);
        if (!isNaN(val)) {
          sum += val;
          count++;
        }
      }
      centroid[i] = (sum / count);
    }
    return new PointWrapper(morpheus.VectorUtil.arrayAsVector(centroid));
  }
884412
def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None):
    """"""

    from matplotlib.patches import Ellipse

    if logger is None:
        logger = logging.getLogger(__name__)

    region = bounding_box.slice
    ref_x = region[1].start
    ref_y = region[0].start
    logger.debug('region ofset is %s, %s', ref_x, ref_y)
    subimage = data[region].copy()
    bkg = sep.Background(subimage)
    data_sub = subimage - bkg
    objects = sep.extract(data_sub, 1.5, err=bkg.globalrms)
    # Select brightest object
    logger.debug('%d object found', len(objects))

    if len(objects) == 0:
        # print('No objects')
        return None

    iadx = objects['flux'].argmax()
    # plot background-subtracted image
    maxflux = objects[iadx]

    if debug_plot:
        fig, ax = plt.subplots()
        m, s = np.mean(data_sub), np.std(data_sub)
        ax.imshow(data_sub, interpolation='nearest', cmap='gray',
                  vmin=m - s, vmax=m + s, origin='lower',
                  extent=bounding_box.extent)
        if plot_reference:
            e = Ellipse(xy=(plot_reference[0], plot_reference[1]),
                        width=6,
                        height=6,
                        angle=0)
            e.set_facecolor('none')
            e.set_edgecolor('green')
            ax.add_artist(e)

        # plot an ellipse for each object
        for idx, obj in enumerate(objects):
            e = Ellipse(xy=(obj['x'] + ref_x, obj['y'] + ref_y),
                        width=6 * obj['a'],
                        height=6 * obj['b'],
                        angle=obj['theta'] * 180. / np.pi)
            e.set_facecolor('none')
            if idx == iadx:
                e.set_edgecolor('blue')
            else:
                e.set_edgecolor('red')
            ax.add_artist(e)
        return maxflux['x'], maxflux['y'], ax
    else:
        return maxflux['x'], maxflux['y']
821190
def centroid(X):
    
    C = np.sum(X, axis=0) / len(X)
    return C
604617
public static int centroids(Relation<? extends NumberVector> rel, List<? extends Cluster<?>> clusters, NumberVector[] centroids, NoiseHandling noiseOption) {
    assert (centroids.length == clusters.size());
    int ignorednoise = 0;
    Iterator<? extends Cluster<?>> ci = clusters.iterator();
    for(int i = 0; ci.hasNext(); i++) {
      Cluster<?> cluster = ci.next();
      if(cluster.size() <= 1 || cluster.isNoise()) {
        switch(noiseOption){
        case IGNORE_NOISE:
          ignorednoise += cluster.size();
        case TREAT_NOISE_AS_SINGLETONS:
          centroids[i] = null;
          continue;
        case MERGE_NOISE:
          break; // Treat as cluster below
        }
      }
      centroids[i] = ModelUtil.getPrototypeOrCentroid(cluster.getModel(), rel, cluster.getIDs());
    }
    return ignorednoise;
  }
9275
private float calculateClusterQuality (ArrayList<Instance> docs,
			HashSparseVector centroid) {
		float quality = 0.0f;
		HashSparseVector c = centroid;

		for (int i = 0; i < docs.size(); ++i) {
			Instance doc = docs.get(i);

			quality += c.distanceEuclidean((HashSparseVector) doc.getData());
		}

		return quality;
	}
155414
def equalfield(bunchdt, data, commdct, idfobj1, idfobj2, fieldname, places=7):
    """"""
    # TODO test if both objects are of same type
    key1 = idfobj1.obj[0].upper()
    key2 = idfobj2.obj[0].upper()
    if key1 != key2:
        raise NotSameObjectError
    vee2 = idfobj2[fieldname]
    return isfieldvalue(
        bunchdt, data, commdct,
        idfobj1, fieldname, vee2, places=places)
930387
def _centroids(self, verts):
        
        '''
        value = sp.zeros([len(verts), 3])
        for i, i_verts in enumerate(verts):
            value[i] = np.mean(i_verts, axis=0)
        return value
723201
def in_field(self, field_name, *field_vals, **field_kwargs):
        
        field_name = self._normalize_field_name(field_name)
        fv = make_list(field_vals[0]) if field_vals else None
        if field_kwargs:
            for k in field_kwargs:
                if not field_kwargs[k]:
                    raise ValueError("Cannot IN an empty list")

                field_kwargs[k] = make_list(field_kwargs[k])

        else:
            if not fv: self.can_get = False

        self.fields_where.append(field_name, ["in", field_name, fv, field_kwargs])
        return self