Python numpy.amin() Examples

The following are 30 code examples for showing how to use numpy.amin(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: tf2-yolo3   Author: akkaze   File: utils.py    License: Apache License 2.0 7 votes vote down vote up
def draw_outputs(img, outputs, class_names=None):
    boxes, objectness, classes = outputs
    #boxes, objectness, classes = boxes[0], objectness[0], classes[0]
    wh = np.flip(img.shape[0:2])
    if img.ndim == 2 or img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    min_wh = np.amin(wh)
    if min_wh <= 100:
        font_size = 0.5
    else:
        font_size = 1
    for i in range(classes.shape[0]):
        x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
        x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
        img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
        img = cv2.putText(img, '{}'.format(int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
                          (0, 0, 255), 1)
    return img 
Example 2
Project: tf2-yolo3   Author: akkaze   File: utils.py    License: Apache License 2.0 7 votes vote down vote up
def draw_labels(x, y, class_names=None):
    img = x.numpy()
    if img.ndim == 2 or img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    boxes, classes = tf.split(y, (4, 1), axis=-1)
    classes = classes[..., 0]
    wh = np.flip(img.shape[0:2])
    min_wh = np.amin(wh)
    if min_wh <= 100:
        font_size = 0.5
    else:
        font_size = 1
    for i in range(len(boxes)):
        x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
        x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
        img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
        if class_names:
            img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
                              (0, 0, 255), 1)
        else:
            img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
    return img 
Example 3
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: detection.py    License: Apache License 2.0 6 votes vote down vote up
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height):
        """Check if constrains are satisfied"""
        if (xmax - xmin) * (ymax - ymin) < 2:
            return False  # only 1 pixel
        x1 = float(xmin) / width
        y1 = float(ymin) / height
        x2 = float(xmax) / width
        y2 = float(ymax) / height
        object_areas = self._calculate_areas(label[:, 1:])
        valid_objects = np.where(object_areas * width * height > 2)[0]
        if valid_objects.size < 1:
            return False
        intersects = self._intersect(label[valid_objects, 1:], x1, y1, x2, y2)
        coverages = self._calculate_areas(intersects) / object_areas[valid_objects]
        coverages = coverages[np.where(coverages > 0)[0]]
        return coverages.size > 0 and np.amin(coverages) > self.min_object_covered 
Example 4
Project: pyscf   Author: pyscf   File: gw.py    License: Apache License 2.0 6 votes vote down vote up
def get_wmin_wmax_tmax_ia_def(self, tol):
    from numpy import log, exp, sqrt, where, amin, amax
    """ 
      This is a default choice of the wmin and wmax parameters for a log grid along 
      imaginary axis. The default choice is based on the eigenvalues. 
    """
    E = self.ksn2e[0,0,:]
    E_fermi = self.fermi_energy
    E_homo = amax(E[where(E<=E_fermi)])
    E_gap  = amin(E[where(E>E_fermi)]) - E_homo  
    E_maxdiff = amax(E) - amin(E)
    d = amin(abs(E_homo-E)[where(abs(E_homo-E)>1e-4)])
    wmin_def = sqrt(tol * (d**3) * (E_gap**3)/(d**2+E_gap**2))
    wmax_def = (E_maxdiff**2/tol)**(0.250)
    tmax_def = -log(tol)/ (E_gap)
    tmin_def = -100*log(1.0-tol)/E_maxdiff
    return wmin_def, wmax_def, tmin_def,tmax_def 
Example 5
Project: pytim   Author: Marcello-Sega   File: sanity_check.py    License: GNU General Public License v3.0 6 votes vote down vote up
def assign_mesh(self, mesh):
        interface = self.interface
        box = interface.universe.dimensions[:3]
        interface.target_mesh = mesh
        if not isinstance(interface.target_mesh, (int, float)):
            raise TypeError(messages.MESH_NAN)
        if interface.target_mesh <= 0:
            raise ValueError(messages.MESH_NEGATIVE)
        if interface.target_mesh >= np.amin(box) / 2.:
            raise ValueError(messages.MESH_LARGE)

        try:
            np.arange(int(self.interface.alpha / self.interface.target_mesh))
        except BaseException:
            print(("Error while initializing ITIM: alpha ({0:f}) too large or\
                  mesh ({1:f}) too small".format(self.interface.alpha,
                                                 self.interface.target_mesh)))
            raise ValueError 
