Python numpy.amax() Examples

The following are 30 code examples for showing how to use numpy.amax(). 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: DOTA_models   Author: ringringyi   File: np_box_list_ops.py    License: Apache License 2.0 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example 2
Project: sparse-subspace-clustering-python   Author: abhinav4192   File: OutlierDetection.py    License: MIT License 6 votes vote down vote up
def OutlierDetection(CMat, s):
    n = np.amax(s)
    _, N = CMat.shape
    OutlierIndx = list()
    FailCnt = 0
    Fail = False

    for i in range(0, N):
        c = CMat[:, i]
        if np.sum(np.isnan(c)) >= 1:
            OutlierIndx.append(i)
            FailCnt += 1
    sc = s.astype(float)
    sc[OutlierIndx] = np.nan
    CMatC = CMat.astype(float)
    CMatC[OutlierIndx, :] = np.nan
    CMatC[:, OutlierIndx] = np.nan
    OutlierIndx = OutlierIndx

    if FailCnt > (N - n):
        CMatC = np.nan
        sc = np.nan
        Fail = True
    return CMatC, sc, OutlierIndx, Fail 
Example 3
Project: object_detector_app   Author: datitran   File: np_box_list_ops.py    License: MIT License 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
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: pyscf   Author: pyscf   File: gw_iter.py    License: Apache License 2.0 6 votes vote down vote up
def si_c_check (self, tol = 1e-5):
    """
    This compares np.solve and LinearOpt-lgmres methods for solving linear equation (1-v\chi_{0}) * W_c = v\chi_{0}v
    """
    import time
    import numpy as np
    ww = 1j*self.ww_ia
    t = time.time()
    si0_1 = self.si_c(ww)      #method 1:  numpy.linalg.solve
    t1 = time.time() - t
    print('numpy: {} sec'.format(t1))
    t2 = time.time()
    si0_2 = self.si_c2(ww)     #method 2:  scipy.sparse.linalg.lgmres
    t3 = time.time() - t2
    print('lgmres: {} sec'.format(t3))
    summ = abs(si0_1 + si0_2).sum()
    diff = abs(si0_1 - si0_2).sum() 
    if diff/summ < tol and diff/si0_1.size < tol:
       print('OK! scipy.lgmres methods and np.linalg.solve have identical results')
    else:
       print('Results (W_c) are NOT similar!')     
    return [[diff/summ] , [np.amax(abs(diff))] ,[tol]]

  #@profile 
Example 6
Project: pyscf   Author: pyscf   File: m_ion_log.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, ao_log, sp):

    self.ion = ao_log.sp2ion[sp]
    self.rr,self.pp,self.nr = ao_log.rr,ao_log.pp,ao_log.nr
    self.interp_rr = log_interp_c(self.rr)
    self.interp_pp = log_interp_c(self.pp)
    
    self.mu2j = ao_log.sp_mu2j[sp]
    self.nmult= len(self.mu2j)
    self.mu2s = ao_log.sp_mu2s[sp]
    self.norbs= self.mu2s[-1]

    self.mu2ff = ao_log.psi_log[sp]
    self.mu2ff_rl = ao_log.psi_log_rl[sp]    
    self.mu2rcut = ao_log.sp_mu2rcut[sp]
    self.rcut = np.amax(self.mu2rcut)
    self.charge = ao_log.sp2charge[sp] 
Example 7
Project: pyscf   Author: pyscf   File: coords2sort_order.py    License: Apache License 2.0 6 votes vote down vote up
def coords2sort_order(a2c):
  """ Delivers a list of atom indices which generates a near-diagonal overlap for a given set of atom coordinates """
  na  = a2c.shape[0]
  aa2d = squareform(pdist(a2c))
  mxd = np.amax(aa2d)+1.0
  a = 0
  lsa = []
  for ia in range(na):
    lsa.append(a)
    asrt = np.argsort(aa2d[a])
    for ja in range(1,na):
      b = asrt[ja]
      if b not in lsa: break
    aa2d[a,b] = aa2d[b,a] = mxd
    a = b
  return np.array(lsa) 
