static void newton(mpf_t x, double seed, fun_3term *fun, fun_3term *der, int n) { DECLARE_3VARS(ox,f,df); mpf_set_d(x, seed); do { mpf_set(ox, x); fun(f, n,x), der(df, n,x), mpf_div(f, f,df), mpf_sub(x, x,f); } while(!is_small(f,x)); fun( f, n,x), der(df, n,x), mpf_div(f, f,df), mpf_sub(x, x,f); }
double DistanceFromContour::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { Vector distance = getSeparation( getPosition(getNumberOfAtoms()-1), myatoms.getPosition(0) ); std::vector<double> pp(3), der(3,0); for(unsigned j=0;j<3;++j) pp[j] = distance[j]; // Now create the kernel and evaluate KernelFunctions kernel( pp, bw, kerneltype, false, 1.0, true ); double newval = kernel.evaluate( pval, der, true ); if( mybasemulticolvars[0]->isDensity() ){ if( !doNotCalculateDerivatives() && derivTime ){ MultiValue& myvals=myatoms.getUnderlyingMultiValue(); Vector vder; unsigned basen=myvals.getNumberOfDerivatives() - 12; for(unsigned i=0;i<3;++i){ vder[i]=der[i]; myvals.addDerivative( 1, basen+i, vder[i] ); } myatoms.setValue( 2, der[dir] ); addAtomDerivatives( 1, 0, -vder, myatoms ); myatoms.addBoxDerivatives( 1, Tensor(vder,distance) ); } myatoms.setValue( 0, 1.0 ); return newval; } // This does the stuff for averaging myatoms.setValue( 0, newval ); // This gets the average if we are using a phase field std::vector<double> cvals( mybasemulticolvars[0]->getNumberOfQuantities() ); mybasedata[0]->retrieveValueWithIndex( tindex, false, cvals ); return newval*cvals[0]*cvals[1]; }
CertificateCollection qca_get_systemstore(const QString &provider) { CertificateCollection col; HCERTSTORE hSystemStore; hSystemStore = CertOpenSystemStoreA(0, "ROOT"); if(!hSystemStore) return col; PCCERT_CONTEXT pc = NULL; while(1) { pc = CertFindCertificateInStore( hSystemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, pc); if(!pc) break; int size = pc->cbCertEncoded; QByteArray der(size, 0); memcpy(der.data(), pc->pbCertEncoded, size); Certificate cert = Certificate::fromDER(der, 0, provider); if(!cert.isNull()) col.addCertificate(cert); } CertCloseStore(hSystemStore, 0); return col; }
SX Variable::highest() const{ if(isDifferential()){ return der(); } else { return var(); } }
/* * BER encode a PKCS #8 private key, encrypted */ std::vector<uint8_t> BER_encode_encrypted_pbkdf_iter(const Private_Key& key, RandomNumberGenerator& rng, const std::string& pass, size_t pbkdf_iterations, const std::string& cipher, const std::string& pbkdf_hash) { #if defined(BOTAN_HAS_PKCS5_PBES2) const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info = pbes2_encrypt_iter(key.private_key_info(), pass, pbkdf_iterations, cipher.empty() ? "AES-256/CBC" : cipher, pbkdf_hash.empty() ? "SHA-256" : pbkdf_hash, rng); std::vector<uint8_t> output; DER_Encoder der(output); der.start_cons(SEQUENCE) .encode(pbe_info.first) .encode(pbe_info.second, OCTET_STRING) .end_cons(); return output; #else BOTAN_UNUSED(key, rng, pass, pbkdf_iterations, cipher, pbkdf_hash); throw Encoding_Error("PKCS8::BER_encode_encrypted_pbkdf_iter cannot encrypt because PBES2 disabled in build"); #endif }
Function Switch ::get_forward(casadi_int nfwd, const std::string& name, const std::vector<std::string>& inames, const std::vector<std::string>& onames, const Dict& opts) const { // Derivative of each case vector<Function> der(f_.size()); for (casadi_int k=0; k<f_.size(); ++k) { if (!f_[k].is_null()) der[k] = f_[k].forward(nfwd); } // Default case Function der_def; if (!f_def_.is_null()) der_def = f_def_.forward(nfwd); // New Switch for derivatives Function sw = Function::conditional("switch_" + name, der, der_def); // Get expressions for the derivative switch vector<MX> arg = sw.mx_in(); vector<MX> res = sw(arg); // Ignore seed for ind arg.insert(arg.begin() + n_in_ + n_out_, MX(1, nfwd)); // Create wrapper return Function(name, arg, res, inames, onames, opts); }
Function Switch ::get_reverse(casadi_int nadj, const std::string& name, const std::vector<std::string>& inames, const std::vector<std::string>& onames, const Dict& opts) const { // Derivative of each case vector<Function> der(f_.size()); for (casadi_int k=0; k<f_.size(); ++k) { if (!f_[k].is_null()) der[k] = f_[k].reverse(nadj); } // Default case Function der_def; if (!f_def_.is_null()) der_def = f_def_.reverse(nadj); // New Switch for derivatives Function sw = Function::conditional("switch_" + name, der, der_def); // Get expressions for the derivative switch vector<MX> arg = sw.mx_in(); vector<MX> res = sw(arg); // No derivatives with respect to index res.insert(res.begin(), MX(1, nadj)); // Create wrapper return Function(name, arg, res, inames, onames, opts); }
/* * BER encode a PKCS #8 private key, encrypted */ std::vector<uint8_t> BER_encode(const Private_Key& key, RandomNumberGenerator& rng, const std::string& pass, std::chrono::milliseconds msec, const std::string& pbe_algo) { #if defined(BOTAN_HAS_PKCS5_PBES2) const auto pbe_params = choose_pbe_params(pbe_algo, key.algo_name()); const std::pair<AlgorithmIdentifier, std::vector<uint8_t>> pbe_info = pbes2_encrypt_msec(PKCS8::BER_encode(key), pass, msec, nullptr, pbe_params.first, pbe_params.second, rng); std::vector<uint8_t> output; DER_Encoder der(output); der.start_cons(SEQUENCE) .encode(pbe_info.first) .encode(pbe_info.second, OCTET_STRING) .end_cons(); return output; #else BOTAN_UNUSED(key, rng, pass, msec, pbe_algo); throw Encoding_Error("PKCS8::BER_encode cannot encrypt because PBES2 was disabled in build"); #endif }
Variable::Variable(const string& name, bool create_expression){ assignNode(new VariableInternal(name)); if(create_expression){ setExpression(SX(name)); setDerivative(SX("der_" + name)); setBinding(var(),false); setBinding(der(),true); } }
void supder(abin *A){ abin aux; aux=der(*A); if(!esVacio(aux)){ supizq(&aux); supder(&aux); (*A)->der=NULL; free(aux); } }
Function SwitchInternal ::getDerReverse(const std::string& name, int nadj, Dict& opts) { // Derivative of each case vector<Function> der(f_.size()); for (int k=0; k<f_.size(); ++k) { if (!f_[k].isNull()) der[k] = f_[k].derReverse(nadj); } // Default case Function der_def; if (!f_def_.isNull()) der_def = f_def_.derReverse(nadj); // New Switch for derivatives stringstream ss; ss << "adj" << nadj << "_" << name_; Switch sw(ss.str(), der, der_def); // Construct wrapper inputs and arguments for calling sw vector<MX> arg = symbolicInput(); vector<MX> res = symbolicOutput(); vector<vector<MX> > seed = symbolicAdjSeed(nadj, res); vector<MX> w_in = arg; w_in.insert(w_in.end(), res.begin(), res.end()); // Arguments for calling sw being constructed vector<MX> v; v.push_back(arg.at(0)); // index for (int d=0; d<nadj; ++d) { // Add to wrapper input w_in.insert(w_in.end(), seed[d].begin(), seed[d].end()); // Add to sw argument vector v.insert(v.end(), arg.begin()+1, arg.end()); v.insert(v.end(), res.begin(), res.end()); v.insert(v.end(), seed[d].begin(), seed[d].end()); } // Construct wrapper outputs casadi_assert(v.size()==sw.nIn()); v = sw(v); vector<MX> w_out; MX ind_sens = MX(1, 1); // no dependency on index vector<MX>::const_iterator v_it = v.begin(), v_it_next; for (int d=0; d<nadj; ++d) { w_out.push_back(ind_sens); v_it_next = v_it + (nIn()-1); w_out.insert(w_out.end(), v_it, v_it_next); v_it = v_it_next; } // Create wrapper return MXFunction(name, w_in, w_out, opts); }
bool EciesHelper::Decrypt(const ByteArray &chiper, ByteArray &plain) { assert (valid_); try { DER der(chiper); ECIES decrypt = der.toECIES(); OCTETSTR temp = decrypt.decrypt(*sk_); plain = toByteArray(temp); return true; } catch (borzoiException e) { //e.debug_print (); return false; } }
bool EciesHelper::Encrypt(const ByteArray &plain, ByteArray &chipher) { assert (valid_); try { ECIES enc(const_cast<ByteArray&>(plain), *pk_); DER der(enc); HexEncoder hex(der); const std::string s = to_str(hex); chipher = ByteArray::fromHexStr(s); return true; } catch (borzoiException e) { return false; } }
/*! \internal Returns a PEM key formatted as DER. */ QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem, QMap<QByteArray, QByteArray> *headers) const { const QByteArray header = pemHeader(); const QByteArray footer = pemFooter(); QByteArray der(pem); const int headerIndex = der.indexOf(header); const int footerIndex = der.indexOf(footer); if (headerIndex == -1 || footerIndex == -1) return QByteArray(); der = der.mid(headerIndex + header.size(), footerIndex - (headerIndex + header.size())); if (der.contains("Proc-Type:")) { // taken from QHttpNetworkReplyPrivate::parseHeader const QByteArrayMatcher lf("\n"); const QByteArrayMatcher colon(":"); int i = 0; while (i < der.count()) { int j = colon.indexIn(der, i); // field-name if (j == -1) break; const QByteArray field = der.mid(i, j - i).trimmed(); j++; // any number of LWS is allowed before and after the value QByteArray value; do { i = lf.indexIn(der, j); if (i == -1) break; if (!value.isEmpty()) value += ' '; // check if we have CRLF or only LF bool hasCR = (i && der[i-1] == '\r'); int length = i -(hasCR ? 1: 0) - j; value += der.mid(j, length).trimmed(); j = ++i; } while (i < der.count() && (der.at(i) == ' ' || der.at(i) == '\t')); if (i == -1) break; // something is wrong headers->insert(field, value); } der = der.mid(i); } return QByteArray::fromBase64(der); // ignores newlines }
/*! \internal Returns a PEM key formatted as DER. */ QByteArray QSslKeyPrivate::derFromPem(const QByteArray &pem) const { const QByteArray header = pemHeader(); const QByteArray footer = pemFooter(); QByteArray der(pem); const int headerIndex = der.indexOf(header); const int footerIndex = der.indexOf(footer); if (headerIndex == -1 || footerIndex == -1) return QByteArray(); der = der.mid(headerIndex + header.size(), footerIndex - (headerIndex + header.size())); return QByteArray::fromBase64(der); // ignores newlines }
/** Used by the GSL to calculate the derivatives. * @param x :: Vector with parameters * @param params :: Pointer to a DerivMinimizer * @param g :: Buffer for the derivatives */ void DerivMinimizer::dfun(const gsl_vector *x, void *params, gsl_vector *g) { DerivMinimizer &minimizer = *static_cast<DerivMinimizer *>(params); size_t n = minimizer.m_costFunction->nParams(); for (size_t i = 0; i < n; ++i) { minimizer.m_costFunction->setParameter(i, gsl_vector_get(x, i)); } boost::shared_ptr<CostFunctions::CostFuncFitting> fitting = boost::dynamic_pointer_cast<CostFunctions::CostFuncFitting>( minimizer.m_costFunction); if (fitting) { fitting->getFittingFunction()->applyTies(); } std::vector<double> der(n); minimizer.m_costFunction->deriv(der); for (size_t i = 0; i < n; ++i) { gsl_vector_set(g, i, der[i]); } }
ptr_lib::shared_ptr<PublicKey> FilePrivateKeyStorage::getPublicKey(const Name& keyName) { string keyURI = keyName.toUri(); if (!doesKeyExist(keyName, KEY_CLASS_PUBLIC)) throw SecurityException("Public Key does not exist."); ifstream file(nameTransform(keyURI, ".pub").c_str()); stringstream base64; base64 << file.rdbuf(); // Use a vector in a shared_ptr so we can make it a Blob without copying. ptr_lib::shared_ptr<vector<uint8_t> > der(new vector<uint8_t>()); fromBase64(base64.str(), *der); Blob derBlob(der, false); return ptr_lib::shared_ptr<PublicKey>(new PublicKey(derBlob)); }
Function SwitchInternal ::getDerForward(const std::string& name, int nfwd, Dict& opts) { // Derivative of each case vector<Function> der(f_.size()); for (int k=0; k<f_.size(); ++k) { if (!f_[k].isNull()) der[k] = f_[k].derForward(nfwd); } // Default case Function der_def; if (!f_def_.isNull()) der_def = f_def_.derForward(nfwd); // New Switch for derivatives stringstream ss; ss << "fwd" << nfwd << "_" << name_; Switch sw(ss.str(), der, der_def); // Construct wrapper inputs and arguments for calling sw vector<MX> arg = symbolicInput(); vector<MX> res = symbolicOutput(); vector<vector<MX> > seed = symbolicFwdSeed(nfwd, arg); // Wrapper input being constructed vector<MX> w_in = arg; w_in.insert(w_in.end(), res.begin(), res.end()); // Arguments for calling sw being constructed vector<MX> v; v.insert(v.end(), arg.begin(), arg.end()); v.insert(v.end(), res.begin(), res.end()); for (int d=0; d<nfwd; ++d) { // ignore seed for ind seed[d][0] = MX::sym(seed[d][0].getName(), Sparsity::scalar(false)); // Add to wrapper input w_in.insert(w_in.end(), seed[d].begin(), seed[d].end()); // Add to sw argument vector v.insert(v.end(), seed[d].begin()+1, seed[d].end()); } // Create wrapper casadi_assert(v.size()==sw.nIn()); return MXFunction(name, w_in, sw(v), opts); }
Document *DocumentBuilder::parse(InputSource *is, const char *codepage) { const byte *bytes = is->openStream(); int length = is->length(); DefaultEntityResolver der(is); EntityResolver *old_er = er; Document *_doc = null; er = &der; try{ _doc = parse(bytes, length, codepage); }catch(ParseException &e){ er = old_er; is->closeStream(); throw e; } er = old_er; is->closeStream(); return _doc; }
static PyObject *dtw_der(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *x = NULL; PyObject *x_a = NULL; PyObject *out_a = NULL; npy_intp out_dims[1]; npy_intp n; double *out_v, *x_v; /* Parse Tuple*/ static char *kwlist[] = {"x", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "O", kwlist, &x)) return NULL; x_a = PyArray_FROM_OTF(x, NPY_DOUBLE, NPY_IN_ARRAY); if (x_a == NULL) return NULL; if (PyArray_NDIM(x_a) != 1){ PyErr_SetString(PyExc_ValueError, "x should be 1D numpy array or list"); return NULL; } x_v = (double *) PyArray_DATA(x_a); n = (int) PyArray_DIM(x_a, 0); out_dims[0] = (npy_intp) n; out_a = PyArray_SimpleNew(1, out_dims, NPY_DOUBLE); out_v = (double *) PyArray_DATA(out_a); der(x_v, n, out_v); Py_DECREF(x_a); return Py_BuildValue("N", out_a); }
void BiasRepresentation::pushKernel( IFile *ifile ){ KernelFunctions *kk; // here below the reading of the kernel is completely hidden if(histosigma.size()==0){ ifile->allowIgnoredFields(); kk=KernelFunctions::read(ifile,names) ; }else{ // when doing histogram assume gaussian with a given diagonal sigma // and neglect all the rest kk=readFromPoint(ifile) ; } hills.push_back(kk); // the bias factor is not something about the kernels but // must be stored to keep the bias/free energy duality string dummy; double dummyd; if(ifile->FieldExist("biasf")){ ifile->scanField("biasf",dummy); Tools::convert(dummy,dummyd); }else{dummyd=1.0;} biasf.push_back(dummyd); // the domain does not pertain to the kernel but to the values here defined string mins,maxs,minv,maxv,mini,maxi;mins="min_";maxs="max_"; for(int i=0 ; i<ndim; i++){ if(values[i]->isPeriodic()){ ifile->scanField(mins+names[i],minv); ifile->scanField(maxs+names[i],maxv); // verify that the domain is correct values[i]->getDomain(mini,maxi); plumed_massert(mini==minv,"the input periodicity in hills and in value definition does not match" ); plumed_massert(maxi==maxv,"the input periodicity in hills and in value definition does not match" ); } } // if grid is defined then it should be added on the grid //cerr<<"now with "<<hills.size()<<endl; if(hasgrid){ vector<unsigned> nneighb=kk->getSupport(BiasGrid_->getDx()); vector<unsigned> neighbors=BiasGrid_->getNeighbors(kk->getCenter(),nneighb); vector<double> der(ndim); vector<double> xx(ndim); if(mycomm.Get_size()==1){ for(unsigned i=0;i<neighbors.size();++i){ unsigned ineigh=neighbors[i]; for(int j=0;j<ndim;++j){der[j]=0.0;} BiasGrid_->getPoint(ineigh,xx); // assign xx to a new vector of values for(int j=0;j<ndim;++j){values[j]->set(xx[j]);} double bias=kk->evaluate(values,der,true); if(rescaledToBias){ double f=(biasf.back()-1.)/(biasf.back()); bias*=f; for(int j=0;j<ndim;++j){der[j]*=f;} } BiasGrid_->addValueAndDerivatives(ineigh,bias,der); } } else { unsigned stride=mycomm.Get_size(); unsigned rank=mycomm.Get_rank(); vector<double> allder(ndim*neighbors.size(),0.0); vector<double> allbias(neighbors.size(),0.0); vector<double> tmpder(ndim); for(unsigned i=rank;i<neighbors.size();i+=stride){ unsigned ineigh=neighbors[i]; BiasGrid_->getPoint(ineigh,xx); for(int j=0;j<ndim;++j){values[j]->set(xx[j]);} allbias[i]=kk->evaluate(values,tmpder,true); if(rescaledToBias){ double f=(biasf.back()-1.)/(biasf.back()); allbias[i]*=f; for(int j=0;j<ndim;++j){tmpder[j]*=f;} } // this solution with the temporary vector is rather bad, probably better to take // a pointer of double as it was in old gaussian for(int j=0;j<ndim;++j){ allder[ndim*i+j]=tmpder[j];tmpder[j]=0.;} } mycomm.Sum(allbias); mycomm.Sum(allder); for(unsigned i=0;i<neighbors.size();++i){ unsigned ineigh=neighbors[i]; for(int j=0;j<ndim;++j){der[j]=allder[ndim*i+j];} BiasGrid_->addValueAndDerivatives(ineigh,allbias[i],der); } } } }
void VectorFrames:: Decide(int i,double marca,Mat velocara,Almacena cara,int profilesL, int profilesR, Mat pintar){ if(i==0){frames[i].setlanzado(1);} enum options {N,UP,R,D,L,U} alg1,alg2,decision; alg1=U; alg2=U; int contquietohor=0; int contnoquietohor=0; int contquietover=0; int contnoquietover=0; int contador=0; int aux=i; double time; time=frames[i].getTime(); for(size_t w = 0; w < (cara.get_faces()).size(); w++){ if(i>20){ while(marca-time <1000){ aux--; time=frames[aux].getTime(); contador++; if(abs(frames[i].getposcenter_x() - frames[aux].getposcenter_x()) < 0.08*cara.get_faces()[w].width){contquietohor++;} else{contnoquietohor++;} if(abs(frames[i].getposcenter_y() - frames[aux].getposcenter_y()) < 0.06*cara.get_faces()[w].height){contquietover++;} else{contnoquietover++;} } if(contquietohor>contnoquietohor && contquietohor> 0.8 *contador){frames[i].setmy_decisionhor(0);} else{frames[i].setmy_decisionhor(1);} if(contquietover>contnoquietover && contquietover> 0.8 *contador){frames[i].setmy_decisionver(0);} else{frames[i].setmy_decisionver(1);} line(velocara,Point(0,120),Point(320,120),Scalar(255,255,255),1,8,0); line(velocara,Point(160,0),Point(160,240),Scalar(255,255,255),1,8,0); if(frames[i].getmy_decisionhor()==0){line(velocara,Point(160,120),Point(160+40,120),Scalar(0,0,255),2,8,0);}//quiero rojo if(frames[i].getmy_decisionhor()==1){line(velocara,Point(160,120),Point(160+40,120),Scalar(255,0,0),2,8,0);}//movimiento azul if(frames[i].getmy_decisionver()==0){line(velocara,Point(160,120),Point(160,120-40),Scalar(0,0,255),2,8,0);}//quiero rojo if(frames[i].getmy_decisionver()==1){line(velocara,Point(160,120),Point(160,120-40),Scalar(255,0,0),2,8,0);}//movimiento azul aux=i; if(frames[i].getmy_decisionhor()==0){ int comp; bool evento=false; aux--; int contposi=0; int contnega=0; int contprofilesL = 0; int contprofilesR = 0; int contadoraux = 0; while(frames[aux].getmy_decisionhor()!=0 && aux>=0){ if(frames[aux].getposcenter_x() > frames[i].getposcenter_x()){contposi++;} if(frames[aux].getposcenter_x() < frames[i].getposcenter_x()){contnega++;} comp=abs(frames[i].getposcenter_x() - frames[aux].getposcenter_x()); if(comp>0.18*cara.get_faces()[w].width){evento=true;} if (frames[aux].getprofileR() == 1) { contprofilesR++; } if (frames[aux].getprofileL() == 1) { contprofilesL++; } aux--; contadoraux++; } if(aux!=i-1){ if(abs(frames[i].getposcenter_x() - frames[aux].getposcenter_x()) < 0.10*cara.get_faces()[w].width){ if(evento==true){ frames[i].setalgdecision(1); if(contposi>contnega){alg1=R;} if(contnega>contposi){alg1=L;} } } if (abs( frames[i].getposcenter_x() - frames[aux].getposcenter_x()) > 0.18 * cara.get_faces()[w].width) { int der=0; int izq=0; int aux2=i; for(int b=0;b<3;b++){ if(frames[aux2].getfacestate()==2){izq++;} if(frames[aux2].getfacestate()==3){der++;} aux2--; } if(izq>=2 || (profilesL == 1 && contprofilesL > 0.7 * contadoraux)){ frames[i].setalgdecision(2); alg1 = L; } if(der>=2|| (profilesR == 1 && contprofilesR > 0.7 * contadoraux) ){ frames[i].setalgdecision(2); alg1 = R; } } } else { while (frames[aux].getlanzado() != 1) { if (frames[aux].getmy_decisionhor() == 1) { break; } aux--; } if (frames[aux].getalgdecision() == 2) { if (marca - frames[aux].getTime() > 1000) { frames[i].setalgdecision(2); switch (frames[aux].getalg1()) { case 2: alg1 = R; break; case 4: alg1 = L; break; } } } } } aux=i; if(frames[i].getmy_decisionver()==0){ aux--; int comp2; bool evento2=false; int contposi=0; int contnega=0; while(frames[aux].getmy_decisionver()!=0 && aux>=0){ if(frames[aux].getposcenter_y() > frames[i].getposcenter_y()){contposi++;} if(frames[aux].getposcenter_y() < frames[i].getposcenter_y()){contnega++;} comp2=abs(frames[i].getposcenter_y() - frames[aux].getposcenter_y()); if(comp2>0.18*cara.get_faces()[w].height){evento2=true;} aux--; } if(aux!=i-1){ if(abs(frames[i].getposcenter_y() - frames[aux].getposcenter_y()) < 0.15*cara.get_faces()[w].height){ if(evento2==true){ if(contposi>contnega){alg2=D;} if(contnega>contposi){alg2=UP;} } } } } Point izq(0,120); Point der(230,120); Point arr(120,10); Point aba(120,240); if ((alg1==L) && (alg2==U)){frames[i].setalg1(L);decision=L;cout<<"izquierda"<<endl;putText(pintar,"IZQUIERDA",izq,FONT_HERSHEY_COMPLEX_SMALL,0.80,(255,255,0),1,8);} if ((alg1==R) && (alg2==U)){frames[i].setalg1(R);decision=R;cout<<"derecha"<<endl;putText(pintar,"DERECHA",der,FONT_HERSHEY_COMPLEX_SMALL,0.80,(255,255,0),1,8);} if ((alg1==U) && (alg2==UP)){decision=UP;cout<<"arriba"<<endl;putText(pintar,"ARRIBA",arr,FONT_HERSHEY_COMPLEX_SMALL,0.80,(255,255,0),1,8);} if ((alg1==U) && (alg2==D)){decision=D;cout<<"abajo"<<endl;putText(pintar,"ABAJO",aba,FONT_HERSHEY_COMPLEX_SMALL,0.80,(255,255,0),1,8);} if(decision==L || decision==R || decision==UP || decision==D){ frames[i].setlanzado(1); aux = i; while ((frames[aux].getlanzado()) != 1) { frames.erase(frames.begin(), frames.begin() + aux); aux--; } } } } }
void Histogram::compute( const unsigned& current, MultiValue& myvals ) const { if( mvectors ) { std::vector<double> cvals( myvessels[0]->getNumberOfQuantities() ); stashes[0]->retrieveSequentialValue( current, true, cvals ); for(unsigned i=2; i<myvessels[0]->getNumberOfQuantities(); ++i) myvals.setValue( i-1, cvals[i] ); myvals.setValue( 0, cvals[0] ); myvals.setValue( myvessels[0]->getNumberOfQuantities() - 1, ww ); if( in_apply ) { MultiValue& tmpval = stashes[0]->getTemporyMultiValue(0); if( tmpval.getNumberOfValues()!=myvessels[0]->getNumberOfQuantities() || tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) tmpval.resize( myvessels[0]->getNumberOfQuantities(), myvessels[0]->getNumberOfDerivatives() ); stashes[0]->retrieveDerivatives( stashes[0]->getTrueIndex(current), true, tmpval ); for(unsigned j=0; j<tmpval.getNumberActive(); ++j) { unsigned jder=tmpval.getActiveIndex(j); myvals.addDerivative( 0, jder, tmpval.getDerivative(0, jder) ); for(unsigned i=2; i<myvessels[0]->getNumberOfQuantities(); ++i) myvals.addDerivative( i-1, jder, tmpval.getDerivative(i, jder) ); } myvals.updateDynamicList(); } } else if( myvessels.size()>0 ) { std::vector<double> cvals( myvessels[0]->getNumberOfQuantities() ); stashes[0]->retrieveSequentialValue( current, false, cvals ); unsigned derbase; double totweight=cvals[0], tnorm = cvals[0]; myvals.setValue( 1, cvals[1] ); // Get the derivatives as well if we are in apply if( in_apply ) { // This bit gets the total weight double weight0 = cvals[0]; // Store the current weight for(unsigned j=1; j<myvessels.size(); ++j) { stashes[j]->retrieveSequentialValue( current, false, cvals ); totweight *= cvals[0]; } // And this bit the derivatives MultiValue& tmpval = stashes[0]->getTemporyMultiValue(0); if( tmpval.getNumberOfValues()!=myvessels[0]->getNumberOfQuantities() || tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) tmpval.resize( myvessels[0]->getNumberOfQuantities(), myvessels[0]->getNumberOfDerivatives() ); stashes[0]->retrieveDerivatives( stashes[0]->getTrueIndex(current), false, tmpval ); for(unsigned j=0; j<tmpval.getNumberActive(); ++j) { unsigned jder=tmpval.getActiveIndex(j); myvals.addDerivative( 1, jder, tmpval.getDerivative(1,jder) ); myvals.addDerivative( 0, jder, (totweight/weight0)*tmpval.getDerivative(0,jder) ); } derbase = myvessels[0]->getNumberOfDerivatives(); } for(unsigned i=1; i<myvessels.size(); ++i) { if( cvals.size()!=myvessels[i]->getNumberOfQuantities() ) cvals.resize( myvessels[i]->getNumberOfQuantities() ); stashes[i]->retrieveSequentialValue( current, false, cvals ); tnorm *= cvals[0]; myvals.setValue( 1+i, cvals[1] ); // Get the derivatives as well if we are in apply if( in_apply ) { MultiValue& tmpval = stashes[0]->getTemporyMultiValue(0); if( tmpval.getNumberOfValues()!=myvessels[0]->getNumberOfQuantities() || tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) tmpval.resize( myvessels[0]->getNumberOfQuantities(), myvessels[0]->getNumberOfDerivatives() ); stashes[i]->retrieveDerivatives( stashes[i]->getTrueIndex(current), false, tmpval ); for(unsigned j=0; j<tmpval.getNumberActive(); ++j) { unsigned jder=tmpval.getActiveIndex(j); myvals.addDerivative( 1+i, derbase+jder, tmpval.getDerivative(1,jder) ); myvals.addDerivative( 0, derbase+jder, (totweight/cvals[0])*tmpval.getDerivative(0,jder) ); } derbase += myvessels[i]->getNumberOfDerivatives(); } } myvals.setValue( 0, tnorm ); myvals.setValue( 1+myvessels.size(), ww ); if( in_apply ) myvals.updateDynamicList(); } else { plumed_assert( !in_apply ); std::vector<Value*> vv( myhist->getVectorOfValues() ); std::vector<double> val( getNumberOfArguments() ), der( getNumberOfArguments() ); // Retrieve the location of the grid point at which we are evaluating the kernel mygrid->getGridPointCoordinates( current, val ); if( kernel ) { for(unsigned i=0; i<getNumberOfArguments(); ++i) vv[i]->set( val[i] ); // Evaluate the histogram at the relevant grid point and set the values double vvh = kernel->evaluate( vv, der,true); myvals.setValue( 1, vvh ); } else { plumed_merror("normalisation of vectors does not work with arguments and spherical grids"); // Evalulate dot product double dot=0; for(unsigned j=0; j<getNumberOfArguments(); ++j) { dot+=val[j]*getArgument(j); der[j]=val[j]; } // Von misses distribution for concentration parameter double newval = (myhist->von_misses_norm)*exp( (myhist->von_misses_concentration)*dot ); myvals.setValue( 1, newval ); // And final derivatives for(unsigned j=0; j<getNumberOfArguments(); ++j) der[j] *= (myhist->von_misses_concentration)*newval; } // Set the derivatives and delete the vector of values for(unsigned i=0; i<getNumberOfArguments(); ++i) { myvals.setDerivative( 1, i, der[i] ); delete vv[i]; } } }
bool search(int matriz[3][3],int profundidad,float tasa){ int vec[2]; float tasap; int aux[3][3]; //printf("%s%d\n","contador:",cont ); imprimir(matriz); buscarCero(matriz,vec); push(matriz); profundidad++; if(sonIguales(matriz,destino)==9){ return true; } tasap=calculaTasa(matriz); printf("tasa padre%f\n",tasa); printf("tasa actual:%f\n",tasap); if(tasap<tasa){ pop(); return false; } //copiar(matriz,aux); //imprimir(aux); if(profundidad<stck){ if(vec[1]>0){ //imprimir(matriz); ////printf("\n"); copiar(matriz,aux); buscarCero(aux,vec); //imprimir(aux); //printf("%d %d\n",vec[0],vec[1]); izq(vec[0],vec[1],aux); //printf("%s\n","auxi izq"); //imprimir(aux); //printf("****\n"); if(search(aux,profundidad,tasap)==true)return true; else imprimir(matriz); } if(vec[1]<2){ //imprimir(matriz); //printf("\n"); copiar(matriz,aux); buscarCero(aux,vec); //imprimir(aux); //printf("%d %d\n",vec[0],vec[1]); der(vec[0],vec[1],aux); //printf("%s\n","auxi der"); //imprim//ir(aux); //printf("****\n"); if(search(aux,profundidad,tasap)==true)return true; else imprimir(matriz); } if(vec[0]>0){ //imprimir(matriz); //printf("\n"); copiar(matriz,aux); buscarCero(aux,vec); //imprimir(aux); //printf("%d %d\n",vec[0],vec[1]); arriba(vec[0],vec[1],aux); //printf("%s\n","auxi arriba"); //imprimir(aux); //printf("****\n"); if(search(aux,profundidad,tasap)==true)return true; else imprimir(matriz); } if(vec[0]<2){ //imprimir(matriz); //printf("\n"); copiar(matriz,aux); buscarCero(aux,vec); //imprimir(aux); //printf("%d %d\n",vec[0],vec[1]); abajo(vec[0],vec[1],aux); //printf("%s\n","auxi abajo"); //imprimir(aux); //printf("****\n"); if(search(aux,profundidad,tasap)==true)return true; else imprimir(matriz); } } //printf("false:\n"); //imprimir(matriz); //printf("falseend\n"); pop(); return false; }
void HistogramOnGrid::calculate( const unsigned& current, MultiValue& myvals, std::vector<double>& buffer, std::vector<unsigned>& der_list ) const { if( addOneKernelAtATime ) { plumed_dbg_assert( myvals.getNumberOfValues()==2 && !wasforced ); std::vector<double> der( dimension ); for(unsigned i=0; i<dimension; ++i) der[i]=myvals.getDerivative( 1, i ); accumulate( getAction()->getPositionInCurrentTaskList(current), myvals.get(0), myvals.get(1), der, buffer ); } else { plumed_dbg_assert( myvals.getNumberOfValues()==dimension+2 ); std::vector<double> point( dimension ); double weight=myvals.get(0)*myvals.get( 1+dimension ); for(unsigned i=0; i<dimension; ++i) point[i]=myvals.get( 1+i ); // Get the kernel unsigned num_neigh; std::vector<unsigned> neighbors; std::vector<double> der( dimension ); KernelFunctions* kernel=getKernelAndNeighbors( point, num_neigh, neighbors ); // If no kernel normalize the vector so von misses distribution is calculated correctly if( !kernel ) { double norm=0; for(unsigned j=0; j<dimension; ++j) norm += point[j]*point[j]; norm=sqrt( norm ); for(unsigned j=0; j<dimension; ++j) point[j] = point[j] / norm; } if( !kernel && getType()=="flat" ) { plumed_dbg_assert( num_neigh==1 ); accumulate( neighbors[0], weight, 1.0, der, buffer ); } else { double totwforce=0.0; std::vector<double> intforce( 2*dimension, 0.0 ); std::vector<Value*> vv( getVectorOfValues() ); double newval; std::vector<double> xx( dimension ); for(unsigned i=0; i<num_neigh; ++i) { unsigned ineigh=neighbors[i]; if( inactive( ineigh ) ) continue ; getGridPointCoordinates( ineigh, xx ); for(unsigned j=0; j<dimension; ++j) vv[j]->set(xx[j]); if( kernel ) { newval = kernel->evaluate( vv, der, true ); } else { // Evalulate dot product double dot=0; for(unsigned j=0; j<dimension; ++j) { dot+=xx[j]*point[j]; der[j]=xx[j]; } // Von misses distribution for concentration parameter newval = von_misses_norm*exp( von_misses_concentration*dot ); // And final derivatives for(unsigned j=0; j<dimension; ++j) der[j] *= von_misses_concentration*newval; } accumulate( ineigh, weight, newval, der, buffer ); if( wasForced() ) { accumulateForce( ineigh, weight, der, intforce ); totwforce += myvals.get( 1+dimension )*newval*forces[ineigh]; } } if( wasForced() ) { unsigned nder = getAction()->getNumberOfDerivatives(); unsigned gridbuf = getNumberOfBufferPoints()*getNumberOfQuantities(); for(unsigned j=0; j<dimension; ++j) { for(unsigned k=0; k<myvals.getNumberActive(); ++k) { // Minus sign here as we are taking derivative with respect to position of center of kernel NOT derivative wrt to // grid point unsigned kder=myvals.getActiveIndex(k); buffer[ bufstart + gridbuf + kder ] -= intforce[j]*myvals.getDerivative( j+1, kder ); } } // Accumulate the sum of all the weights buffer[ bufstart + gridbuf + nder ] += myvals.get(0); // Add the derivatives of the weights into the force -- this is separate loop as weights of all parts are considered together for(unsigned k=0; k<myvals.getNumberActive(); ++k) { unsigned kder=myvals.getActiveIndex(k); buffer[ bufstart + gridbuf + kder ] += totwforce*myvals.getDerivative( 0, kder ); buffer[ bufstart + gridbuf + nder + 1 + kder ] += myvals.getDerivative( 0, kder ); } } delete kernel; for(unsigned i=0; i<dimension; ++i) delete vv[i]; } } }