Python numpy.argmin() Examples

The following are 30 code examples of numpy.argmin(). 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: TripletSampler.py    From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def hard_negative_multilabel(self):
        """Hard Negative Sampling based on multilabel assumption

        Search the negative sample with largest distance (smallest sim)
        with the anchor within self._k negative samplels
        """
        # During early iterations of sampling, use random sampling instead
        if self._iteration <= self._n:
            return self.random_multilabel()

        anchor_class_id, negative_class_id = np.random.choice(
            self._index.keys(), 2)
        anchor_id, positive_id = np.random.choice(
            self._index[anchor_class_id], 2)
        negative_ids = np.random.choice(
            self._index[negative_class_id], self._k)
        # calcualte the smallest simlarity one with negatives
        anchor_label = parse_label(self._labels[anchor_id])
        positive_label = parse_label(self._labels[positive_id])
        negative_labels = [parse_label(self._labels[negative_id]) for
                           negative_id in negative_ids]
        p_sim = intersect_sim(anchor_label, positive_label)
        n_sims = np.array(
            [intersect_sim(anchor_label, negative_label) for
             negative_label in negative_labels])
        min_sim_id = np.argmin(n_sims)
        negative_id = negative_ids[min_sim_id]
        n_sim = n_sims[min_sim_id]
        margin = p_sim - n_sim
        return (anchor_id, positive_id, negative_id, margin) 
Example #2
Source File: nsga3.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def get_extreme_points_c(F, ideal_point, extreme_points=None):
    # calculate the asf which is used for the extreme point decomposition
    weights = np.eye(F.shape[1])
    weights[weights == 0] = 1e6

    # add the old extreme points to never loose them for normalization
    _F = F
    if extreme_points is not None:
        _F = np.concatenate([extreme_points, _F], axis=0)

    # use __F because we substitute small values to be 0
    __F = _F - ideal_point
    __F[__F < 1e-3] = 0

    # update the extreme points for the normalization having the highest asf value each
    F_asf = np.max(__F * weights[:, None, :], axis=2)

    I = np.argmin(F_asf, axis=1)
    extreme_points = _F[I, :]

    return extreme_points 
Example #3
Source File: metrics.py    From DDPAE-video-prediction with MIT License 6 votes vote down vote up
def find_match(self, pred, gt):
    '''
    Match component to balls.
    '''
    batch_size, n_frames_input, n_components, _ = pred.shape
    diff = pred.reshape(batch_size, n_frames_input, n_components, 1, 2) - \
               gt.reshape(batch_size, n_frames_input, 1, n_components, 2)
    diff = np.sum(np.sum(diff ** 2, axis=-1), axis=1)
    # Direct indices
    indices = np.argmin(diff, axis=2)
    ambiguous = np.zeros(batch_size, dtype=np.int8)
    for i in range(batch_size):
      _, counts = np.unique(indices[i], return_counts=True)
      if not np.all(counts == 1):
        ambiguous[i] = 1
    return indices, ambiguous 
Example #4
Source File: Gradients.py    From sopt with MIT License 6 votes vote down vote up
def run(self):
        variables = self.init_variables
        self.s = np.zeros(self.variables_num)
        self.m = np.zeros(self.variables_num)
        for i in range(self.epochs):
            grads = gradients(self.func,variables)
            self.m = self.beta1*self.m +(1-self.beta1)*grads
            self.s = self.beta2*self.s + (1-self.beta2)*np.square(grads)
            self.m /= (1-self.beta1**(i+1))
            self.s /= (1-self.beta2**(i+1))
            if self.func_type == gradients_config.func_type_min:
                variables -= self.lr*self.m/(np.sqrt(self.s+self.eps))
            else:
                variables += self.lr*self.m/(np.sqrt(self.s+self.eps))
            self.generations_points.append(variables)
            self.generations_targets.append(self.func(variables))

        if self.func_type == gradients_config.func_type_min:
            self.global_best_target = np.min(np.array(self.generations_targets))
            self.global_best_index = np.argmin(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)]
        else:
            self.global_best_target = np.max(np.array(self.generations_targets))
            self.global_best_index = np.argmax(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)] 