Example 6
Project: pytim   Author: Marcello-Sega   File: utilities.py    License: GNU General Public License v3.0 6 votes vote down vote up
def guess_normal(universe, group):
    """
    Guess the normal of a liquid slab

    """
    universe.atoms.pack_into_box()
    dim = universe.coord.dimensions

    delta = []
    for direction in range(0, 3):
        histo, _ = np.histogram(
            group.positions[:, direction],
            bins=5,
            range=(0, dim[direction]),
            density=True)
        max_val = np.amax(histo)
        min_val = np.amin(histo)
        delta.append(np.sqrt((max_val - min_val)**2))

    if np.max(delta) / np.min(delta) < 5.0:
        print("Warning: the result of the automatic normal detection (",
              np.argmax(delta), ") is not reliable")
    return np.argmax(delta) 
Example 7
Project: DeepFloorplan   Author: zlzeng   File: util.py    License: GNU General Public License v3.0 6 votes vote down vote up
def refine_room_region(cw_mask, rm_ind):
	label_rm, num_label = ndimage.label((1-cw_mask))
	new_rm_ind = np.zeros(rm_ind.shape)
	for j in xrange(1, num_label+1):  
		mask = (label_rm == j).astype(np.uint8)
		ys, xs = np.where(mask!=0)
		area = (np.amax(xs)-np.amin(xs))*(np.amax(ys)-np.amin(ys))
		if area < 100:
			continue
		else:
			room_types, type_counts = np.unique(mask*rm_ind, return_counts=True)
			if len(room_types) > 1:
				room_types = room_types[1:] # ignore background type which is zero
				type_counts = type_counts[1:] # ignore background count
			new_rm_ind += mask*room_types[np.argmax(type_counts)]

	return new_rm_ind 
Example 8
Project: phoenics   Author: aspuru-guzik-group   File: benchmark_functions.py    License: Apache License 2.0 6 votes vote down vote up
def discrete_ackley(vector):
	# takes k-dimensional vector
	vector = np.array(vector)
	vector = 100 * vector - 50
	bounds = [1.0, 2.0, 3.0, 4.0, 5.0]
	bounds = np.array(bounds)**2
	result = 5
	for bound in bounds[::-1]:
		if np.amax(np.abs(vector)) < bound:
			result -= 1
	bounds = [1.25, 2.0, 2.5]
	bounds = np.array(bounds)**2

	domain = np.linspace(-50, 50, 10)
	dx = domain[1] - domain[0]
	imaged = np.array([np.amin(np.abs(element - domain)) for element in vector]) 
	new_res = 5
	for bound in bounds[::-1]:
		if np.amax(np.abs(imaged)) < bound:
			new_res -= 1
		result = np.amin([result, new_res])
	result = np.amin([4, result])
	return result 
Example 9
Project: phoenics   Author: aspuru-guzik-group   File: benchmark_functions.py    License: Apache License 2.0 6 votes vote down vote up
def discrete_michalewicz(vector):
	vector = np.array(vector)
	vector = 100 * vector - 40

	bounds = [1.0, 2.0, 3.0, 4.0, 5.0]
	bounds = np.array(bounds)**2
	result = 5
	for bound in bounds[::-1]:
		if np.amax(np.abs(vector)) < bound:
			result -= 1
	bounds = [1.25, 2.0, 2.5, 3.0]
	bounds = np.array(bounds)**2
	new_res = 5
	for bound in bounds[::-1]:
		if np.amin(np.abs(vector)) < bound:
			new_res -= 1
	result = np.amin([result, new_res, 4])
	return result 
