Python numpy.minimum() Examples
The following are 30
code examples of numpy.minimum().
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 also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: net_utils.py From cascade-rcnn_Pytorch with MIT License | 6 votes |
def vis_det_and_mask(im, class_name, dets, masks, thresh=0.8): """Visual debugging of detections.""" num_dets = np.minimum(10, dets.shape[0]) colors_mask = random_colors(num_dets) colors_bbox = np.round(np.random.rand(num_dets, 3) * 255) # sort rois according to the coordinates, draw upper bbox first draw_mask = np.zeros(im.shape[:2], dtype=np.uint8) for i in range(1): bbox = tuple(int(np.round(x)) for x in dets[i, :4]) mask = masks[i, :, :] full_mask = unmold_mask(mask, bbox, im.shape) score = dets[i, -1] if score > thresh: word_width = len(class_name) cv2.rectangle(im, bbox[0:2], bbox[2:4], colors_bbox[i], 2) cv2.rectangle(im, bbox[0:2], (bbox[0] + 18 + word_width*8, bbox[1]+15), colors_bbox[i], thickness=cv2.FILLED) apply_mask(im, full_mask, draw_mask, colors_mask[i], 0.5) draw_mask += full_mask cv2.putText(im, '%s' % (class_name), (bbox[0]+5, bbox[1] + 12), cv2.FONT_HERSHEY_PLAIN, 1.0, (255,255,255), thickness=1) return im
Example #2
Source File: test_utils.py From object_detector_app with MIT License | 6 votes |
def create_random_boxes(num_boxes, max_height, max_width): """Creates random bounding boxes of specific maximum height and width. Args: num_boxes: number of boxes. max_height: maximum height of boxes. max_width: maximum width of boxes. Returns: boxes: numpy array of shape [num_boxes, 4]. Each row is in form [y_min, x_min, y_max, x_max]. """ y_1 = np.random.uniform(size=(1, num_boxes)) * max_height y_2 = np.random.uniform(size=(1, num_boxes)) * max_height x_1 = np.random.uniform(size=(1, num_boxes)) * max_width x_2 = np.random.uniform(size=(1, num_boxes)) * max_width boxes = np.zeros(shape=(num_boxes, 4)) boxes[:, 0] = np.minimum(y_1, y_2) boxes[:, 1] = np.minimum(x_1, x_2) boxes[:, 2] = np.maximum(y_1, y_2) boxes[:, 3] = np.maximum(x_1, x_2) return boxes.astype(np.float32)
Example #3
Source File: np_box_ops.py From object_detector_app with MIT License | 6 votes |
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2)) intersect_heights = np.maximum( np.zeros(all_pairs_max_ymin.shape), all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2)) all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2)) intersect_widths = np.maximum( np.zeros(all_pairs_max_xmin.shape), all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
Example #4
Source File: test_quantization.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def test_quantize_float32_to_int8(): shape = rand_shape_nd(4) data = rand_ndarray(shape, 'default', dtype='float32') min_range = mx.nd.min(data) max_range = mx.nd.max(data) qdata, min_val, max_val = mx.nd.contrib.quantize(data, min_range, max_range, out_type='int8') data_np = data.asnumpy() min_range = min_range.asscalar() max_range = max_range.asscalar() real_range = np.maximum(np.abs(min_range), np.abs(max_range)) quantized_range = 127.0 scale = quantized_range / real_range assert qdata.dtype == np.int8 assert min_val.dtype == np.float32 assert max_val.dtype == np.float32 assert same(min_val.asscalar(), -real_range) assert same(max_val.asscalar(), real_range) qdata_np = (np.sign(data_np) * np.minimum(np.abs(data_np) * scale + 0.5, quantized_range)).astype(np.int8) assert_almost_equal(qdata.asnumpy(), qdata_np, atol = 1)
Example #5
Source File: map_utils.py From DOTA_models with Apache License 2.0 | 6 votes |
def resize_maps(map, map_scales, resize_method): scaled_maps = [] for i, sc in enumerate(map_scales): if resize_method == 'antialiasing': # Resize using open cv so that we can compute the size. # Use PIL resize to use anti aliasing feature. map_ = cv2.resize(map*1, None, None, fx=sc, fy=sc, interpolation=cv2.INTER_LINEAR) w = map_.shape[1]; h = map_.shape[0] map_img = PIL.Image.fromarray((map*255).astype(np.uint8)) map__img = map_img.resize((w,h), PIL.Image.ANTIALIAS) map_ = np.asarray(map__img).astype(np.float32) map_ = map_/255. map_ = np.minimum(map_, 1.0) map_ = np.maximum(map_, 0.0) elif resize_method == 'linear_noantialiasing': map_ = cv2.resize(map*1, None, None, fx=sc, fy=sc, interpolation=cv2.INTER_LINEAR) else: logging.error('Unknown resizing method') scaled_maps.append(map_) return scaled_maps
Example #6
Source File: detection.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def _update_labels(self, label, crop_box, height, width): """Convert labels according to crop box""" xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3)] -= xmin out[:, (2, 4)] -= ymin out[:, (1, 3)] /= w out[:, (2, 4)] /= h out[:, 1:5] = np.maximum(0, out[:, 1:5]) out[:, 1:5] = np.minimum(1, out[:, 1:5]) coverage = self._calculate_areas(out[:, 1:]) * w * h / self._calculate_areas(label[:, 1:]) valid = np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2]) valid = np.logical_and(valid, coverage > self.min_eject_coverage) valid = np.where(valid)[0] if valid.size < 1: return None out = out[valid, :] return out
Example #7
Source File: nav_env.py From DOTA_models with Apache License 2.0 | 6 votes |
def raw_valid_fn_vec(self, xyt): """Returns if the given set of nodes is valid or not.""" height = self.traversible.shape[0] width = self.traversible.shape[1] x = np.round(xyt[:,[0]]).astype(np.int32) y = np.round(xyt[:,[1]]).astype(np.int32) is_inside = np.all(np.concatenate((x >= 0, y >= 0, x < width, y < height), axis=1), axis=1) x = np.minimum(np.maximum(x, 0), width-1) y = np.minimum(np.maximum(y, 0), height-1) ind = np.ravel_multi_index((y,x), self.traversible.shape) is_traversible = self.traversible.ravel()[ind] is_valid = np.all(np.concatenate((is_inside[:,np.newaxis], is_traversible), axis=1), axis=1) return is_valid
Example #8
Source File: SurveySimulation.py From EXOSIMS with BSD 3-Clause "New" or "Revised" License | 6 votes |
def revisitFilter(self,sInds,tmpCurrentTimeNorm): """Helper method for Overloading Revisit Filtering Args: sInds - indices of stars still in observation list tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form Returns: sInds - indices of stars still in observation list """ tovisit = np.zeros(self.TargetList.nStars, dtype=bool) if len(sInds) > 0: tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \ & (self.starVisits[sInds] < self.nVisitsMax))#Checks that no star has exceeded the number of revisits and the indicies of all considered stars have minimum number of observations #The above condition should prevent revisits so long as all stars have not been observed if self.starRevisit.size != 0: dt_rev = np.abs(self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm) ind_rev = [int(x) for x in self.starRevisit[dt_rev < self.dt_max,0] if x in sInds] tovisit[ind_rev] = (self.starVisits[ind_rev] < self.nVisitsMax) sInds = np.where(tovisit)[0] return sInds
Example #9
Source File: np_box_ops.py From DOTA_models with Apache License 2.0 | 6 votes |
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2)) intersect_heights = np.maximum( np.zeros(all_pairs_max_ymin.shape), all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2)) all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2)) intersect_widths = np.maximum( np.zeros(all_pairs_max_xmin.shape), all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
Example #10
Source File: bbox.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 6 votes |
def clip_boxes(boxes, im_shape): """ Clip boxes to image boundaries. :param boxes: [N, 4* num_classes] :param im_shape: tuple of 2 :return: [N, 4* num_classes] """ # x1 >= 0 boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0) # y1 >= 0 boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0) # x2 < im_shape[1] boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0) # y2 < im_shape[0] boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0) return boxes
Example #11
Source File: dataloader_m.py From models with MIT License | 6 votes |
def _prepro_cpg(self, states, dists): """Preprocess the state and distance of neighboring CpG sites.""" prepro_states = [] prepro_dists = [] for state, dist in zip(states, dists): nan = state == dat.CPG_NAN if np.any(nan): state[nan] = np.random.binomial(1, state[~nan].mean(), nan.sum()) dist[nan] = self.cpg_max_dist dist = np.minimum(dist, self.cpg_max_dist) / self.cpg_max_dist prepro_states.append(np.expand_dims(state, 1)) prepro_dists.append(np.expand_dims(dist, 1)) prepro_states = np.concatenate(prepro_states, axis=1) prepro_dists = np.concatenate(prepro_dists, axis=1) if self.cpg_wlen: center = prepro_states.shape[2] // 2 delta = self.cpg_wlen // 2 tmp = slice(center - delta, center + delta) prepro_states = prepro_states[:, :, tmp] prepro_dists = prepro_dists[:, :, tmp] return (prepro_states, prepro_dists)
Example #12
Source File: attacks_tf.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
def apply_perturbations(i, j, X, increase, theta, clip_min, clip_max): """ TensorFlow implementation for apply perturbations to input features based on salency maps :param i: index of first selected feature :param j: index of second selected feature :param X: a matrix containing our input features for our sample :param increase: boolean; true if we are increasing pixels, false otherwise :param theta: delta for each feature adjustment :param clip_min: mininum value for a feature in our sample :param clip_max: maximum value for a feature in our sample : return: a perturbed input feature matrix for a target class """ # perturb our input sample if increase: X[0, i] = np.minimum(clip_max, X[0, i] + theta) X[0, j] = np.minimum(clip_max, X[0, j] + theta) else: X[0, i] = np.maximum(clip_min, X[0, i] - theta) X[0, j] = np.maximum(clip_min, X[0, j] - theta) return X
Example #13
Source File: model_utils.py From medicaldetectiontoolkit with Apache License 2.0 | 6 votes |
def compute_iou_3D(box, boxes, box_volume, boxes_volume): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2, z1, z2] (typically gt box) boxes: [boxes_count, (y1, x1, y2, x2, z1, z2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficency. Calculate once in the caller to avoid duplicate work. """ # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) z1 = np.maximum(box[4], boxes[:, 4]) z2 = np.minimum(box[5], boxes[:, 5]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) * np.maximum(z2 - z1, 0) union = box_volume + boxes_volume[:] - intersection[:] iou = intersection / union return iou
Example #14
Source File: model_utils.py From medicaldetectiontoolkit with Apache License 2.0 | 6 votes |
def compute_iou_2D(box, boxes, box_area, boxes_area): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2] THIS IS THE GT BOX boxes: [boxes_count, (y1, x1, y2, x2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficency. Calculate once in the caller to avoid duplicate work. """ # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou
Example #15
Source File: net_utils.py From cascade-rcnn_Pytorch with MIT License | 6 votes |
def vis_detections(im, class_name, dets, thresh=0.8): """Visual debugging of detections.""" for i in range(np.minimum(10, dets.shape[0])): bbox = tuple(int(np.round(x)) for x in dets[i, :4]) score = dets[i, -1] if score > thresh: cv2.rectangle(im, bbox[0:2], bbox[2:4], (0, 204, 0), 2) cv2.putText(im, '%s: %.3f' % (class_name, score), (bbox[0], bbox[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) return im # Borrow from matterport mask R-CNN implementation
Example #16
Source File: deform.py From dataflow with Apache License 2.0 | 6 votes |
def np_sample(img, coords): # a numpy implementation of ImageSample layer coords = np.maximum(coords, 0) coords = np.minimum(coords, np.array([img.shape[0] - 1, img.shape[1] - 1])) lcoor = np.floor(coords).astype('int32') ucoor = lcoor + 1 ucoor = np.minimum(ucoor, np.array([img.shape[0] - 1, img.shape[1] - 1])) diff = coords - lcoor neg_diff = 1.0 - diff lcoory, lcoorx = np.split(lcoor, 2, axis=2) ucoory, ucoorx = np.split(ucoor, 2, axis=2) diff = np.repeat(diff, 3, 2).reshape((diff.shape[0], diff.shape[1], 2, 3)) neg_diff = np.repeat(neg_diff, 3, 2).reshape((diff.shape[0], diff.shape[1], 2, 3)) diffy, diffx = np.split(diff, 2, axis=2) ndiffy, ndiffx = np.split(neg_diff, 2, axis=2) ret = img[lcoory, lcoorx, :] * ndiffx * ndiffy + \ img[ucoory, ucoorx, :] * diffx * diffy + \ img[lcoory, ucoorx, :] * ndiffy * diffx + \ img[ucoory, lcoorx, :] * diffy * ndiffx return ret[:, :, 0, :]
Example #17
Source File: pano_lsd_align.py From HorizonNet with MIT License | 6 votes |
def paintParameterLine(parameterLine, width, height): lines = parameterLine.copy() panoEdgeC = np.zeros((height, width)) num_sample = max(height, width) for i in range(len(lines)): n = lines[i, :3] sid = lines[i, 4] * 2 * np.pi eid = lines[i, 5] * 2 * np.pi if eid < sid: x = np.linspace(sid, eid + 2 * np.pi, num_sample) x = x % (2 * np.pi) else: x = np.linspace(sid, eid, num_sample) u = -np.pi + x.reshape(-1, 1) v = computeUVN(n, u, lines[i, 3]) xyz = uv2xyzN(np.hstack([u, v]), lines[i, 3]) uv = xyz2uvN(xyz, 1) m = np.minimum(np.floor((uv[:,0] + np.pi) / (2 * np.pi) * width) + 1, width).astype(np.int32) n = np.minimum(np.floor(((np.pi / 2) - uv[:, 1]) / np.pi * height) + 1, height).astype(np.int32) panoEdgeC[n-1, m-1] = i return panoEdgeC
Example #18
Source File: metrics_test.py From fine-lm with MIT License | 6 votes |
def testMultilabelMatch3(self): predictions = np.random.randint(1, 5, size=(100, 1, 1, 1)) targets = np.random.randint(1, 5, size=(100, 10, 1, 1)) weights = np.random.randint(0, 2, size=(100, 1, 1, 1)) targets *= weights predictions_repeat = np.repeat(predictions, 10, axis=1) expected = (predictions_repeat == targets).astype(float) expected = np.sum(expected, axis=(1, 2, 3)) expected = np.minimum(expected / 3.0, 1.) expected = np.sum(expected * weights[:, 0, 0, 0]) / weights.shape[0] with self.test_session() as session: scores, weights_ = metrics.multilabel_accuracy_match3( tf.one_hot(predictions, depth=5, dtype=tf.float32), tf.constant(targets, dtype=tf.int32)) a, a_op = tf.metrics.mean(scores, weights_) session.run(tf.local_variables_initializer()) session.run(tf.global_variables_initializer()) _ = session.run(a_op) actual = session.run(a) self.assertAlmostEqual(actual, expected, places=6)
Example #19
Source File: test_parameters.py From pywr with GNU General Public License v3.0 | 6 votes |
def test_deficit_parameter(): """Test DeficitParameter Here we test both uses of the DeficitParameter: 1) Recording the deficit for a node each timestep 2) Using yesterday's deficit to control today's flow """ model = load_model("deficit.json") model.run() max_flow = np.array([5, 6, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8]) demand = 10.0 supplied = np.minimum(max_flow, demand) expected = demand - supplied actual = model.recorders["deficit_recorder"].data assert_allclose(expected, actual[:,0]) expected_yesterday = [0]+list(expected[0:-1]) actual_yesterday = model.recorders["yesterday_recorder"].data assert_allclose(expected_yesterday, actual_yesterday[:,0])
Example #20
Source File: test_parameters.py From pywr with GNU General Public License v3.0 | 6 votes |
def test_flow_parameter(): """test FlowParameter """ model = load_model("flow_parameter.json") model.run() max_flow = np.array([5, 6, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8]) demand = 10.0 supplied = np.minimum(max_flow, demand) actual = model.recorders["flow_recorder"].data assert_allclose(supplied, actual[:,0]) expected_yesterday = [3.1415]+list(supplied[0:-1]) actual_yesterday = model.recorders["yesterday_flow_recorder"].data assert_allclose(expected_yesterday, actual_yesterday[:,0])
Example #21
Source File: face_attack.py From Adversarial-Face-Attack with GNU General Public License v3.0 | 6 votes |
def detect(self, img): """ img: rgb 3 channel """ minsize = 20 # minimum size of face threshold = [0.6, 0.7, 0.7] # three steps's threshold factor = 0.709 # scale factor bounding_boxes, _ = FaceDet.detect_face( img, minsize, self.pnet, self.rnet, self.onet, threshold, factor) area = (bounding_boxes[:, 2] - bounding_boxes[:, 0]) * (bounding_boxes[:, 3] - bounding_boxes[:, 1]) face_idx = area.argmax() bbox = bounding_boxes[face_idx][:4] # xy,xy margin = 32 x0 = np.maximum(bbox[0] - margin // 2, 0) y0 = np.maximum(bbox[1] - margin // 2, 0) x1 = np.minimum(bbox[2] + margin // 2, img.shape[1]) y1 = np.minimum(bbox[3] + margin // 2, img.shape[0]) x0, y0, x1, y1 = bbox = [int(k + 0.5) for k in [x0, y0, x1, y1]] cropped = img[y0:y1, x0:x1, :] scaled = cv2.resize(cropped, (160, 160), interpolation=cv2.INTER_LINEAR) return scaled, bbox
Example #22
Source File: test_utils.py From DOTA_models with Apache License 2.0 | 6 votes |
def create_random_boxes(num_boxes, max_height, max_width): """Creates random bounding boxes of specific maximum height and width. Args: num_boxes: number of boxes. max_height: maximum height of boxes. max_width: maximum width of boxes. Returns: boxes: numpy array of shape [num_boxes, 4]. Each row is in form [y_min, x_min, y_max, x_max]. """ y_1 = np.random.uniform(size=(1, num_boxes)) * max_height y_2 = np.random.uniform(size=(1, num_boxes)) * max_height x_1 = np.random.uniform(size=(1, num_boxes)) * max_width x_2 = np.random.uniform(size=(1, num_boxes)) * max_width boxes = np.zeros(shape=(num_boxes, 4)) boxes[:, 0] = np.minimum(y_1, y_2) boxes[:, 1] = np.minimum(x_1, x_2) boxes[:, 2] = np.maximum(y_1, y_2) boxes[:, 3] = np.maximum(x_1, x_2) return boxes.astype(np.float32)
Example #23
Source File: test_recorders.py From pywr with GNU General Public License v3.0 | 5 votes |
def test_array_deficit_recoder(self, simple_linear_model): """Test `NumpyArrayNodeDeficitRecorder` """ model = simple_linear_model model.timestepper.delta = 1 otpt = model.nodes['Output'] inflow = np.arange(365) * 0.1 demand = np.ones_like(inflow) * 30.0 model.nodes['Input'].max_flow = ArrayIndexedParameter(model, inflow) otpt.max_flow = ArrayIndexedParameter(model, demand) otpt.cost = -2.0 expected_supply = np.minimum(inflow, demand) expected_deficit = demand - expected_supply rec = NumpyArrayNodeDeficitRecorder(model, otpt) model.run() assert rec.data.shape == (365, 1) np.testing.assert_allclose(expected_deficit[:, np.newaxis], rec.data) df = rec.to_dataframe() assert df.shape == (365, 1) np.testing.assert_allclose(expected_deficit[:, np.newaxis], df.values)
Example #24
Source File: test_recorders.py From pywr with GNU General Public License v3.0 | 5 votes |
def test_array_supplied_ratio_recoder(self, simple_linear_model): """Test `NumpyArrayNodeSuppliedRatioRecorder` """ model = simple_linear_model model.timestepper.delta = 1 otpt = model.nodes['Output'] inflow = np.arange(365) * 0.1 demand = np.ones_like(inflow) * 30.0 model.nodes['Input'].max_flow = ArrayIndexedParameter(model, inflow) otpt.max_flow = ArrayIndexedParameter(model, demand) otpt.cost = -2.0 expected_supply = np.minimum(inflow, demand) expected_ratio = expected_supply / demand rec = NumpyArrayNodeSuppliedRatioRecorder(model, otpt) model.run() assert rec.data.shape == (365, 1) np.testing.assert_allclose(expected_ratio[:, np.newaxis], rec.data) df = rec.to_dataframe() assert df.shape == (365, 1) np.testing.assert_allclose(expected_ratio[:, np.newaxis], df.values)
Example #25
Source File: sort.py From sort with GNU General Public License v3.0 | 5 votes |
def iou(bb_test, bb_gt): """ Computes IUO between two bboxes in the form [x1,y1,x2,y2] """ xx1 = np.maximum(bb_test[0], bb_gt[0]) yy1 = np.maximum(bb_test[1], bb_gt[1]) xx2 = np.minimum(bb_test[2], bb_gt[2]) yy2 = np.minimum(bb_test[3], bb_gt[3]) w = np.maximum(0., xx2 - xx1) h = np.maximum(0., yy2 - yy1) wh = w * h o = wh / ((bb_test[2] - bb_test[0]) * (bb_test[3] - bb_test[1]) + (bb_gt[2] - bb_gt[0]) * (bb_gt[3] - bb_gt[1]) - wh) return(o)
Example #26
Source File: test_recorders.py From pywr with GNU General Public License v3.0 | 5 votes |
def test_array_curtailment_ratio_recoder(self, simple_linear_model): """Test `NumpyArrayNodeCurtailmentRatioRecorder` """ model = simple_linear_model model.timestepper.delta = 1 otpt = model.nodes['Output'] inflow = np.arange(365) * 0.1 demand = np.ones_like(inflow) * 30.0 model.nodes['Input'].max_flow = ArrayIndexedParameter(model, inflow) otpt.max_flow = ArrayIndexedParameter(model, demand) otpt.cost = -2.0 expected_supply = np.minimum(inflow, demand) expected_curtailment_ratio = 1 - expected_supply / demand rec = NumpyArrayNodeCurtailmentRatioRecorder(model, otpt) model.run() assert rec.data.shape == (365, 1) np.testing.assert_allclose(expected_curtailment_ratio[:, np.newaxis], rec.data) df = rec.to_dataframe() assert df.shape == (365, 1) np.testing.assert_allclose(expected_curtailment_ratio[:, np.newaxis], df.values)
Example #27
Source File: wfg.py From pymoo with Apache License 2.0 | 5 votes |
def _transformation_bias_flat(y, a, b, c): ret = a + np.minimum(0, np.floor(y - b)) * (a * (b - y) / b) \ - np.minimum(0, np.floor(c - y)) * ((1.0 - a) * (y - c) / (1.0 - c)) return correct_to_01(ret)
Example #28
Source File: test_common.py From pyscf with Apache License 2.0 | 5 votes |
def phase_difference(a, b, axis=0, threshold=1e-5): """The phase difference between vectors.""" v1, v2 = numpy.asarray(a), numpy.asarray(b) testing.assert_equal(v1.shape, v2.shape) v1, v2 = pull_dim(v1, axis), pull_dim(v2, axis) g1 = abs(v1) > threshold g2 = abs(v2) > threshold g12 = numpy.logical_and(g1, g2) if numpy.any(g12.sum(axis=1) == 0): desired_threshold = numpy.minimum(abs(v1), abs(v2)).max(axis=1).min() raise ValueError("Cannot find an anchor for the rotation, maximal value for the threshold is: {:.3e}".format( desired_threshold )) anchor_index = tuple(numpy.where(i)[0][0] for i in g12) return sign(v2[numpy.arange(len(v2)), anchor_index]) / sign(v1[numpy.arange(len(v1)), anchor_index])
Example #29
Source File: activations.py From lightnn with Apache License 2.0 | 5 votes |
def leaky_relu(z, alpha=0.3): z = np.asarray(z) return np.maximum(z, 0) + np.minimum(z, 0) * alpha
Example #30
Source File: augmentations.py From CSD-SSD with MIT License | 5 votes |
def intersect(box_a, box_b): max_xy = np.minimum(box_a[:, 2:], box_b[2:]) min_xy = np.maximum(box_a[:, :2], box_b[:2]) inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf) return inter[:, 0] * inter[:, 1]