Example #5
Source File: dataloader.py    From models with MIT License 6 votes vote down vote up
def _extract(self, intervals, out, **kwargs):

        def find_closest(ldm, interval, use_strand=True):
            """Uses
            """
            # subset the positions to the appropriate strand
            # and extract the positions
            ldm_positions = ldm.loc[interval.chrom]
            if use_strand and interval.strand != ".":
                ldm_positions = ldm_positions.loc[interval.strand]
            ldm_positions = ldm_positions.position.values

            int_midpoint = (interval.end + interval.start) // 2
            dist = (ldm_positions - 1) - int_midpoint  # -1 for 0, 1 indexed positions
            if use_strand and interval.strand == "-":
                dist = - dist

            return dist[np.argmin(np.abs(dist))]

        out[:] = np.array([[find_closest(self.landmarks[ldm_name], interval, self.use_strand)
                            for ldm_name in self.columns]
                           for interval in intervals], dtype=float)

        return out 
Example #6
Source File: stability.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def rohf_internal(mf, with_symmetry=True, verbose=None):
    log = logger.new_logger(mf, verbose)
    g, hop, hdiag = newton_ah.gen_g_hop_rohf(mf, mf.mo_coeff, mf.mo_occ,
                                             with_symmetry=with_symmetry)
    hdiag *= 2
    def precond(dx, e, x0):
        hdiagd = hdiag - e
        hdiagd[abs(hdiagd)<1e-8] = 1e-8
        return dx/hdiagd
    def hessian_x(x): # See comments in function rhf_internal
        return hop(x).real * 2

    x0 = numpy.zeros_like(g)
    x0[g!=0] = 1. / hdiag[g!=0]
    if not with_symmetry:  # allow to break point group symmetry
        x0[numpy.argmin(hdiag)] = 1
    e, v = lib.davidson(hessian_x, x0, precond, tol=1e-4, verbose=log)
    if e < -1e-5:
        log.note('ROHF wavefunction has an internal instability.')
        mo = _rotate_mo(mf.mo_coeff, mf.mo_occ, v)
    else:
        log.note('ROHF wavefunction is stable in the internal stability analysis')
        mo = mf.mo_coeff
    return mo 
Example #7
Source File: pseudo_weights.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, F, return_pseudo_weights=False, **kwargs):

        # here the normalized values are ignored but the ideal and nadir points are estimated to calculate trade-off
        _, norm, ideal_point, nadir_point = normalize(F, self.ideal_point, self.nadir_point,
                                                      estimate_bounds_if_none=True, return_bounds=True)

        # normalized distance to the worst solution
        pseudo_weights = ((nadir_point - F) / norm)

        # normalize weights to sum up to one
        pseudo_weights = pseudo_weights / np.sum(pseudo_weights, axis=1)[:, None]

        # search for the closest individual having this pseudo weights
        I = np.argmin(np.sum(np.abs(pseudo_weights - self.weights), axis=1))

        if return_pseudo_weights:
            return I, pseudo_weights
        else:
            return I 
Example #8
Source File: Gradients.py    From sopt with MIT License 6 votes vote down vote up
def run(self):
        variables = self.init_variables
        for i in range(self.epochs):
            grads = gradients(self.func,variables)
            if self.func_type == gradients_config.func_type_min:
                variables -= self.lr*grads
            else:
                variables += self.lr*grads
            self.generations_points.append(variables)
            self.generations_targets.append(self.func(variables))

        if self.func_type == gradients_config.func_type_min:
            self.global_best_target = np.min(np.array(self.generations_targets))
            self.global_best_index = np.argmin(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)]
        else:
            self.global_best_target = np.max(np.array(self.generations_targets))
            self.global_best_index = np.argmax(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)] 
Example #9
Source File: stability.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def ghf_stability(mf, verbose=None):
    log = logger.new_logger(mf, verbose)
    with_symmetry = True
    g, hop, hdiag = newton_ah.gen_g_hop_ghf(mf, mf.mo_coeff, mf.mo_occ,
                                            with_symmetry=with_symmetry)
    hdiag *= 2
    def precond(dx, e, x0):
        hdiagd = hdiag - e
        hdiagd[abs(hdiagd)<1e-8] = 1e-8
        return dx/hdiagd
    def hessian_x(x): # See comments in function rhf_internal
        return hop(x).real * 2

    x0 = numpy.zeros_like(g)
    x0[g!=0] = 1. / hdiag[g!=0]
    if not with_symmetry:  # allow to break point group symmetry
        x0[numpy.argmin(hdiag)] = 1
    e, v = lib.davidson(hessian_x, x0, precond, tol=1e-4, verbose=log)
    if e < -1e-5:
        log.note('GHF wavefunction has an internal instability')
        mo = _rotate_mo(mf.mo_coeff, mf.mo_occ, v)
    else:
        log.note('GHF wavefunction is stable in the internal stability analysis')
        mo = mf.mo_coeff
    return mo 