Example 10
Project: phoenics   Author: aspuru-guzik-group   File: phoenics.py    License: Apache License 2.0 6 votes vote down vote up
def _generate_sampled(self, num_samples, observ_dict):
		# clean observations
		obs_params, obs_losses = self.observation_parser.parse(observ_dict)
		lowest_loss   = np.amin(obs_losses)
		lowest_params = obs_params[np.argmin(obs_losses)]

		self.obs_params, self.obs_losses = self.observation_parser._raw_obs_params, self.observation_parser._raw_obs_losses
		self._compute_characteristic_distances()

		# create and sample the model
		print('# running density estimation')
		self.network = BayesianNeuralNetwork(self.var_dicts, obs_params, obs_losses, self.param_dict['general']['batch_size'], backend = self.param_dict['general']['backend'])
		self.network.create_model()
		self.network.sample()
		self.network.build_penalties()

		# sample the acquisition function
		print('# proposing new samples')
		self.proposed_samples = self.acq_func_sampler.sample(lowest_params, self.network.penalty_contributions, 
															 self.network.lambda_values, parallel = self.param_dict['general']['parallel_evaluations']) 
Example 11
Project: phoenics   Author: aspuru-guzik-group   File: hierarchies.py    License: Apache License 2.0 6 votes vote down vote up
def rescale_losses(self, losses):
		for index in range(losses.shape[1]):
			min_loss, max_loss = np.amin(losses[:, index]), np.amax(losses[:, index])
			losses[:, index] = (losses[:, index] - min_loss) / (max_loss - min_loss)
			losses = np.where(np.isnan(losses), 0., losses)

#		print(losses.shape)
#		quit()
		self.unscaled_losses = losses.transpose()

		self._build_tolerances()
		self._construct_objective()

		return self.loss.transpose()

#======================================================================== 
Example 12
Project: model-optimization   Author: tensorflow   File: gather_encoder_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_state_aggregation_modes(self):
    """Tests that all state updates tensors can be aggregated."""
    x_fn = lambda: tf.random.uniform((5,))
    encoder = gather_encoder.GatherEncoder.from_encoder(
        core_encoder.EncoderComposer(
            test_utils.StateUpdateTensorsEncodingStage()).make(),
        tf.TensorSpec.from_tensor(x_fn()))

    iteration = _make_iteration_function(encoder, x_fn, 3)
    data = self.evaluate(iteration(encoder.initial_state()))

    expected_sum = np.sum(data.x)
    expected_min = np.amin(data.x)
    expected_max = np.amax(data.x)
    expected_stack_values = 15  # 3 values of shape 5.
    expected_state = [
        expected_sum, expected_min, expected_max, expected_stack_values
    ]
    # We are not in control of ordering of the elements in state tuple.
    self.assertAllClose(sorted(expected_state), sorted(data.updated_state)) 
Example 13
Project: pytorchrl   Author: nosyndicate   File: multigoal_env.py    License: MIT License 6 votes vote down vote up
def step(self, action):
        action = action.ravel()

        a_lb, a_ub = self.action_space.bounds
        action = np.clip(action, a_lb, a_ub).ravel()

        next_obs = self.dynamics.forward(self.observation, action)
        o_lb, o_ub = self.observation_space.bounds
        next_obs = np.clip(next_obs, o_lb, o_ub)

        reward = self.compute_reward(self.observation, action)
        cur_position = self.observation
        dist_to_goal = np.amin([
            np.linalg.norm(cur_position - goal_position)
            for goal_position in self.goal_positions
        ])
        done = dist_to_goal < self.goal_threshold
        if done:
            reward += self.goal_reward

        self.observation = np.copy(next_obs)
        return next_obs, reward, done, {'pos': next_obs} 