Example 8
Project: pyscf   Author: pyscf   File: test_0092_ag2_ae.py    License: Apache License 2.0 6 votes vote down vote up
def test_gw(self):
    """ This is GW """
    mol = gto.M(verbose=0, atom='''Ag 0 0 -0.3707; Ag 0 0 0.3707''', basis = 'cc-pvdz-pp',)
    gto_mf = scf.RHF(mol)#.density_fit()
    gto_mf.kernel()
    #print('gto_mf.mo_energy:', gto_mf.mo_energy)
    s = nao(mf=gto_mf, gto=mol, verbosity=0)
    oref = s.overlap_coo().toarray()
    #print('s.norbs:', s.norbs, oref.sum())

    pb = prod_basis(nao=s, algorithm='fp')
    pab2v = pb.get_ac_vertex_array()
    mom0,mom1=pb.comp_moments()
    orec = np.einsum('p,pab->ab', mom0, pab2v)
    self.assertTrue(np.allclose(orec,oref, atol=1e-3), \
      "{} {}".format(abs(orec-oref).sum()/oref.size, np.amax(abs(orec-oref)))) 
Example 9
Project: NanoPlot   Author: wdecoster   File: spatial_heatmap.py    License: GNU General Public License v3.0 6 votes vote down vote up
def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
    """Taking channel information and creating post run channel activity plots."""
    logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
                 .format(array.size))
    activity_map = Plot(
        path=path + "." + figformat,
        title="Number of reads generated per channel")
    layout = make_layout(maxval=np.amax(array))
    valueCounts = pd.value_counts(pd.Series(array))
    for entry in valueCounts.keys():
        layout.template[np.where(layout.structure == entry)] = valueCounts[entry]
    plt.figure()
    ax = sns.heatmap(
        data=pd.DataFrame(layout.template, index=layout.yticks, columns=layout.xticks),
        xticklabels="auto",
        yticklabels="auto",
        square=True,
        cbar_kws={"orientation": "horizontal"},
        cmap=color,
        linewidths=0.20)
    ax.set_title(title or activity_map.title)
    activity_map.fig = ax.get_figure()
    activity_map.save(format=figformat)
    plt.close("all")
    return [activity_map] 
Example 10
Project: pyqmc   Author: WagnerGroup   File: reblock.py    License: MIT License 6 votes vote down vote up
def optimally_reblocked(data):
    """
        Find optimal reblocking of input data. Takes in pandas
        DataFrame of raw data to reblock, returns DataFrame
        of reblocked data.
    """
    opt = opt_block(data)
    n_reblock = int(np.amax(opt))
    rb_data = reblock_by2(data, n_reblock)
    serr = rb_data.sem(axis=0)
    d = {
        "mean": rb_data.mean(axis=0),
        "standard error": serr,
        "standard error error": serr / np.sqrt(2 * (len(rb_data) - 1)),
        "reblocks": n_reblock,
    }
    return pd.DataFrame(d) 