Example #10
Source File: mpi.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def work_balanced_partition(tasks, costs=None):
    if costs is None:
        costs = numpy.ones(tasks)
    if rank == 0:
        segsize = float(sum(costs)) / pool.size
        loads = []
        cum_costs = numpy.cumsum(costs)
        start_id = 0
        for k in range(pool.size):
            stop_id = numpy.argmin(abs(cum_costs - (k+1)*segsize)) + 1
            stop_id = max(stop_id, start_id+1)
            loads.append([start_id,stop_id])
            start_id = stop_id
        comm.bcast(loads)
    else:
        loads = comm.bcast()
    if rank < len(loads):
        start, stop = loads[rank]
        return tasks[start:stop]
    else:
        return tasks[:0] 
Example #11
Source File: SLSQPScheduler.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def whichTimeComesNext(self, absTs):
        """ Determine which absolute time comes next from current time
        Specifically designed to determine when the next local zodiacal light event occurs form fZQuads 
        Args:
            absTs (list) - the absolute times of different events (list of absolute times)
        Return:
            absT (astropy time quantity) - the absolute time which occurs next
        """
        TK = self.TimeKeeping
        #Convert Abs Times to norm Time
        tabsTs = list()
        for i in np.arange(len(absTs)):
            tabsTs.append((absTs[i] - TK.missionStart).value) # all should be in first year
        tSinceStartOfThisYear = TK.currentTimeNorm.copy().value%365.25
        if len(tabsTs) == len(np.where(tSinceStartOfThisYear < np.asarray(tabsTs))[0]): # time strictly less than all absTs
            absT = absTs[np.argmin(tabsTs)]
        elif len(tabsTs) == len(np.where(tSinceStartOfThisYear > np.asarray(tabsTs))[0]):
            absT = absTs[np.argmin(tabsTs)]
        else: #Some are above and some are below
            tmptabsTsInds = np.where(tSinceStartOfThisYear < np.asarray(tabsTs))[0]
            absT = absTs[np.argmin(np.asarray(tabsTs)[tmptabsTsInds])] # of times greater than current time, returns smallest

        return absT 
Example #12
Source File: Gradients.py    From sopt with MIT License 6 votes vote down vote up
def run(self):
        variables = self.init_variables
        self.s = np.zeros(self.variables_num)
        for i in range(self.epochs):
            grads = gradients(self.func,variables)
            self.s += np.square(grads)
            if self.func_type == gradients_config.func_type_min:
                variables -= self.lr*grads/(np.sqrt(self.s+self.eps))
            else:
                variables += self.lr*grads/(np.sqrt(self.s+self.eps))
            self.generations_points.append(variables)
            self.generations_targets.append(self.func(variables))

        if self.func_type == gradients_config.func_type_min:
            self.global_best_target = np.min(np.array(self.generations_targets))
            self.global_best_index = np.argmin(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)]
        else:
            self.global_best_target = np.max(np.array(self.generations_targets))
            self.global_best_index = np.argmax(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)] 
Example #13
Source File: Gradients.py    From sopt with MIT License 6 votes vote down vote up
def run(self):
        variables = self.init_variables
        self.s = np.zeros(self.variables_num)
        for i in range(self.epochs):
            grads = gradients(self.func,variables)
            self.s = self.beta*self.s + (1-self.beta)*np.square(grads)
            if self.func_type == gradients_config.func_type_min:
                variables -= self.lr*grads/(np.sqrt(self.s+self.eps))
            else:
                variables += self.lr*grads/(np.sqrt(self.s+self.eps))
            self.generations_points.append(variables)
            self.generations_targets.append(self.func(variables))

        if self.func_type == gradients_config.func_type_min:
            self.global_best_target = np.min(np.array(self.generations_targets))
            self.global_best_index = np.argmin(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)]
        else:
            self.global_best_target = np.max(np.array(self.generations_targets))
            self.global_best_index = np.argmax(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)] 