Example 14
Project: pytorchrl   Author: nosyndicate   File: multigoal_env.py    License: MIT License 6 votes vote down vote up
def compute_reward(self, observation, action):
        # penalize the L2 norm of acceleration
        # noinspection PyTypeChecker
        action_cost = np.sum(action ** 2) * self.action_cost_coeff

        # penalize squared dist to goal
        cur_position = observation
        # noinspection PyTypeChecker
        goal_cost = np.amin([
            np.sum((cur_position - goal_position) ** 2)
            for goal_position in self.goal_positions
        ])

        # penalize staying with the log barriers
        costs = [action_cost, goal_cost]
        reward = -np.sum(costs)
        return reward 
Example 15
Project: pytorchrl   Author: nosyndicate   File: multigoal_env.py    License: MIT License 6 votes vote down vote up
def plot_position_cost(self, ax):
        delta = 0.01
        x_min, x_max = tuple(1.1 * np.array(self.xlim))
        y_min, y_max = tuple(1.1 * np.array(self.ylim))
        X, Y = np.meshgrid(
            np.arange(x_min, x_max, delta),
            np.arange(y_min, y_max, delta)
        )
        goal_costs = np.amin([
            (X - goal_x) ** 2 + (Y - goal_y) ** 2
            for goal_x, goal_y in self.goal_positions
        ], axis=0)
        costs = goal_costs

        contours = ax.contour(X, Y, costs, 20)
        ax.clabel(contours, inline=1, fontsize=10, fmt='%.0f')
        ax.set_xlim([x_min, x_max])
        ax.set_ylim([y_min, y_max])
        goal = ax.plot(self.goal_positions[:, 0],
                       self.goal_positions[:, 1], 'ro')
        return [contours, goal] 
Example 16
Project: snowy   Author: prideout   File: test_io.py    License: MIT License 6 votes vote down vote up
def test_range():

    source = path('../docs/ground.jpg')
    ground = snowy.load(source)
    assert np.amin(ground) >= 0 and np.amax(ground) <= 1

    with tempfile.NamedTemporaryFile() as fp:
        target = fp.name + '.png'
        snowy.export(ground, target)
        show_filename(target)

    show_filename(source)
    show_array(ground, True)

    blurred = snowy.blur(ground, radius=10)
    snowy.show(blurred) 
Example 17
Project: DOTA_models   Author: ringringyi   File: np_box_list_ops.py    License: Apache License 2.0 5 votes vote down vote up
def gather(boxlist, indices, fields=None):
  """Gather boxes from BoxList according to indices and return new BoxList.

  By default, Gather returns boxes corresponding to the input index list, as
  well as all additional fields stored in the boxlist (indexing into the
  first dimension).  However one can optionally only gather from a
  subset of fields.

  Args:
    boxlist: BoxList holding N boxes
    indices: a 1-d numpy array of type int_
    fields: (optional) list of fields to also gather from.  If None (default),
        all fields are gathered from.  Pass an empty fields list to only gather
        the box coordinates.

  Returns:
    subboxlist: a BoxList corresponding to the subset of the input BoxList
        specified by indices

  Raises:
    ValueError: if specified field is not contained in boxlist or if the
        indices are not of type int_
  """
  if indices.size:
    if np.amax(indices) >= boxlist.num_boxes() or np.amin(indices) < 0:
      raise ValueError('indices are out of valid range.')
  subboxlist = np_box_list.BoxList(boxlist.get()[indices, :])
  if fields is None:
    fields = boxlist.get_extra_fields()
  for field in fields:
    extra_field_data = boxlist.get_field(field)
    subboxlist.add_field(field, extra_field_data[indices, ...])
  return subboxlist 