Example 11
Project: vehicle_counting_tensorflow   Author: ahmetozlu   File: np_box_list_ops.py    License: MIT License 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example 12
Project: vehicle_counting_tensorflow   Author: ahmetozlu   File: np_box_mask_list_ops.py    License: MIT License 6 votes vote down vote up
def prune_non_overlapping_masks(box_mask_list1, box_mask_list2, minoverlap=0.0):
  """Prunes the boxes in list1 that overlap less than thresh with list2.

  For each mask in box_mask_list1, we want its IOA to be more than minoverlap
  with at least one of the masks in box_mask_list2. If it does not, we remove
  it. If the masks are not full size image, we do the pruning based on boxes.

  Args:
    box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks.
    box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned box_mask_list with size [N', 4].
  """
  intersection_over_area = ioa(box_mask_list2, box_mask_list1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_box_mask_list1 = gather(box_mask_list1, keep_inds)
  return new_box_mask_list1 
Example 13
Project: LearningX   Author: ankonzoid   File: cartpole.py    License: MIT License 6 votes vote down vote up
def train(self, batch_size=32):
            # Train using replay experience
            minibatch = random.sample(self.memory, batch_size)
            for memory in minibatch:
                state, action, reward, state_next, done = memory
                # Build Q target:
                # -> Qtarget[!action] = Q[!action]
                #    Qtarget[action] = reward + gamma * max[a'](Q_next(state_next))
                Qtarget = self.model.predict(state)
                dQ = reward
                if not done:
                    dQ += self.gamma * np.amax(self.model.predict(state_next)[0])
                Qtarget[0][action] = dQ
                self.model.fit(state, Qtarget, epochs=1, verbose=0)

            # Decary exploration after training
            if self.epsilon > self.epsilon_min:
                self.epsilon *= self.epsilon_decay 
Example 14
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 15
Project: aboleth   Author: gradientinstitute   File: multi_input.py    License: Apache License 2.0 6 votes vote down vote up
def input_fn(df):
    """Format the downloaded data."""
    # Creates a dictionary mapping from each continuous feature column name (k)
    # to the values of that column stored in a constant Tensor.
    continuous_cols = [df[k].values for k in CONTINUOUS_COLUMNS]
    X_con = np.stack(continuous_cols).astype(np.float32).T

    # Standardise
    X_con -= X_con.mean(axis=0)
    X_con /= X_con.std(axis=0)

    # Creates a dictionary mapping from each categorical feature column name
    categ_cols = [np.where(pd.get_dummies(df[k]).values)[1][:, np.newaxis]
                  for k in CATEGORICAL_COLUMNS]
    n_values = [np.amax(c) + 1 for c in categ_cols]
    X_cat = np.concatenate(categ_cols, axis=1).astype(np.int32)

    # Converts the label column into a constant Tensor.
    label = df[LABEL_COLUMN].values[:, np.newaxis]

    # Returns the feature columns and the label.
    return X_con, X_cat, n_values, label 
Example 16
Project: SlowFast-Network-pytorch   Author: MagicChuyi   File: np_box_list_ops.py    License: MIT License 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example 17
Project: SlowFast-Network-pytorch   Author: MagicChuyi   File: np_box_mask_list_ops.py    License: MIT License 6 votes vote down vote up
def prune_non_overlapping_masks(box_mask_list1, box_mask_list2, minoverlap=0.0):
  """Prunes the boxes in list1 that overlap less than thresh with list2.

  For each mask in box_mask_list1, we want its IOA to be more than minoverlap
  with at least one of the masks in box_mask_list2. If it does not, we remove
  it. If the masks are not full size image, we do the pruning based on boxes.

  Args:
    box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks.
    box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned box_mask_list with size [N', 4].
  """
  intersection_over_area = ioa(box_mask_list2, box_mask_list1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_box_mask_list1 = gather(box_mask_list1, keep_inds)
  return new_box_mask_list1 
Example 18
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 19
Project: tf-pose   Author: SrikanthVelpuri   File: pose_dataset.py    License: Apache License 2.0 6 votes vote down vote up
def get_heatmap(self, target_size):
        heatmap = np.zeros((CocoMetadata.__coco_parts, self.height, self.width), dtype=np.float32)

        for joints in self.joint_list:
            for idx, point in enumerate(joints):
                if point[0] < 0 or point[1] < 0:
                    continue
                CocoMetadata.put_heatmap(heatmap, idx, point, self.sigma)

        heatmap = heatmap.transpose((1, 2, 0))

        # background
        heatmap[:, :, -1] = np.clip(1 - np.amax(heatmap, axis=2), 0.0, 1.0)

        if target_size:
            heatmap = cv2.resize(heatmap, target_size, interpolation=cv2.INTER_AREA)

        return heatmap.astype(np.float16) 
Example 20
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 21
Project: kitti-object-eval-python   Author: traveller59   File: kitti_common.py    License: MIT License 5 votes vote down vote up
def filter_kitti_anno(image_anno,
                      used_classes,
                      used_difficulty=None,
                      dontcare_iou=None):
    if not isinstance(used_classes, (list, tuple)):
        used_classes = [used_classes]
    img_filtered_annotations = {}
    relevant_annotation_indices = [
        i for i, x in enumerate(image_anno['name']) if x in used_classes
    ]
    for key in image_anno.keys():
        img_filtered_annotations[key] = (
            image_anno[key][relevant_annotation_indices])
    if used_difficulty is not None:
        relevant_annotation_indices = [
            i for i, x in enumerate(img_filtered_annotations['difficulty'])
            if x in used_difficulty
        ]
        for key in image_anno.keys():
            img_filtered_annotations[key] = (
                img_filtered_annotations[key][relevant_annotation_indices])

    if 'DontCare' in used_classes and dontcare_iou is not None:
        dont_care_indices = [
            i for i, x in enumerate(img_filtered_annotations['name'])
            if x == 'DontCare'
        ]
        # bounding box format [y_min, x_min, y_max, x_max]
        all_boxes = img_filtered_annotations['bbox']
        ious = iou(all_boxes, all_boxes[dont_care_indices])

        # Remove all bounding boxes that overlap with a dontcare region.
        if ious.size > 0:
            boxes_to_remove = np.amax(ious, axis=1) > dontcare_iou
            for key in image_anno.keys():
                img_filtered_annotations[key] = (img_filtered_annotations[key][
                    np.logical_not(boxes_to_remove)])
    return img_filtered_annotations 
Example 22
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 23
Project: pymoo   Author: msu-coinlab   File: rmetric.py    License: Apache License 2.0 5 votes vote down vote up
def _preprocess(self, data, ref_point, w_point):

        datasize = np.size(data, 0)

        # Identify representative point
        ref_matrix = np.tile(ref_point, (datasize, 1))
        w_matrix = np.tile(w_point, (datasize, 1))
        # ratio of distance to the ref point over the distance between the w_point and the ref_point
        diff_matrix = (data - ref_matrix) / (w_matrix - ref_matrix)
        agg_value = np.amax(diff_matrix, axis=1)
        idx = np.argmin(agg_value)
        zp = [data[idx, :]]

        return zp, 
Example 24
Project: pyscf   Author: pyscf   File: m_prod_basis_obsolete.py    License: Apache License 2.0 5 votes vote down vote up
def overlap_check(self, **kw):
    """ Our standard minimal check comparing with overlaps """
    sref = self.sv.overlap_coo(**kw).toarray()
    mom0,mom1 = self.comp_moments()
    vpab = self.get_ac_vertex_array()
    sprd = np.einsum('p,pab->ab', mom0,vpab)
    return [[abs(sref-sprd).sum()/sref.size, np.amax(abs(sref-sprd))]] 
Example 25
Project: pyscf   Author: pyscf   File: test_0095_h2_ae_rescf.py    License: Apache License 2.0 5 votes vote down vote up
def test_gw(self):
    """ This is GW """
    mol = gto.M( verbose = 0, atom = '''H 0.0 0.0 -0.3707;  H 0.0 0.0 0.3707''', basis = 'def2-TZVP',)
    gto_mf = scf.RHF(mol)#.density_fit()
    gto_mf.kernel()
    print('gto_mf.mo_energy:', gto_mf.mo_energy)
    s = nao(mf=gto_mf, gto=mol, verbosity=0)
    oref = s.overlap_coo().toarray()
    print('s.norbs:', s.norbs, oref.sum())

    pb = prod_basis(nao=s, algorithm='fp')
    pab2v = pb.get_ac_vertex_array()
    mom0,mom1=pb.comp_moments()
    orec = np.einsum('p,pab->ab', mom0, pab2v)
    print( abs(orec-oref).sum()/oref.size, np.amax(abs(orec-oref)) ) 
Example 26
Project: pyscf   Author: pyscf   File: prod_basis.py    License: Apache License 2.0 5 votes vote down vote up
def overlap_check(self, **kw):
    """ Our standard minimal check comparing with overlaps """
    sref = self.sv.overlap_coo(**kw).toarray()
    mom0,mom1 = self.comp_moments()
    vpab = self.get_ac_vertex_array()
    sprd = np.einsum('p,pab->ab', mom0,vpab)
    return [[abs(sref-sprd).sum()/sref.size, np.amax(abs(sref-sprd))]] 
Example 27
Project: NanoPlot   Author: wdecoster   File: timeplots.py    License: GNU General Public License v3.0 5 votes vote down vote up
def length_over_time(dfs, path, figformat, title, log_length=False, plot_settings={}):
    if log_length:
        time_length = Plot(path=path + "TimeLogLengthViolinPlot." + figformat,
                           title="Violin plot of log read lengths over time")
    else:
        time_length = Plot(path=path + "TimeLengthViolinPlot." + figformat,
                           title="Violin plot of read lengths over time")
    sns.set(style="white", **plot_settings)
    if log_length:
        length_column = "log_lengths"
    else:
        length_column = "lengths"

    if "length_filter" in dfs:  # produced by NanoPlot filtering of too long reads
        temp_dfs = dfs[dfs["length_filter"]]
    else:
        temp_dfs = dfs

    ax = sns.violinplot(x="timebin",
                        y=length_column,
                        data=temp_dfs,
                        inner=None,
                        cut=0,
                        linewidth=0)
    ax.set(xlabel='Interval (hours)',
           ylabel="Read length",
           title=title or time_length.title)
    if log_length:
        ticks = [10**i for i in range(10) if not 10**i > 10 * np.amax(dfs["lengths"])]
        ax.set(yticks=np.log10(ticks),
               yticklabels=ticks)
    plt.xticks(rotation=45, ha='center', fontsize=8)
    time_length.fig = ax.get_figure()
    time_length.save(format=figformat)
    plt.close("all")
    return time_length 
Example 28
Project: Mastering-Machine-Learning-Algorithms   Author: PacktPublishing   File: actor_critic_td0.py    License: MIT License 5 votes vote down vote up
def get_softmax_policy():
    softmax_policy = policy_importances - np.amax(policy_importances, axis=2, keepdims=True)
    return np.exp(softmax_policy) / np.sum(np.exp(softmax_policy), axis=2, keepdims=True) 
Example 29
def softmax(data):
    e = np.exp(data - np.amax(data, axis=-1, keepdims=True))
    s = np.sum(e, axis=-1, keepdims=True)
    return e / s 
Example 30
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)