Example #14
Source File: pano_lsd_align.py    From HorizonNet with MIT License 5 votes vote down vote up
def assignVanishingType(lines, vp, tol, area=10):
    numLine = len(lines)
    numVP = len(vp)
    typeCost = np.zeros((numLine, numVP))
    # perpendicular
    for vid in range(numVP):
        cosint = (lines[:, :3] * vp[[vid]]).sum(1)
        typeCost[:, vid] = np.arcsin(np.abs(cosint).clip(-1, 1))

    # infinity
    u = np.stack([lines[:, 4], lines[:, 5]], -1)
    u = u.reshape(-1, 1) * 2 * np.pi - np.pi
    v = computeUVN_vec(lines[:, :3], u, lines[:, 3])
    xyz = uv2xyzN_vec(np.hstack([u, v]), np.repeat(lines[:, 3], 2))
    xyz = multi_linspace(xyz[0::2].reshape(-1), xyz[1::2].reshape(-1), 100)
    xyz = np.vstack([blk.T for blk in np.split(xyz, numLine)])
    xyz = xyz / np.linalg.norm(xyz, axis=1, keepdims=True)
    for vid in range(numVP):
        ang = np.arccos(np.abs((xyz * vp[[vid]]).sum(1)).clip(-1, 1))
        notok = (ang < area * np.pi / 180).reshape(numLine, 100).sum(1) != 0
        typeCost[notok, vid] = 100

    I = typeCost.min(1)
    tp = typeCost.argmin(1)
    tp[I > tol] = numVP + 1

    return tp, typeCost 
Example #15
Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_best_objval_and_solution(self):
        if len(self) > 0:
            idx = np.argmin(self._objvals)
            return float(self._objvals[idx]), np.copy(self._solutions[idx,])
        else:
            return np.empty(shape = 0), np.empty(shape = (0, P)) 
Example #16
Source File: eventrelated_utils.py    From NeuroKit with MIT License 5 votes vote down vote up
def _eventrelated_rate(epoch, output={}, var="ECG_Rate"):

    # Sanitize input
    colnames = epoch.columns.values
    if len([i for i in colnames if var in i]) == 0:
        print(
            "NeuroKit warning: *_eventrelated(): input does not"
            "have an `" + var + "` column. Will skip all rate-related features."
        )
        return output

    # Get baseline
    zero = find_closest(0, epoch.index.values, return_index=True)  # Find closest to 0
    baseline = epoch[var].iloc[zero]

    signal = epoch[var].values[zero + 1 : :]
    index = epoch.index.values[zero + 1 : :]

    # Max / Min / Mean
    output[var + "_Baseline"] = baseline
    output[var + "_Max"] = np.max(signal) - baseline
    output[var + "_Min"] = np.min(signal) - baseline
    output[var + "_Mean"] = np.mean(signal) - baseline

    # Time of Max / Min
    output[var + "_Max_Time"] = index[np.argmax(signal)]
    output[var + "_Min_Time"] = index[np.argmin(signal)]

    # Modelling
    # These are experimental indices corresponding to parameters of a quadratic model
    # Instead of raw values (such as min, max etc.)
    coefs = np.polyfit(index, signal - baseline, 2)
    output[var + "_Trend_Quadratic"] = coefs[0]
    output[var + "_Trend_Linear"] = coefs[1]
    output[var + "_Trend_R2"] = fit_r2(
        y=signal - baseline, y_predicted=np.polyval(coefs, index), adjusted=False, n_parameters=3
    )

    return output 
Example #17
Source File: ctaea.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def _associate(self, pop):
        """Associate each individual with a weight vector and calculate decomposed fitness"""
        F = pop.get("F")
        dist_matrix = self._calc_perpendicular_distance(F - self.ideal_point, self.ref_dirs)
        niche_of_individuals = np.argmin(dist_matrix, axis=1)
        FV = self._decomposition.do(F, weights=self.ref_dirs[niche_of_individuals, :],
                                    ideal_point=self.ideal_point, weight_0=1e-4)
        pop.set("niche", niche_of_individuals)
        pop.set("FV", FV)
        return niche_of_individuals, FV 