Example 18
Project: object_detector_app   Author: datitran   File: np_box_list_ops.py    License: MIT License 5 votes vote down vote up
def gather(boxlist, indices, fields=None):
  """Gather boxes from BoxList according to indices and return new BoxList.

  By default, Gather returns boxes corresponding to the input index list, as
  well as all additional fields stored in the boxlist (indexing into the
  first dimension).  However one can optionally only gather from a
  subset of fields.

  Args:
    boxlist: BoxList holding N boxes
    indices: a 1-d numpy array of type int_
    fields: (optional) list of fields to also gather from.  If None (default),
        all fields are gathered from.  Pass an empty fields list to only gather
        the box coordinates.

  Returns:
    subboxlist: a BoxList corresponding to the subset of the input BoxList
        specified by indices

  Raises:
    ValueError: if specified field is not contained in boxlist or if the
        indices are not of type int_
  """
  if indices.size:
    if np.amax(indices) >= boxlist.num_boxes() or np.amin(indices) < 0:
      raise ValueError('indices are out of valid range.')
  subboxlist = np_box_list.BoxList(boxlist.get()[indices, :])
  if fields is None:
    fields = boxlist.get_extra_fields()
  for field in fields:
    extra_field_data = boxlist.get_field(field)
    subboxlist.add_field(field, extra_field_data[indices, ...])
  return subboxlist 
Example 19
Project: pyqmc   Author: WagnerGroup   File: supercell.py    License: MIT License 5 votes vote down vote up
def get_supercell_kpts(supercell):
    Sinv = np.linalg.inv(supercell.S).T
    u = [0, 1]
    unit_box = np.stack([x.ravel() for x in np.meshgrid(*[u] * 3, indexing="ij")]).T
    unit_box_ = np.dot(unit_box, supercell.S.T)
    xyz_range = np.stack([f(unit_box_, axis=0) for f in (np.amin, np.amax)]).T
    kptmesh = np.meshgrid(*[np.arange(*r) for r in xyz_range], indexing="ij")
    possible_kpts = np.dot(np.stack([x.ravel() for x in kptmesh]).T, Sinv)
    in_unit_box = (possible_kpts >= 0) * (possible_kpts < 1 - 1e-12)
    select = np.where(np.all(in_unit_box, axis=1))[0]
    reclatvec = np.linalg.inv(supercell.original_cell.lattice_vectors()).T * 2 * np.pi
    return np.dot(possible_kpts[select], reclatvec) 
Example 20
Project: pyqmc   Author: WagnerGroup   File: supercell.py    License: MIT License 5 votes vote down vote up
def get_supercell(cell, S):
    """
    Inputs:
        cell: pyscf Cell object
        S: (3, 3) supercell matrix for QMC from cell defined by cell.a. In other words, the QMC calculation cell is qmc_cell = np.dot(S, cell.lattice_vectors()). For a 2x2x2 supercell, S is [[2, 0, 0], [0, 2, 0], [0, 0, 2]].
    """
    from pyscf.pbc import gto

    def get_supercell_copies(latvec, S):
        Sinv = np.linalg.inv(S).T
        u = [0, 1]
        unit_box = np.stack([x.ravel() for x in np.meshgrid(*[u] * 3, indexing="ij")]).T
        unit_box_ = np.dot(unit_box, S)
        xyz_range = np.stack([f(unit_box_, axis=0) for f in (np.amin, np.amax)]).T
        mesh = np.meshgrid(*[np.arange(*r) for r in xyz_range], indexing="ij")
        possible_pts = np.dot(np.stack([x.ravel() for x in mesh]).T, Sinv.T)
        in_unit_box = (possible_pts >= 0) * (possible_pts < 1 - 1e-12)
        select = np.where(np.all(in_unit_box, axis=1))[0]
        return np.linalg.multi_dot((possible_pts[select], S, latvec))

    scale = np.abs(int(np.round(np.linalg.det(S))))
    superlattice = np.dot(S, cell.lattice_vectors())
    Rpts = get_supercell_copies(cell.lattice_vectors(), S)
    atom = []
    for (name, xyz) in cell._atom:
        atom.extend([(name, xyz + R) for R in Rpts])
    supercell = gto.Cell()
    supercell.a = superlattice
    supercell.atom = atom
    supercell.ecp = cell.ecp
    supercell.basis = cell.basis
    supercell.exp_to_discard = cell.exp_to_discard
    supercell.unit = "Bohr"
    supercell.spin = cell.spin * scale
    supercell.build()
    supercell.original_cell = cell
    supercell.S = S
    supercell.scale = scale
    return supercell 
