void UPolynomial<T>:: solve(const RationalFunctionP& rf, RootStack& stack) { typedef SYNAPS::Seq<RootType> RootSeq; AssertMsg(stack.empty(), "Stack must be empty before solve"); RootSeq seq_num = SYNAPS::solve(SynapsTraits<T>::convert(rf.numerator()), Solver()); RootSeq seq_den = SYNAPS::solve(SynapsTraits<T>::convert(rf.denominator()), Solver()); // TODO: assert that all roots in seq_den have positive multiplicity // TODO: deal with multiplicities for the numerator for (typename RootSeq::const_reverse_iterator cur = seq_num.rbegin(); cur != seq_num.rend(); ++cur) { if (SynapsTraits<T>::multiplicity(*cur) % 2 != 0) { if (!stack.empty() && stack.top() == *cur) // get rid of even multiplicities // TODO: add logging information for this stack.pop(); else stack.push(*cur); } } }
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]); std::vector<std::vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig // IsStandardTx() will have already returned false // and this method isn't called. std::vector<std::vector<unsigned char> > stack; if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker())) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); std::vector<std::vector<unsigned char> > vSolutions2; txnouttype whichType2; if (Solver(subscript, whichType2, vSolutions2)) { int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } else { // Any other Script with less than 15 sigops OK: unsigned int sigops = subscript.GetSigOpCount(true); // ... extra data left on the stack after execution is OK, too: return (sigops <= MAX_P2SH_SIGOPS); } } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; }
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out; std::vector<std::vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; if (whichType == TX_SCRIPTHASH) { std::vector<std::vector<unsigned char> > stack; // convert the scriptSig into a stack, so we can inspect the redeemScript if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SIGVERSION_BASE)) return false; if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) { return false; } } } return true; }
void Solver() { int i, j, k; if(FullFill()) { OutputSudoku(); return; } for(i=0; i<9; i++) { for(j=0; j<9; j++) { if(Sudoku[i][j]==0) { for(k=1; k<10; k++) { if(Check(i, j, k)) { Sudoku[i][j]=k; Solver(); } } if(k==10) { Sudoku[i][j]=0; return; } } } } }
bool PhysicsEngine::Init(double dGravity, double dTimeStep, double nMaxSubSteps){ timestep_ = dTimeStep; gravity_acc_ = dGravity; time_max_substeps_ = nMaxSubSteps; // Physics stuff // See http://bulletphysics.org/mediawiki-1.5.8/index.php/Hello_World std::shared_ptr<btCollisionDispatcher> Dispatcher( new btCollisionDispatcher(&collision_configuration_) ); bt_dispatcher_ = Dispatcher; std::shared_ptr<btDbvtBroadphase> Broadphase( new btDbvtBroadphase ); bt_broadphase_ = Broadphase; std::shared_ptr<btSequentialImpulseConstraintSolver> Solver( new btSequentialImpulseConstraintSolver ); bt_solver_ = Solver; std::shared_ptr<btDiscreteDynamicsWorld> DWorld( new btDiscreteDynamicsWorld(bt_dispatcher_.get(), bt_broadphase_.get(), bt_solver_.get(), &collision_configuration_) ); dynamics_world_ = DWorld; dynamics_world_->setGravity( btVector3(0, 0, gravity_acc_) ); dynamics_world_->setDebugDrawer( &debug_drawer_ ); dynamics_world_->getDebugDrawer()-> setDebugMode(btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_FastWireframe + btIDebugDraw::DBG_DrawConstraints); vehicle_raycaster_ = new btDefaultVehicleRaycaster(dynamics_world_.get()); return true; }
SynapsTraits<QQ>::RootType SynapsTraits<QQ>:: root(const CoefficientType& r) { ZZ p[2] = { -SYNAPS::numerator(r), SYNAPS::denominator(r) }; return SYNAPS::solve(SolverPolynomial(2, p), Solver(), 0); }
double FilmMinimizerTM::func(const gsl_vector * x, void * params) { double ret=100; int status; FilmFuncParams* p=(FilmFuncParams*)params; double &n1=p->n1, &n3=p->n3, &k=p->k, *bettaexp=p->bettaexp; FilmParams film(x); DispEqTMSolver Solver(DispEqTMFuncParams(n1, film.n, n3, k*film.H)); if( (status=Solver.Run(n3,film.n, 1e-6)) ==GSL_SUCCESS) { int i,j,roots_n=Solver.roots.GetSize(),betta_n=Solver.min_roots; double cur_ret; for(i=0;i<=roots_n-betta_n;i++) { cur_ret=0; for(j=0;j<betta_n;j++) { cur_ret+=abs(Solver.roots[j+i]-bettaexp[j]); } if(cur_ret<ret) { ret=cur_ret; p->betta_teor.RemoveAll(); betta_info t; for(j=0;j<betta_n;j++) { t.val=Solver.roots[j+i]; t.n=j+i; p->betta_teor.Add(t); } } } } func_call_cntr+=DispEqTMSolver::func_call_cntr; return ret; }
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } // Multisig txns have more than one address... return false; }
/** * Sign scriptPubKey using signature made with creator. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed), * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script. * Returns false if scriptPubKey could not be completely satisfied. */ static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion) { CScript scriptRet; uint160 h160; ret.clear(); std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, whichTypeRet, vSolutions)) return false; CKeyID keyID; switch (whichTypeRet) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_WITNESS_UNKNOWN: return false; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); return Sign1(provider, keyID, creator, scriptPubKey, ret, sigversion); case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!Sign1(provider, keyID, creator, scriptPubKey, ret, sigversion)) return false; else { CPubKey vch; provider.GetPubKey(keyID, vch); ret.push_back(ToByteVector(vch)); } return true; case TX_SCRIPTHASH: if (provider.GetCScript(uint160(vSolutions[0]), scriptRet)) { ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end())); return true; } return false; case TX_MULTISIG: ret.push_back(valtype()); // workaround CHECKMULTISIG bug return (SignN(provider, vSolutions, creator, scriptPubKey, ret, sigversion)); case TX_WITNESS_V0_KEYHASH: ret.push_back(vSolutions[0]); return true; case TX_WITNESS_V0_SCRIPTHASH: CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin()); if (provider.GetCScript(h160, scriptRet)) { ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end())); return true; } return false; default: return false; } }
SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const SignatureData& scriptSig1, const SignatureData& scriptSig2) { txnouttype txType; std::vector<std::vector<unsigned char> > vSolutions; Solver(scriptPubKey, txType, vSolutions); return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1), Stacks(scriptSig2), SIGVERSION_BASE).Output(); }
mat Scheme::implicitScheme(int nSteps, double tSteps, double(*u_s)(double)) { //input: nSteps (# of interior points), time, tSteps, u_s(x) double deltaX = 1.0 / (nSteps + 1); double deltaT = 1.0 / tSteps; double alpha = deltaT / pow(deltaX,2); vec v(nSteps), vNext(nSteps), u(nSteps); int printIndex = tSteps / 10; mat M(printIndex, nSteps); int index = 0; for( int i = 0; i < nSteps; i++) { double x = (i + 1) * deltaX; vNext[i] = v[i] = -u_s(x); } // Boundary conditions v[0] = vNext[0] = v[nSteps] = vNext[nSteps] = 0; double a = -alpha; // diagonal element double b = 1 + 2*alpha; // off-diagonal element Solver solv = Solver(); for(int t = 1; t <= tSteps; t++) { solv.tridiagonalSolver(a, b, v, vNext); // Initial conditions vNext[0] = vNext[nSteps] = 0; v = vNext; for (int i = 0; i < nSteps; i++) { double x = (i + 1) * deltaX; u[i] = v[i] + u_s(x); } // Print to file ! if (t % 10 == 0) { for (int i = 0; i < nSteps; i++) M(index, i) = u[i]; index++; } } for (int i = 0; i < printIndex; i++) { for (int j = 0; j < nSteps; j++) printf("%f \t", M(i, j)); } return M; }
int main() { const int n = 500; // Number of atoms, molecules const int mt = 20; // Max time steps const int dtxyz = 100; // Time interval to output xyz int i; int j; double *x; double *v; double *f; const double domain = 300; // Domain size (a.u.) const double dt = 10; // Time interval (a.u.) const double ms = 0.0; // Max speed (a.u.) const double em = 1822.88839 * 28.0134; // Effective mass of N2 const double lje = 0.000313202; // Lennard-Jones epsilon of N2 const double ljs = 6.908841465; // Lennard-Jones sigma of N2 #ifdef MKLRNG VSLStreamStatePtr stream; vslNewStream(&stream, VSL_BRNG_MT19937, 5489); // Initiation, type, seed //vslNewStream(&stream, VSL_BRNG_SFMT19937, 5489); // Initiation, type, seed #endif x = (double *) malloc(n * 3 * sizeof(double)); v = (double *) malloc(n * 3 * sizeof(double)); f = (double *) malloc(n * 3 * sizeof(double)); // Initialization for (i=0; i<n; i++) for (j=0; j<3; j++) x[i*3+j] = domain * rand() / (RAND_MAX + 1.0); for (i=0; i<n; i++) for (j=0; j<3; j++) v[i*3+j] = ms * (rand() / (RAND_MAX + 1.0) - 0.5); // Dynamics printf("# Index dTime KinEng PotEng TotEng\n"); for (i=0; i<mt; i++) { Force(n, lje, ljs, x, f); Solver(n, dt, em, x, v, f); Output_energy(i, n, dt, em, lje, ljs, x, v); if (i % dtxyz == 0) Output_xyz(i, n, x); } Output_xyz(i, n, x); return 0; }
bool findOutputInTransaction( CTransaction const & _tx, CKeyID const & _findId, std::vector< CTxOut > & _txouts, std::vector< unsigned int > & _ids ) { for (unsigned int i = 0; i < _tx.vout.size(); i++) { const CTxOut& txout = _tx.vout[i]; opcodetype opcode; std::vector<unsigned char> data; CScript::const_iterator pc = txout.scriptPubKey.begin(); //sanity check while( pc != txout.scriptPubKey.end() ) { if (!txout.scriptPubKey.GetOp(pc, opcode, data)) return false; } txnouttype type; std::vector< std:: vector<unsigned char> > vSolutions; if (Solver(txout.scriptPubKey, type, vSolutions) && (type == TX_PUBKEY || type == TX_PUBKEYHASH)) { std::vector<std::vector<unsigned char> >::iterator it = vSolutions.begin(); while( it != vSolutions.end() ) { if ( type == TX_PUBKEY ) { // impossible to be here ?? if ( _findId == Hash160( *it ) ) { _txouts.push_back( txout ); _ids.push_back( i ); } } else { if ( _findId == uint160( *it ) ) { _txouts.push_back( txout ); _ids.push_back( i ); } } it++; } } } return !_txouts.empty(); }
CScript GetScriptForWitness(const CScript& redeemscript) { txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { return GetScriptForDestination(WitnessV0KeyHash(Hash160(vSolutions[0].begin(), vSolutions[0].end()))); } else if (typ == TX_PUBKEYHASH) { return GetScriptForDestination(WitnessV0KeyHash(vSolutions[0])); } } return GetScriptForDestination(WitnessV0ScriptHash(redeemscript)); }
void ScriptToUniv(const CScript& script, UniValue& out, bool include_address) { out.pushKV("asm", ScriptToAsmStr(script)); out.pushKV("hex", HexStr(script.begin(), script.end())); std::vector<std::vector<unsigned char>> solns; txnouttype type; Solver(script, type, solns); out.pushKV("type", GetTxnOutputType(type)); CTxDestination address; if (include_address && ExtractDestination(script, address)) { out.pushKV("address", EncodeDestination(address)); } }
bool IndexPCalculator::ComputeP() { DBG_START_METH("IndexPCalculator::ComputeP", dbg_verbosity); bool retval = true; // 1. check whether all columns needed by data_A() are in map cols_ - we suppose data_A is IndexSchurData const std::vector<Index>* p2col_idx = dynamic_cast<const IndexSchurData*>(GetRawPtr(data_A()))->GetColIndices(); Index col; Number* col_values = NULL; Index curr_dim, curr_schur_row=0; SmartPtr<const DenseVector> comp_vec; const Number* comp_values; std::map< Index, SmartPtr<PColumn> >::iterator find_it; SmartPtr<IteratesVector> col_vec = IpData().curr()->MakeNewIteratesVector(); SmartPtr<IteratesVector> sol_vec = col_vec->MakeNewIteratesVector(); for (std::vector<Index>::const_iterator col_it=p2col_idx->begin(); col_it!=p2col_idx->end(); ++col_it){ col = *col_it; find_it = cols_.find(col); if (find_it==cols_.end()) { // column is in data_A but not in P-matrix ->create data_A()->GetRow(curr_schur_row, *col_vec); retval = Solver()->Solve(sol_vec, ConstPtr(col_vec)); DBG_ASSERT(retval); /* This part is for displaying norm2(I_z*K^(-1)*I_1) */ DBG_PRINT((dbg_verbosity,"\ncurr_schur_row=%d, ",curr_schur_row)); DBG_PRINT((dbg_verbosity,"norm2(z)=%23.16e\n",sol_vec->x()->Nrm2())); /* end displaying norm2 */ DBG_ASSERT(col_values== NULL); col_values = new Number[nrows_]; curr_dim = 0; for (Index j=0; j<sol_vec->NComps(); ++j) { comp_vec = dynamic_cast<const DenseVector*>(GetRawPtr(sol_vec->GetComp(j))); comp_values = comp_vec->Values(); IpBlasDcopy(comp_vec->Dim(), comp_values, 1, col_values+curr_dim,1); curr_dim += comp_vec->Dim(); } cols_[col] = new PColumn(nrows_, col_values); col_values = NULL; } curr_schur_row++; } return retval; }
CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { return GetScriptForDestination(WitnessV0KeyHash(Hash160(vSolutions[0].begin(), vSolutions[0].end()))); } else if (typ == TX_PUBKEYHASH) { return GetScriptForDestination(WitnessV0KeyHash(vSolutions[0])); } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); return GetScriptForDestination(WitnessV0ScriptHash(hash)); }
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) { std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { CPubKey pubKey(vSolutions[0]); if (!pubKey.IsValid()) return false; addressRet = pubKey.GetID(); return true; } else if (whichType == TX_PUBKEYHASH) { addressRet = CKeyID(uint160(vSolutions[0])); return true; } else if (whichType == TX_SCRIPTHASH) { addressRet = CScriptID(uint160(vSolutions[0])); return true; } else if (whichType == TX_WITNESS_V0_KEYHASH) { WitnessV0KeyHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } else if (whichType == TX_WITNESS_V0_SCRIPTHASH) { WitnessV0ScriptHash hash; std::copy(vSolutions[0].begin(), vSolutions[0].end(), hash.begin()); addressRet = hash; return true; } else if (whichType == TX_WITNESS_UNKNOWN) { WitnessUnknown unk; unk.version = vSolutions[0][0]; std::copy(vSolutions[1].begin(), vSolutions[1].end(), unk.program); unk.length = vSolutions[1].size(); addressRet = unk; return true; } // Multisig txns have more than one address... return false; }
std::vector< CAvailableCoin > getAvailableCoins( CCoins const & _coins, uint160 const & _pubId, uint256 const & _hash ) { std::vector< CAvailableCoin > availableCoins; for (unsigned int i = 0; i < _coins.vout.size(); i++) { const CTxOut& txout = _coins.vout[i]; opcodetype opcode; std::vector<unsigned char> data; CScript::const_iterator pc = txout.scriptPubKey.begin(); //sanity check while( pc != txout.scriptPubKey.end() ) { if (!txout.scriptPubKey.GetOp(pc, opcode, data)) return std::vector< CAvailableCoin >(); } txnouttype type; std::vector< std:: vector<unsigned char> > vSolutions; if (Solver(txout.scriptPubKey, type, vSolutions) && (type == TX_PUBKEY || type == TX_PUBKEYHASH)) { std::vector<std::vector<unsigned char> >::iterator it = vSolutions.begin(); while( it != vSolutions.end() ) { if ( ( ( type == TX_PUBKEY ) && ( _pubId == Hash160( *it ) ) ) || ( ( type == TX_PUBKEYHASH ) && ( _pubId == uint160( *it ) ) ) ) { if ( !txout.IsNull() ) availableCoins.push_back( CAvailableCoin( txout, i, _hash ) ); break; } it++; } } } return availableCoins; }
bool Solver(vector<vector<char>>& board) { int row, col; // find a unfilled position if(!findUnfilledPos(board, row, col)) return true; // consider digits from 1 to 9 for(int num = 1; num <= 9; num++){ if(isSafe(board, row, col, num+'0')){ board[row][col] = num+'0'; if(Solver(board)) return true; board[row][col] = '.'; } } return false; }
int main(int argc, char * argv[]) { clock_t startTime, endTime; startTime = clock(); Rule rules[NUM_RULES]; initRules(rules); Contradiction contradictions[NUM_CONTRADICTIONS]; initContradictions(contradictions); int selectedRules[NUM_RULES - NUM_CONST_RULES]; for (int i = 0; i < NUM_RULES - NUM_CONST_RULES; i++) { selectedRules[i] = i; } for (int i = 1; i < argc; i++) { char * filename = argv[i]; std::cout << "Puzzle: " << filename << std::endl; Grid grid; Import importer = Import(grid, filename); Export exporter = Export(grid); Solver solver = Solver(grid, rules, contradictions, selectedRules, NUM_RULES - NUM_CONST_RULES, 100); exporter.print(); if (grid.isSolved()) { std::cout << "Solved" << std::endl; } else { if (solver.testContradictions()) { std::cout << "Invalid puzzle" << std::endl; } else if (solver.hasMultipleSolutions()) { std::cout << "Puzzle has multiple solutions" << std::endl; } else { std::cout << "Not solved" << std::endl; } } } endTime = clock(); float diff = ((float)endTime - (float)startTime) / CLOCKS_PER_SEC; std::cout << "Total time:\t" << diff << " seconds" << std::endl; return EXIT_SUCCESS; }
bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType) { std::vector<std::vector<unsigned char> > vSolutions; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_MULTISIG) { unsigned char m = vSolutions.front()[0]; unsigned char n = vSolutions.back()[0]; // Support up to x-of-3 multisig txns as standard if (n < 1 || n > 3) return false; if (m < 1 || m > n) return false; } return whichType != TX_NONSTANDARD; }
int main() { const int n = 500; // Number of atoms, molecules const int mt = 1000; // Max time steps const int dtxyz = 100; // Time interval to output xyz int i, j; double *x, *v, *f; const double domain = 600; // Domain size (a.u.) const double dt = 10; // Time interval (a.u.) const double ms = 0.00001; // Max speed (a.u.) const double em = 1822.88839 * 28.0134; // Effective mass of N2 const double lje = 0.000313202; // Lennard-Jones epsilon of N2 const double ljs = 6.908841465; // Lennard-Jones sigma of N2 x = (double *) malloc(n * 3 * sizeof(double)); v = (double *) malloc(n * 3 * sizeof(double)); f = (double *) malloc(n * 3 * sizeof(double)); // Initialization for (i=0; i<n; i++) for (j=0; j<3; j++) x[i*3+j] = domain * rand() / (RAND_MAX + 1.0); for (i=0; i<n; i++) for (j=0; j<3; j++) v[i*3+j] = ms * (rand() / (RAND_MAX + 1.0) - 0.5); // Dynamics for (i=0; i<mt; i++) { Force(n, lje, ljs, x, f); Solver(n, dt, em, x, v, f); //Output_energy(i, n, dt, em, lje, ljs, x, v); //if (i % dtxyz == 0) Output_xyz(i, n, x); } //Output_xyz(i, n, x); return 0; }
bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType) { std::vector<std::vector<unsigned char> > vSolutions; if (!Solver(scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_MULTISIG) { unsigned char m = vSolutions.front()[0]; unsigned char n = vSolutions.back()[0]; // Support up to x-of-3 multisig txns as standard if (n < 1 || n > 3) return false; if (m < 1 || m > n) return false; } else if (whichType == TX_NULL_DATA && (!fAcceptDatacarrier || scriptPubKey.size() > nMaxDatacarrierBytes)) return false; return whichType != TX_NONSTANDARD; }
void HamiltonianPart::compute() //method of diagonalization classificated part of Hamiltonian { if (Status >= Computed) return; if (H.rows() == 1) { #ifdef POMEROL_COMPLEX_MATRIX_ELEMENS assert (std::abs(H(0,0) - std::real(H(0,0))) < std::numeric_limits<RealType>::epsilon()); #endif Eigenvalues.resize(1); #ifdef POMEROL_COMPLEX_MATRIX_ELEMENS Eigenvalues << std::real(H(0,0)); #else Eigenvalues << H(0,0); #endif H(0,0) = 1; } else { Eigen::SelfAdjointEigenSolver<MatrixType> Solver(H,Eigen::ComputeEigenvectors); H = Solver.eigenvectors(); Eigenvalues = Solver.eigenvalues(); // eigenvectors are ready } Status = Computed; }
CScript GetScriptForWitness(const CScript& redeemscript) { CScript ret; txnouttype typ; std::vector<std::vector<unsigned char> > vSolutions; if (Solver(redeemscript, typ, vSolutions)) { if (typ == TX_PUBKEY) { unsigned char h160[20]; CHash160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160); ret << OP_0 << std::vector<unsigned char>(&h160[0], &h160[20]); return ret; } else if (typ == TX_PUBKEYHASH) { ret << OP_0 << vSolutions[0]; return ret; } } uint256 hash; CSHA256().Write(&redeemscript[0], redeemscript.size()).Finalize(hash.begin()); ret << OP_0 << ToByteVector(hash); return ret; }
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet) { addressRet.clear(); typeRet = TX_NONSTANDARD; std::vector<valtype> vSolutions; if (!Solver(scriptPubKey, typeRet, vSolutions)) return false; if (typeRet == TX_NULL_DATA){ // This is data, not addresses return false; } if (typeRet == TX_MULTISIG) { nRequiredRet = vSolutions.front()[0]; for (unsigned int i = 1; i < vSolutions.size()-1; i++) { CPubKey pubKey(vSolutions[i]); if (!pubKey.IsValid()) continue; CTxDestination address = pubKey.GetID(); addressRet.push_back(address); } if (addressRet.empty()) return false; } else { nRequiredRet = 1; CTxDestination address; if (!ExtractDestination(scriptPubKey, address)) return false; addressRet.push_back(address); } return true; }
template <bool F> matrix_type BetheSalpeter<matrix_type, F>::solve_inversion() { if (verbosity_ > 0) INFO_NONEWLINE("Running" << ((!fwd)?" inverse ":" ") << "matrix BS equation..."); size_t size = vertex_.rows(); matrix_type V4Chi = fwd ? matrix_type(matrix_type::Identity(size,size) - vertex_*bubble_) : matrix_type(matrix_type::Identity(size,size) + bubble_*vertex_); Eigen::PartialPivLU<matrix_type> Solver(V4Chi); det_ = Solver.determinant(); assert(is_float_equal(det_, V4Chi.determinant(), 1e-6)); if (std::abs(std::imag(det_))>1e-2 * std::abs(std::real(det_))) { ERROR("Determinant : " << det_); throw (std::logic_error("Complex determinant in BS. Exiting.")); }; if ((std::real(det_))<1e-2) INFO3("Determinant : " << det_); if (std::real(det_) < std::numeric_limits<real_type>::epsilon()) { ERROR("Can't solve Bethe-Salpeter equation by inversion"); return std::move(V4Chi); } V4Chi = fwd ? matrix_type(Solver.solve(vertex_)) : matrix_type(vertex_*Solver.inverse()); //V4Chi=vertex_*Solver.inverse(); if (verbosity_ > 0) INFO("done."); return std::move(V4Chi); }
int main(int argc, char *argv[]) { #ifdef HAVE_MPI MPI_Init(&argc,&argv); Epetra_MpiComm Comm( MPI_COMM_WORLD ); #else Epetra_SerialComm Comm; #endif Teuchos::ParameterList GaleriList; // The problem is defined on a 2D grid, global size is nx * nx. int nx = 30; GaleriList.set("n", nx * nx); GaleriList.set("nx", nx); GaleriList.set("ny", nx); Teuchos::RefCountPtr<Epetra_Map> Map = Teuchos::rcp( Galeri::CreateMap64("Linear", Comm, GaleriList) ); Teuchos::RefCountPtr<Epetra_RowMatrix> A = Teuchos::rcp( Galeri::CreateCrsMatrix("Laplace2D", &*Map, GaleriList) ); // =============================================================== // // B E G I N N I N G O F I F P A C K C O N S T R U C T I O N // // =============================================================== // Teuchos::ParameterList List; // allocates an IFPACK factory. No data is associated // to this object (only method Create()). Ifpack Factory; // create the preconditioner. For valid PrecType values, // please check the documentation string PrecType = "ILU"; // incomplete LU int OverlapLevel = 1; // must be >= 0. If Comm.NumProc() == 1, // it is ignored. Teuchos::RefCountPtr<Ifpack_Preconditioner> Prec = Teuchos::rcp( Factory.Create(PrecType, &*A, OverlapLevel) ); assert(Prec != Teuchos::null); // specify parameters for ILU List.set("fact: drop tolerance", 1e-9); List.set("fact: level-of-fill", 1); // the combine mode is on the following: // "Add", "Zero", "Insert", "InsertAdd", "Average", "AbsMax" // Their meaning is as defined in file Epetra_CombineMode.h List.set("schwarz: combine mode", "Add"); // sets the parameters IFPACK_CHK_ERR(Prec->SetParameters(List)); // initialize the preconditioner. At this point the matrix must // have been FillComplete()'d, but actual values are ignored. IFPACK_CHK_ERR(Prec->Initialize()); // Builds the preconditioners, by looking for the values of // the matrix. IFPACK_CHK_ERR(Prec->Compute()); // =================================================== // // E N D O F I F P A C K C O N S T R U C T I O N // // =================================================== // // At this point, we need some additional objects // to define and solve the linear system. // defines LHS and RHS Epetra_Vector LHS(A->OperatorDomainMap()); Epetra_Vector RHS(A->OperatorDomainMap()); // solution is constant LHS.PutScalar(1.0); // now build corresponding RHS A->Apply(LHS,RHS); // now randomize the solution RHS.Random(); // need an Epetra_LinearProblem to define AztecOO solver Epetra_LinearProblem Problem(&*A,&LHS,&RHS); // now we can allocate the AztecOO solver AztecOO Solver(Problem); // specify solver Solver.SetAztecOption(AZ_solver,AZ_gmres); Solver.SetAztecOption(AZ_output,32); // HERE WE SET THE IFPACK PRECONDITIONER Solver.SetPrecOperator(&*Prec); // .. and here we solve Solver.Iterate(1550,1e-8); cout << *Prec; #ifdef HAVE_MPI MPI_Finalize() ; #endif return(EXIT_SUCCESS); }
// // Interface functions // model* train(const problem *prob, const parameter *param) { int i,j; int l = prob->l; int n = prob->n; model *model_ = Malloc(model,1); if(prob->bias>=0) model_->nr_feature=n-1; else model_->nr_feature=n; model_->param = *param; model_->bias = prob->bias; int nr_class; int *label = NULL; int *start = NULL; int *count = NULL; int *perm = Malloc(int,l); // group training data of the same class group_classes(prob,&nr_class,&label,&start,&count,perm); model_->nr_class=nr_class; model_->label = Malloc(int,nr_class); for(i=0;i<nr_class;i++) model_->label[i] = label[i]; // calculate weighted C double *weighted_C = Malloc(double, nr_class); for(i=0;i<nr_class;i++) weighted_C[i] = param->C; for(i=0;i<param->nr_weight;i++) { for(j=0;j<nr_class;j++) if(param->weight_label[i] == label[j]) break; if(j == nr_class) fprintf(stderr,"warning: class label %d specified in weight is not found\n", param->weight_label[i]); else weighted_C[j] *= param->weight[i]; } // constructing the subproblem feature_node **x = Malloc(feature_node *,l); for(i=0;i<l;i++) x[i] = prob->x[perm[i]]; int k; problem sub_prob; sub_prob.l = l; sub_prob.n = n; sub_prob.x = Malloc(feature_node *,sub_prob.l); sub_prob.y = Malloc(int,sub_prob.l); for(k=0; k<sub_prob.l; k++) sub_prob.x[k] = x[k]; // multi-class svm by Crammer and Singer if(param->solver_type == MCSVM_CS) { model_->w=Malloc(double, n*nr_class); for(i=0;i<nr_class;i++) for(j=start[i];j<start[i]+count[i];j++) sub_prob.y[j] = i; Solver_MCSVM_CS Solver(&sub_prob, nr_class, weighted_C, param->eps); Solver.Solve(model_->w); }