template <bool align, bool first> SIMD_INLINE void BgrToYuv422p(const uint8_t * bgr, Storer<align> & y, Storer<align> & u, Storer<align> & v) { v128_u8 blue[2], green[2], red[2]; LoadBgr<align>(bgr, blue[0], green[0], red[0]); Store<align, first>(y, BgrToY(blue[0], green[0], red[0])); LoadBgr<align>(bgr + 3 * A, blue[1], green[1], red[1]); Store<align, false>(y, BgrToY(blue[1], green[1], red[1])); v128_s16 blueAvg[2], greenAvg[2], redAvg[2]; blueAvg[0] = Average(blue[0]); blueAvg[1] = Average(blue[1]); greenAvg[0] = Average(green[0]); greenAvg[1] = Average(green[1]); redAvg[0] = Average(red[0]); redAvg[1] = Average(red[1]); Store<align, first>(u, vec_pack(BgrToU(blueAvg[0], greenAvg[0], redAvg[0]), BgrToU(blueAvg[1], greenAvg[1], redAvg[1]))); Store<align, first>(v, vec_pack(BgrToV(blueAvg[0], greenAvg[0], redAvg[0]), BgrToV(blueAvg[1], greenAvg[1], redAvg[1]))); }
template <bool align, bool first> SIMD_INLINE void BgrToYuv420p(const uint8_t * bgr0, size_t bgrStride, Storer<align> & y0, Storer<align> & y1, Storer<align> & u, Storer<align> & v) { const uint8_t * bgr1 = bgr0 + bgrStride; v128_u8 blue[2][2], green[2][2], red[2][2]; LoadBgr<align>(bgr0, blue[0][0], green[0][0], red[0][0]); Store<align, first>(y0, BgrToY(blue[0][0], green[0][0], red[0][0])); LoadBgr<align>(bgr0 + 3 * A, blue[0][1], green[0][1], red[0][1]); Store<align, false>(y0, BgrToY(blue[0][1], green[0][1], red[0][1])); LoadBgr<align>(bgr1, blue[1][0], green[1][0], red[1][0]); Store<align, first>(y1, BgrToY(blue[1][0], green[1][0], red[1][0])); LoadBgr<align>(bgr1 + 3 * A, blue[1][1], green[1][1], red[1][1]); Store<align, false>(y1, BgrToY(blue[1][1], green[1][1], red[1][1])); v128_s16 blueAvg[2], greenAvg[2], redAvg[2]; blueAvg[0] = Average(blue[0][0], blue[1][0]); blueAvg[1] = Average(blue[0][1], blue[1][1]); greenAvg[0] = Average(green[0][0], green[1][0]); greenAvg[1] = Average(green[0][1], green[1][1]); redAvg[0] = Average(red[0][0], red[1][0]); redAvg[1] = Average(red[0][1], red[1][1]); Store<align, first>(u, vec_pack(BgrToU(blueAvg[0], greenAvg[0], redAvg[0]), BgrToU(blueAvg[1], greenAvg[1], redAvg[1]))); Store<align, first>(v, vec_pack(BgrToV(blueAvg[0], greenAvg[0], redAvg[0]), BgrToV(blueAvg[1], greenAvg[1], redAvg[1]))); }
SQuaternion Average( const CSymmetryType & oSym, const vector< SQuaternion > &vQuatList ) { return Average( oSym, vQuatList.begin(), vQuatList.end(), Utilities::QuaternionToQuaternion() ); }
SQuaternion Average( const CSymmetryType & oSym, const vector< SVector3 > &vAngleList ) { return Average( oSym, vAngleList.begin(), vAngleList.end(), Utilities::AngleToQuaternion() ); }
static int DecodeACComponent(WinZipJPEGDecompressor *self,int comp,unsigned int k,bool canbezero, const WinZipJPEGBlock *current,const WinZipJPEGBlock *north,const WinZipJPEGBlock *west, const WinZipJPEGQuantizationTable *quantization) { if(!north) north=&ZeroBlock; if(!west) west=&ZeroBlock; int val1; if(IsFirstRowOrColumn(k)) val1=Abs(BDR(k,current,north,west,quantization)); else val1=Average(k,north,west,quantization); int val2=Sum(k,current); if(canbezero) { // Decode zero/non-zero bit. (5.6.6.1) int zerocontext1=Min(Category(val1),2); int zerocontext2=Min(Category(val2),5); int nonzero=NextBitFromWinZipJPEGArithmeticDecoder(&self->decoder, &self->zerobins[comp][k-1][zerocontext1][zerocontext2]); // If this component is zero, there is no need to decode further parameters. if(!nonzero) return 0; } // This component is not zero. Proceed with decoding absolute value. int absvalue; // Decode pivot (abs>=2). (5.6.6.2) int pivotcontext1=Min(Category(val1),4); int pivotcontext2=Min(Category(val2),6); int pivot=NextBitFromWinZipJPEGArithmeticDecoder(&self->decoder, &self->pivotbins[comp][k-1][pivotcontext1][pivotcontext2]); if(!pivot) { // The absolute of this component is not >=2. It must therefore be 1, // and there is no need to decode the value. absvalue=1; } else { // The absolute of this component is >=2. Proceed with decoding // the absolute value. (5.6.6.3) int val3,n; if(IsFirstRow(k)) { val3=Column(k)-1; n=0; } else if(IsFirstColumn(k)) { val3=Row(k)-1; n=1; } else { val3=Category(k-4); n=2; } int magnitudecontext1=Min(Category(val1),8); int magnitudecontext2=Min(Category(val2),8); int remaindercontext=val3; // Decode absolute value. absvalue=DecodeBinarization(&self->decoder, self->acmagnitudebins[comp][n][magnitudecontext1][magnitudecontext2], self->acremainderbins[comp][n][remaindercontext], 14,9)+2; } if(DecodeACSign(self,comp,k,absvalue,current,north,west,quantization)) return -absvalue; else return absvalue; }
int main(int argc, char ** argv) { if(argc < 3){ std::cout << "Wrong number of arguments. Usage: F1Score <partitionA> <partitionB>" << std::endl; exit(0); } std::ifstream inputFileA; inputFileA.open(argv[1]); if(!inputFileA.is_open()) { std::cout << "PARTITION FILE A NOT FOUND" << std::endl; exit(1); } std::ifstream inputFileB; inputFileB.open(argv[2]); if(!inputFileB.is_open()){ std::cout << "PARTITION FILE B NOT FOUND" << std::endl; exit(1); } std::cout << "Parsing Input Files"<< std::endl; partitionA = ParseSets(inputFileA); inputFileA.close(); partitionB = ParseSets(inputFileB); inputFileB.close(); std::map<unsigned int, std::set<unsigned int> > nodePartitionA; std::map<unsigned int, std::set<unsigned int> > nodePartitionB; std::cout << "Partition A size: " << partitionA->size() << std::endl; std::cout << "Partition B size: " << partitionB->size() << std::endl; double maxSetsF1Scores = 0.0f; double maxTagsF1Scores = 0.0f; std::cout << "Creating Indexes of Partition A" << std::endl; for( unsigned int i = 0; i < partitionA->size(); i++){ std::set<unsigned int>* community = (*partitionA)[i]; for( auto it = community->begin(); it != community->end(); it++ ){ unsigned int node = *it; auto it2 = nodePartitionA.find(node); nodePartitionA[node].insert(i); } } std::cout << "Creating Indexes of Partition B" << std::endl; for( unsigned int i = 0; i < partitionB->size(); i++){ std::set<unsigned int>* community = (*partitionB)[i]; for( auto it = community->begin(); it != community->end(); it++ ){ unsigned int node = *it; auto it2 = nodePartitionB.find(node); nodePartitionB[node].insert(i); } } double* f1ScorePartitionA = new double[partitionA->size()]; double* f1ScorePartitionB = new double[partitionB->size()]; double* precisionPartitionA = new double[partitionA->size()]; double* precisionPartitionB = new double[partitionB->size()]; double* recallPartitionA = new double[partitionA->size()]; double* recallPartitionB = new double[partitionB->size()]; /** Initializing arrays to 0 **/ std::memset(f1ScorePartitionA,0,sizeof(double)*partitionA->size()); std::memset(precisionPartitionA,0,sizeof(double)*partitionA->size()); std::memset(recallPartitionA,0,sizeof(double)*partitionA->size()); std::memset(f1ScorePartitionB,0,sizeof(double)*partitionB->size()); std::memset(precisionPartitionB,0,sizeof(double)*partitionB->size()); std::memset(recallPartitionB,0,sizeof(double)*partitionB->size()); std::cout << "Computing F1Score of partition A" << std::endl; for( unsigned int i = 0; i < partitionA->size(); i++){ std::set<unsigned int>* community = (*partitionA)[i]; std::set<unsigned int> communities; // Selecting candidate communities to compare with. for( auto it = community->begin(); it != community->end(); it++ ) { auto it2 = nodePartitionB.find(*it); if(it2 != nodePartitionB.end()) { for( auto it3 = (*it2).second.begin(); it3 != (*it2).second.end(); it3++ ) { communities.insert(*it3); } } } for( auto it = communities.begin(); it != communities.end(); it++){ std::set<unsigned int>* community2 = (*partitionB)[*it]; double precision; double recall; double f1Score = F1Score(*community,*community2, &precision, &recall ); f1ScorePartitionA[i] = f1Score > f1ScorePartitionA[i] ? f1Score : f1ScorePartitionA[i]; precisionPartitionA[i] = precision > precisionPartitionA[i] ? precision : precisionPartitionA[i]; recallPartitionA[i] = recall > recallPartitionA[i] ? recall : recallPartitionA[i]; } } std::cout << "Computing F1Score of partition B" << std::endl; for( unsigned int i = 0; i < partitionB->size(); i++){ std::set<unsigned int>* community = (*partitionB)[i]; std::set<unsigned int> communities; // Selecting candidate communities to compare with. for( auto it = community->begin(); it != community->end(); it++ ) { auto it2 = nodePartitionA.find(*it); if(it2 != nodePartitionA.end()) { for( auto it3 = (*it2).second.begin(); it3 != (*it2).second.end(); it3++ ) { communities.insert(*it3); } } } for( auto it = communities.begin(); it != communities.end(); it++){ std::set<unsigned int>* community2 = (*partitionA)[*it]; double precision; double recall; double f1Score = F1Score(*community,*community2, &precision, &recall ); f1ScorePartitionB[i] = f1Score > f1ScorePartitionB[i] ? f1Score : f1ScorePartitionB[i]; precisionPartitionB[i] = precision > precisionPartitionB[i] ? precision : precisionPartitionB[i]; recallPartitionB[i] = recall > recallPartitionB[i] ? recall : recallPartitionB[i]; } } std::cout << "Average precision partition A: " << Average(precisionPartitionA, partitionA->size() ) << std::endl; std::cout << "Average recall partition A: " << Average(recallPartitionA, partitionA->size() ) << std::endl; std::cout << "Average precision partition B: " << Average(precisionPartitionB, partitionB->size() ) << std::endl; std::cout << "Average recall partition B: " << Average(recallPartitionB, partitionB->size() ) << std::endl; std::cout << "F1Score: " << (Average( f1ScorePartitionA, partitionA->size() ) + Average( f1ScorePartitionB, partitionB->size() )) / 2 << std::endl; delete [] f1ScorePartitionA; delete [] f1ScorePartitionB; delete [] precisionPartitionA; delete [] precisionPartitionB; delete [] recallPartitionA; delete [] recallPartitionB; return 0; }
double Vector::Average(double returnIfNull) { if (Length() == 0) return returnIfNull; return Average(); }
//----------------------------------------------------------------------------- void TestCommandHandle::Execute() { if (!engine) { Output() << "Engine not set for 'test' command"; return; } if (fileName.empty()) { Output() << "FileName not set for 'test' command"; return; } char fen[16384]; int depth = 0; int line = 0; int maxSearchDepth = 0; int maxSeldepth = 0; int minSearchDepth = -1; int minSeldepth = -1; int passed = 0; int positions = 0; int seldepth = 0; int tested = 0; int totalDepth = 0; int totalSeldepth = 0; uint64_t nodes = 0; uint64_t qnodes = 0; uint64_t time = 0; uint64_t totalNodes = 0; uint64_t totalQnodes = 0; uint64_t totalTime = 0; FILE* fp = NULL; try { MoveFinder moveFinder; if (!(fp = fopen(fileName.c_str(), "r"))) { Output() << "Cannot open '" << fileName << "': " << strerror(errno); return; } engine->ClearStopFlags(); engine->ResetStatsTotals(); while (fgets(fen, sizeof(fen), fp)) { line++; char* f = fen; if (!*NextWord(f) || (*f == '#')) { continue; } positions++; if (skipCount && (positions <= skipCount)) { continue; } Output() << "--- Test " << (++tested) << " at line " << line << ' ' << f; NormalizeString(f); const char* next = engine->SetPosition(f); if (!next || !moveFinder.LoadFEN(f)) { break; } f += (next - f); // consume 'am' and 'bm' parameters std::set<std::string> avoid; std::set<std::string> best; while (f && *NextWord(f)) { // null terminate this parameter (parameters end with ; or end of line) char* end = strchr(f, ';'); if (end) { *end = 0; } if (!strncmp(f, "am ", 3)) { f += 3; while (*NextWord(f)) { std::string coord = moveFinder.ToCoordinates(f); if (coord.size()) { avoid.insert(coord); } else { break; } } } else if (!strncmp(f, "bm ", 3)) { f += 3; while (*NextWord(f)) { std::string coord = moveFinder.ToCoordinates(f); if (coord.size()) { best.insert(coord); } else { break; } } } // move 'f' to beginning of next parameter if (end) { f = (end + 1); continue; } break; } if (avoid.empty() && best.empty()) { Output() << "error at line " << line << ", no best or avoid moves specified"; break; } if (!noClear) { engine->ClearSearchData(); } if (printBoard) { engine->PrintBoard(); } const std::string bestmove = engine->Go(maxDepth, 0, maxTime); Output(Output::NoPrefix) << "bestmove " << bestmove; engine->GetStats(&depth, &seldepth, &nodes, &qnodes, &time); if (bestmove.empty() || (best.size() && !best.count(bestmove)) || (avoid.size() && avoid.count(bestmove))) { Output() << "--- FAILED! line " << line << " (" << Percent(passed, tested) << "%) " << f; } else { passed++; Output() << "--- Passed. line " << line << " (" << Percent(passed, tested) << "%) " << f; } if (depth > maxSearchDepth) { maxSearchDepth = depth; } if ((minSearchDepth < 0) || (depth < minSearchDepth)) { minSearchDepth = depth; } if (seldepth > maxSeldepth) { maxSeldepth = seldepth; } if ((minSeldepth < 0) || (seldepth < minSeldepth)) { minSeldepth = seldepth; } totalDepth += depth; totalNodes += nodes; totalQnodes += qnodes; totalSeldepth += seldepth; totalTime += time; if (engine->StopRequested() || (maxCount && (tested >= maxCount))) { break; } } Output() << "--- Completed " << tested << " test positions"; Output() << "--- Passed " << passed << " passed (" << Percent(passed, tested) << "%)"; Output() << "--- Time " << totalTime << " (" << Average(totalTime, static_cast<uint64_t>(tested)) << " avg)"; Output() << "--- Nodes " << totalNodes << ", " << Rate((totalNodes / 1000), totalTime) << " KNodes/sec"; Output() << "--- QNodes " << totalQnodes << " (" << Percent(totalQnodes, totalNodes) << "%)"; Output() << "--- Depth " << minSearchDepth << " min, " << static_cast<int>(Average(totalDepth, tested)) << " avg, " << maxSearchDepth << " max"; Output() << "--- SelDepth " << minSeldepth << " min, " << static_cast<int>(Average(totalSeldepth, tested)) << " avg, " << maxSeldepth << " max"; engine->ShowStatsTotals(); } catch (const std::exception& e) { Output() << "ERROR: " << e.what(); } catch (...) { Output() << "Unknown error!"; } if (fp) { fclose(fp); fp = NULL; } }
bool AverageRMSD(IT iFirst, IT iLast, VAL &vAve, VAL &vRMSD) { return Average(iFirst, iLast, vAve) && RMSD(iFirst, iLast, vAve, vRMSD); }
/** * Computes and returns the skew. If there are no valid pixels then NULL8 is * returned. Recognize that because of the binning which occurs, in order to * generate the histogram, the skew may not be precise but will be very close. * * @return The skew. */ double Histogram::Skew() const { if (ValidPixels() < 1) return Isis::NULL8; double sdev = StandardDeviation(); if (sdev == 0.0) return 0.0; return 3.0 * (Average() - Median()) / sdev; }
void rules_test (tcb * thisdir, segment * pseg, seglen len, quadrant * pquad, u_short this_ip_id, Bool pkt_already_seen, double recovery_time) { double DeltaT2, RTO, Mean_RTT, RTT_min; char type_of_segment = real_rules_test (thisdir, pseg, len, pquad, this_ip_id, pkt_already_seen, &recovery_time); tcb *otherdir; int dir, num_acked; #ifdef LOG_OOO extern FILE *fp_dup_ooo_log; #endif if (pkt_already_seen) { pseg->type_of_segment = type_of_segment; num_acked = (pseg->prev != NULL) ? pseg->prev->acked : 0; } else { pseg->prev->type_of_segment = type_of_segment; num_acked = (pseg->prev->prev != NULL) ? pseg->prev->prev->acked : 0; } /* LM added */ dir = (&(thisdir->ptp->c2s)) == thisdir; otherdir = (dir == C2S) ? &(thisdir->ptp->s2c) : &(thisdir->ptp->c2s); DeltaT2 = time2double (current_time) - time2double (pquad->seglist_tail->time); Mean_RTT = Average (thisdir->rtt_sum, thisdir->rtt_count) + Average (otherdir->rtt_sum, otherdir->rtt_count); RTO = Mean_RTT + 4 * (Stdev (thisdir->rtt_sum + otherdir->rtt_sum, thisdir->rtt_sum2 + otherdir->rtt_sum2, thisdir->rtt_count + otherdir->rtt_count)); RTT_min = (double) (thisdir->rtt_min + otherdir->rtt_min); #ifdef LOG_OOO if (type_of_segment != 0) { wfprintf (fp_dup_ooo_log, "T: %f ", (elapsed (first_packet, current_time) / 1000.0)); if (dir == C2S) { wfprintf (fp_dup_ooo_log, "%s %s ", HostName (thisdir->ptp->addr_pair.a_address), ServiceName (thisdir->ptp->addr_pair.a_port)); wfprintf (fp_dup_ooo_log, "%s %s ", HostName (thisdir->ptp->addr_pair.b_address), ServiceName (thisdir->ptp->addr_pair.b_port)); } else { wfprintf (fp_dup_ooo_log, "%s %s ", HostName (thisdir->ptp->addr_pair.b_address), ServiceName (thisdir->ptp->addr_pair.b_port)); wfprintf (fp_dup_ooo_log, "%s %s ", HostName (thisdir->ptp->addr_pair.a_address), ServiceName (thisdir->ptp->addr_pair.a_port)); } wfprintf (fp_dup_ooo_log, "%lu %lu %d %d %u %d %u %d %lf %lf %lu %lf %lf %lf %d", thisdir->data_pkts, thisdir->data_bytes, (type_of_segment & 15), thisdir->fsack_req && otherdir->fsack_req, thisdir->mss, (dir == C2S), (internal_dst), thisdir->initialwin_bytes, recovery_time / 1000.0, DeltaT2 / 1000.0, len, RTO / 1000.0, RTT_min / 1000.0, Mean_RTT / 1000.0, num_acked); wfprintf (fp_dup_ooo_log, " %f %f %f %f\n", thisdir->srtt / 1000.0, thisdir->rttvar / 1000.0, otherdir->srtt / 1000.0, otherdir->rttvar / 1000.0); } #endif if (internal_src && !internal_dst) { add_histo (tcp_anomalies_out, aggregateType (type_of_segment)); } else if (!internal_src && internal_dst) { add_histo (tcp_anomalies_in, aggregateType (type_of_segment)); } #ifndef LOG_UNKNOWN else if (internal_src && internal_dst) #else else #endif { add_histo (tcp_anomalies_loc, aggregateType (type_of_segment)); } if (dir == C2S) { add_histo (tcp_anomalies_c2s, aggregateType (type_of_segment)); } else { add_histo (tcp_anomalies_s2c, aggregateType (type_of_segment)); } /* just keep the main classification and discard bit larger than BATCH_CLASSIFICATION*/ switch (type_of_segment & (BATCH_CLASSIFICATION - 1)) { case IN_SEQUENCE: /* just ignore them */ break; case RETRANSMISSION_RTO: thisdir->rtx_RTO++; break; case RETRANSMISSION_FR: thisdir->rtx_FR++; break; case REORDERING: thisdir->reordering++; break; case NETWORK_DUPLICATE: thisdir->net_dup++; break; case FLOW_CONTROL: thisdir->flow_control++; break; case UNNECESSARY_RETRANSMISSION_FR: thisdir->unnecessary_rtx_FR++; break; case UNNECESSARY_RETRANSMISSION_RTO: thisdir->unnecessary_rtx_RTO++; break; default: thisdir->unknown++; } }
/* LM start - Rule number one ** R1.a IP_id_new not equal to IP_id_old ** R1.b this_seg_time-prev_seg_time > ** R1.c number of acks > 3 (or max number permitted) ** DeltaT1: Time between current segment and the last segment before a ooo ** DeltaT2: Time between current segment and the received segment with the maximum sequence number */ char real_rules_test (tcb * thisdir, segment * pseg, seglen len, quadrant * pquad, u_short this_ip_id, Bool pkt_already_seen, double *recovery_time) { double RTO, RTT, Mean_RTT; int Rule1a, Rule1b, Rule1d; int Rule2b, Rule2c; int RuleProbing; tcb *otherdir; char prev_tos; int validRTT; int dir = (&(thisdir->ptp->c2s) == thisdir); otherdir = (dir == C2S) ? &(thisdir->ptp->s2c) : &(thisdir->ptp->c2s); Mean_RTT = Average (thisdir->rtt_sum, thisdir->rtt_count) + Average (otherdir->rtt_sum, otherdir->rtt_count); RTO = Mean_RTT + 4 * (Stdev (thisdir->rtt_sum + otherdir->rtt_sum, thisdir->rtt_sum2 + otherdir->rtt_sum2, thisdir->rtt_count + otherdir->rtt_count)); RTT = (double) (thisdir->rtt_min + otherdir->rtt_min); validRTT = (thisdir->rtt_count != 0 && otherdir->rtt_count != 0); if (RTO < RTO_MIN) RTO = RTO_MIN; if (RTT < RTT_MIN) RTT = RTT_MIN; if (!pkt_already_seen) /* if pkt_already_seen then *recovery_time is passed otherwise it is set below */ *recovery_time = (pseg->prev->prev != NULL) ? time2double (current_time) - time2double (pseg->prev->prev->time) : -1.0; /* take the previous packet classification */ if (pseg->prev != NULL) { if (pkt_already_seen) prev_tos = pseg->prev->type_of_segment; else prev_tos = (pseg->prev->prev != NULL) ? pseg->prev->prev->type_of_segment : IN_SEQUENCE; } else prev_tos = IN_SEQUENCE; if (!validRTT) { RTT = INITIAL_RTT_MIN; RTO = INITIAL_RTO; /* if *recovery_time is -1 then this is the first packet and use next segment as recovery time */ if (*recovery_time == -1.0) *recovery_time = time2double (current_time) - time2double (pseg->time); } Rule1a = (pseg->ip_id != this_ip_id); Rule1b = (*recovery_time > RTO); Rule1d = (*recovery_time < Mean_RTT); if (pkt_already_seen) Rule2b = (pseg->prev != NULL) ? (pseg->prev->acked > 3 && *recovery_time < RTO) : 0; else Rule2b = (pseg->prev->prev != NULL) ? (pseg->prev->prev->acked > 3 && *recovery_time < RTO) : 0; Rule2c = (time2double (current_time) - time2double (pseg->time) < RTT); RuleProbing = ((len == 1) && (otherdir->win_curr == 0) && (thisdir->syn_count != 0) && (otherdir->syn_count != 0)); if (RuleProbing) return FLOW_CONTROL; if (Rule1d && prev_tos != IN_SEQUENCE) return (prev_tos | BATCH_CLASSIFICATION); /* Old Classification with the first bit is 1 */ if (!pseg->acked) { if (pkt_already_seen) { if (!Rule1a) return CLASSIFICATION (NETWORK_DUPLICATE); if (Rule1a && (Rule1b || Rule2b)) return CLASSIFICATION (Rule2b ? RETRANSMISSION_FR : RETRANSMISSION_RTO); if (Rule1d) return CLASSIFICATION (DUPLICATE_WITH_RC_LESS_THAN_RTT_NOT_3DUP_ACK); if (!Rule1b) return CLASSIFICATION (DUPLICATE_WITH_RC_LESS_THAN_RTO_AND_GREATER_THAN_RTT_NOT_3DUP_ACK); return CLASSIFICATION (UNKNOWN); } if (Rule1b || Rule2b) return CLASSIFICATION (Rule2b ? RETRANSMISSION_FR : RETRANSMISSION_RTO); if (Rule2c) return CLASSIFICATION (REORDERING); if (Rule1d) return CLASSIFICATION (OOO_WITH_RC_LESS_THAN_RTT_NOT_3DUP_ACK); if (!Rule1b) return CLASSIFICATION (OOO_WITH_RC_LESS_THAN_RTO_AND_GREATER_THAN_RTT_NOT_3DUP_ACK); return CLASSIFICATION (UNKNOWN); } if (!Rule1a) return CLASSIFICATION (NETWORK_DUPLICATE); if ((Rule1b || Rule2b)) return CLASSIFICATION (Rule2b ? UNNECESSARY_RETRANSMISSION_FR : UNNECESSARY_RETRANSMISSION_RTO); if (Rule1d) return CLASSIFICATION (UNNECESSARY_RETRANSMISSION_WITH_RC_LESS_THAN_RTT_NOT_3DUP_ACK); if (!Rule1b) return CLASSIFICATION (UNNECESSARY_RETRANSMISSION_WITH_RC_LESS_THAN_RTO_AND_GREATER_THAN_RTT_NOT_3DUP_ACK); return CLASSIFICATION (UNKNOWN); }
// Returns the standard deviation double BasicStats::SD() { double average = Average(); return sqrt((squaredsum - (stream_size*average*average))/(stream_size-1)); }
void getAverage() { float avg = Average(); std::cout << "This is the average: " << avg << std::endl; }
float SimpleFilter::WindowFilter(float* list, int windowSize) { float av = Average(MedianFilter(list, windowSize), 3); return av; }
// ---------------------------------------------------------------------------------- // CTCStateTiltListenData::CalculateTilt // ---------------------------------------------------------------------------------- // TBool CTCStateTiltListenData::CalculateTilt() { FUNC_LOG; TBool flush( EFalse ); if( IsSet( EAccelerometerData ) && IsSet( EMagnetometerData ) ) { TTiltCompensationOutput output; Average ( iArrayAcc, iInput.iAccelerationVector.iX, iInput.iAccelerationVector.iY, iInput.iAccelerationVector.iZ ); Average ( iArrayMag, iInput.iMagneticVector.iX, iInput.iMagneticVector.iY, iInput.iMagneticVector.iZ ); INFO_1( "Tilt compensation average MagX: %d", iInput.iMagneticVector.iX ); INFO_1( "Tilt compensation average MagY: %d", iInput.iMagneticVector.iY ); INFO_1( "Tilt compensation average MagZ: %d", iInput.iMagneticVector.iZ ); INFO_1( "Tilt compensation average AccX: %d", iInput.iAccelerationVector.iX ); INFO_1( "Tilt compensation average AccY: %d", iInput.iAccelerationVector.iY ); INFO_1( "Tilt compensation average AccZ: %d", iInput.iAccelerationVector.iZ ); INFO_1( "Tilt compensation iSizeOfAccArray: %d", iSizeOfAccArray ); INFO_1( "Tilt compensation iSizeOfMagArray: %d", iSizeOfMagArray ); INFO_1( "Tilt compensation iPreviousTheta: %d", iPreviousTheta ); INFO_2( "Tilt compensation params: k[%f], m[%f]", iParamsArray[0], iParamsArray[1] ); INFO_2( "Tilt compensation params: tresholdAng1[%f], tresholdAng2[%f]", iParamsArray[2], iParamsArray[3] ); TInt err = iCompensationFunc( iInput, output, iPreviousTheta, iParamsArray ); iPreviousTheta = output.iTheta; ERROR( err, "Tilt compensation failed" ); if( err == KErrNone ) { INFO_1( "Tilt compensation succesfull. Tilt angle: %d", output.iTheta ); // Write data into data buffer TUint8* buffer = iTransactionHandler.DataBuffer(); if( buffer && ( iWriteCount < iTransactionHandler.DataCount() ) ) { // Move pointer if needed buffer += sizeof( TSensrvMagneticNorthData ) * iWriteCount; TSensrvMagneticNorthData* tiltData = reinterpret_cast<TSensrvMagneticNorthData*>( buffer ); iTime.HomeTime(); tiltData->iTimeStamp = iTime; tiltData->iAngleFromMagneticNorth = output.iTheta; if( ++iWriteCount == iTransactionHandler.DataCount() || IsSet( EForceBufferFull ) ) { flush = ETrue; } // Reset state but not write count ResetState( EFalse ); } else { ERROR_GEN( "Tilt data buffer empty" ); } } } return flush; }
template <> SIMD_INLINE uint8_t OperationBinary8u<SimdOperationBinary8uAverage>(const uint8_t & a, const uint8_t & b) { return Average(a, b); }
static void CompressACComponent(JPEGCompressor *self,int comp,unsigned int k,bool canbezero, const JPEGBlock *current,const JPEGBlock *north,const JPEGBlock *west, const JPEGQuantizationTable *quantization) { int value=current->c[k]; if(!north) north=&ZeroBlock; if(!west) west=&ZeroBlock; int val1; if(IsFirstRowOrColumn(k)) val1=Abs(BDR(k,current,north,west,quantization)); else val1=Average(k,north,west,quantization); int val2=Sum(k,current); if(canbezero) { // Compress zero/non-zero bit. int zerocontext1=Min(Category(val1),2); int zerocontext2=Min(Category(val2),5); WriteDynamicBit(&self->encoder,value!=0, &self->zerobins[comp][k-1][zerocontext1][zerocontext2], self->zeroshift); // If this component is zero, there is no need to compress further parameters. if(value==0) return; } // This component is not zero. Proceed with compressing absolute value. int absvalue=Abs(value); // Compress pivot (abs>=2). int pivotcontext1=Min(Category(val1),4); int pivotcontext2=Min(Category(val2),6); WriteDynamicBit(&self->encoder,absvalue>1, &self->pivotbins[comp][k-1][pivotcontext1][pivotcontext2], self->pivotshift); if(absvalue>1) { // The absolute of this component is >=2. Proceed with compressing // the absolute value. int val3,n; if(IsFirstRow(k)) { val3=Column(k)-1; n=0; } else if(IsFirstColumn(k)) { val3=Row(k)-1; n=1; } else { val3=Category(k-4); n=2; } int magnitudecontext1=Min(Category(val1),8); int magnitudecontext2=Min(Category(val2),8); int remaindercontext=val3; // Compress absolute value. WriteUniversalCode(&self->encoder,absvalue-2, self->acmagnitudebins[comp][n][magnitudecontext1][magnitudecontext2], self->acmagnitudeshift, self->acremainderbins[comp][n][remaindercontext], self->acremaindershift); } CompressACSign(self,comp,k,absvalue,current,north,west,quantization); }
void PrintTrace( tcp_pair *ptp) { double etime; u_long etime_secs; u_long etime_usecs; double etime_data1; double etime_data2; tcb *pab = &ptp->a2b; tcb *pba = &ptp->b2a; char *host1 = pab->host_letter; char *host2 = pba->host_letter; char bufl[40],bufr[40]; /* counters to use for seq. space wrap around calculations */ u_llong stream_length_pab=0, stream_length_pba=0; u_long pab_last, pba_last; /* Reset the counter for each connection */ sv_print_count = 1; /* The first field (conn_#) gets printed in trace.c */ /* calculate elapsed time */ etime = elapsed(ptp->first_time,ptp->last_time); etime_secs = etime / 1000000.0; etime_usecs = 1000000 * (etime/1000000.0 - (double)etime_secs); /* Check if comma-separated-values or tab-separated-values * has been requested. */ if(csv || tsv || (sv != NULL)) { fprintf(stdout,"%s%s%s%s%s%s%s%s", ptp->a_hostname, sp, ptp->b_hostname, sp, ptp->a_portname, sp, ptp->b_portname, sp); sv_print_count += 4; /* Print the start and end times. In other words, * print the time of the first and the last packet */ fprintf(stdout,"%ld.%ld %s %ld.%ld %s", (long)ptp->first_time.tv_sec, (long)ptp->first_time.tv_usec, sp, (long)ptp->last_time.tv_sec, (long)ptp->last_time.tv_usec, sp); sv_print_count += 2; } else { fprintf(stdout,"\thost %-4s %s\n", (snprintf(bufl,sizeof(bufl),"%s:", host1),bufl), ptp->a_endpoint); fprintf(stdout,"\thost %-4s %s\n", (snprintf(bufl,sizeof(bufl),"%s:", host2),bufl), ptp->b_endpoint); fprintf(stdout,"\tcomplete conn: %s", ConnReset(ptp)?"RESET":( ConnComplete(ptp)?"yes":"no")); if (ConnComplete(ptp)) fprintf(stdout,"\n"); else fprintf(stdout,"\t(SYNs: %u) (FINs: %u)\n", SynCount(ptp), FinCount(ptp)); fprintf(stdout,"\tfirst packet: %s\n", ts2ascii(&ptp->first_time)); fprintf(stdout,"\tlast packet: %s\n", ts2ascii(&ptp->last_time)); fprintf(stdout,"\telapsed time: %s\n", elapsed2str(etime)); fprintf(stdout,"\ttotal packets: %" FS_ULL "\n", ptp->packets); fprintf(stdout,"\tfilename: %s\n", ptp->filename); fprintf(stdout," %s->%s: %s->%s:\n", host1,host2,host2,host1); } StatLineI("total packets","", pab->packets, pba->packets); if (pab->reset_count || pba->reset_count || csv || tsv || (sv != NULL)) StatLineI("resets sent","", pab->reset_count, pba->reset_count); StatLineI("ack pkts sent","", pab->ack_pkts, pba->ack_pkts); StatLineI("pure acks sent","", pab->pureack_pkts, pba->pureack_pkts); StatLineI("sack pkts sent","", pab->num_sacks, pba->num_sacks); StatLineI("dsack pkts sent","", pab->num_dsacks, pba->num_dsacks); StatLineI("max sack blks/ack","", pab->max_sack_blocks, pba->max_sack_blocks); StatLineI("unique bytes sent","", pab->unique_bytes, pba->unique_bytes); StatLineI("actual data pkts","", pab->data_pkts, pba->data_pkts); StatLineI("actual data bytes","", pab->data_bytes, pba->data_bytes); StatLineI("rexmt data pkts","", pab->rexmit_pkts, pba->rexmit_pkts); StatLineI("rexmt data bytes","", pab->rexmit_bytes, pba->rexmit_bytes); StatLineI("zwnd probe pkts","", pab->num_zwnd_probes, pba->num_zwnd_probes); StatLineI("zwnd probe bytes","", pab->zwnd_probe_bytes, pba->zwnd_probe_bytes); StatLineI("outoforder pkts","", pab->out_order_pkts, pba->out_order_pkts); StatLineI("pushed data pkts","", pab->data_pkts_push, pba->data_pkts_push); StatLineP("SYN/FIN pkts sent","","%s", (snprintf(bufl,sizeof(bufl),"%d/%d", pab->syn_count, pab->fin_count),bufl), (snprintf(bufr,sizeof(bufr),"%d/%d", pba->syn_count, pba->fin_count),bufr)); if (pab->f1323_ws || pba->f1323_ws || pab->f1323_ts || pba->f1323_ts || csv || tsv || (sv != NULL)) { StatLineP("req 1323 ws/ts","","%s", (snprintf(bufl,sizeof(bufl),"%c/%c", pab->f1323_ws?'Y':'N',pab->f1323_ts?'Y':'N'),bufl), (snprintf(bufr,sizeof(bufr),"%c/%c", pba->f1323_ws?'Y':'N',pba->f1323_ts?'Y':'N'),bufr)); } if (pab->f1323_ws || pba->f1323_ws || csv || tsv || (sv != NULL)) { StatLineI("adv wind scale","", (u_long)pab->window_scale, (u_long)pba->window_scale); } if (pab->fsack_req || pba->fsack_req || csv || tsv || (sv != NULL)) { StatLineP("req sack","","%s", pab->fsack_req?"Y":"N", pba->fsack_req?"Y":"N"); StatLineI("sacks sent","", pab->sacks_sent, pba->sacks_sent); } StatLineI("urgent data pkts", "pkts", pab->urg_data_pkts, pba->urg_data_pkts); StatLineI("urgent data bytes", "bytes", pab->urg_data_bytes, pba->urg_data_bytes); StatLineI("mss requested","bytes", pab->mss, pba->mss); StatLineI("max segm size","bytes", pab->max_seg_size, pba->max_seg_size); StatLineI("min segm size","bytes", pab->min_seg_size, pba->min_seg_size); StatLineI("avg segm size","bytes", (int)((double)pab->data_bytes / ((double)pab->data_pkts+.001)), (int)((double)pba->data_bytes / ((double)pba->data_pkts+.001))); StatLineI("max win adv","bytes", pab->win_max, pba->win_max); StatLineI("min win adv","bytes", pab->win_min, pba->win_min); StatLineI("zero win adv","times", pab->win_zero_ct, pba->win_zero_ct); // Average window advertisement is calculated only for window scaled pkts // if we have seen this connection using window scaling. // Otherwise, it is just the regular way of dividing the sum of // all window advertisements by the total number of packets. if (pab->window_stats_updated_for_scaling && pba->window_stats_updated_for_scaling) StatLineI("avg win adv","bytes", pab->win_scaled_pkts==0?0: (pab->win_tot/pab->win_scaled_pkts), pba->win_scaled_pkts==0?0: (pba->win_tot/pba->win_scaled_pkts)); else StatLineI("avg win adv","bytes", pab->packets==0?0:pab->win_tot/pab->packets, pba->packets==0?0:pba->win_tot/pba->packets); if (print_owin) { StatLineI("max owin","bytes", pab->owin_max, pba->owin_max); StatLineI("min non-zero owin","bytes", pab->owin_min, pba->owin_min); StatLineI("avg owin","bytes", pab->owin_count==0?0:pab->owin_tot/pab->owin_count, pba->owin_count==0?0:pba->owin_tot/pba->owin_count); if (etime == 0.0) { StatLineP("wavg owin", "", "%s", "NA", "NA"); } else { StatLineI("wavg owin","bytes", (u_llong)(pab->owin_wavg/((double)etime/1000000)), (u_llong)(pba->owin_wavg/((double)etime/1000000))); } } StatLineI("initial window","bytes", pab->initialwin_bytes, pba->initialwin_bytes); StatLineI("initial window","pkts", pab->initialwin_segs, pba->initialwin_segs); /* compare to theoretical length of the stream (not just what we saw) using the SYN and FIN * Seq. Space wrap around calculations: * Calculate stream length using last_seq_num seen, first_seq_num * seen and wrap_count. * first_seq_num = syn * If reset_set, last_seq_num = latest_seq * else last_seq_num = fin */ pab_last = (pab->reset_count>0)?pab->latest_seq:pab->fin; pba_last = (pba->reset_count>0)?pba->latest_seq:pba->fin; /* calculating stream length for direction pab */ if ((pab->syn_count > 0) && (pab->fin_count > 0)) { if (pab->seq_wrap_count > 0) { if (pab_last > pab->syn) { stream_length_pab = pab_last + (MAX_32 * pab->seq_wrap_count) - pab->syn - 1; } else { stream_length_pab = pab_last + (MAX_32 * (pab->seq_wrap_count+1)) - pab->syn - 1; } } else { if (pab_last > pab->syn) { stream_length_pab = pab_last - pab->syn - 1; } else { stream_length_pab = MAX_32 + pab_last - pab->syn - 1; } } } /* calculating stream length for direction pba */ if ((pba->syn_count > 0) && (pba->fin_count > 0)) { if (pba->seq_wrap_count > 0) { if (pba_last > pba->syn) { stream_length_pba = pba_last + (MAX_32 * pba->seq_wrap_count) - pba->syn - 1; } else { stream_length_pba = pba_last + (MAX_32 * (pba->seq_wrap_count+1)) - pba->syn - 1; } } else { if (pba_last > pba->syn) { stream_length_pba = pba_last - pba->syn - 1; } else { stream_length_pba = MAX_32 + pba_last - pba->syn - 1; } } } /* print out values */ if ((pab->fin_count > 0) && (pab->syn_count > 0)) { char *format = "%8" FS_ULL; StatLineFieldL("ttl stream length", "bytes", format, stream_length_pab, 0); } else { StatLineField("ttl stream length", "", "%s", (u_long)"NA", 0); } if ((pba->fin_count > 0) && (pba->syn_count > 0)) { char *format = "%8" FS_ULL; StatLineFieldL("ttl stream length", "bytes", format, stream_length_pba, 1); } else { StatLineField("ttl stream length", "", "%s", (u_long)"NA", 1); } if ((pab->fin_count > 0) && (pab->syn_count > 0)) { char *format = "%8" FS_ULL; StatLineFieldL("missed data", "bytes", format, (stream_length_pab - pab->unique_bytes), 0); } else { StatLineField("missed data", "", "%s", (u_long)"NA", 0); } if ((pba->fin_count > 0) && (pba->syn_count > 0)) { char *format = "%8" FS_ULL; StatLineFieldL("missed data", "bytes", format, (stream_length_pba - pba->unique_bytes), 1); } else { StatLineField("missed data", "", "%s", (u_long)"NA", 1); } /* tell how much data was NOT captured in the files */ StatLineI("truncated data","bytes", pab->trunc_bytes, pba->trunc_bytes); StatLineI("truncated packets","pkts", pab->trunc_segs, pba->trunc_segs); /* stats on just the data */ etime_data1 = elapsed(pab->first_data_time, pab->last_data_time); /* in usecs */ etime_data2 = elapsed(pba->first_data_time, pba->last_data_time); /* in usecs */ /* fix from Rob Austein */ StatLineF("data xmit time","secs","%7.3f", etime_data1 / 1000000.0, etime_data2 / 1000000.0); StatLineP("idletime max","ms","%s", ZERO_TIME(&pab->last_time)?"NA": (snprintf(bufl,sizeof(bufl),"%8.1f",(double)pab->idle_max/1000.0),bufl), ZERO_TIME(&pba->last_time)?"NA": (snprintf(bufr,sizeof(bufr),"%8.1f",(double)pba->idle_max/1000.0),bufr)); if ((pab->num_hardware_dups != 0) || (pba->num_hardware_dups != 0) || csv || tsv || (sv != NULL)) { StatLineI("hardware dups","segs", pab->num_hardware_dups, pba->num_hardware_dups); if(!(csv || tsv || (sv != NULL))) fprintf(stdout, " ** WARNING: presence of hardware duplicates makes these figures suspect!\n"); } /* do the throughput calcs */ etime /= 1000000.0; /* convert to seconds */ if (etime == 0.0) StatLineP("throughput","","%s","NA","NA"); else StatLineF("throughput","Bps","%8.0f", (double) (pab->unique_bytes) / etime, (double) (pba->unique_bytes) / etime); if (print_rtt) { if(!(csv || tsv || (sv != NULL))) fprintf(stdout,"\n"); StatLineI("RTT samples","", pab->rtt_count, pba->rtt_count); StatLineF("RTT min","ms","%8.1f", (double)pab->rtt_min/1000.0, (double)pba->rtt_min/1000.0); StatLineF("RTT max","ms","%8.1f", (double)pab->rtt_max/1000.0, (double)pba->rtt_max/1000.0); StatLineF("RTT avg","ms","%8.1f", Average(pab->rtt_sum, pab->rtt_count) / 1000.0, Average(pba->rtt_sum, pba->rtt_count) / 1000.0); StatLineF("RTT stdev","ms","%8.1f", Stdev(pab->rtt_sum, pab->rtt_sum2, pab->rtt_count) / 1000.0, Stdev(pba->rtt_sum, pba->rtt_sum2, pba->rtt_count) / 1000.0); if(!(csv || tsv || (sv != NULL))) fprintf(stdout,"\n"); StatLineF("RTT from 3WHS","ms","%8.1f", (double)pab->rtt_3WHS/1000.0, (double)pba->rtt_3WHS/1000.0); if(!(csv || tsv || (sv != NULL))) fprintf(stdout,"\n"); StatLineI("RTT full_sz smpls","", pab->rtt_full_count, pba->rtt_full_count); StatLineF("RTT full_sz min","ms","%8.1f", (double)pab->rtt_full_min/1000.0, (double)pba->rtt_full_min/1000.0); StatLineF("RTT full_sz max","ms","%8.1f", (double)pab->rtt_full_max/1000.0, (double)pba->rtt_full_max/1000.0); StatLineF("RTT full_sz avg","ms","%8.1f", Average(pab->rtt_full_sum, pab->rtt_full_count) / 1000.0, Average(pba->rtt_full_sum, pba->rtt_full_count) / 1000.0); StatLineF("RTT full_sz stdev","ms","%8.1f", Stdev(pab->rtt_full_sum, pab->rtt_full_sum2, pab->rtt_full_count) / 1000.0, Stdev(pba->rtt_full_sum, pba->rtt_full_sum2, pba->rtt_full_count) / 1000.0); if(!(csv || tsv || (sv != NULL))) fprintf(stdout,"\n"); StatLineI("post-loss acks","", pab->rtt_nosample, pba->rtt_nosample); if (pab->rtt_amback || pba->rtt_amback || csv || tsv || (sv != NULL)) { if(!(csv || tsv || (sv != NULL))) fprintf(stdout, "\ \t For the following 5 RTT statistics, only ACKs for\n\ \t multiply-transmitted segments (ambiguous ACKs) were\n\ \t considered. Times are taken from the last instance\n\ \t of a segment.\n\ "); StatLineI("ambiguous acks","", pab->rtt_amback, pba->rtt_amback); StatLineF("RTT min (last)","ms","%8.1f", (double)pab->rtt_min_last/1000.0, (double)pba->rtt_min_last/1000.0); StatLineF("RTT max (last)","ms","%8.1f", (double)pab->rtt_max_last/1000.0, (double)pba->rtt_max_last/1000.0); StatLineF("RTT avg (last)","ms","%8.1f", Average(pab->rtt_sum_last, pab->rtt_count_last) / 1000.0, Average(pba->rtt_sum_last, pba->rtt_count_last) / 1000.0); StatLineF("RTT sdv (last)","ms","%8.1f", Stdev(pab->rtt_sum_last, pab->rtt_sum2_last, pab->rtt_count_last) / 1000.0, Stdev(pba->rtt_sum_last, pba->rtt_sum2_last, pba->rtt_count_last) / 1000.0); } StatLineI("segs cum acked","", pab->rtt_cumack, pba->rtt_cumack); StatLineI("duplicate acks","", pab->rtt_dupack, pba->rtt_dupack); StatLineI("triple dupacks","", pab->rtt_triple_dupack, pba->rtt_triple_dupack); if (debug) StatLineI("unknown acks:","", pab->rtt_unkack, pba->rtt_unkack); StatLineI("max # retrans","", pab->retr_max, pba->retr_max); StatLineF("min retr time","ms","%8.1f", (double)((double)pab->retr_min_tm/1000.0), (double)((double)pba->retr_min_tm/1000.0)); StatLineF("max retr time","ms","%8.1f", (double)((double)pab->retr_max_tm/1000.0), (double)((double)pba->retr_max_tm/1000.0)); StatLineF("avg retr time","ms","%8.1f", Average(pab->retr_tm_sum, pab->retr_tm_count) / 1000.0, Average(pba->retr_tm_sum, pba->retr_tm_count) / 1000.0); StatLineF("sdv retr time","ms","%8.1f", Stdev(pab->retr_tm_sum, pab->retr_tm_sum2, pab->retr_tm_count) / 1000.0, Stdev(pba->retr_tm_sum, pba->retr_tm_sum2, pba->retr_tm_count) / 1000.0); } if(csv || tsv || (sv != NULL)) { printf("\n"); /* Error checking: print an error message if the count of printed fields * doesn't correspond to the actual fields expected. */ if(sv_print_count != sv_expected_count) { fprintf(stderr, "output.c: Count of printed fields does not correspond to count of header fields for long output with comma/tab/<SP>-separated values.\n"); fprintf(stderr,"sv_print_count=%u, sv_expected_count=%u\n", sv_print_count, sv_expected_count); exit(-1); } } }
/** main proccess user arguments, runs version trails and * provides analytical information about performance and * code correctness. * */ int main(int argc, char **argv) { int i; int threads; int trials; //get NSUB, threads and trails from argument if(argc != 5){ printf("Invalid number of arguments.\n"); printf("Usage: ./fem1d [SUB_SIZE] [NL] [NUM_THREADS] [TRIALS]\n"); exit(EXIT_FAILURE); } else if((NSUB = atoi(argv[1])) == 0) { printf("Invalid subdivison size.\n"); printf("Usage: ./fem1d [SUB_SIZE] [NL] [NUM_THREADS] [TRIALS]\n"); exit(EXIT_FAILURE); } else if ((NL = atoi(argv[2])) == 0){ printf("Invalid number of threads.\n"); printf("Usage: ./fem1d [SUB_SIZE] [NL] [NUM_THREADS] [TRIALS]\n"); exit(EXIT_FAILURE); } else if ((threads = atoi(argv[3])) == 0){ printf("Invalid number of threads.\n"); printf("Usage: ./fem1d [SUB_SIZE] [NL] [NUM_THREADS] [TRIALS]\n"); exit(EXIT_FAILURE); } else if ((trials = atoi(argv[4])) == 0){ printf("Invalid number of trails.\n"); printf("Usage: ./fem1d [SUB_SIZE] [NL] [NUM_THREADS] [TRIALS]\n"); exit(EXIT_FAILURE); } printf("NSUB = %ld, NL = %ld, threads = %d, trails = %d\n", NSUB,NL,threads,trials); //set number of threads omp_set_num_threads(threads); //wipe solutions files fp_sol = fopen("old_sol.txt","w"); fclose(fp_sol); fp_sol = fopen("new_sol.txt","w"); fclose(fp_sol); //time spent on execution for each trail double time_spent[trials]; int ver = 0; double old_time[trials]; double new_time[trials]; int oc = 0; int nc = 0; //toggle between versions and perform trials for(i=0;i<(trials*2);i++){ if(ver == 0){ printf("Running old version: trail %d...\n",oc+1); old_time[oc]= run(0); printf("Succesfully complete: Time taken: %fsec\n",old_time[oc]); oc++; ver++; } else if (ver == 1){ printf("Running new version trail %d...\n",nc+1); new_time[nc]= run(1); printf("Succesfully complete: Time taken: %fsec\n",new_time[nc]); nc++; ver = ver - 1; } } //print results printf("********************************** RESULTS ************************************\n"); double o_time = Average(old_time); double n_time = Average(new_time); printf("NSUB = %ld, NL = %ld, threads = %d, trails = %d\n",NSUB,NL,threads,trials); printf("New version Average Time: %fsec\n",n_time); printf("Old version Average Time: %fsec\n",o_time); printf("Speed up: %fsec\n", (o_time - n_time)); /* //RUN OLD VERSION TRAILS printf("**************************** RUNNING OLD VERSION ******************************\n"); for(i=0;i<trials;i++){ printf("Running old version, trail %d...\n",i+1); time_spent[i] = run(0); printf("Old version, trail %d succesfully complete.\n",i+1); printf("Time taken: %fsec\n",time_spent[i]); } //store old time for later display double old_time = Average(time_spent); printf("**************************** RUNNING NEW VERSION ******************************\n"); //RUN NEW VERSION TRAILS for(i=0;i<trials;i++){ printf("Running new version, trail %d...\n",i+1); time_spent[i] = run(1); printf("New version, trail %d succesfully complete.\n", i+1); printf("Time taken: %fsec\n",time_spent[i]); } printf("********************************** RESULTS ************************************\n"); double new_time = Average(time_spent); printf("New version Average Time: %fsec\n",new_time); printf("Old version Average Time: %fsec\n",old_time); printf("Speed up: %fsec\n", (old_time - new_time)); */ //CHECK FOR CORRCTNESS if(check()==0){ printf("CORRECT: Outputs are identical.\n"); } else { printf("INCORRECT: Outputs are not identical.\n"); } return 0; }
int main() { /* Kamus Lokal */ List MyList, List2, List3; int i; infotype isi; address P, Prec; /* Program */ CreateList (&MyList); printf ("Jml Elemen List adalah : %d \n", NbElmt(MyList)); /* Menambah List di awal */ i = 1; while (i <= 5) { InsVFirst (&MyList, i*5); i++; } printf ("Hasil InsVFirst 5 x adalah : "); PrintInfo (MyList); printf ("Node Maksimal = %d ",Max (MyList)); printf ("Node Minimal = %d ",Min (MyList)); printf ("Rata-rata = %d \n",Average (MyList)); /* Mencari suatu elemen di list */ P = Search(MyList, 15); printf ("Search yang berhasil (15) : P = %d, Ketemu = %d \n",P,FSearch(MyList,P)); DelP (&MyList, 15); /* Insert di Last */ printf ("Insert di akhir nilai 723 : "); InsVLast (&MyList, 723); PrintInfo (MyList); /* Insert diantara 2 elemen */ printf ("Insert sebelum elemen 10 : "); Prec = SearchPrec (MyList, 10); P = Alokasi (2712); if (P != Nil) { InsertAfter (&MyList, P, Prec); } PrintInfo (MyList); /* Menghapus elemen List */ printf ("\tHasil Delete dari elemen List :\n"); printf ("Jumlah elemen list = %d \n", NbElmt(MyList)); DelVFirst (&MyList, &isi); printf ("DelVFirst adalah %d\t", isi); DelVLast (&MyList, &isi); printf ("DelVLast adalah %d\t", isi); /* Menghapus elemen di tengah-tengah */ Prec = SearchPrec (MyList, 10); /* Node yang akan dihapus */ if (Prec != Nil) { DelAfter (&MyList, &P, Prec); isi = Info(P); DeAlokasi (P); printf ("DelAfter adalah %d\n", isi); } printf ("Hasil setelah delete : "); PrintInfo (MyList); printf ("Insert sebelum elemen 5 : "); Prec = SearchPrec (MyList, 5); P = Alokasi (-987); if (P != Nil) { InsertAfter (&MyList, P, Prec); } PrintInfo (MyList); /* Invers List */ printf ("\tHasil Invers dari List yang ada : \n"); printf ("Versi 1 : "); List2 = FInversList (MyList); PrintInfo (List2); printf ("Versi 2 : "); InversList (&MyList); PrintInfo (MyList); /* Copy List */ printf ("\tHasil Copy dari List yang ada : \n"); printf("Versi 1 : "); CopyList (MyList, &List2); PrintInfo (List2); printf ("Versi 2 : "); List3 = FCopyList (MyList); PrintInfo (List3); printf ("Versi 3 : "); CpAlokList (MyList, &List2); PrintInfo (List2); /* Konkat */ printf("\tHasil Konkat Invers dan List asli : \n"); List2 = FInversList (MyList); Konkat (List2, List3, &MyList); printf("Versi 1 : "); PrintInfo (MyList); Konkat1 (&List2, &List3, &MyList); printf("Versi 2 : "); PrintInfo (MyList); /* Pecah List */ PecahList (&List2, &List3, MyList); printf ("\tHasil membagi dua list adalah : \n"); printf ("L1 = "); PrintInfo (List2); printf ("L2 = "); PrintInfo (List3); /* Finishing */ P = First(MyList); DeAlokasi (P); P = First(List2); DeAlokasi (P); P = First(List3); DeAlokasi (P); return 0; }
int main(int argc, char const **argv) { int TRIALS; bool error = false; //get NSUB, threads, tasks and trails from argument if(argc != 6) { error = true; } else if((NSUB = atoi(argv[1])) == 0) { printf("Invalid subdivison size.\n"); error = true; } else if ((NL = atoi(argv[2])) == 0) { printf("Invalid base function degree.\n"); error = true; } else if ((THREADS = atoi(argv[3])) == 0) { printf("Invalid number of threads.\n"); error = true; } else if ((TASKS = atoi(argv[4])) == 0) { printf("Invalid number of tasks.\n"); error = true; } else if ((TRIALS = atoi(argv[5])) == 0) { printf("Invalid number of trails.\n"); error = true; } if(error) { printf("Usage: ./fem [SUB_SIZE] [NL] [NUM_THREADS] [NUM_TASKS] [TRIALS]\n"); exit(EXIT_FAILURE); } printf("NSUB = %ld, NL = %ld, threads = %d,tasks = %d, trails = %d\n", NSUB,NL,THREADS,TASKS,TRIALS); //wipe solutions, output & times files fp_sol = fopen("old_sol.txt","w"); fclose(fp_sol); fp_sol = fopen("new_sol.txt","w"); fclose(fp_sol); fp_out = fopen("old_out.txt","w"); fclose(fp_sol); fp_out = fopen("new_out.txt","w"); fclose(fp_sol); fp_time = fopen("times.txt","w"); fclose(fp_time); //time spent on execution for each trail double time_spent[TRIALS]; int ver = 0; int oc = 0; int nc = 0; char cmdNew[200]; char cmdOld[200]; sprintf(cmdNew, "mpirun -np %d --hostfile my_hosts new %ld %ld %d",TASKS,NSUB,NL,THREADS); sprintf(cmdOld, "./old %ld %ld",NSUB,NL); //toggle between versions and perform TRIALS for(int i=0; i<(TRIALS*2); i++) { if(ver == 0) { printf("Running old version: trail %d...\n",oc+1); system(cmdOld); printf("Succesfully complete.\n"); oc++; ver++; } else if (ver == 1) { printf("Running new version trail %d...\n",nc+1); if(system(cmdNew)==0) { printf("Succesfully complete.\n"); } else { printf("Failed to complete: MPI funnel not provided.\n"); exit(EXIT_FAILURE); } nc++; ver = ver - 1; } } double old_time[TRIALS]; double new_time[TRIALS]; bool old = true; FILE *fp_time = fopen("times.txt","r"); char *line = NULL; size_t len = 0; int b=0; while(getline(&line,&len,fp_time)!=-1) { if(old) { sscanf(line,"%lf",&old_time[b]); } else { sscanf(line,"%lf",&new_time[b]); b++; } old = !old; } //print results printf("********************************** RESULTS ************************************\n"); double o_time = Average(old_time); double n_time = Average(new_time); printf("NSUB = %ld, NL = %ld, threads = %d,tasks = %d, trails = %d\n", NSUB,NL,THREADS,TASKS,TRIALS); printf("New version Average Time: %fsec\n",n_time); printf("Old version Average Time: %fsec\n",o_time); printf("Speed up: %fsec\n", (o_time - n_time)); //CHECK FOR CORRCTNESS if(check()==0) { printf("CORRECT: Outputs are identical.\n"); } else { printf("INCORRECT: Outputs are not identical.\n"); } return 0; }
/** * \brief Computes the parameter space metric for a coherent pulsar search. * \author Creighton, T. D., Jolien Creighton * \date 2000 - 2003 * \ingroup StackMetric_h * * This function computes the metric \f$g_{\alpha\beta}(\mathbf{\lambda})\f$, as * discussed in \ref StackMetric_h, under the assumption * that the search consists of scanning the Fourier power spectrum * constructed from a single time interval \f$\Delta t\f$. The indecies * \f$\alpha\f$ and \f$\beta\f$ are assumed to run from 0 to \f$n\f$, where \f$n\f$ is * the total number of shape parameters. * The argument \c metric is normally a vector of length * \f$(n+1)(n+2)/2\f$ storing all non-redundant coefficients of * \f$g_{\alpha\beta}\f$. The indexing scheme is as follows: Let us assume * that \f$\alpha\geq\beta\f$. Then * \f$g_{\alpha\beta} = g_{\beta\alpha} = \f$metric->data[\f$\beta + \alpha(\alpha+1)/2]\f$. * If <tt>params->errors</tt> is nonzero, then \a *metric must be double * this length, and LALCoherentMetric() will store metric * components and their estimated uncertainty in alternate slots; i.e. * the metric component * \f$g_{\alpha\beta}=\f$metric->data[\f$2\beta+\alpha(\alpha+1)]\f$, * and the uncertainty * \f$s_{\alpha\beta}=\f$metric->data[\f$1+2\beta+\alpha(\alpha+1)]\f$. * * The argument \a lambda is another vector, of length \f$n+1\f$, * storing the components of \f$\mathbf{\lambda}=(\lambda^0,\ldots,\lambda^n)\f$ * for the parameter space point at which the metric is being evaluated. * The argument \a *params stores the remaining parameters for * computing the metric, as given in the Structures section of StackMetric.h. * * ### Algorithm ### * * This routine simply computes the function given in \eqref{eq_gab_phi} * of \ref StackMetric_h. Most of the work is done by the * function \a params->dtCanon(), which computes the value and * parameter derivatives of the canonical time coordinate * \f$\tau[t;\vec{\lambda}]\f$. Since the phase function is simply * \f$\phi[t;\mathbf{\lambda}]=2\pi\lambda^0 \tau[t;\vec\lambda]\f$, where * \f$\lambda^0=f_0\f$, the metric components are simply: * \f{eqnarray}{ * g_{00}(\mathbf{\lambda}) & = & * 4\pi^2\bigg\langle\!(\tau[t;\vec\lambda])^2\bigg\rangle - * 4\pi^2\bigg\langle\!\tau[t;\vec\lambda]\bigg\rangle^2 \; , \\ * g_{i0}(\mathbf{\lambda}) \;\; = \;\; * g_{0i}(\mathbf{\lambda}) & = & * 4\pi^2 f_0\bigg\langle\! * \tau[t;\vec\lambda] * \frac{\partial\tau[t;\vec\lambda]}{\partial\lambda^i} * \bigg\rangle * - * 4\pi^2 f_0\bigg\langle\! * \tau[t;\vec\lambda] * \bigg\rangle * \bigg\langle * \frac{\partial\tau[t;\vec\lambda]}{\partial\lambda^i} * \bigg\rangle \; ,\\ * g_{ij}(\mathbf{\lambda}) & = & * 4\pi^2 f_0^2\bigg\langle * \frac{\partial\tau[t;\vec\lambda]}{\partial\lambda^i} * \frac{\partial\tau[t;\vec\lambda]}{\partial\lambda^j} * \bigg\rangle * - * 4\pi^2 f_0^2\bigg\langle * \frac{\partial\tau[t;\vec\lambda]}{\partial\lambda^i} * \bigg\rangle * \bigg\langle * \frac{\partial\tau[t;\vec\lambda]}{\partial\lambda^j} * \bigg\rangle \; , * \f} * where the indecies \f$i\f$ and \f$j\f$ run from 1 to \f$n\f$. * * In the rigorous definition of the metric, the angle brackets denote an * average over the \em canonical time, not the detector time, so we have: * \f{eqnarray}{ * \bigg\langle\ldots\bigg\rangle * & = & \frac{1}{\tau(t_\mathrm{start}+\Delta t)-\tau(t_\mathrm{start})} * \int_{\tau(t_\mathrm{start})}^{\tau(t_\mathrm{start}+\Delta t)} * \ldots\,d\tau\\ * & = & \frac{1}{\tau(t_\mathrm{start}+\Delta t)-\tau(t_\mathrm{start})} * \int_{t_\mathrm{start}}^{t_\mathrm{start}+\Delta t} * \ldots\frac{\partial\tau}{\partial t}\,dt\\ * & \approx & \frac{1}{\Delta t} * \int_{t_\mathrm{start}}^{t_\mathrm{start}+\Delta t} * \ldots\,dt \; , * \f} * where the approximation is good to order \f$\epsilon\f$ equal to the * maximum difference between 1 and \f$\partial\tau/\partial t\f$. For an * Earth-motion barycentred time coordinate, for instance, \f$\epsilon\f$ is * of order \f$10^{-4}\f$ and the approximation is quite good. However, the * current implementation of the metric algorithm uses the second, exact * formula. If speed considerations become important, this is one * obvious area for simplification. * * At present, the time averaging is performed by evaluating \f$\tau\f$ and * its derivatives at equally-spaced points over \f$\Delta t\f$ and applying * a trapezoidal method; i.e. * \f[ * \frac{1}{T}\int_0^T F(t)\,dt \approx \frac{1}{N}\left(\frac{1}{2}F_0 * + F_1 + F_2 + \ldots + F_{N-1} + \frac{1}{2}F_N \right) \; , * \f] * where \f$F_k=F(kT/N)\f$ are the \f$N+1\f$ sample points of the integrand. The * number of points is a compiled-in constant. The error is on the order * of \f$F''T^2/N^2\f$, where \f$F''\f$ is the second derivative of \f$F(t)\f$ at * some point in the interval; we liberally estimate the error to be: * \f[ * \sigma = \max_{k\in\{1,\ldots,N-1\}} * \left\{F_{k-1} - 2F_k + F_{k+1}\right\} \; . * \f] * Other more sophisticated integration techniques may be considered in * future. To save on recomputing costs, the derivatives of \f$\tau\f$ at * all times are stored in a large vector sequence. */ void LALCoherentMetric( LALStatus *stat, REAL8Vector *metric, REAL8Vector *lambda, MetricParamStruc *params ) { UINT4 s = 0; /* The number of parameters. */ UINT4 i, j, k, l; /* Indecies. */ REAL8 dt; /* The sampling interval, in s. */ REAL8 f0; /* The frequency scale, lambda->data[0]. */ REAL8 *data; /* Multipurpose pointer to vector data. */ REAL8Vector *a=NULL; /* Data for the first time average. */ REAL8Vector *b=NULL; /* Data for the second time average. */ REAL8Vector *c=NULL; /* Data for the third time average. */ REAL8Vector d; /* Temporary variable. */ REAL8Vector *variables=NULL; /* Input to time function. */ REAL8VectorSequence *dSeq=NULL; /* Phase derivatives. */ CreateVectorSequenceIn in; /* Input structure. */ PulsarTimesParamStruc *constants; /* Timing constants. */ INITSTATUS(stat); ATTATCHSTATUSPTR(stat); /* Make sure parameter structures and their fields exist. */ ASSERT(metric,stat,STACKMETRICH_ENUL,STACKMETRICH_MSGENUL); ASSERT(metric->data,stat,STACKMETRICH_ENUL,STACKMETRICH_MSGENUL); ASSERT(lambda,stat,STACKMETRICH_ENUL,STACKMETRICH_MSGENUL); ASSERT(lambda->data,stat,STACKMETRICH_ENUL,STACKMETRICH_MSGENUL); ASSERT(params,stat,STACKMETRICH_ENUL,STACKMETRICH_MSGENUL); ASSERT(params->dtCanon,stat,STACKMETRICH_ENUL,STACKMETRICH_MSGENUL); /* Make sure parameters are valid. */ s=lambda->length; ASSERT(s,stat,STACKMETRICH_EBAD,STACKMETRICH_MSGEBAD); if(params->errors) { ASSERT(metric->length==s*(s+1),stat,STACKMETRICH_EBAD, STACKMETRICH_MSGEBAD); } else { ASSERT(metric->length==(s*(s+1))>>1,stat,STACKMETRICH_EBAD, STACKMETRICH_MSGEBAD); } ASSERT(params->n==1,stat,STACKMETRICH_EBAD, STACKMETRICH_MSGEBAD); /* Set vector sequence creation structure, and compute sampling rate. */ in.vectorLength=s+1; in.length=COHERENTMETRICC_NPTS; dt=params->deltaT/(COHERENTMETRICC_NPTS-1.0); /* Create temporary storage. */ TRY(LALDCreateVector(stat->statusPtr,&a,COHERENTMETRICC_NPTS),stat); LALDCreateVector(stat->statusPtr,&b,COHERENTMETRICC_NPTS); BEGINFAIL(stat) TRY(LALDDestroyVector(stat->statusPtr,&a),stat); ENDFAIL(stat); LALDCreateVector(stat->statusPtr,&c,COHERENTMETRICC_NPTS); BEGINFAIL(stat) { TRY(LALDDestroyVector(stat->statusPtr,&a),stat); TRY(LALDDestroyVector(stat->statusPtr,&b),stat); } ENDFAIL(stat); LALDCreateVectorSequence(stat->statusPtr,&dSeq,&in); BEGINFAIL(stat) { TRY(LALDDestroyVector(stat->statusPtr,&a),stat); TRY(LALDDestroyVector(stat->statusPtr,&b),stat); TRY(LALDDestroyVector(stat->statusPtr,&c),stat); } ENDFAIL(stat); LALDCreateVector(stat->statusPtr,&variables,s); BEGINFAIL(stat) { TRY(LALDDestroyVector(stat->statusPtr,&a),stat); TRY(LALDDestroyVector(stat->statusPtr,&b),stat); TRY(LALDDestroyVector(stat->statusPtr,&c),stat); TRY(LALDDestroyVectorSequence(stat->statusPtr,&dSeq),stat); } ENDFAIL(stat); /* Set up passing structure for the canonical time function. */ memcpy(variables->data,lambda->data,s*sizeof(REAL8)); *(variables->data)=params->start; f0=lambda->data[0]; constants=params->constants; d.length=s+1; d.data=dSeq->data; l=COHERENTMETRICC_NPTS; /* Compute canonical time and its derivatives. */ while(l--){ (params->dtCanon)(stat->statusPtr,&d,variables,constants); BEGINFAIL(stat) { TRY(LALDDestroyVector(stat->statusPtr,&a),stat); TRY(LALDDestroyVector(stat->statusPtr,&b),stat); TRY(LALDDestroyVector(stat->statusPtr,&c),stat); TRY(LALDDestroyVectorSequence(stat->statusPtr,&dSeq),stat); TRY(LALDDestroyVector(stat->statusPtr,&variables),stat); } ENDFAIL(stat); *(variables->data)+=dt; d.data+=s+1; } /* Compute the overall correction factor to convert the canonical time interval into the detector time interval. */ #ifndef APPROXIMATE dt=params->deltaT/(dSeq->data[(s+1)*(COHERENTMETRICC_NPTS-1)] - dSeq->data[0]); #else dt=1.0; #endif /* Compute metric components. First generate the g00 component. */ /* Fill integrand arrays. */ data=dSeq->data+1; l=COHERENTMETRICC_NPTS; k=0; while(l--){ #ifndef APPROXIMATE a->data[l]=*data*data[-1]*data[-1]; b->data[l]=c->data[l]=*data*data[-1]; #else a->data[l]=data[-1]*data[-1]; b->data[l]=c->data[l]=data[-1]; #endif data+=s+1; } /* Integrate to get the metric component. */ if(params->errors){ REAL8 aErr=0,bErr=0,cErr=0; REAL8 aAvg=Average(a,&aErr); REAL8 bAvg=Average(b,&bErr); REAL8 cAvg=Average(c,&cErr); metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt*(aAvg-dt*bAvg*cAvg); metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt* (aErr + dt*bErr*fabs(cAvg) + dt*cErr*fabs(bAvg)); }else metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt* (Average(a,0)-dt*Average(b,0)*Average(c,0)); for(i=1;i<s;i++){ /* Now generate the gi0 components. */ /* Fill integrand arrays. */ data=dSeq->data+1; l=COHERENTMETRICC_NPTS; while(l--){ #ifndef APPROXIMATE a->data[l]=*data*data[-1]*f0*data[i]; b->data[l]=*data*data[-1]; c->data[l]=*data*f0*data[i]; #else a->data[l]=data[-1]*f0*data[i]; b->data[l]=data[-1]; c->data[l]=f0*data[i]; #endif data+=s+1; } /* Integrate to get the metric component. */ if(params->errors){ REAL8 aErr=0,bErr=0,cErr=0; REAL8 aAvg=Average(a,&aErr); REAL8 bAvg=Average(b,&bErr); REAL8 cAvg=Average(c,&cErr); metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt*(aAvg-dt*bAvg*cAvg); metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt* (aErr + dt*bErr*fabs(cAvg) + dt*cErr*fabs(bAvg)); }else metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt* (Average(a,0)-dt*Average(b,0)*Average(c,0)); for(j=1;j<=i;j++){ /* Now generate the gij components. */ /* Fill integrand arrays. */ data=dSeq->data+1; l=COHERENTMETRICC_NPTS; while(l--){ #ifndef APPROXIMATE a->data[l]=*data*f0*f0*data[i]*data[j]; b->data[l]=*data*f0*data[i]; c->data[l]=*data*f0*data[j]; #else a->data[l]=f0*f0*data[i]*data[j]; b->data[l]=f0*data[i]; c->data[l]=f0*data[j]; #endif data+=s+1; } /* Integrate to get the metric component. */ if(params->errors){ REAL8 aErr=0,bErr=0,cErr=0; REAL8 aAvg=Average(a,&aErr); REAL8 bAvg=Average(b,&bErr); REAL8 cAvg=Average(c,&cErr); metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt*(aAvg-dt*bAvg*cAvg); metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt* (aErr + dt*bErr*fabs(cAvg) + dt*cErr*fabs(bAvg)); }else metric->data[k++]=LAL_TWOPI*LAL_TWOPI*dt* (Average(a,0)-dt*Average(b,0)*Average(c,0)); } } /* Destroy temporary storage, and exit. */ TRY(LALDDestroyVector(stat->statusPtr,&a),stat); TRY(LALDDestroyVector(stat->statusPtr,&b),stat); TRY(LALDDestroyVector(stat->statusPtr,&c),stat); TRY(LALDDestroyVectorSequence(stat->statusPtr,&dSeq),stat); TRY(LALDDestroyVector(stat->statusPtr,&variables),stat); DETATCHSTATUSPTR(stat); RETURN(stat); }
void VideoFluids::trackVelocity(Matrix& Zn1,Matrix& Zn,Matrix& U,Matrix& V) { Matrix Zx(height,width),Zy(height,width),ZZx(height,width),ZZy(height,width),Zt(height,width),ZZt(height,width),ZZtx(height,width),ZZty(height,width); Matrix Au1(height,width),Au2(height,width),Av1(height,width),Av2(height,width); Matrix Z2x(height,width),Z2y(height,width),Z2(height,width); Matrix Cu(height,width),Cv(height,width); Matrix tmp(height,width),tmp1(height,width); Matrix U_old(height,width),V_old(height,width),Ux(height,width),Uy(height,width),Vx(height,width),Vy(height,width),Uax(height,width),Uay(height,width),Vax(height,width),Vay(height,width),Uxy(height,width),Vxy(height,width); Matrix Coe(height,width); Zt = Zn; Zt -= Zn1; DotMul(Zn,Zt,ZZt); Zn.output("Zn.txt"); Zn1.output("Zn1.txt"); Zt.output("Zt.txt"); Partial(ZZt,ZZtx,AXIS_X); Partial(ZZt,ZZty,AXIS_Y); Partial(Zn,Zx,AXIS_X); Partial(Zn,Zy,AXIS_Y); DotMul(Zn,Zx,ZZx); DotMul(Zn,Zy,ZZy); DotMul(Zx,Zx,Au1); Partial(ZZx,tmp,AXIS_X); Au1-=tmp; DotMul(Zn,Zn,tmp); Au1+=tmp; Au1+=2*alpha*alpha; DotMul(Zx,Zy,Au2); Partial(ZZy,tmp,AXIS_X); Au2-=tmp; DotMul(Zx,Zy,Av1); Partial(ZZx,tmp,AXIS_Y); Av1-=tmp; DotMul(Zy,Zy,Av2); Partial(ZZy,tmp,AXIS_Y); Av2-=tmp; DotMul(Zn,Zn,tmp); Av2+=tmp; Av2+=2*alpha*alpha; DotMul(Zn,Zn,Z2); Partial(Z2,Z2x,AXIS_X); Partial(Z2,Z2y,AXIS_Y); for (int i = 0;i<height;i++) for (int j = 0;j<width;j++) Coe[i][j] = 1.0/(Au1[i][j]*Av2[i][j]-Au2[i][j]*Av1[i][j]); U = 0.0; V = 0.0; for (int iter_time = 0;iter_time<iterationTime;iter_time++) { V_old = V; U_old = U; Partial(U,Ux,AXIS_X); Partial(U,Uy,AXIS_Y); Partial(V,Vx,AXIS_X); Partial(V,Vy,AXIS_Y); Partial(Vx,Vxy,AXIS_Y); Partial(Ux,Uxy,AXIS_Y); Average(U,Uax,AXIS_X); Average(U,Uay,AXIS_Y); Average(V,Vax,AXIS_X); Average(V,Vay,AXIS_Y); DotMul(Z2x,Ux,Cu); DotMul(ZZy,Vx,tmp); Cu += tmp; tmp = ZZx*-1; tmp+=Z2x; DotMul(tmp,Vy,tmp1); Cu+=tmp1; tmp = Z2; tmp+=alpha*alpha; DotMul(tmp,Uax,tmp1); Cu+=tmp1; tmp1=Uay; tmp1*=alpha*alpha; Cu+=tmp1; DotMul(Z2,Vxy,tmp1); Cu+=tmp1; DotMul(Zx,Zt,tmp); Cu-=tmp; Cu+=ZZtx; DotMul(Z2y,Vy,Cv); DotMul(ZZx,Uy,tmp); Cv += tmp; tmp = ZZy; tmp*=-1; tmp+=Z2y; DotMul(tmp,Ux,tmp1); Cv+=tmp1; tmp = Z2; tmp+=alpha*alpha; DotMul(tmp,Vay,tmp1); Cv+=tmp1; tmp1=Vax; tmp1*=alpha*alpha; Cv+=tmp1; DotMul(Z2,Uxy,tmp1); Cv+=tmp1; DotMul(Zy,Zt,tmp); Cv-=tmp; Cv+=ZZty; for (int i = 0;i<height;i++) for (int j = 0;j<width;j++) { U[i][j] = Coe[i][j]*(Av2[i][j]*Cu[i][j]-Au2[i][j]*Cv[i][j]); V[i][j] = Coe[i][j]*(-Av1[i][j]*Cu[i][j]+Au1[i][j]*Cv[i][j]); } for (int i = 0;i<height;i++) { U[i][0] = U[i][1]; U[i][width-1] = U[i][width-2]; V[i][0] = V[i][1]; V[i][width-1] =V[i][width-2]; } for (int i = 0;i<width;i++) { U[0][i] = U[1][i]; U[height-1][i] = U[height-2][i]; V[0][i] = V[1][i]; V[height-1][i] =V[height-2][i]; } FILE* fp; // Au1.output("Au1.txt"); // Au2.output("Au2.txt"); // Av1.output("Av1.txt"); // Av2.output("Av2.txt"); // Cu.output("Cu.txt"); // Cv.output("Cv.txt"); float d1 = Difference(U,U_old); float d2 = Difference(V,V_old); // U.output("U.txt"); // U_old.output("U_old.txt"); // V.output("V.txt"); cout<<d1<<' '<<d2<<endl; if (d1<iterationTorlerance && d2<iterationTorlerance) break; } U.output("U.txt"); cv::Mat showV(height,width,CV_8UC3); float lowv=10000000,lowu=10000000,highu=-10000000,highv=-1000000; for(int j=0;j<height;j++){ for(int k=0;k<width;k++){ if(U[j][k]>highu) highu=U[j][k]; if(U[j][k]<lowu) lowu=U[j][k]; if(V[j][k]>highv) highv=V[j][k]; if(V[j][k]<lowv) lowv=V[j][k]; } } for(int j=0;j<height;j++){ for(int k=0;k<width;k++){ //printf("%d %d\n",j,k); //if(sfs_list[i][j][k]<low) // showH.at<uchar>(j,k)=0; //else float u=(U[j][k]-lowu)/(highu-lowu); float v=(V[j][k]-lowv)/(highv-lowv); if(u>0.5) showV.at<cv::Vec3b>(j,k)[2]=255; else showV.at<cv::Vec3b>(j,k)[2]=255*u; if(v>0.5){ showV.at<cv::Vec3b>(j,k)[0]=255; showV.at<cv::Vec3b>(j,k)[1]=255*(1-v); } else{ showV.at<cv::Vec3b>(j,k)[1]=255; showV.at<cv::Vec3b>(j,k)[0]=255*v; } } } cv::imwrite("testV.bmp",showV); printf("show you"); }