Example 21
Project: pyqmc   Author: WagnerGroup   File: ewald.py    License: MIT License 5 votes vote down vote up
def set_up_reciprocal_ewald_sum(self, ewald_gmax):
        r"""
        Determine parameters for Ewald sums. 

        :math:`\alpha` determines the partitioning of the real and reciprocal-space parts.

        We define a weight `gweight` for the part of the reciprocal-space sums that doesn't depend on the coordinates:
        
        .. math:: W_G = \frac{4\pi}{V |\vec{G}|^2} e^{- \frac{|\vec{G}|^2}{ 4\alpha^2}}

        Inputs:
            latvec: (3, 3) array of lattice vectors; latvec[0] is the first
            ewald_gmax: int, max number of reciprocal lattice vectors to check away from 0
        """
        cellvolume = np.linalg.det(self.latvec)
        recvec = np.linalg.inv(self.latvec)
        crossproduct = recvec.T * cellvolume

        # Determine alpha
        tmpheight_i = np.einsum("ij,ij->i", crossproduct, self.latvec)
        length_i = np.linalg.norm(crossproduct, axis=1)
        smallestheight = np.amin(np.abs(tmpheight_i) / length_i)
        self.alpha = 5.0 / smallestheight
        print("Setting Ewald alpha to ", self.alpha)

        # Determine G points to include in reciprocal Ewald sum
        XYZ = np.meshgrid(*[np.arange(-ewald_gmax, ewald_gmax + 1)] * 3, indexing="ij")
        X, Y, Z = [x.ravel() for x in XYZ]
        positive_octants = X + 1e-6 * Y + 1e-12 * Z > 0  # assume ewald_gmax < 1e5
        gpoints = np.stack((X, Y, Z), axis=-1)[positive_octants]
        gpoints = np.dot(gpoints, recvec) * 2 * np.pi
        gsquared = np.sum(gpoints ** 2, axis=1)
        gweight = 4 * np.pi * np.exp(-gsquared / (4 * self.alpha ** 2))
        gweight /= cellvolume * gsquared
        bigweight = gweight > 1e-10
        self.gpoints = gpoints[bigweight]
        self.gweight = gweight[bigweight]

        self.set_ewald_constants(cellvolume) 
Example 22
Project: TGC-Designer-Tools   Author: chadrockey   File: GeoPointCloud.py    License: Apache License 2.0 5 votes vote down vote up
def xmin(self):
        if self._xmin is None:
            self._xmin =  numpy.amin(self.point_matrix, axis=0)[0]
        return self._xmin 
Example 23
Project: TGC-Designer-Tools   Author: chadrockey   File: GeoPointCloud.py    License: Apache License 2.0 5 votes vote down vote up
def ymin(self):
        if self._ymin is None:
            self._ymin = numpy.amin(self.point_matrix, axis=0)[1]
        return self._ymin 
Example 24
Project: TGC-Designer-Tools   Author: chadrockey   File: GeoPointCloud.py    License: Apache License 2.0 5 votes vote down vote up
def zmin(self):
        if self._zmin is None:
            self._zmin = numpy.amin(self.point_matrix, axis=0)[2]
        return self._zmin 
Example 25
Project: TGC-Designer-Tools   Author: chadrockey   File: GeoPointCloud.py    License: Apache License 2.0 5 votes vote down vote up
def imin(self):
        if self._imin is None:
            self._imin = numpy.amin(self.point_matrix, axis=0)[3]
        return self._imin 
