pagmo::decision_vector base_tsp::randomkeys2cities(const pagmo::decision_vector &x) const { if (x.size() != m_n_cities) { pagmo_throw(value_error,"input representation of a tsp solution (RANDOMKEYS encoding) looks unfeasible [wrong length]"); } pagmo::decision_vector retval(m_n_cities); std::vector<std::pair<double,int> > pairs(m_n_cities); for (pagmo::decision_vector::size_type i=0;i<m_n_cities;++i) { pairs[i].first = x[i]; pairs[i].second = i; } std::sort(pairs.begin(),pairs.end(),comparator); for (pagmo::decision_vector::size_type i=0;i<m_n_cities;++i) { retval[i] = pairs[i].second; } return retval; }
void PmQuery::addButtons(char *string) // comma-separated label:exitcode string { char *n; QString pairs(string); static int next = 100; QStringList list = pairs.split(","); for (QStringList::Iterator it = list.begin(); it != list.end(); ++it) { QString name = (*it).section(":", 0, 0); QString code = (*it).section(":", 1, 1); if (!name.isEmpty()) { int sts = code.isEmpty() ? ++next : code.toInt(); if ((n = strdup(name.toLatin1().data())) == NULL) nomem(); addButton(n, false, sts); } } }
inline void SortEig( DistMatrix<R,VR,STAR>& w, DistMatrix<Complex<R> >& Z ) { #ifndef RELEASE PushCallStack("SortEig"); #endif const int n = Z.Height(); const int k = Z.Width(); const Grid& g = Z.Grid(); DistMatrix<Complex<R>,VC,STAR> Z_VC_STAR( Z ); DistMatrix<R,STAR,STAR> w_STAR_STAR( w ); // Initialize the pairs of indices and eigenvalues std::vector<internal::IndexValuePair<R> > pairs( k ); for( int i=0; i<k; ++i ) { pairs[i].index = i; pairs[i].value = w_STAR_STAR.GetLocal(i,0); } // Sort the eigenvalues and simultaneously form the permutation std::sort ( pairs.begin(), pairs.end(), internal::IndexValuePair<R>::Compare ); // Locally reorder the eigenvectors and eigenvalues using the new ordering const int mLocal = Z_VC_STAR.LocalHeight(); DistMatrix<Complex<R>,VC,STAR> ZPerm_VC_STAR( n, k, g ); for( int j=0; j<k; ++j ) { const int source = pairs[j].index; MemCopy ( ZPerm_VC_STAR.LocalBuffer(0,j), Z_VC_STAR.LockedLocalBuffer(0,source), mLocal ); w_STAR_STAR.SetLocal(j,0,pairs[j].value); } Z_VC_STAR.Empty(); Z = ZPerm_VC_STAR; w = w_STAR_STAR; #ifndef RELEASE PopCallStack(); #endif }
void TestDigestOrMAC(TestData &v, bool testDigest) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); const char *digestName = testDigest ? "Digest" : "MAC"; member_ptr<MessageAuthenticationCode> mac; member_ptr<HashTransformation> hash; HashTransformation *pHash = NULL; TestDataNameValuePairs pairs(v); if (testDigest) { hash.reset(ObjectFactoryRegistry<HashTransformation>::Registry().CreateObject(name.c_str())); pHash = hash.get(); } else { mac.reset(ObjectFactoryRegistry<MessageAuthenticationCode>::Registry().CreateObject(name.c_str())); pHash = mac.get(); std::string key = GetDecodedDatum(v, "Key"); mac->SetKey((const byte *)key.c_str(), key.size(), pairs); } if (test == "Verify" || test == "VerifyTruncated" || test == "NotVerify") { int digestSize = -1; if (test == "VerifyTruncated") digestSize = pairs.GetIntValueWithDefault(Name::DigestSize(), digestSize); HashVerificationFilter verifierFilter(*pHash, NULL, HashVerificationFilter::HASH_AT_BEGIN, digestSize); PutDecodedDatumInto(v, digestName, verifierFilter); PutDecodedDatumInto(v, "Message", verifierFilter); verifierFilter.MessageEnd(); if (verifierFilter.GetLastResult() == (test == "NotVerify")) SignalTestFailure(); } else { SignalTestError(); assert(false); } }
Interpolation::Interpolation(const shared_ptr<ValueObject>& prop, const vector<Real>& x, const vector<Handle<Quote> >& yh, bool permanent) : Extrapolator(prop, permanent) { QL_REQUIRE(!x.empty(), "empty x vector"); Size n = x.size(); QL_REQUIRE(n==yh.size(), "unmatched size between x (" << n << ") and y(" << yh.size() << ")"); x_.reserve(n); yh_.reserve(n); y_.reserve(n); vector<pair<Real, Handle<Quote> > > pairs(n); for (Size i=0; i<n; ++i) pairs[i] = std::make_pair(x[i], yh[i]); std::sort(pairs.begin(), pairs.end(), QuoteHandleSorter()); vector<pair<Real, Handle<Quote> > >::iterator j=pairs.begin(); x_.push_back(j->first); yh_.push_back(j->second); registerWith(yh_.back()); yh_.back()->isValid() ? y_.push_back(yh_.back()->value()) : y_.push_back(1.0); for (j=pairs.begin()+1; j<pairs.end(); ++j) { if (x_.back() == j->first) { QL_ENSURE(yh_.back() == j->second, "duplicated x value (" << j->first << ") with different y values"); } else { x_.push_back(j->first); yh_.push_back(j->second); registerWith(yh_.back()); yh_.back()->isValid() ? y_.push_back(yh_.back()->value()) : y_.push_back(1.0); } } n_ = x_.size(); }
int main () { int size, i, k, item, p; // size and difference scanf ("%d %d", &size, &k); // items int arr[size]; for (i = 0; i < size; i++) { scanf ("%d", &item); arr[i] = item; } // find pairs p = pairs (size, arr, k); printf ("pairs: %d\n", p); return 0; }
int main() { int N=5; int data[10]= {1,2,7,8,13,14,10,11,4,5}; Pairs pairs( data, N ); std::cout << "unsorted" << std::endl; for(int i=0; i<N; ++i) std::cout << i << ": (" << pairs[i].first() << ", " << pairs[i].second() << ")" << std::endl; std::sort(pairs.begin(), pairs.end()); std::cout << "sorted" << std::endl; for(int i=0; i<N; ++i) std::cout << i << ": (" << pairs[i][0] // same as pairs[i].first() << ", " << pairs[i][1] // same as pairs[i].second() << ")" << std::endl; return 0; }
ValueInt<Real> Median( const Matrix<Real>& x ) { EL_DEBUG_CSE const Int m = x.Height(); const Int n = x.Width(); if( m != 1 && n != 1 ) LogicError("Median is meant for a single vector"); const Int k = ( n==1 ? m : n ); const Int stride = ( n==1 ? 1 : x.LDim() ); const Real* xBuffer = x.LockedBuffer(); vector<ValueInt<Real>> pairs( k ); for( Int i=0; i<k; ++i ) { pairs[i].value = xBuffer[i*stride]; pairs[i].index = i; } std::sort( pairs.begin(), pairs.end(), ValueInt<Real>::Lesser ); return pairs[k/2]; }
void TestAsymmetricCipher(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); member_ptr<PK_Encryptor> encryptor(ObjectFactoryRegistry<PK_Encryptor>::Registry().CreateObject(name.c_str())); member_ptr<PK_Decryptor> decryptor(ObjectFactoryRegistry<PK_Decryptor>::Registry().CreateObject(name.c_str())); std::string keyFormat = GetRequiredDatum(v, "KeyFormat"); if (keyFormat == "DER") { decryptor->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PrivateKey")).Ref()); encryptor->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PublicKey")).Ref()); } else if (keyFormat == "Component") { TestDataNameValuePairs pairs(v); decryptor->AccessMaterial().AssignFrom(pairs); encryptor->AccessMaterial().AssignFrom(pairs); } if (test == "DecryptMatch") { std::string decrypted, expected = GetDecodedDatum(v, "Plaintext"); StringSource ss(GetDecodedDatum(v, "Ciphertext"), true, new PK_DecryptorFilter(GlobalRNG(), *decryptor, new StringSink(decrypted))); if (decrypted != expected) SignalTestFailure(); } else if (test == "KeyPairValidAndConsistent") { TestKeyPairValidAndConsistent(encryptor->AccessMaterial(), decryptor->GetMaterial()); } else { SignalTestError(); assert(false); } }
void Generation::produce_offspring(genetic_parameters const& genetic_param, std::vector<bound> const& param_bounds) { // Initialize random generator std::random_device rd; std::array<unsigned int, std::mt19937::state_size> seed_data; std::generate_n(seed_data.begin(), seed_data.size(), std::ref(rd)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::mt19937 engine(seq); // Check if the number of chromosomes is even size_t pairs(0); if (size % 2 == 0) { pairs = size / 2; } else { pairs = (size + 1) / 2; } // Select the pairs of parents and produce an offspring for (size_t i = 0; i < pairs; ++i) { // Select parents via tournament selection Chromosome parent1 = chromosomes[tournament_selection(engine)]; Chromosome parent2 = chromosomes[tournament_selection(engine)]; // Crossover parents crossover_chromosomes(parent1, parent2, genetic_param.prob_crossover, engine); // Mutate parents mutate_chromosome(parent1, genetic_param.prob_mutation, param_bounds, engine); mutate_chromosome(parent2, genetic_param.prob_mutation, param_bounds, engine); // Save new chromosomes offspring.push_back(parent1); if (2 * (i + 1) <= size) { offspring.push_back(parent2); } } // Save new generation chromosomes = offspring; offspring.clear(); }
void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters) { std::string type = GetRequiredDatum(v, "AlgorithmType"); std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::string key = GetDecodedDatum(v, "Key"); std::string plaintext = GetOptionalDecodedDatum(v, "Plaintext"); std::string ciphertext = GetOptionalDecodedDatum(v, "Ciphertext"); std::string header = GetOptionalDecodedDatum(v, "Header"); std::string footer = GetOptionalDecodedDatum(v, "Footer"); std::string mac = GetOptionalDecodedDatum(v, "MAC"); TestDataNameValuePairs testDataPairs(v); CombinedNameValuePairs pairs(overrideParameters, testDataPairs); if (test == "Encrypt" || test == "EncryptXorDigest" || test == "NotVerify") { member_ptr<AuthenticatedSymmetricCipher> asc1, asc2; asc1.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str())); asc2.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str())); asc1->SetKey((const byte *)key.data(), key.size(), pairs); asc2->SetKey((const byte *)key.data(), key.size(), pairs); std::string encrypted, decrypted; AuthenticatedEncryptionFilter ef(*asc1, new StringSink(encrypted)); bool macAtBegin = !mac.empty() && !GlobalRNG().GenerateBit(); // test both ways randomly AuthenticatedDecryptionFilter df(*asc2, new StringSink(decrypted), macAtBegin ? AuthenticatedDecryptionFilter::MAC_AT_BEGIN : 0); if (asc1->NeedsPrespecifiedDataLengths()) { asc1->SpecifyDataLengths(header.size(), plaintext.size(), footer.size()); asc2->SpecifyDataLengths(header.size(), plaintext.size(), footer.size()); } StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer), sm(mac); if (macAtBegin) RandomizedTransfer(sm, df, true); sh.CopyTo(df, LWORD_MAX, AAD_CHANNEL); RandomizedTransfer(sc, df, true); sf.CopyTo(df, LWORD_MAX, AAD_CHANNEL); if (!macAtBegin) RandomizedTransfer(sm, df, true); df.MessageEnd(); RandomizedTransfer(sh, ef, true, AAD_CHANNEL); RandomizedTransfer(sp, ef, true); RandomizedTransfer(sf, ef, true, AAD_CHANNEL); ef.MessageEnd(); if (test == "Encrypt" && encrypted != ciphertext+mac) { std::cout << "incorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(2048); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } if (test == "Encrypt" && decrypted != plaintext) { std::cout << "incorrectly decrypted: "; StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } if (ciphertext.size()+mac.size()-plaintext.size() != asc1->DigestSize()) { std::cout << "bad MAC size\n"; SignalTestFailure(); } if (df.GetLastResult() != (test == "Encrypt")) { std::cout << "MAC incorrectly verified\n"; SignalTestFailure(); } } else { std::cout << "unexpected test name\n"; SignalTestError(); } }
int main (int argc, const char ** argv) { ProgramArgument program_args=ProcessArguments(argc,argv); bool print_ali=program_args.print_ali; ParseMatrix submatParser(program_args.matrixname); #ifdef DEBUG std::cout << "Print Matrix\n"; submatParser.print(); #endif SubstitutionMatrix subMatrix(submatParser.scores, submatParser.row_index); #ifdef DEBUG std::cout << "Print SubMatrix!\n"; subMatrix.print(); #endif SequenceLibrary sequences(program_args.seqlib); const size_t max_seq_size = sequences.get_max_seq_size(); PairsLibrary pairs(program_args.pairs,&sequences); GotohEight gotohAlgo(max_seq_size,&subMatrix, program_args.go, program_args.ge, program_args.mode); SequenceEight sequenceQuery(max_seq_size, subMatrix.aa2short,subMatrix.short2aa); SequenceEight sequenceTemplate(max_seq_size, subMatrix.aa2short,subMatrix.short2aa); char buffer[2097152]; std::cout.rdbuf()->pubsetbuf(buffer, 2097152); const char ** template_sequences=(const char **)memalign(16,(VEC_SIZE)*sizeof(const char *)); const char ** template_keys=(const char **)memalign(16,(VEC_SIZE)*sizeof(const char *)); std::map< std::string,std::vector<std::pair<std::string,size_t> > >::iterator it = pairs.pairs.begin(); for( ; it != pairs.pairs.end(); ++it ){ std::pair<std::string, size_t> query = sequences.get_sequence(it->first); std::string query_key = it->first.c_str(); sequenceQuery.MapOneSEQToSEQ8(query.first.c_str()); std::vector<std::pair<std::string, size_t> > t_seq = it->second; sort (t_seq.begin(), t_seq.end(), sort_seq_vector); int elem_count=0; size_t t_seq_size = t_seq.size(); for(std::vector<int>::size_type i = 0; i < t_seq_size ; i++) { std::string template_key=t_seq[i].first; template_keys[i%VEC_SIZE] = template_key.c_str(); template_sequences[i%VEC_SIZE] = sequences.get_sequence(template_key).first.c_str(); elem_count++; if((i+1)%VEC_SIZE==0){ elem_count=0; sequenceTemplate.MapSEQArrayToSEQ8(template_sequences, VEC_SIZE); GotohEight::GotohMatrix matrix= gotohAlgo.calc_matrix(&sequenceQuery, &sequenceTemplate); if(print_ali == true){ std::vector<char *> alignments=gotohAlgo.backtrace(matrix,&sequenceQuery,&sequenceTemplate); for(size_t i = 0; i < 8; i++) { if(program_args.check==true){ float check_score=gotohAlgo.calc_check_score(alignments[(i*2)],alignments[(i*2)+1]); printf("check score: %.3f\n",check_score); } print_ali_result(alignments[(i*2)],alignments[(i*2)+1],matrix.score[i],query_key,template_keys[i]); } }else{ print_score(matrix,query_key,template_keys,VEC_SIZE); } } } if(elem_count!=0){ sequenceTemplate.MapSEQArrayToSEQ8(template_sequences, elem_count); GotohEight::GotohMatrix matrix= gotohAlgo.calc_matrix(&sequenceQuery, &sequenceTemplate); if(print_ali == true){ std::vector<char *> alignments=gotohAlgo.backtrace(matrix,&sequenceQuery,&sequenceTemplate); for(size_t i = 0; i < elem_count; i++) { if(program_args.check==true){ float check_score=gotohAlgo.calc_check_score(alignments[(i*2)],alignments[(i*2)+1]); printf("check score: %.3f\n",check_score); } print_ali_result(alignments[(i*2)],alignments[(i*2)+1],matrix.score[i],query_key,template_keys[i]); } }else{ print_score(matrix,query_key,template_keys,elem_count); } } } std::cout.flush(); free(template_keys); free(template_sequences); return 0; }
void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::string key = GetDecodedDatum(v, "Key"); std::string plaintext = GetDecodedDatum(v, "Plaintext"); TestDataNameValuePairs testDataPairs(v); CombinedNameValuePairs pairs(overrideParameters, testDataPairs); if (test == "Encrypt" || test == "EncryptXorDigest" || test == "Resync" || test == "EncryptionMCT" || test == "DecryptionMCT") { static member_ptr<SymmetricCipher> encryptor, decryptor; static std::string lastName; if (name != lastName) { encryptor.reset(ObjectFactoryRegistry<SymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str())); decryptor.reset(ObjectFactoryRegistry<SymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str())); lastName = name; } ConstByteArrayParameter iv; if (pairs.GetValue(Name::IV(), iv) && iv.size() != encryptor->IVSize()) SignalTestFailure(); if (test == "Resync") { encryptor->Resynchronize(iv.begin(), (int)iv.size()); decryptor->Resynchronize(iv.begin(), (int)iv.size()); } else { encryptor->SetKey((const byte *)key.data(), key.size(), pairs); decryptor->SetKey((const byte *)key.data(), key.size(), pairs); } int seek = pairs.GetIntValueWithDefault("Seek", 0); if (seek) { encryptor->Seek(seek); decryptor->Seek(seek); } std::string encrypted, xorDigest, ciphertext, ciphertextXorDigest; if (test == "EncryptionMCT" || test == "DecryptionMCT") { SymmetricCipher *cipher = encryptor.get(); SecByteBlock buf((byte *)plaintext.data(), plaintext.size()), keybuf((byte *)key.data(), key.size()); if (test == "DecryptionMCT") { cipher = decryptor.get(); ciphertext = GetDecodedDatum(v, "Ciphertext"); buf.Assign((byte *)ciphertext.data(), ciphertext.size()); } for (int i=0; i<400; i++) { encrypted.reserve(10000 * plaintext.size()); for (int j=0; j<10000; j++) { cipher->ProcessString(buf.begin(), buf.size()); encrypted.append((char *)buf.begin(), buf.size()); } encrypted.erase(0, encrypted.size() - keybuf.size()); xorbuf(keybuf.begin(), (const byte *)encrypted.data(), keybuf.size()); cipher->SetKey(keybuf, keybuf.size()); } encrypted.assign((char *)buf.begin(), buf.size()); ciphertext = GetDecodedDatum(v, test == "EncryptionMCT" ? "Ciphertext" : "Plaintext"); if (encrypted != ciphertext) { std::cout << "incorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } return; } StreamTransformationFilter encFilter(*encryptor, new StringSink(encrypted), StreamTransformationFilter::NO_PADDING); RandomizedTransfer(StringStore(plaintext).Ref(), encFilter, true); encFilter.MessageEnd(); /*{ std::string z; encryptor->Seek(seek); StringSource ss(plaintext, false, new StreamTransformationFilter(*encryptor, new StringSink(z), StreamTransformationFilter::NO_PADDING)); while (ss.Pump(64)) {} ss.PumpAll(); for (int i=0; i<z.length(); i++) assert(encrypted[i] == z[i]); }*/ if (test != "EncryptXorDigest") ciphertext = GetDecodedDatum(v, "Ciphertext"); else { ciphertextXorDigest = GetDecodedDatum(v, "CiphertextXorDigest"); xorDigest.append(encrypted, 0, 64); for (size_t i=64; i<encrypted.size(); i++) xorDigest[i%64] ^= encrypted[i]; } if (test != "EncryptXorDigest" ? encrypted != ciphertext : xorDigest != ciphertextXorDigest) { std::cout << "incorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(2048); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } std::string decrypted; StreamTransformationFilter decFilter(*decryptor, new StringSink(decrypted), StreamTransformationFilter::NO_PADDING); RandomizedTransfer(StringStore(encrypted).Ref(), decFilter, true); decFilter.MessageEnd(); if (decrypted != plaintext) { std::cout << "incorrectly decrypted: "; StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } } else { std::cout << "unexpected test name\n"; SignalTestError(); } }
void TestSignatureScheme(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::auto_ptr<PK_Signer> signer(ObjectFactoryRegistry<PK_Signer>::Registry().CreateObject(name.c_str())); std::auto_ptr<PK_Verifier> verifier(ObjectFactoryRegistry<PK_Verifier>::Registry().CreateObject(name.c_str())); TestDataNameValuePairs pairs(v); std::string keyFormat = GetRequiredDatum(v, "KeyFormat"); if (keyFormat == "DER") verifier->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PublicKey")).Ref()); else if (keyFormat == "Component") verifier->AccessMaterial().AssignFrom(pairs); if (test == "Verify" || test == "NotVerify") { VerifierFilter verifierFilter(*verifier, NULL, VerifierFilter::SIGNATURE_AT_BEGIN); PutDecodedDatumInto(v, "Signature", verifierFilter); PutDecodedDatumInto(v, "Message", verifierFilter); verifierFilter.MessageEnd(); if (verifierFilter.GetLastResult() == (test == "NotVerify")) SignalTestFailure(); } else if (test == "PublicKeyValid") { if (!verifier->GetMaterial().Validate(GlobalRNG(), 3)) SignalTestFailure(); } else goto privateKeyTests; return; privateKeyTests: if (keyFormat == "DER") signer->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PrivateKey")).Ref()); else if (keyFormat == "Component") signer->AccessMaterial().AssignFrom(pairs); if (test == "KeyPairValidAndConsistent") { TestKeyPairValidAndConsistent(verifier->AccessMaterial(), signer->GetMaterial()); } else if (test == "Sign") { SignerFilter f(GlobalRNG(), *signer, new HexEncoder(new FileSink(cout))); StringSource ss(GetDecodedDatum(v, "Message"), true, new Redirector(f)); SignalTestFailure(); } else if (test == "DeterministicSign") { SignalTestError(); assert(false); // TODO: implement } else if (test == "RandomSign") { SignalTestError(); assert(false); // TODO: implement } else if (test == "GenerateKey") { SignalTestError(); assert(false); } else { SignalTestError(); assert(false); } }
void TestSignatureScheme(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); member_ptr<PK_Signer> signer(ObjectFactoryRegistry<PK_Signer>::Registry().CreateObject(name.c_str())); member_ptr<PK_Verifier> verifier(ObjectFactoryRegistry<PK_Verifier>::Registry().CreateObject(name.c_str())); TestDataNameValuePairs pairs(v); if (test == "GenerateKey") { signer->AccessPrivateKey().GenerateRandom(GlobalRNG(), pairs); verifier->AccessPublicKey().AssignFrom(signer->AccessPrivateKey()); } else { std::string keyFormat = GetRequiredDatum(v, "KeyFormat"); if (keyFormat == "DER") verifier->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PublicKey")).Ref()); else if (keyFormat == "Component") verifier->AccessMaterial().AssignFrom(pairs); if (test == "Verify" || test == "NotVerify") { VerifierFilter verifierFilter(*verifier, NULL, VerifierFilter::SIGNATURE_AT_BEGIN); PutDecodedDatumInto(v, "Signature", verifierFilter); PutDecodedDatumInto(v, "Message", verifierFilter); verifierFilter.MessageEnd(); if (verifierFilter.GetLastResult() == (test == "NotVerify")) SignalTestFailure(); return; } else if (test == "PublicKeyValid") { if (!verifier->GetMaterial().Validate(GlobalRNG(), 3)) SignalTestFailure(); return; } if (keyFormat == "DER") signer->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PrivateKey")).Ref()); else if (keyFormat == "Component") signer->AccessMaterial().AssignFrom(pairs); } if (test == "GenerateKey" || test == "KeyPairValidAndConsistent") { TestKeyPairValidAndConsistent(verifier->AccessMaterial(), signer->GetMaterial()); VerifierFilter verifierFilter(*verifier, NULL, VerifierFilter::THROW_EXCEPTION); verifierFilter.Put((const byte *)"abc", 3); StringSource ss("abc", true, new SignerFilter(GlobalRNG(), *signer, new Redirector(verifierFilter))); } else if (test == "Sign") { SignerFilter f(GlobalRNG(), *signer, new HexEncoder(new FileSink(cout))); StringSource ss(GetDecodedDatum(v, "Message"), true, new Redirector(f)); SignalTestFailure(); } else if (test == "DeterministicSign") { // This test is specialized for RFC 6979. The RFC is a drop-in replacement // for DSA and ECDSA, and access to the seed or secret is not needed. If // additional determinsitic signatures are added, then the test harness will // likely need to be extended. string signature; SignerFilter f(GlobalRNG(), *signer, new HexEncoder(new StringSink(signature))); StringSource ss(GetDecodedDatum(v, "Message"), true, new Redirector(f)); if (GetDecodedDatum(v, "Signature") != signature) SignalTestFailure(); return; } else if (test == "RandomSign") { SignalTestError(); assert(false); // TODO: implement } else { SignalTestError(); assert(false); } }
//Float //pibond(BrennerMainInfo *const info, struct AtomPairInfoState *const apis) Float BrennerPotential::pibond() { const int num_atms = nAtoms; /* When we're looking at a bond from atom i to atom j, and we're considering all neighbors of j, then xk will be the bren_vector from atom i to each neighbor of j. */ bren_vector xk[250+1]; /* Similarly, when we're considering all neighbors of i, xl will be the bren_vector from atom j to each neighbor of i. */ bren_vector xl[250+1],cj,ck,cl,rk,rl,dt2dik,dt2djl,dt2dij; Float xsik[250+1],xsjk[250+1],xsil[250+1],xsjl[250+1] ,dexni[2],dexnj[2],xni[2],xnj[2] ,cfuni[ncc],cfunj[ncc],dcfuni[ncc],dcfunj[ncc] ,cosk[250+1],cosl[250+1],sink[250+1],sinl[250+1] ,dctjk[250+1],dctij[250+1],dctik[250+1],dctil[250+1],dctji[250+1], dctjl[250+1]; Float tote = 0; int i; vector<Float> hydrogens_connected(num_atms); vector<Float> carbons_connected(num_atms); //Float *hydrogens_connected = (Float*)xmalloc(num_atms*sizeof(Float)); //Float *carbons_connected = (Float*)xmalloc(num_atms*sizeof(Float)); Float *xhc[2]; //const struct NeighborState *const cans = caNeighborsconst (info); xhc[0] = &hydrogens_connected[0]; xhc[1] = &carbons_connected[0]; for(i = 0; i < num_atms; ++i) xhc[0][i] = xhc[1][i] = 0; for(i = 0; i < ncc; ++i) cfuni[i] = cfunj[i] = dcfuni[i] = dcfunj[i] = 0; dexni[0]=dexnj[0]=xni[0]=xnj[0] = 0; dexni[1]=dexnj[1]=xni[1]=xnj[1] = 0; /* * Find the number of hydrogens and carbons connected to each atom. */ // Allocate buffers for neighbor list data int nmaxnb = nblist->MaxNeighborListLength(); vector<int> iNeighbors(nmaxnb); vector<Vec> distances(nmaxnb); // Not used? vector<double> sq_distances(nmaxnb); // Not used? for(i = 0; i < num_atms; ++i) { int sizemax = nmaxnb; int nCount = nblist->GetFullNeighbors(i, &iNeighbors[0], &distances[0], &sq_distances[0], sizemax); /* Early escape if there is no neighbours to this atoms. This also avoids a memory access error */ if (nCount == 0) continue; const struct AtomPairInfo *const pairs = pairsconst (i, apis); int jn; /* Why do we start counting at 1 instead of 0 here? We might not have any hydrogens at all in the figure, and in that case we'll set some field of hydrogens_connected to 1. Weird. Tim Freeman 6 Sep 2000. */ hydrogens_connected[i] = 1; carbons_connected[i] = 1; for (jn = 0; jn < nCount; jn++) { if(1 == pairs[jn].lcheck) { const int j = iNeighbors [jn]; const int atype = getKtype(j); assert(atype > 0 && atype <= 2); xhc[atype-1][i] += pairs[jn].ww; } } } /* * Sum over bonds between atoms I and J */ for(i = 0; i < num_atms; ++i) { /* j is the index of this neighbor pair in the neighbors array. Note that j is an entirely different beast from i, which is an index into the atom array. */ int j; const int ki = getKtype(i); int sizemax = nmaxnb; int nCount = nblist->GetFullNeighbors(i, &iNeighbors[0], &distances[0], &sq_distances[0], sizemax); /* Early escape if there is no neighbours to this atoms. This also avoids a memory access error */ if (nCount == 0) continue; const struct AtomPairInfo *const atom_pair = pairsconst (i, apis); for (j = 0; j < nCount; j++) { /* jn will be the atom number of the current neighbor. */ const int jn = iNeighbors [j]; /* calc_dihedral_terms adds a value to btot but does not otherwise read its value. */ Float conjug, xnt1, xnt2, btot; /* vdbdi, vdbdj, vdrdi, vdrdj, and vdrdc are variables that are consequences of what we got from calc_dihedral_terms and then inputs into calc_many_body. */ Float vdbdi, vdbdj, vdrdi, vdrdj, vdrdc; /* sdalik and sdaljl are outputs from calc1side I don't understand yet and inputs to calc_many_body. */ Float sdalik, sdaljl; /* conk and conl are outputs from calc1side I don't understand yet and inputs into calc_many_body. */ Float conk, conl; /* cj is the bren_vector from i to j. */ bren_vector cj; /* If one of them isn't hydrogen or carbon, then look at the next pair. */ if(atom_pair[j].lcheck != 1) continue; if(i >= jn) continue; /* Now we're considering each pair only once. */ cj = atom_pair[j].cor; { /* kj will be the ktype for the current neighbor. */ const int kj = getKtype(jn); /* sij will be the distance from one atom to the other. */ const Float sij = atom_pair[j].rcor; const Float rsqij = sij*sij; /* xsij and xsji are an output from calc1side I don't understand yet. */ Float xsij, xsji; /* ssumk is the middle term under the square root in equation 7 on page 10. */ Float ssumk, ssuml; /* exnij is pi super rc sub i j, mentioned in equation 3 on page 6 and defined in equation 12 on page 14. exnji is pi super rc sub j i. */ Float exnij, exnji; // XXXX Remove info from following calls! calc1side(ki, kj, i, j, j, -1, xni, atom_pair, atom_pair, cj, &xsij, xhc, cfuni, dcfuni, &conk, dctjk, dctij, dctik, &ssumk, &sdalik, xsjk, xsik, sij, rsqij, xk, cosk, sink, &exnij, dexni); calc1side(kj, ki, jn, i, j, 1, xnj, atom_pair, pairs (jn, apis), cj, &xsji, xhc, cfunj, dcfunj, &conl, dctil, dctji, dctjl, &ssuml, &sdaljl, xsil, xsjl, sij, rsqij, xl, cosl, sinl, &exnji, dexnj); { Float dbdzi, dbdzj; Float dradi = 0.0; Float dradj = 0.0; Float drdc = 0.0; { Float bji, bij, rad; { Float dij; /* dij is the expression inside the square root of equation 7 on page 10. */ dij = (1.0+exnij+ssumk); /* The next line is equation 7 on page 10. bij is p super sigma pi sub i j. */ bij = 1/sqrt(dij); dbdzi = -0.50*bij/dij; } /* Forget dij. */ { Float dji = (1.0+exnji+ssuml); bji = 1/sqrt(dji); dbdzj = -0.50*bji/dji; } /* Forget dji. */ /* Next line is equation 13 on page 14. conjug is N super conj sub i j. */ conjug = 1.0 + (conk*conk) + (conl*conl); /* Next line is equation 8a on page 11. xnt1 is N super C sub i. */ xnt1 = xni[0]+xni[1]-1.0; /* Next line is equation 8b on page 11. xnt2 is N super H sub i. */ xnt2 = xnj[0]+xnj[1]-1.0; /* Next line is equation 12 on page 14. rad is pi super rc sub i j. rc probably stands for radical. */ rad = RADIC(ki,kj,xnt1,xnt2,conjug,&dradi,&dradj,&drdc); // XXX btot = (bji+bij+rad); } /* Forget bji, bij, rad. */ { /* vatt is the energy due to attraction between the pair. */ const Float vatt = atom_pair[j].exx1; const int kikj = ki+kj; /* * Dihedral terms */ /* ndihed is 2, and kikj is the sum of the ktypes ki and kj, so "kikj == ndihed" is a very obscure way to say that both i and j are carbon (ktype 1), since ktype's are integers and are never zero or negative. */ if(kikj == ndihed) // XXXX Remove info calc_dihedral_terms(i, j, jn, apis, xnt1, xnt2, conjug, sij, sink, sinl, dctik, dctjk, dctil, dctij, dctjl, dctji, cosk, cosl, cj, vatt, xk, xl, &btot, &dradi, &dradj, &drdc); /* btot is the sum of the b's, specifically the b sub i j in equation 1 on page 4. vatt is V super A sub i j in equation 1 on page 4. */ tote -= btot*vatt; /* dbdzi is the derivative of b with respect to i-dont-know-what. vdbdi is the derivative of the total energy with respect to the same thing, due to changes in b. */ vdbdi = vatt*dbdzi; vdbdj = vatt*dbdzj; vdrdc = vatt*drdc; vdrdi = vatt*dradi; vdrdj = vatt*dradj; } /* Forget vatt. */ } /* Forget dbdzi, dbdzj, drdc, dradi, dradj */ { Float rp = vdbdi*xsij + vdbdj*xsji + btot*atom_pair[j].dexx1; #ifndef NDEBUG if(!(rp < 1.e99)) printf("rp %d %d %d %11.8f %11.8f %11.8f %11.8f %11.8f %11.8f\n", j, i, jn, vdbdi,xsij, vdbdj,xsji, btot, atom_pair[j].dexx1); #endif transForce(i, jn, rp*cj); } /* Forget rp. */ } /* Forget sij, rsqij, xsij, xsji. */ /* * Add many-body forces */ // XXX Remove info calc_many_body(apis, 1, i, jn, j, /* i side */ vdbdi, xsik, dexni, vdrdi, vdrdc, cfuni, sdalik, xsjk, xk, dcfuni, conk); calc_many_body(apis, 0, jn, i, -1, /* j side */ vdbdj, xsjl, dexnj, vdrdj, vdrdc, cfunj, sdaljl, xsil, xl, dcfunj, conl); } } //free(hydrogens_connected); //free(carbons_connected); return tote; }
char* TMD5Auth::getChallenge(const TCHAR *challenge) { if (iCallCount > 0) return NULL; iCallCount++; unsigned resultLen; ptrA text((char*)mir_base64_decode( _T2A(challenge), &resultLen)); TStringPairs pairs(text); const char *realm = pairs["realm"], *nonce = pairs["nonce"]; char cnonce[40], tmpBuf[40]; DWORD digest[4], hash1[4], hash2[4]; mir_md5_state_t ctx; Utils_GetRandom(digest, sizeof(digest)); mir_snprintf(cnonce, _countof(cnonce), "%08x%08x%08x%08x", htonl(digest[0]), htonl(digest[1]), htonl(digest[2]), htonl(digest[3])); T2Utf uname(info->conn.username), passw(info->conn.password); ptrA serv(mir_utf8encode(info->conn.server)); mir_md5_init(&ctx); mir_md5_append(&ctx, (BYTE*)(char*)uname, (int)mir_strlen(uname)); mir_md5_append(&ctx, (BYTE*)":", 1); mir_md5_append(&ctx, (BYTE*)realm, (int)mir_strlen(realm)); mir_md5_append(&ctx, (BYTE*)":", 1); mir_md5_append(&ctx, (BYTE*)(char*)passw, (int)mir_strlen(passw)); mir_md5_finish(&ctx, (BYTE*)hash1); mir_md5_init(&ctx); mir_md5_append(&ctx, (BYTE*)hash1, 16); mir_md5_append(&ctx, (BYTE*)":", 1); mir_md5_append(&ctx, (BYTE*)nonce, (int)mir_strlen(nonce)); mir_md5_append(&ctx, (BYTE*)":", 1); mir_md5_append(&ctx, (BYTE*)cnonce, (int)mir_strlen(cnonce)); mir_md5_finish(&ctx, (BYTE*)hash1); mir_md5_init(&ctx); mir_md5_append(&ctx, (BYTE*)"AUTHENTICATE:xmpp/", 18); mir_md5_append(&ctx, (BYTE*)(char*)serv, (int)mir_strlen(serv)); mir_md5_finish(&ctx, (BYTE*)hash2); mir_md5_init(&ctx); mir_snprintf(tmpBuf, _countof(tmpBuf), "%08x%08x%08x%08x", htonl(hash1[0]), htonl(hash1[1]), htonl(hash1[2]), htonl(hash1[3])); mir_md5_append(&ctx, (BYTE*)tmpBuf, (int)mir_strlen(tmpBuf)); mir_md5_append(&ctx, (BYTE*)":", 1); mir_md5_append(&ctx, (BYTE*)nonce, (int)mir_strlen(nonce)); mir_snprintf(tmpBuf, _countof(tmpBuf), ":%08d:", iCallCount); mir_md5_append(&ctx, (BYTE*)tmpBuf, (int)mir_strlen(tmpBuf)); mir_md5_append(&ctx, (BYTE*)cnonce, (int)mir_strlen(cnonce)); mir_md5_append(&ctx, (BYTE*)":auth:", 6); mir_snprintf(tmpBuf, _countof(tmpBuf), "%08x%08x%08x%08x", htonl(hash2[0]), htonl(hash2[1]), htonl(hash2[2]), htonl(hash2[3])); mir_md5_append(&ctx, (BYTE*)tmpBuf, (int)mir_strlen(tmpBuf)); mir_md5_finish(&ctx, (BYTE*)digest); char *buf = (char*)alloca(8000); int cbLen = mir_snprintf(buf, 8000, "username=\"%s\",realm=\"%s\",nonce=\"%s\",cnonce=\"%s\",nc=%08d," "qop=auth,digest-uri=\"xmpp/%s\",charset=utf-8,response=%08x%08x%08x%08x", uname, realm, nonce, cnonce, iCallCount, serv, htonl(digest[0]), htonl(digest[1]), htonl(digest[2]), htonl(digest[3])); return mir_base64_encode((PBYTE)buf, cbLen); }
int CS_DrawStruct(struct pair_prob *pair, char *string, PAR *par, float coord[], struct xyplot *my_xyplot) { float alpha, xmin, xmax, ymin, ymax, alpha_i, delta, charsize; int i, k, l, lmax, length, tag, incr, first; int par0, par9; float para, rfactor; length = strlen(string); if (length>MAXLENGTH) { printf("Sequence too long, not doing xy_plot\n"); return(FALSE); } /* printf("\nCheck auf Korrektheit der Bp ..."); */ for (i=1; i<=length; i++) { if ((pair[i].pair != 0) && (pair[pair[i].pair].pair != i)) { printf("Inconsistent pairing list: %d:%d != %d:%d\n", i, pair[i].pair, pair[i].pair, pair[pair[i].pair].pair); /*return(FALSE);*/ } if ((pair[i].pair != 0) && (i == pair[i].pair)) { printf("Inconsistent pairing list: %d:%d !\n", i, pair[i].pair); /*return(FALSE);*/ } if (pair[i].pair != 0) { l = 0; for (k=1; k<=length; k++) if (pair[k].pair==pair[i].pair) l++; if (l>1) { printf("Inconsistent pairing list: %d:%d && %d:%d!\n", i, pair[i].pair, k, pair[k].pair); /*return(FALSE);*/ } } } /* printf(" ok\n"); */ /* printf("\nEinzelne Bp loeschen ..."); if (par->single==FALSE) { for (i=2; i<length; i++) { if (pair[i].pair != 0) { k = pair[i].pair; if ((pair[i-1].pair != k+1) && (pair[i+1].pair != k-1)) { * printf("\nBp(%d:%d) and Bp(%d:%d) deleted ...", i, k, k, pair[k].pair); * pair[k].pair = 0; pair[i].pair = 0; } } } } printf(" ok\n"); */ /* printf("\nSeq ueberweisen ..."); */ for (i=0; i<length; i++) { my_xyplot[i].pair = pair[i+1].pair; my_xyplot[i].nuc = *(string+i); } /* printf(" ok\n"); */ /* printf("\nUebergabe pair -> bond ..."); */ base_pair = (struct bond *) Scalloc(1+length/2, sizeof(struct bond)); base_pair->j = 0; base_pair++; l = 0; tag = 1; incr = FALSE; first = TRUE; for ( i = 1; i <= length; i++ ) { if ( pair[i].pair != 0 ) { incr = TRUE; base_pair->i = i; base_pair->j = pair[i].pair; if ( first || pair[i-1].pair == pair[i].pair+1 ) { if ( first ) { my_xyplot[ i -1].tag = -1*tag; my_xyplot[pair[i].pair-1].tag = -1*tag; first = FALSE; } else { my_xyplot[ i -1].tag = tag; my_xyplot[pair[i].pair-1].tag = tag; } } else { tag++; my_xyplot[ i -1].tag = -1*tag; my_xyplot[pair[i].pair-1].tag = -1*tag; } base_pair++; pair[pair[i].pair].pair=0; l++; } else { if ( incr ) { tag++; incr = FALSE; first = TRUE; } } } base_pair-=(l+1); base_pair->i=l; /* * for ( i = 0; i < length; i++ ) { * printf("i:j = %d:%d, tag = %d\n", i+1, my_xyplot[i].pair, my_xyplot[i].tag); * } */ /* printf(" ok\n"); */ /* printf("\nparse(string) ..."); */ straight = par->straight; parse(string); /* printf(" ok\n"); */ alpha = INIT_ANGLE; x[0] = INIT_X; y[0] = INIT_Y; xmin = xmax = x[0]; ymin = ymax = y[0]; /* printf("\nPivot (%d) ...", par->pivot); */ if (par->pivot==TRUE && par->numangle>0 ) { for (l=0; l<par->numangle; l++) { if ( par->angle0[l]<1 ) par->angle0[l]=1; /* erstes Nukleotid */ if ( par->angle9[l]>=length ) par->angle9[l]=length; /* letztes Nukleotid */ if ( par->angle9[l]==0 ) par->angle9[l]=length; par->angle[l]*=PI/180.; /* Drehwinkel */ } for ( l=1; l<par->numangle; l++ ) { /* Sortieren durch Einfuegen */ /* => par->angle0[i] < par->angle0[i+1] */ par0 = par->angle0[l]; par9 = par->angle9[l]; para = par->angle[ l]; i = l-1; while ( i>=0 && par0 < par->angle0[i] ) { par->angle0[i+1] = par->angle0[i]; par->angle9[i+1] = par->angle9[i]; par->angle[ i+1] = par->angle[ i]; i--; } par->angle0[i+1] = par0; par->angle9[i+1] = par9; par->angle[ i+1] = para; } l=0; for (i = 1; i <= length; i++) { if ( l<par->numangle && i==par->angle0[l] ) { /* i=[0,length-1] !!! d.h. jetzt 5' Helixrandnukleotid+1 */ delta = alpha+par->angle[l]; x[i] = x[i-1]+RADIUS*cos(-delta); /* 2. Stapel knicken */ y[i] = y[i-1]+RADIUS*sin(-delta); k = par->angle9[l]; /* 3' Helixrandnukleotid+1 */ /* * printf("l=%d\ti=%d\tk=%d\t",l,i,k); * printf("cos(-alpha-pi/2 )=cos(%f)=%f\t",-alpha-PIHALF, cos(-alpha-PIHALF) ); * printf("cos(-alpha+angle)=cos(%f)=", -alpha+angle[k] ); * printf( "%f\n", cos(-alpha+angle[k])); */ /* * | 5' Helixrandnukleotid * | | + 90 Grad = 3' Helixrandnukleotid * | | | + naechster Winkel = 3' Helixrandnukleotid+1 * | | | */ x[k] = x[i-1]+RADIUS*(cos(-alpha-PIHALF)+cos(-alpha+angle[k])); y[k] = y[i-1]+RADIUS*(sin(-alpha-PIHALF)+sin(-alpha+angle[k])); alpha_i = alpha; alpha = delta+PI-angle[i+1]; /* mit Knick weiter */ par->angle[l] = alpha_i-angle[k]; /* ohne Knick ab 3' Helixrandnukleotid+1 */ l++; } else { if ( x[i]==0. ) { /* wie ueblich */ x[i] = x[i-1]+RADIUS*cos(-alpha); y[i] = y[i-1]+RADIUS*sin(-alpha); alpha+= PI-angle[i+1]; } else { /* 3' Helixrandnukleotid+1 */ for (k=0; k<par->numangle; k++) { /* siehe oben: x[k], y[k] */ if ( i==par->angle9[k] ) { alpha = par->angle[k]; /* Winkel ohne Knick rueckspeichern */ alpha+= PI-angle[i+1]; /* und normal weiter */ break; /* raus aus FOR-Schleife */ } } } } } } else { /* no pivot */ for (i = 1; i <= length; i++) { x[i] = x[i-1]+RADIUS*cos(-alpha); /* korr. 5'-> 3' orient.: alpha -> -alpha */ y[i] = y[i-1]+RADIUS*sin(-alpha); /* korr. 5'-> 3' orient.: alpha -> -alpha */ alpha+= PI-angle[i+1]; } } /* printf(" ok\n"); */ /* printf("\nmin/max ..."); */ for (i = 1; i < length; i++) { xmin = x[i] < xmin ? x[i] : xmin; xmax = x[i] > xmax ? x[i] : xmax; ymin = y[i] < ymin ? y[i] : ymin; ymax = y[i] > ymax ? y[i] : ymax; } /* printf(" ok\n"); */ /* printf("\nscale factor ..."); */ if (par->scf != 0.0) { /* abs. scaling */ /* sm */ xmax = xmin + par->scf; ymax = ymin + par->scf; } else { /* * printf( "MaxScalingFactor %.1f \n", MAX((fabs(xmin)+fabs(xmax)),(fabs(ymin)+fabs(ymax))) ); */ } /* printf(" ok\n"); */ /* printf("\ntext (%d) ...", par->text); */ charsize = .75*RADIUS; /* char size = .5*bond length */ xmin -= 2.*1.5*RADIUS + 4.*charsize; /* add space for numbering */ xmax += 2.*1.5*RADIUS + 4.*charsize; ymin -= 2.*1.5*RADIUS + 4.*charsize; ymax += 2.*1.5*RADIUS + 4.*charsize; if ( par->text==TRUE ) { /* space for 4 top lines (4*0.8 cm) */ ymax+=6.*charsize; coord[4] = (xmin+xmax)/2.; /* PLOTSTRUCTURE of: squfile; month day, year; hour:min */ coord[5] = ymax-charsize; coord[6] = (xmin+xmax)/2.; coord[7] = ymax-3.*charsize; /* FOLD of : ... */ coord[8] = (xmin+xmax)/2.; coord[9] = ymax-5.*charsize; /* Length: ... */ } else { for ( i=4; i<=9; i++ ) coord[i]=0.; } coord[ 0] = xmin; /* size of graph */ coord[ 1] = ymin; coord[ 2] = xmax; coord[ 3] = ymax; coord[10] = charsize; /* char size = .5*bond length */ coord[11] = charsize/2.; /* char width */ /* printf(" ok\n"); */ /* printf("\nbackbone (%d) ...", par->backbone); */ if (par->backbone==TRUE) { /* draw backbone */ /* printf(" draw backbone ..."); */ for ( i = 0; i < length; i++ ) { my_xyplot[i].back_x1 = x[i ]; my_xyplot[i].back_y1 = y[i ]; my_xyplot[i].back_x2 = x[i+1]; /* ??????????????????? */ my_xyplot[i].back_y2 = y[i+1]; /* ??????????????????? */ } } /* printf(" ok\n"); */ /* printf("\nnuc (%d) ...", par->nuc); */ if (par->nuc==TRUE) { /* draw nucleotides */ if ( par->numnuc>0 ) { for (k=0; k<par->numnuc; k++) { if ( par->nuc0[k]<1 ) par->nuc0[k]=1; if ( par->nuc9[k]>=length ) par->nuc9[k]=length; if ( par->nuc9[k]==0 ) par->nuc9[k]=length; for (i=-1+par->nuc0[k]; i<par->nuc9[k]; i+=10 ) { lmax = (i+10)<par->nuc9[k]?(i+10):par->nuc9[k]; for (l = i; l < lmax; l++ ) { /* * if (*(string+l)!='X' && *(string)!='x') { */ if ( l==0 ) { my_xyplot[l].nuc_x = x[l]+(y[l] -y[l+1])/2.; my_xyplot[l].nuc_y = y[l]+(x[l+1]-x[l] )/2.; } else { my_xyplot[l].nuc_x = x[l]+(y[l-1]-y[l+1])/4.; my_xyplot[l].nuc_y = y[l]+(x[l+1]-x[l-1])/4.; } /* * } */ } } } } else { for (i = 0; i < length; i+=10 ) { lmax = (i+10)<length?(i+10):length; for (l = i; l < lmax; l++ ) { if (*(string+l)!='X' && *(string)!='x') { my_xyplot[l].nuc_x = x[l]+(y[l] -y[l+1])/2.; my_xyplot[l].nuc_y = y[l]+(x[l+1]-x[l] )/2.; } } } } } /* printf(" ok\n"); */ /* printf("\nbonds (%d) ...", par->bonds); */ if ( par->bonds==TRUE ) { /* draw bonds */ for (i = 0; i < length; i++ ) { l = pairs(i); if (l) { my_xyplot[i-1].bond_x1 = x[i-1]; my_xyplot[i-1].bond_y1 = y[i-1]; my_xyplot[i-1].bond_x2 = x[l-1]; my_xyplot[i-1].bond_y2 = y[l-1]; } } } /* printf(" ok\n"); */ /* printf("\nnumbers (%d) ...", par->numbers); */ if (par->numbers>0) { /* draw numbering */ if (par->nuc==TRUE) rfactor=0.5; else rfactor=0.0; if (*(string)!='X' && *(string)!='x') { my_xyplot[0].line_x1 = x[0]+(y[length-1]-y[ 1])*rfactor; my_xyplot[0].line_y1 = y[0]+(x[ 1]-x[length-1])*rfactor; my_xyplot[0].line_x2 = x[0]+ y[length-1]-y[ 1]; my_xyplot[0].line_y2 = y[0]+ x[ 1]-x[length-1]; my_xyplot[0].lpos_x = x[0]+(y[length-1]-y[ 1])*1.5; my_xyplot[0].lpos_y = y[0]+(x[ 1]-x[length-1])*1.5; my_xyplot[0].label = 1; } if (par->numbers==1) k=-1+2*par->numbers; else k=-1+ par->numbers; for (i = k; i < length; i+=par->numbers ) if (*(string+i)!='X' && *(string+i)!='x') { my_xyplot[i].line_x1 = x[i]+(y[i-1]-y[i+1])*rfactor; my_xyplot[i].line_y1 = y[i]+(x[i+1]-x[i-1])*rfactor; my_xyplot[i].line_x2 = x[i]+ y[i-1]-y[i+1]; my_xyplot[i].line_y2 = y[i]+ x[i+1]-x[i-1]; my_xyplot[i].lpos_x = x[i]+(y[i-1]-y[i+1])*1.5; my_xyplot[i].lpos_y = y[i]+(x[i+1]-x[i-1])*1.5; my_xyplot[i].label = i+1; } } /* printf(" ok\n"); */ /* printf("\nrange (%d) ...", par->range); */ if (par->range==TRUE) { /* draw modified numbering */ if (par->nuc==TRUE) rfactor=0.5; else rfactor=0.0; if (par->range0==1) k=-1+2*par->range0; else k=-1+ par->range0; for (i = k; i < length; i+=par->rangestep ) if (*(string+i)!='X' && *(string)!='x') { my_xyplot[i].line_x1 = x[i]+(y[i-1]-y[i+1])*rfactor; my_xyplot[i].line_y1 = y[i]+(x[i+1]-x[i-1])*rfactor; my_xyplot[i].line_x2 = x[i]+ y[i-1]-y[i+1]; my_xyplot[i].line_y2 = y[i]+ x[i+1]-x[i-1]; my_xyplot[i].lpos_x = x[i]+(y[i-1]-y[i+1])*1.5; my_xyplot[i].lpos_y = y[i]+(x[i+1]-x[i-1])*1.5; my_xyplot[i].label = i + 1 + par->range1 - par->range0; } } /* printf(" ok\n"); */ free((struct bond *)base_pair); /* printf("RETURN\n"); */ return(TRUE); }
static void loop(int i, int j, int cc) /* i, j are the positions AFTER the last pair of a stack; i.e i-1 and j+1 are paired. */ /* cc corrects count of the first loop */ { int count = 2; /* counts the VERTICES of a loop polygon; that's NOT necessarily the number of unpaired bases! Upon entry the loop has already 2 vertices, namely the pair i-1/j+1. */ int r = 0, bubble = 0; /* bubble counts the unpaired digits in loops */ int i_old, partner, k, l, start_k, start_l, fill, ladder; int begin, v, diff, diff1, diff2, remember[2*BRANCH]; float polygon; /* printf("loop start: %4d %4d %4d\n",i,j,cc); */ /* sm */ count-=cc; i_old = i-1, j++; /* j has now been set to the partner of the previous pair for correct while-loop termination. */ while (i != j) { partner = pairs(i); if (!partner) { i++, count++, bubble++; /* printf("\tif: i=%d, j=%d, pairs(i)=%d, count=%d, bubble=%d\n",i, j, pairs(i), count, bubble); */ } else { /* printf("\telse: i=%d, j=%d, pairs(i)=%d, count=%d, bubble=%d\n",i, j, pairs(i), count, bubble); */ count += 2; k = i, l = partner; /* beginning of stack */ remember[++r] = k; remember[++r] = l; i = partner+1; /* next i for the current loop */ start_k = k, start_l = l; ladder = 0; do { k++, l--, ladder++; /* go along the stack region */ } while (pairs(k) == l); fill = ladder-2; if (ladder >= 2) { angle[start_k+1+fill] += PIHALF; /* Loop entries and */ angle[start_l-1-fill] += PIHALF; /* exits get an */ angle[start_k] += PIHALF; /* additional PI/2. */ angle[start_l] += PIHALF; /* Why ? (exercise) */ if (ladder > 2) { for (; fill >= 1; fill--) { angle[start_k+fill] = PI; /* fill in the angles */ angle[start_l-fill] = PI; /* for the backbone */ } } } this_stack_size[++stk] = ladder; loop(k, l, 0); } } remember[++r] = j; begin = i_old < 0 ? 0 : i_old; if (straight==TRUE) { if ((r==3) && (begin>0) && ((remember[1]-begin)!=(remember[3]-remember[2]))) { /* printf("asymm. interner loop/bulge\n\tS : count = %d; ", count); */ count = remember[1]-begin+remember[3]-remember[2]; /* i.e. loop size +2 */ polygon = PI*(count-2)/(float)count; /* Innenwinkel */ /* printf("diff1+diff2 = %d\n", count); */ diff1 = remember[1]-begin; /* printf("\t1.: diff = %d = remember[1] - begin = %d - %d\n", diff1, remember[1], begin); */ /* printf("\t polygon = %f = %f; count = %d\n", polygon, polygon*180./PI, diff1-1); */ for (fill = 1; fill < diff1; fill++) angle[begin+fill] += polygon; angle[begin ] += PIHALF+(PI-polygon)*(diff1-1)/2.; /* Korrektur fuer Eintrittswinkel der Helix */ angle[begin+diff1] += PIHALF+(PI-polygon)*(diff1-1)/2.; /* Korrektur fuer Austrittswinkel der Helix */ /* for (fill = 0; fill <= diff1; fill++) */ /* printf("\t angle(%d) = %f\n", begin+fill, angle[begin+fill]*180./PI); */ begin = remember[2]; diff2 = remember[3]-begin; /* printf("\t2.: diff = %d = remember[3] - begin = %d - %d\n", diff2, remember[3], begin); */ /* printf("\t polygon = %f = %f; count = %d\n", polygon, polygon*180./PI, diff2-1); */ for (fill = 1; fill < diff2; fill++) angle[begin+fill] += polygon; angle[begin ] += PIHALF+(PI-polygon)*(diff2-1)/2.; angle[begin+diff2] += PIHALF+(PI-polygon)*(diff2-1)/2.; /* for (fill = 0; fill <= diff2; fill++) */ /* printf("\t angle(%d) = %f\n", begin+fill, angle[begin+fill]*180./PI); */ } else { /* if ((r==3) && (remember[1]-begin==remember[3]-remember[2])) { */ /* printf("symm. interner loop\n"); */ /* } else { */ /* if (r==1) { */ /* printf("hairpin\n"); */ /* } else { */ /* printf("bifurcation\n"); */ /* } */ /* } */ polygon = PI*(count-2)/(float)count; /* bending angle in loop polygon */ for (v = 1; v <= r; v++) { diff = remember[v]-begin; /* printf("\tdiff = %d = remember[%d] - begin = %d - %d\n", diff, v, remember[v], begin); */ /* printf("\tpolygon = %f = %f; count = %d\n", polygon, polygon*180./PI, count); */ for (fill = 0; fill <= diff; fill++) angle[begin+fill] += polygon; /* for (fill = 0; fill <= diff; fill++) */ /* printf("\tangle(%d) = %f\n", begin+fill, angle[begin+fill]*180./PI); */ if (v > r) break; begin = remember[++v]; } } } else { /* par->straight==FALSE */ polygon = PI*(count-2)/(float)count; for (v = 1; v <= r; v++) { diff = remember[v]-begin; for (fill = 0; fill <= diff; fill++) angle[begin+fill] += polygon; if (v > r) break; begin = remember[++v]; } } this_loop_size[++lp] = bubble; /* printf("loop end : %4d %4d %4d\n",i,j,bubble); */ /* sm */ }
int main(int argc, char **argv){ if (argc != 3){ fprintf( stderr, "Usage:\n %s data_file bins_file > outfile\n", argv[0]); exit(EXIT_FAILURE); } FILE *data_file; if((data_file=fopen(argv[1],"r"))==NULL){ fprintf(stderr,"Error: Cannot open file %s \n", argv[1]); exit(EXIT_FAILURE); } FILE *bins_file; if((bins_file=fopen(argv[2],"r"))==NULL){ fprintf(stderr,"Error: Cannot open file %s \n", argv[1]); exit(EXIT_FAILURE); } int nbins; fscanf(bins_file, "%d", &nbins); CORRELATION *corr; corr = calloc(nbins, sizeof(CORRELATION)); int i, k; /* read in bin settings and prepare corr */ for(k = 0; k < nbins; k++){ fscanf(bins_file, "%lf", &corr[k].r_lower); fscanf(bins_file, "%lf", &corr[k].r_upper); fscanf(bins_file, "%lf", &corr[k].r_middle); fscanf(bins_file, "%lf", &corr[k].bin_size); corr[k].r2_lower = corr[k].r_lower * corr[k].r_lower; corr[k].r2_upper = corr[k].r_upper * corr[k].r_upper; corr[k].DD_N = 0; //raw pair counts corr[k].DD = 0.0; //normalized pair counts } /* load data file */ int N_data; POINT *data; fprintf(stderr, "data file is: %s\n", argv[1]); fprintf(stderr, "Reading data .. \n"); fscanf(data_file, "%d", &N_data); /* first read in the length of the list */ /* Claim an array for a list of pointing */ data = calloc(N_data, sizeof(POINT)); for(i = 0; i < N_data; i++){ fscanf(data_file, "%lf", &data[i].x); fscanf(data_file, "%lf", &data[i].y); fscanf(data_file, "%lf", &data[i].z); } fprintf(stderr, "Read %d stars. \n", N_data); fclose(data_file); /* calculate the correlation */ fprintf(stderr, "Start calculating uniform pair counts... \n"); long int normalization = pairs_norm(data, N_data); pairs(data, N_data, corr, nbins); /* output */ for(k = 0; k < nbins; k++){ corr[k].DD = (double)corr[k].DD_N / (double)normalization; // fprintf(stdout, "%lf\t%lf\t%lf\t%lf\t%ld\t%le\n", // corr[k].r_lower, corr[k].r_upper, corr[k].r_middle, corr[k].bin_size, // corr[k].DD_N, corr[k].DD); fprintf( stdout, "%lf\n", corr[k].DD ); } fprintf(stderr, "Done calculation and output. \n"); return EXIT_SUCCESS; }
int bad_possible_elimination(sudoku_board board, int side){ int i, j, k, n, m,aa=0, abc, alone_ok=0; sudoku_board test_board; // print_board(board, side); for (i=0; i<side; ++i) {//ROW for (j=0; j<side; ++j) {//COLUMN //printf("row=%d column=%d\n", i, j); //printf("\tvalue = %d\n", get_value(&board[i][j])); if (get_value(&board[i][j])==0) { for (k=0; k<side; ++k) {//POSSIBLE //printf("k=%d possible=%d\n", k, board[i][j].possible[k]); if (board[i][j].possible[k]){ test_board = create_board(side); for (n=0; n<side; ++n) for (m=0; m<side; ++m){ if (get_value(&board[n][m])) found_value(test_board, side, n, m, get_value(&board[n][m])); } found_value(test_board, side, i, j, board[i][j].possible[k]); alone_ok=0; for (n=0; n<side; ++n) { if ((board[i][n].possibles)==1) { for (m=0; m<side; ++m) { if (board[i][n].possible[m]) { alone_ok = 1; found_value(test_board, side, i, n, board[i][n].possible[m]); } } } if ((board[n][j].possibles)==1) { for (m=0; m<side; ++m) { if (board[n][j].possible[m]) { alone_ok = 1; found_value(test_board, side, n, j, board[n][j].possible[m]); } } } } if (singleton(test_board, side, i, j, i+1, j+1)) alone_ok = 1; if (pairs(test_board, side, i, j, i+1, j+1)) alone_ok = 1; if (alone_ok) { while (1){ if (alone(board, side)) continue; if (singleton(board, side, 0, 0, side, side)) continue; if (pairs(board, side, 0, 0, side, side)) continue; break; } } abc = check_solution(test_board, side); //printf("%d\n", aa); switch (abc) { case 0: found_value(board, side, i, j, board[i][j].possible[k]); delete_board(test_board, side); return -1; case 1: delete_possible(&board[i][j], board[i][j].possible[k], side); ++aa; break; default: break; } delete_board(test_board, side); } } } } } return aa; }
/* Score the hand */ score_t score(hand_t * hand) { return right_jack(hand) + runs(hand) + pairs(hand) + fifteens(hand); }
/* Return number of hints. The hints mechanism should attempt to find * 'easy' moves first, and if none are possible, then try for more * cryptic moves. */ int findhints( void ) { int i, n, mutated = 0; rb->yield(); n = findmoves( ); if( n < 2 ) { /* Each call to pairs() can mutate the board state, making the * hints very, very cryptic... so later undo the mutations. */ for( i = 0 ; i < 9 ; ++i ) { count_set_digits( i, idx_row ); pairs( i, idx_row ); count_set_digits( i, idx_column ); pairs( i, idx_column ); count_set_digits( i, idx_block ); pairs( i, idx_block ); } mutated = 1; n = findmoves( ); } if( n < 2 ) { for( i = 0 ; i < 9 ; ++i ) { block( i ); common( i ); } mutated = 1; n = findmoves( ); } /* Sort the possible moves, and allow just one hint per square */ if( 0 < n ) { int i, j; rb->qsort( possible, n, sizeof( int ), cmpindex ); for( i = 0, j = 1 ; j < n ; ++j ) { if( GET_INDEX( possible[ i ] ) == GET_INDEX( possible[ j ] ) ) { /* Let the user make mistakes - do not assume the * board is in a consistent state. */ if( GET_DIGIT( possible[i] ) == GET_DIGIT( possible[j] ) ) possible[ i ] |= possible[ j ]; } else i = j; } n = i + 1; } /* Undo any mutations of the board state */ if( mutated ) reapply( ); return n; }
void cv::merge(const Mat* mv, size_t n, OutputArray _dst) { CV_Assert( mv && n > 0 ); int depth = mv[0].depth(); bool allch1 = true; int k, cn = 0; size_t i; for( i = 0; i < n; i++ ) { CV_Assert(mv[i].size == mv[0].size && mv[i].depth() == depth); allch1 = allch1 && mv[i].channels() == 1; cn += mv[i].channels(); } CV_Assert( 0 < cn && cn <= CV_CN_MAX ); _dst.create(mv[0].dims, mv[0].size, CV_MAKETYPE(depth, cn)); Mat dst = _dst.getMat(); if( n == 1 ) { mv[0].copyTo(dst); return; } if( !allch1 ) { AutoBuffer<int> pairs(cn*2); int j, ni=0; for( i = 0, j = 0; i < n; i++, j += ni ) { ni = mv[i].channels(); for( k = 0; k < ni; k++ ) { pairs[(j+k)*2] = j + k; pairs[(j+k)*2+1] = j + k; } } mixChannels( mv, n, &dst, 1, &pairs[0], cn ); return; } size_t esz = dst.elemSize(), esz1 = dst.elemSize1(); int blocksize0 = (int)((BLOCK_SIZE + esz-1)/esz); AutoBuffer<uchar> _buf((cn+1)*(sizeof(Mat*) + sizeof(uchar*)) + 16); const Mat** arrays = (const Mat**)(uchar*)_buf; uchar** ptrs = (uchar**)alignPtr(arrays + cn + 1, 16); arrays[0] = &dst; for( k = 0; k < cn; k++ ) arrays[k+1] = &mv[k]; NAryMatIterator it(arrays, ptrs, cn+1); int total = (int)it.size, blocksize = cn <= 4 ? total : std::min(total, blocksize0); MergeFunc func = mergeTab[depth]; for( i = 0; i < it.nplanes; i++, ++it ) { for( int j = 0; j < total; j += blocksize ) { int bsz = std::min(total - j, blocksize); func( (const uchar**)&ptrs[1], ptrs[0], bsz, cn ); if( j + blocksize < total ) { ptrs[0] += bsz*esz; for( int k = 0; k < cn; k++ ) ptrs[k+1] += bsz*esz1; } } } }
void HestonSLVMCModel::performCalculations() const { const boost::shared_ptr<HestonProcess> hestonProcess = hestonModel_->process(); const boost::shared_ptr<Quote> spot = hestonProcess->s0().currentLink(); const boost::shared_ptr<YieldTermStructure> rTS = hestonProcess->riskFreeRate().currentLink(); const boost::shared_ptr<YieldTermStructure> qTS = hestonProcess->dividendYield().currentLink(); const Real v0 = hestonProcess->v0(); const DayCounter dc = hestonProcess->riskFreeRate()->dayCounter(); const Date referenceDate = hestonProcess->riskFreeRate()->referenceDate(); const Volatility lv0 = localVol_->localVol(0.0, spot->value())/std::sqrt(v0); const boost::shared_ptr<Matrix> L(new Matrix(nBins_, timeGrid_->size())); std::vector<boost::shared_ptr<std::vector<Real> > > vStrikes(timeGrid_->size()); for (Size i=0; i < timeGrid_->size(); ++i) { const Integer u = nBins_/2; const Real dx = spot->value()*std::sqrt(QL_EPSILON); vStrikes[i] = boost::make_shared<std::vector<Real> >(nBins_); for (Integer j=0; j < Integer(nBins_); ++j) vStrikes[i]->at(j) = spot->value() + (j - u)*dx; } std::fill(L->column_begin(0),L->column_end(0), lv0); leverageFunction_ = boost::make_shared<FixedLocalVolSurface>( referenceDate, std::vector<Time>(timeGrid_->begin(), timeGrid_->end()), vStrikes, L, dc); const boost::shared_ptr<HestonSLVProcess> slvProcess = boost::make_shared<HestonSLVProcess>(hestonProcess, leverageFunction_); std::vector<std::pair<Real, Real> > pairs( calibrationPaths_, std::make_pair(spot->value(), v0)); const Size k = calibrationPaths_ / nBins_; const Size m = calibrationPaths_ % nBins_; const Size timeSteps = timeGrid_->size()-1; typedef boost::multi_array<Real, 3> path_type; path_type paths(boost::extents[calibrationPaths_][timeSteps][2]); const boost::shared_ptr<BrownianGenerator> brownianGenerator = brownianGeneratorFactory_->create(2, timeSteps); for (Size i=0; i < calibrationPaths_; ++i) { brownianGenerator->nextPath(); std::vector<Real> tmp(2); for (Size j=0; j < timeSteps; ++j) { brownianGenerator->nextStep(tmp); paths[i][j][0] = tmp[0]; paths[i][j][1] = tmp[1]; } } for (Size n=1; n < timeGrid_->size(); ++n) { const Time t = timeGrid_->at(n-1); const Time dt = timeGrid_->dt(n-1); Array x0(2), dw(2); for (Size i=0; i < calibrationPaths_; ++i) { x0[0] = pairs[i].first; x0[1] = pairs[i].second; dw[0] = paths[i][n-1][0]; dw[1] = paths[i][n-1][1]; x0 = slvProcess->evolve(t, x0, dt, dw); pairs[i].first = x0[0]; pairs[i].second = x0[1]; } std::sort(pairs.begin(), pairs.end()); Size s = 0u, e = 0u; for (Size i=0; i < nBins_; ++i) { const Size inc = k + (i < m); e = s + inc; Real sum=0.0; for (Size j=s; j < e; ++j) { sum+=pairs[j].second; } sum/=inc; vStrikes[n]->at(i) = 0.5*(pairs[e-1].first + pairs[s].first); (*L)[i][n] = std::sqrt(square<Real>()( localVol_->localVol(t, vStrikes[n]->at(i), true))/sum); s = e; } leverageFunction_->setInterpolation<Linear>(); } }
bool CGrammarItem::fromString(string& Result) { StringTokenizer lines (Result.c_str(), "\r\n"); int LineNo = 0; while (lines()) { LineNo++; string line = lines.val(); if (LineNo == 1) continue; if (LineNo == 2) { char buff1[1024]; char buff2[1024]; int iMeta; int iTokenType; if (sscanf(line.c_str(), "%i %s %s %i\n", &iMeta, buff1, buff2, &iTokenType) != 4) return false; m_bMeta = (bool)iMeta; m_TokenType = (MainTokenTypeEnum)iTokenType; m_ItemStrId = buff1; if (m_ItemStrId.empty()) return false; m_Token = buff2; if (m_Token == "null") m_Token = ""; }; if (LineNo == 3) { char buff1[1024]; int Count = sscanf(line.c_str(), "%[^\x1]", buff1); if (Count != 1) return false; m_Source = buff1; }; if (LineNo == 4) { if (!m_MorphPattern.FromString(line)) return false; }; if (LineNo == 5) { int i1, i2,i3, i4; if (sscanf(line.c_str(), "%i %i %i %i", &i1, &i2, &i3, &i4) != 4) return false; m_bGrammarRoot = i1==1; m_bSynMain = i2==1; m_bCanHaveManyHomonyms = i3==1; m_Register = (RegisterEnum)i4; }; if (LineNo == 6) { m_Attributes.clear(); StringTokenizer pairs(line.c_str(), ";"); while (pairs()) { char buff1[1024]; char buff2[1024]; string _pair = pairs.val(); sscanf (_pair.c_str(), "%s %s", buff1, buff2); m_Attributes[buff1] = buff2; }; }; }; if (LineNo != 7) return false; return true; }
/* calculate the energy for the surface scan - same as function energy() but without observables */ double surface_energy(system_t *system, int energy_type) { double rd_energy, coulombic_energy, polar_energy, vdw_energy; /* zero the initial values */ rd_energy = 0; coulombic_energy = 0; polar_energy = 0; vdw_energy = 0; /* get the pairwise terms necessary for the energy calculation */ pairs(system); // energy_type = ENERGY_TOTAL // all other params are 0 switch(energy_type) { case ENERGY_TOTAL: if(!(system->sg || system->rd_only)) coulombic_energy = coulombic_nopbc(system->molecules); if(system->polarization) polar_energy = polar(system); if(system->polarvdw) vdw_energy = vdw(system); if(system->sg) rd_energy = sg_nopbc(system->molecules); else if(system->cdvdw_exp_repulsion) rd_energy = exp_repulsion(system); else if(system->dreiding) rd_energy = dreiding_nopbc(system->molecules); else if(system->lj_buffered_14_7) rd_energy = lj_buffered_14_7_nopbc(system); else if(system->disp_expansion) rd_energy = disp_expansion_nopbc(system); else rd_energy = lj_nopbc(system); break; case ENERGY_ES: if(!(system->sg || system->rd_only)) coulombic_energy = coulombic_nopbc(system->molecules); break; case ENERGY_RD: if(system->sg) { rd_energy = sg_nopbc(system->molecules); } else if(system->dreiding) { rd_energy = dreiding_nopbc(system->molecules); } else if(system->lj_buffered_14_7) { rd_energy = lj_buffered_14_7_nopbc(system); } else if(system->disp_expansion) { rd_energy = disp_expansion_nopbc(system); } else { rd_energy = lj_nopbc(system); } break; case ENERGY_POLAR: if(system->polarization) polar_energy = polar(system); break; case ENERGY_VDW: if(system->polarvdw) vdw_energy = vdw(system); break; } /* return the total potential energy */ return rd_energy + coulombic_energy + polar_energy + vdw_energy; }
int main(int argc, char *argv[]) { unsigned int t = time(NULL); srand(t); itk::Size<2> size; size.Fill(100); itk::Index<2> index; index.Fill(0); itk::ImageRegion<2> region(index, size); /* // Generate a random image (this method doesn't work with VectorImage) itk::RandomImageSource<FloatVectorImageType>::Pointer imageSource = itk::RandomImageSource<FloatVectorImageType>::New(); imageSource->SetNumberOfThreads(1); // to produce non-random results imageSource->SetSize(size); imageSource->SetMin(0); imageSource->SetMax(100); imageSource->Update(); FloatVectorImageType::Pointer image = imageSource->GetOutput(); */ // Generate a random image FloatVectorImageType::Pointer image = FloatVectorImageType::New(); image->SetRegions(region); image->SetNumberOfComponentsPerPixel(3); image->Allocate(); { itk::ImageRegionIterator<FloatVectorImageType> imageIterator(image, image->GetLargestPossibleRegion()); while(!imageIterator.IsAtEnd()) { FloatVectorImageType::PixelType pixel; pixel.SetSize(3); pixel[0] = drand48(); pixel[1] = drand48(); pixel[2] = drand48(); imageIterator.Set(pixel); ++imageIterator; } } // Generate a random membership image IntImageType::Pointer membershipImage = IntImageType::New(); membershipImage->SetRegions(region); membershipImage->Allocate(); membershipImage->FillBuffer(0); { itk::ImageRegionIterator<IntImageType> membershipImageIterator(membershipImage, membershipImage->GetLargestPossibleRegion()); while(!membershipImageIterator.IsAtEnd()) { IntImageType::PixelType pixel; pixel = rand() / 1000; membershipImageIterator.Set(pixel); ++membershipImageIterator; } } // Write the image itk::ImageFileWriter<FloatVectorImageType>::Pointer imageWriter = itk::ImageFileWriter<FloatVectorImageType>::New(); imageWriter->SetFileName("image.mha"); imageWriter->SetInput(image); imageWriter->Update(); // // Generate a random mask // itk::RandomImageSource<Mask>::Pointer maskSource = itk::RandomImageSource<Mask>::New(); // maskSource->SetNumberOfThreads(1); // to produce non-random results // maskSource->SetSize(size); // maskSource->SetMin(0); // maskSource->SetMax(255); // maskSource->Update(); // // // Threshold the mask // //typedef itk::ThresholdImageFilter <UnsignedCharImageType> ThresholdImageFilterType; // typedef itk::BinaryThresholdImageFilter <Mask, Mask> ThresholdImageFilterType; // ThresholdImageFilterType::Pointer thresholdFilter = ThresholdImageFilterType::New(); // thresholdFilter->SetInput(maskSource->GetOutput()); // thresholdFilter->SetLowerThreshold(0); // thresholdFilter->SetUpperThreshold(122); // thresholdFilter->SetOutsideValue(1); // thresholdFilter->SetInsideValue(0); // thresholdFilter->Update(); // Mask::Pointer mask = thresholdFilter->GetOutput(); std::cout << "Creating mask..." << std::endl; Mask::Pointer mask = Mask::New(); mask->SetRegions(region); mask->Allocate(); { itk::ImageRegionIterator<Mask> maskIterator(mask, mask->GetLargestPossibleRegion()); while(!maskIterator.IsAtEnd()) { int randomNumber = rand()%10; //std::cout << "randomNumber: " << randomNumber << std::endl; if(randomNumber > 5) { maskIterator.Set(mask->GetHoleValue()); } else { maskIterator.Set(mask->GetValidValue()); } ++maskIterator; } } std::cout << "Writing mask..." << std::endl; // Write the mask itk::ImageFileWriter<Mask>::Pointer maskWriter = itk::ImageFileWriter<Mask>::New(); maskWriter->SetFileName("mask.png"); maskWriter->SetInput(mask); maskWriter->Update(); std::cout << "Creating source patches..." << std::endl; unsigned int patchRadius = 10; // Create source patches itk::ImageRegionConstIterator<FloatVectorImageType> imageIterator(image, image->GetLargestPossibleRegion()); std::vector<Patch> sourcePatches; while(!imageIterator.IsAtEnd()) { itk::Index<2> currentPixel = imageIterator.GetIndex(); itk::ImageRegion<2> region = Helpers::GetRegionInRadiusAroundPixel(currentPixel, patchRadius); if(image->GetLargestPossibleRegion().IsInside(region)) { sourcePatches.push_back(Patch(region)); } ++imageIterator; } std::cout << "Source patches: " << sourcePatches.size() << std::endl; itk::Size<2> targetSize; targetSize.Fill(patchRadius * 2 + 1); itk::Index<2> targetIndex; targetIndex.Fill(3); itk::ImageRegion<2> targetRegion(targetIndex, targetSize); Patch targetPatch(targetRegion); CandidatePairs pairs(targetPatch); pairs.AddPairFromPatch(targetPatch); itk::ImageRegion<2> adjacentRegion = targetRegion; itk::Index<2> adjacentIndex; adjacentIndex[0] = targetIndex[0] + 1; adjacentIndex[1] = targetIndex[1] + 1; adjacentRegion.SetIndex(adjacentIndex); Patch adjacentPatch(adjacentRegion); pairs.AddPairFromPatch(adjacentPatch); //pairs.AddPairFromPatch(sourcePatches[0]); SelfPatchCompare patchCompare; patchCompare.SetPairs(&pairs); patchCompare.SetImage(image); patchCompare.SetMask(mask); patchCompare.SetNumberOfComponentsPerPixel(3); patchCompare.SetMembershipImage(membershipImage); patchCompare.FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchMembershipDifference,&patchCompare,_1)); patchCompare.ComputeAllSourceDifferences(); std::cout << "pairs: " << pairs.size() << std::endl; for(unsigned int i = 0; i < pairs.size(); ++i) { std::cout << "MembershipDifference: " << pairs[i].DifferenceMap[PatchPair::MembershipDifference] << std::endl; } //unsigned int bestMatchSourcePatchId = patchCompare.FindBestPatch(); //std::cout << "bestMatchSourcePatchId: " << bestMatchSourcePatchId << std::endl; /* unsigned int patchId = 1; float slowPatchDifference = patchCompare.SlowDifference(sourcePatches[patchId]); std::cout << "slowPatchDifference: " << slowPatchDifference << std::endl; float fastPatchDifference = patchCompare.PatchDifference(sourcePatches[patchId]); std::cout << "fastPatchDifference: " << fastPatchDifference << std::endl; unsigned int iterations = 1e6; itk::TimeProbe slowTimer; slowTimer.Start(); for(unsigned int i = 0; i < iterations; ++i) { float slowPatchDifference = patchCompare.SlowDifference(sourcePatches[patchId]); } slowTimer.Stop(); std::cout << "Slow Total: " << slowTimer.GetTotal() << std::endl; itk::TimeProbe fastTimer; fastTimer.Start(); for(unsigned int i = 0; i < iterations; ++i) { float fastPatchDifference = patchCompare.PatchDifference(sourcePatches[patchId]); } fastTimer.Stop(); std::cout << "Fast Total: " << fastTimer.GetTotal() << std::endl;*/ return EXIT_SUCCESS; }
bool CalibratorGaussian::calibrateCore(File& iFile, const ParameterFile* iParameterFile) const { int nLat = iFile.getNumLat(); int nLon = iFile.getNumLon(); int nEns = iFile.getNumEns(); int nTime = iFile.getNumTime(); vec2 lats = iFile.getLats(); vec2 lons = iFile.getLons(); vec2 elevs = iFile.getElevs(); // Loop over offsets for(int t = 0; t < nTime; t++) { Field& field = *iFile.getField(mMainPredictor, t); Parameters parameters; if(!iParameterFile->isLocationDependent()) parameters = iParameterFile->getParameters(t); #pragma omp parallel for for(int i = 0; i < nLat; i++) { for(int j = 0; j < nLon; j++) { if(iParameterFile->isLocationDependent()) parameters = iParameterFile->getParameters(t, Location(lats[i][j], lons[i][j], elevs[i][j])); // Compute model variables float total2 = 0; float total = 0; int counter = 0; bool isValid = true; for(int e = 0; e < nEns; e++) { // Create a neighbourhood ensemble for(int ii = std::max(0, i-mNeighbourhoodSize); ii <= std::min(nLat-1, i+mNeighbourhoodSize); ii++) { for(int jj = std::max(0, j-mNeighbourhoodSize); jj <= std::min(nLon-1, j+mNeighbourhoodSize); jj++) { float value = field(ii,jj,e); if(Util::isValid(value)) { total += value; total2 += value*value; counter++; } } } } const std::vector<float>& raw = field(i,j); // Only calibrate the ensemble if all members are available. Otherwise // use the raw members. if(counter > 0) { float ensMean = Util::MV; float ensSpread = Util::MV; if(counter > 0) { ensMean = total / counter; ensSpread = sqrt(total2/counter - (ensMean*ensMean)); } // Calibrate std::vector<std::pair<float,int> > pairs(nEns); std::vector<float> valuesCal(nEns); for(int e = 0; e < nEns; e++) { float quantile = ((float) e+0.5)/nEns; float valueCal = getInvCdf(quantile, ensMean, ensSpread, parameters); field(i,j,e) = valueCal; if(!Util::isValid(valueCal)) isValid = false; } if(isValid) { std::vector<float> cal = field(i,j); Calibrator::shuffle(raw, cal); for(int e = 0; e < nEns; e++) { field(i,j,e) = cal[e]; } } else { // Calibrator produced some invalid members. Revert to the raw values. for(int e = 0; e < nEns; e++) { field(i,j,e) = raw[e]; } } } else { // One or more members are missing, don't calibrate for(int e = 0; e < nEns; e++) { field(i,j,e) = raw[e]; } } } } } return true; }
void construct_neutral_set(const message &M1, const message &M2, const difference &D, const DifferentialPath &P){ int r = 0; set<vector<int>> bad_pairs; //read(bad_pairs); //cout << "bad set size: " << bad_pairs.size() << endl; ofstream pairs("pairs.txt"); set<int> bad_set; for (int v = 0; v < 512; v++){ if (P.checkBit(v)){ message tmp_m1(M1); message tmp_m2(M2); tmp_m1.modify(xor_vec(M1.W, v, -1, -1, -1, -1), R); tmp_m2.modify(xor_vec(M2.W, v, -1, -1, -1, -1), R); if (P.check(tmp_m1, tmp_m2) >= R){ #pragma omp critical { pairs << v << " -1 -1 -1 -1" << endl; bad_set.insert(v); } } } } time_t seconds = time(NULL); omp_set_num_threads(16); //* #pragma omp parallel for for (int v = 0; v < 512; v++){ if (P.checkBit(v)){ message tmp_m1(M1); message tmp_m2(M2); if (bad_set.find(v) == bad_set.end()){ for (int q = v + 1; q < 512; q++){ if (P.checkBit(q) && (bad_set.find(q) == bad_set.end())){ tmp_m1.modify(xor_vec(M1.W, v, q, -1, -1, -1), R); tmp_m2.modify(xor_vec(M2.W, v, q, -1, -1, -1), R); if (P.check(tmp_m1, tmp_m2) >= R){ #pragma omp critical { pairs << v << " " << q << " -1 -1 -1" << endl; //bad_pairs.insert(vector<int>{v,q}); } } } } } } } //*/ //cout << "pairs time: " << time(NULL) - seconds << endl; seconds = time(NULL); //* #pragma omp parallel for for (int v = 0; v < 512; v++){ if (P.checkBit(v)){ message tmp_m1(M1); message tmp_m2(M2); if (bad_set.find(v) == bad_set.end()){ for (int q = v + 1; q < 512; q++){ if (P.checkBit(q) && (bad_set.find(q) == bad_set.end()) //&& (bad_pairs.find({ v, q }) == bad_pairs.end()) ){ for (int w = q + 1; w < 512; w++){ if (P.checkBit(w) && (bad_set.find(w) == bad_set.end()) //&& (bad_pairs.find({ v, w }) == bad_pairs.end()) //&& (bad_pairs.find({ q, w }) == bad_pairs.end()) ){ tmp_m1.modify(xor_vec(M1.W, v, q, w, -1, -1), R); tmp_m2.modify(xor_vec(M2.W, v, q, w, -1, -1), R); if (P.check(tmp_m1, tmp_m2) >= R){ #pragma omp critical { pairs << v << " " << q << " " << w << " -1 -1" << endl; //bad_pairs.insert(vector<int>{v, q, w}); } } } } } } } } //cout << time(NULL) - t << " "; } //*/ //cout << dec << "triplets time: " << time(NULL) - seconds << endl; seconds = time(NULL); //* #pragma omp parallel for for (int v = 0; v < 512; v++){ if (P.checkBit(v)){ message tmp_m1(M1); message tmp_m2(M2); if (bad_set.find(v) == bad_set.end()){ for (int q = v + 1; q < 512; q++){ if (P.checkBit(q) && (bad_set.find(q) == bad_set.end())){ for (int w = q + 1; w < 512; w++){ if (P.checkBit(w) && (bad_set.find(w) == bad_set.end())){ for (int s = w + 1; s < 512; s++){ if (P.checkBit(s) && (bad_set.find(s) == bad_set.end())){ tmp_m1.modify(xor_vec(M1.W, v, q, w, s, -1), R); tmp_m2.modify(xor_vec(M2.W, v, q, w, s, -1), R); if (P.check(tmp_m1, tmp_m2) >= R){ #pragma omp critical { pairs << v << " " << q << " " << w << " " << s << " -1" << endl; } } } } } } } } } } //cout << time(NULL) - t << " "; } //*/ //cout << "quadroplets time: " << time(NULL) - seconds << endl; pairs.close(); }