Example #18
Source File: m_x_zip.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def x_zip(n2e, na2x, eps, emax):
  """ Construct a 'presummed' set of eigenvectors, the effect must be a smaller number of eigenvectors """
  assert len(n2e.shape) == 1
  assert len(na2x.shape) == 2
  assert eps>0.0
  assert emax>0.0
  
  if len(np.where(n2e>emax)[0])==0: return n2e.size,[],[],n2e,na2x
    
  #print(__name__, max(n2e), emax)  
  vst = min(np.where(n2e>emax)[0])
  v2e = n2e[vst:]
  i2w,i2dos = ee2dos(v2e, eps) 
  j2e = detect_maxima(i2w, -i2dos.imag)
  nj = len(j2e)
  ja2x = np.zeros((len(j2e), na2x.shape[1]))
  for v,e in enumerate(n2e[vst:]):
    j = np.argmin(abs(j2e-e))

    # Sharing method: saved 16 out of 318 extra iterations caused by x-zip feature in case of Na20 chain.
    jp = j+1 if j<nj-1 else j
    jm = j-1 if j>0 else j
    if j2e[jm]<=e and e<=j2e[j]: 
      wj = (e-j2e[jm])/(j2e[j]-j2e[jm])
      ja2x[jm] += (1.0-wj)*na2x[vst+v]
      ja2x[j] += wj*na2x[vst+v]
      #print(v, 'share? -', jm, j, j2e[jm], e, j2e[j], wj, 1.0-wj)
    elif j2e[j]<=e and e<=j2e[jp]:
      wj = (j2e[jp]-e)/(j2e[jp]-j2e[j])
      ja2x[j] += wj*na2x[vst+v]
      ja2x[jp] += (1.0-wj)*na2x[vst+v]
      #print(v, 'share? + ', j, jp, j2e[j], e, j2e[jp], wj, 1.0-wj)
    else:
      #print(v, 'just sum', j2e[j], e)
      ja2x[j] += na2x[vst+v]

  m2e = concatenate((n2e[0:vst],j2e))
  ma2x = vstack((na2x[0:vst], ja2x))
  return vst,i2w,i2dos,m2e,ma2x 
Example #19
Source File: stability.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def rhf_external(mf, with_symmetry=True, verbose=None):
    log = logger.new_logger(mf, verbose)
    hop1, hdiag1, hop2, hdiag2 = _gen_hop_rhf_external(mf, with_symmetry)

    def precond(dx, e, x0):
        hdiagd = hdiag1 - e
        hdiagd[abs(hdiagd)<1e-8] = 1e-8
        return dx/hdiagd
    x0 = numpy.zeros_like(hdiag1)
    x0[hdiag1>1e-5] = 1. / hdiag1[hdiag1>1e-5]
    if not with_symmetry:  # allow to break point group symmetry
        x0[numpy.argmin(hdiag1)] = 1
    e1, v1 = lib.davidson(hop1, x0, precond, tol=1e-4, verbose=log)
    if e1 < -1e-5:
        log.note('RHF/RKS wavefunction has a real -> complex instability')
    else:
        log.note('RHF/RKS wavefunction is stable in the real -> complex stability analysis')

    def precond(dx, e, x0):
        hdiagd = hdiag2 - e
        hdiagd[abs(hdiagd)<1e-8] = 1e-8
        return dx/hdiagd
    x0 = v1
    e3, v3 = lib.davidson(hop2, x0, precond, tol=1e-4, verbose=log)
    if e3 < -1e-5:
        log.note('RHF/RKS wavefunction has a RHF/RKS -> UHF/UKS instability.')
        mo = (_rotate_mo(mf.mo_coeff, mf.mo_occ, v3), mf.mo_coeff)
    else:
        log.note('RHF/RKS wavefunction is stable in the RHF/RKS -> UHF/UKS stability analysis')
        mo = (mf.mo_coeff, mf.mo_coeff)
    return mo 