Example 26
Project: vehicle_counting_tensorflow   Author: ahmetozlu   File: np_box_list_ops.py    License: MIT License 5 votes vote down vote up
def gather(boxlist, indices, fields=None):
  """Gather boxes from BoxList according to indices and return new BoxList.

  By default, gather returns boxes corresponding to the input index list, as
  well as all additional fields stored in the boxlist (indexing into the
  first dimension).  However one can optionally only gather from a
  subset of fields.

  Args:
    boxlist: BoxList holding N boxes
    indices: a 1-d numpy array of type int_
    fields: (optional) list of fields to also gather from.  If None (default),
        all fields are gathered from.  Pass an empty fields list to only gather
        the box coordinates.

  Returns:
    subboxlist: a BoxList corresponding to the subset of the input BoxList
        specified by indices

  Raises:
    ValueError: if specified field is not contained in boxlist or if the
        indices are not of type int_
  """
  if indices.size:
    if np.amax(indices) >= boxlist.num_boxes() or np.amin(indices) < 0:
      raise ValueError('indices are out of valid range.')
  subboxlist = np_box_list.BoxList(boxlist.get()[indices, :])
  if fields is None:
    fields = boxlist.get_extra_fields()
  for field in fields:
    extra_field_data = boxlist.get_field(field)
    subboxlist.add_field(field, extra_field_data[indices, ...])
  return subboxlist 
Example 27
Project: recruit   Author: Frank-qlu   File: test_function_base.py    License: Apache License 2.0 5 votes vote down vote up
def test_basic(self):
        a = [3, 4, 5, 10, -3, -5, 6.0]
        assert_equal(np.amin(a), -5.0)
        b = [[3, 6.0, 9.0],
             [4, 10.0, 5.0],
             [8, 3.0, 2.0]]
        assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0])
        assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0]) 
Example 28
Project: pytim   Author: Marcello-Sega   File: sanity_check.py    License: GNU General Public License v3.0 5 votes vote down vote up
def assign_alpha(self, alpha):
        try:
            box = self.interface.universe.dimensions[:3]
        except BaseException:
            raise Exception("Cannot set alpha before having a simulation box")
        if alpha < 0:
            raise ValueError(messages.ALPHA_NEGATIVE)
        if alpha >= np.amin(box):
            raise ValueError(messages.ALPHA_LARGE)
        self.interface.alpha = alpha 
Example 29
Project: deepchem   Author: deepchem   File: splitters.py    License: MIT License 5 votes vote down vote up
def get_task_split_indices(self, y, w, frac_split):
    """Returns num datapoints needed per task to split properly."""
    w_present = (w != 0)
    y_present = y * w_present

    # Compute number of actives needed per task.
    task_actives = np.sum(y_present, axis=0)
    task_split_actives = (frac_split * task_actives).astype(int)

    # loop through each column and obtain index required to splice out for
    # required fraction of hits
    split_indices = []
    n_tasks = np.shape(y)[1]
    for task in range(n_tasks):
      actives_count = task_split_actives[task]
      cum_task_actives = np.cumsum(y_present[:, task])
      # Find the first index where the cumulative number of actives equals
      # the actives_count
      split_index = np.amin(np.where(cum_task_actives >= actives_count)[0])
      # Note that np.where tells us last index required to exceed
      # actives_count, so we actually want the following location
      split_indices.append(split_index + 1)
    return split_indices

  # TODO(rbharath): Refactor this split method to match API of other
  # splits (or potentially refactor those to match this). 
Example 30
Project: deepchem   Author: deepchem   File: splitters.py    License: MIT License 5 votes vote down vote up
def get_task_split_indices(self, y, w, frac_split):
    """Returns num datapoints needed per task to split properly."""
    w_present = (w != 0)
    y_present = y * w_present

    # Compute number of actives needed per task.
    task_actives = np.sum(y_present, axis=0)
    task_split_actives = (frac_split * task_actives).astype(int)

    # loop through each column and obtain index required to splice out for
    # required fraction of hits
    split_indices = []
    n_tasks = np.shape(y)[1]
    for task in range(n_tasks):
      actives_count = task_split_actives[task]
      cum_task_actives = np.cumsum(y_present[:, task])
      # Find the first index where the cumulative number of actives equals
      # the actives_count
      split_index = np.amin(np.where(cum_task_actives >= actives_count)[0])
      # Note that np.where tells us last index required to exceed
      # actives_count, so we actually want the following location
      split_indices.append(split_index + 1)
    return split_indices

    # TODO(rbharath): Refactor this split method to match API of other splits (or

  # potentially refactor those to match this.