Example #20
Source File: stability.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def rhf_internal(mf, with_symmetry=True, verbose=None):
    log = logger.new_logger(mf, verbose)
    g, hop, hdiag = newton_ah.gen_g_hop_rhf(mf, mf.mo_coeff, mf.mo_occ,
                                            with_symmetry=with_symmetry)
    hdiag *= 2
    def precond(dx, e, x0):
        hdiagd = hdiag - e
        hdiagd[abs(hdiagd)<1e-8] = 1e-8
        return dx/hdiagd
    # The results of hop(x) corresponds to a displacement that reduces
    # gradients g.  It is the vir-occ block of the matrix vector product
    # (Hessian*x). The occ-vir block equals to x2.T.conj(). The overall
    # Hessian for internal reotation is x2 + x2.T.conj(). This is
    # the reason we apply (.real * 2) below
    def hessian_x(x):
        return hop(x).real * 2

    x0 = numpy.zeros_like(g)
    x0[g!=0] = 1. / hdiag[g!=0]
    if not with_symmetry:  # allow to break point group symmetry
        x0[numpy.argmin(hdiag)] = 1
    e, v = lib.davidson(hessian_x, x0, precond, tol=1e-4, verbose=log)
    if e < -1e-5:
        log.note('RHF/RKS wavefunction has an internal instability')
        mo = _rotate_mo(mf.mo_coeff, mf.mo_occ, v)
    else:
        log.note('RHF/RKS wavefunction is stable in the internal stability analysis')
        mo = mf.mo_coeff
    return mo 
Example #21
Source File: kccsd_rhf.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def leaccsd(self, nroots=2*4, kptlist=None):
        time0 = time.clock(), time.time()
        log = logger.Logger(self.stdout, self.verbose)
        nocc = self.nocc
        nvir = self.nmo - nocc
        nkpts = self.nkpts
        if kptlist is None:
            kptlist = range(nkpts)
        size = self.vector_size_ea()
        for k,kshift in enumerate(kptlist):
            self.kshift = kshift
            nfrozen = np.sum(self.mask_frozen_ea(np.zeros(size, dtype=int), kshift, const=1))
            nroots = min(nroots, size - nfrozen)
        evals = np.zeros((len(kptlist),nroots), np.float)
        evecs = np.zeros((len(kptlist),nroots,size), np.complex)

        for k,kshift in enumerate(kptlist):
            self.kshift = kshift
            diag = self.eaccsd_diag()
            precond = lambda dx, e, x0: dx/(diag-e)
            # Initial guess from file
            amplitude_filename = "__leaccsd" + str(kshift) + "__.hdf5"
            rsuccess, x0 = read_eom_amplitudes((nroots,size),filename=amplitude_filename)
            if x0 is not None:
                x0 = x0.T
            #if not rsuccess:
            #    x0 = np.zeros_like(diag)
            #    x0[np.argmin(diag)] = 1.0

            conv, evals_k, evecs_k = eigs(self.leaccsd_matvec, size, nroots, x0=x0, Adiag=diag, verbose=self.verbose)

            evals_k = evals_k.real
            evals[k] = evals_k
            evecs[k] = evecs_k.T

            write_eom_amplitudes(evecs[k],amplitude_filename)
        time0 = log.timer_debug1('converge lea-ccsd', *time0)
        comm.Barrier()
        return evals.real, evecs 
Example #22
Source File: ctaea.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def _updateDA(self, pop, Hd, n_survive):
        """Update the Diversity archive (DA)"""
        niche_Hd, FV = self._associate(Hd)
        niche_CA, _ = self._associate(pop)

        itr = 1
        S = []
        while len(S) < n_survive:
            for i in range(n_survive):
                current_ca, = np.where(niche_CA == i)
                if len(current_ca) < itr:
                    for _ in range(itr - len(current_ca)):
                        current_da = np.where(niche_Hd == i)[0]
                        if current_da.size > 0:
                            F = Hd[current_da].get('F')
                            nd = NonDominatedSorting().do(F, only_non_dominated_front=True, n_stop_if_ranked=0)
                            i_best = current_da[nd[np.argmin(FV[current_da[nd]])]]
                            niche_Hd[i_best] = -1
                            if len(S) < n_survive:
                                S.append(i_best)
                        else:
                            break
                if len(S) == n_survive:
                    break
            itr += 1
        return Hd[S] 
Example #23
Source File: kccsd_rhf.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def eaccsd(self, nroots=2*4, kptlist=None):
        time0 = time.clock(), time.time()
        log = logger.Logger(self.stdout, self.verbose)
        nocc = self.nocc
        nvir = self.nmo - nocc
        nkpts = self.nkpts
        if kptlist is None:
            kptlist = range(nkpts)
        size = self.vector_size_ea()
        for k,kshift in enumerate(kptlist):
            self.kshift = kshift
            nfrozen = np.sum(self.mask_frozen_ea(np.zeros(size, dtype=int), kshift, const=1))
            nroots = min(nroots, size - nfrozen)
        evals = np.zeros((len(kptlist),nroots), np.float)
        evecs = np.zeros((len(kptlist),nroots,size), np.complex)

        for k,kshift in enumerate(kptlist):
            self.kshift = kshift
            diag = self.eaccsd_diag()
            diag = self.mask_frozen_ea(diag, kshift, const=LARGE_DENOM)
            precond = lambda dx, e, x0: dx/(diag-e)
            # Initial guess from file
            amplitude_filename = "__reaccsd" + str(kshift) + "__.hdf5"
            rsuccess, x0 = read_eom_amplitudes((nroots,size),filename=amplitude_filename)
            if x0 is not None:
                x0 = x0.T
            #if not rsuccess:
            #    x0 = np.zeros_like(diag)
            #    x0[np.argmin(diag)] = 1.0

            conv, evals_k, evecs_k = eigs(self.eaccsd_matvec, size, nroots, x0=x0, Adiag=diag, verbose=self.verbose)

            evals_k = evals_k.real
            evals[k] = evals_k
            evecs[k] = evecs_k.T

            write_eom_amplitudes(evecs[k],filename=amplitude_filename)
        time0 = log.timer_debug1('converge ea-ccsd', *time0)
        comm.Barrier()
        return evals.real, evecs 
Example #24
Source File: nsga3.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def _set_optimum(self, **kwargs):
        if not has_feasible(self.pop):
            self.opt = self.pop[[np.argmin(self.pop.get("CV"))]]
        else:
            self.opt = self.survival.opt 
Example #25
Source File: algorithm.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def filter_optimum(pop, least_infeasible=False):
    # first only choose feasible solutions
    ret = pop[pop.get("feasible")[:, 0]]

    # if at least one feasible solution was found
    if len(ret) > 0:

        # then check the objective values
        F = ret.get("F")

        if F.shape[1] > 1:
            I = NonDominatedSorting().do(F, only_non_dominated_front=True)
            ret = ret[I]

        else:
            ret = ret[np.argmin(F)]

    # no feasible solution was found
    else:
        # if flag enable report the least infeasible
        if least_infeasible:
            ret = pop[np.argmin(pop.get("CV"))]
        # otherwise just return none
        else:
            ret = None

    if isinstance(ret, Individual):
        ret = Population().create(ret)

    return ret 
Example #26
Source File: GA.py    From sopt with MIT License 5 votes vote down vote up
def run(self):
        self.init_population()
        for i in range(self.generations):
            self.select(complex_constraints=self.complex_constraints,complex_constraints_C=self.complex_constraints_C,M=self.M)
            self.cross()
            self.mutate()
            if self.code_type == code_type.real:
                self.calculate(self.population,self.population,complex_constraints=self.complex_constraints,complex_constraints_C=self.complex_constraints_C)
            else:
                self.calculate(self.population,complex_constraints=self.complex_constraints,complex_constraints_C=self.complex_constraints_C)
            if self.select_method == select_method.keep_best:
                if self.code_type == code_type.real:
                    real_population = self.population
                elif self.code_type == code_type.binary:
                    real_population = self._convert_binary_to_real(self.population,self.cross_code)
                else:
                    population = self._convert_gray_to_binary(self.population,self.cross_code)
                    real_population = self._convert_binary_to_real(population)
                targets_func = np.zeros(self.population_size)
                for i in range(self.population_size):
                    targets_func[i] = self.func(real_population[i])
                    if self.complex_constraints:
                        tmp_plus = self._check_constraints(real_population[i],self.complex_constraints)
                        if self.func_type == ga_config.func_type_min:
                            targets_func[i] += tmp_plus
                        else:
                            targets_func -= tmp_plus
                if self.func_type == ga_config.func_type_min:
                    worst_target_index = np.argmax(targets_func)
                else:
                    worst_target_index = np.argmin(targets_func)
                self.population[worst_target_index] = self.global_best_raw_point
            self.global_generations_step += 1

        if self.func_type == ga_config.func_type_min:
            self.global_best_index = np.array(self.generations_best_targets).argmin()
        else:
            self.global_best_index = np.array(self.generations_best_targets).argmax() 
Example #27
Source File: Newton.py    From sopt with MIT License 5 votes vote down vote up
def run(self):
        B = np.eye(self.variables_num, self.variables_num)
        x = self.init_variables.reshape(-1, 1)
        iteration = 0
        for i in range(self.epochs):
            g1 = gradients(self.func, x.flatten()).reshape((self.variables_num, 1))
            d = linalg.inv(B).dot(g1)  # D is approximately equals to Hessain Matrix
            best_step = self.find_best_step(x, d)
            s = best_step * d
            x -= s
            iteration += 1
            g2 = gradients(self.func, x.flatten()).reshape((self.variables_num, 1))
            if np.sqrt((g2 ** 2).sum()) < self.eps:
                break
            y = g2 - g1
            # update D
            B += y.dot(y.T) / ((y.T).dot(s)) - (B.dot(s).dot(s.T).dot(B)) / (s.T.dot(B).dot(s))
            self.generations_points.append(x.flatten())
            self.generations_targets.append(self.func(x.flatten()))

        if self.func_type == newton_config.func_type_min:
            self.global_best_target = np.min(np.array(self.generations_targets))
            self.global_best_index = np.argmin(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)]
        else:
            self.global_best_target = np.max(np.array(self.generations_targets))
            self.global_best_index = np.argmax(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)] 
Example #28
Source File: Newton.py    From sopt with MIT License 5 votes vote down vote up
def run(self):
        D = np.eye(self.variables_num,self.variables_num)
        x = self.init_variables.reshape(-1,1)
        iteration = 0
        for i in range(self.epochs):
            g1 = gradients(self.func,x.flatten()).reshape((self.variables_num,1))
            d = D.dot(g1) # D is approximately equals to Hessain Matrix
            best_step = self.find_best_step(x,d)
            s = best_step * d
            x -= s
            iteration += 1
            g2 = gradients(self.func,x.flatten()).reshape((self.variables_num,1))
            if np.sqrt((g2 ** 2).sum()) < self.eps:
                break
            y = g2 - g1
            # update D
            D += s.dot(s.T) / ((s.T).dot(y)) - D.dot(y).dot(y.T).dot(D) / ((y.T).dot(D).dot(y))
            self.generations_points.append(x.flatten())
            self.generations_targets.append(self.func(x.flatten()))


        if self.func_type == newton_config.func_type_min:
            self.global_best_target = np.min(np.array(self.generations_targets))
            self.global_best_index = np.argmin(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)]
        else:
            self.global_best_target = np.max(np.array(self.generations_targets))
            self.global_best_index = np.argmax(np.array(self.generations_targets))
            self.global_best_point = self.generations_points[int(self.global_best_index)] 
Example #29
Source File: k_means.py    From differential-privacy-library with MIT License 5 votes vote down vote up
def _distances_labels(self, X, centers):
        distances = np.zeros((X.shape[0], self.n_clusters))

        for cluster in range(self.n_clusters):
            distances[:, cluster] = ((X - centers[cluster, :]) ** 2).sum(axis=1)

        labels = np.argmin(distances, axis=1)
        return distances, labels 
Example #30
Source File: bbox_transform.py    From ICDAR-2019-SROIE with MIT License 5 votes vote down vote up
def bbox_transform(ex_rois, gt_rois):
    """
    computes the distance from ground-truth boxes to the given boxes, normed by their size
    :param ex_rois: n * 4 numpy array, given boxes
    :param gt_rois: n * 4 numpy array, ground-truth boxes
    :return: deltas: n * 4 numpy array, ground-truth boxes
    """
    ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0
    ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0
    ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths
    ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights

    assert np.min(ex_widths) > 0.1 and np.min(ex_heights) > 0.1, \
        'Invalid boxes found: {} {}'.format(ex_rois[np.argmin(ex_widths), :], ex_rois[np.argmin(ex_heights), :])

    gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0
    gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0
    gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths
    gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights

    # warnings.catch_warnings()
    # warnings.filterwarnings('error')
    targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths
    targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights
    targets_dw = np.log(gt_widths / ex_widths)
    targets_dh = np.log(gt_heights / ex_heights)

    targets = np.vstack(
        (targets_dx, targets_dy, targets_dw, targets_dh)).transpose()

    return targets