int main(void) { struct timeval t; struct timeval beginning = current_time(); float m; /* Used for a fun calculation. */ t = current_time(); printf("Current time in seconds since the epoch: %d.%06ds\n", t.tv_sec, t.tv_usec); t = time_difference(current_time(), t); printf("Since that last printf, %d.%06d seconds have passed.\n", t.tv_sec, t.tv_usec); printf("Now we'll sleep for a second and time it. (whee...)\n"); t = current_time(); sleep(1); t = time_difference(current_time(), t); m = 100.0 * ((float)t.tv_sec - 1.0 + (float)(t.tv_usec) / 1000000.0); printf("'sleep(1)' actually took %d.%06ds; it was off by %f%%.\n", t.tv_sec, t.tv_usec, m); printf("thank you for your time...your %dms to be more precise.\n", time_ms(time_difference(current_time(), beginning))); return 0; }
void testDistance() { Algorithms test(std::shared_ptr<HSAContext>(HSAContext::Create())); int element_size = 256; int window_size = 1024*128; int numerics_size = 512; std::vector<double> query; std::vector<double> window; std::vector<double> ranges; std::vector<double> result; query.resize(element_size); window.resize(element_size * window_size); result.resize(window_size); ranges.resize(element_size*2); for (int i = 0 ;i < element_size ; ++i) { ranges[2*i] = 1; ranges[2*i+1] = 2; } timeval tv1; timeval tv2; gettimeofday(&tv1, 0); for (int i = 0 ;i < 1000 ; ++i) test.m_square_distance2.calculate(&query[0], &window[0], window_size, &ranges[0], element_size, numerics_size, &result[0]); gettimeofday(&tv2, 0); printf("%ld\n", time_difference(tv1,tv2)/1000); }
static gboolean foreach_rate_limiter_fire (gpointer key, gpointer value, gpointer user_data) { RateLimiter *limiter = value; ForEachData *data = user_data; if (limiter->send_delayed_change_at != 0 && time_difference (data->time_now, limiter->send_delayed_change_at) == 0) rate_limiter_send_delayed_change_now (data->monitor, limiter, data->time_now); if (limiter->send_virtual_changes_done_at != 0 && time_difference (data->time_now, limiter->send_virtual_changes_done_at) == 0) rate_limiter_send_virtual_changes_done_now (data->monitor, limiter); return calc_min_time (data->monitor, limiter, data->time_now, &data->min_time); }
static gboolean calc_min_time (GFileMonitor *monitor, RateLimiter *limiter, guint32 time_now, guint32 *min_time) { gboolean delete_me; guint32 expire_at; delete_me = TRUE; if (limiter->last_sent_change_time != 0) { /* Set a timeout at 2*rate limit so that we can clear out the change from the hash eventualy */ expire_at = limiter->last_sent_change_time + 2 * monitor->priv->rate_limit_msec; if (time_difference (time_now, expire_at) > 0) { delete_me = FALSE; *min_time = MIN (*min_time, time_difference (time_now, expire_at)); } } if (limiter->send_delayed_change_at != 0) { delete_me = FALSE; *min_time = MIN (*min_time, time_difference (time_now, limiter->send_delayed_change_at)); } if (limiter->send_virtual_changes_done_at != 0) { delete_me = FALSE; *min_time = MIN (*min_time, time_difference (time_now, limiter->send_virtual_changes_done_at)); } return delete_me; }
int adjust_stats(packet_source_t *pss) { packet_source_t *ps; unsigned long tmpb; unsigned long tmpp; double tdif; tdif = time_difference(); if(tdif < 0.01) /* Too short period */ return -1; for(ps = pss; ps; ps = ps->next) { /* Semi-atomic */ tmpb = ps->bytes_cur; ps->bytes_cur = 0; tmpp = ps->packets_cur; ps->packets_cur= 0; /* * Bytes */ ps->bytes_prev = tmpb; if(ps->bytes_lp == -1) { ps->bytes_lp = tmpb * (ps->avg_period / tdif); } else { ps->bytes_lp = (1 - tdif / ps->avg_period) * ps->bytes_lp + tmpb; } /* Estimate bps */ ps->bps_lp = ps->bytes_lp / ps->avg_period; /* * Packets */ ps->packets_prev = tmpp; if(ps->packets_lp == -1) { ps->packets_lp = tmpp * (ps->avg_period / tdif); } else { ps->packets_lp = (1 - tdif / ps->avg_period) * ps->packets_lp + tmpp; } /* Estimate bps */ ps->pps_lp = ps->packets_lp / ps->avg_period; } return 0; }
void getCenterTime(char *start_time, char *end_time, char *center_time) { ymd_date beginDate, endDate; hms_time beginTime, endTime; sscanf(start_time, "%d-%d-%d %d:%d:%lf", &beginDate.year, &beginDate.month, &beginDate.day, &beginTime.hour, &beginTime.min, &beginTime.sec); sscanf(end_time, "%d-%d-%d %d:%d:%lf", &endDate.year, &endDate.month, &endDate.day, &endTime.hour, &endTime.min, &endTime.sec); double deltaTime = fabs(time_difference(&beginDate, &beginTime, &endDate, &endTime)) / 2.0; add_time(deltaTime, &beginDate, &beginTime); sprintf(center_time, "%04d-%02d-%02d %02d:%02d:%02.0lf\n", beginDate.year, beginDate.month, beginDate.day, beginTime.hour, beginTime.min, beginTime.sec); }
int main() { int seconds,swi=1; char enter; printf("1 example of program:\ni\n60\nresult: 00:01:00\n"); printf("2 example of program:\nd\n15:00:20 15:00:00\nresult: 20 seconds\n"); t_1.hours=0; t_1.minutes=0; t_1.seconds=0; t_2.hours=0; t_2.minutes=0; t_2.seconds=0; printf("\nstart %02d:%02d:%02d\n",t_1.hours,t_1.minutes,t_1.seconds); while (swi) { scanf("%c",&enter); fflush(stdin); if(enter=='i') { scanf("%d",&seconds); fflush(stdin); t_1=time_sum(seconds,t_1); printf("\n%02d:%02d:%02d\n",t_1.hours,t_1.minutes,t_1.seconds); } if(enter=='d') { scanf("%d:%d:%d",&t_1.hours,&t_1.minutes,&t_1.seconds); fflush(stdin); scanf("%d:%d:%d",&t_2.hours,&t_2.minutes,&t_2.seconds); fflush(stdin); printf("\nresult: %d seconds\n",time_difference(t_1,t_2)); } if (enter!='i' && enter!='d') printf("\nInvalid operation!\n"); printf("\nDo you want to exit the program? - yes (y) no (n)\n"); scanf("%c",&enter); fflush(stdin); if (enter=='y') swi=0; } return 0; }
unsigned int test_context_run_tests(TestContext *tc, List *tests) { struct timeval ta, tb, res; gettimeofday(&ta, NULL); list_foreach(tests, CBFUNC(test_context_run_test), tc); gettimeofday(&tb, NULL); time_difference(&tb, &ta, &res); if (!TC_IS_QUIET(tc)) { printf("\n\n"); oqueue_flush(tc->logs, stdout); printf("%u tests, %u crashes, %u skipped, %u checks, %u failed" " (%ld.%03ld seconds)\n", tc->test_num, tc->crashed, tc->skipped, tc->check_num, tc->check_failed, res.tv_sec, res.tv_usec / 1000); } return tc->check_failed; }
void testSum() { int workgroup_size = 256; int compute_nodes = 1; Algorithms test(std::shared_ptr<HSAContext>(HSAContext::Create())); timeval tv1; timeval tv2; FILE* output = fopen("/tmp/log.txt", "w+"); std::vector<double> input1; std::vector<double> input2; std::vector<double> result; for (int global_size = 1024; global_size <= 1024 ; global_size += 256) for (compute_nodes = 1 ; compute_nodes <= global_size/256; ++compute_nodes) { int size = workgroup_size * compute_nodes; input1.resize(size); input2.resize(size); result.resize(size); memset(&result[0], 0, size * sizeof(double)); gettimeofday(&tv1, 0); test.m_vector_sum.begin(); for (int i = 0 ;i < 100 ; ++i) { test.m_vector_sum.compute(global_size,&input1[0],&input2[0], &result[0], size, i==99); } test.m_vector_sum.commit(); gettimeofday(&tv2, 0); for (int i = 0 ;i < size-1; ++i) if (result[i] != 1000) printf("invalid code\n"); fprintf(output,"%d,%d,%ld\n",global_size, compute_nodes, time_difference(tv1,tv2)/100); //printf("Size %d Warps scheduled %d Runtime is %ld \n", size, compute_nodes, time_difference(tv1,tv2)/10000); } fclose(output); }
static void update_rate_limiter_timeout (GFileMonitor *monitor, guint new_time) { ForEachData data; GSource *source; if (monitor->priv->timeout_fires_at != 0 && new_time != 0 && time_difference (new_time, monitor->priv->timeout_fires_at) == 0) return; /* Nothing to do, we already fire earlier than that */ data.min_time = G_MAXUINT32; data.monitor = monitor; data.time_now = get_time_msecs (); g_hash_table_foreach_remove (monitor->priv->rate_limiter, foreach_rate_limiter_update, &data); /* Remove old timeout */ if (monitor->priv->timeout) { g_source_destroy (monitor->priv->timeout); g_source_unref (monitor->priv->timeout); monitor->priv->timeout_fires_at = 0; monitor->priv->timeout = NULL; } /* Set up new timeout */ if (data.min_time != G_MAXUINT32) { source = g_timeout_source_new (data.min_time + 1); /* + 1 to make sure we've really passed the time */ g_source_set_callback (source, rate_limiter_timeout, monitor, NULL); g_source_attach (source, monitor->priv->context); monitor->priv->timeout = source; monitor->priv->timeout_fires_at = data.time_now + data.min_time; } }
terrasar_meta *read_terrasar_meta(const char *dataFile) { int ii, kk, numStateVectors, numDopplerEstimates; ymd_date imgStartDate, imgDopplerDate, date; hms_time imgStartTime, imgDopplerTime, time; julian_date julianDate; char timeStr[30], str[50]; tsx_doppler_params *tsx; terrasar_meta *terrasar = terrasar_meta_init(); if (!fileExists(dataFile)) asfPrintError("Metadata file (%s) does not exist!\n", dataFile); xmlDoc *doc = xmlReadFile(dataFile, NULL, 0); if (!doc) asfPrintError("Could not parse file %s\n", dataFile); strcpy(terrasar->filename, xml_get_string_value(doc, "level1Product.productComponents.annotation.file.location.filename")); strcpy(terrasar->mission, xml_get_string_value(doc, "level1Product.productInfo.missionInfo.mission")); strcpy(terrasar->sensor, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.sensor")); strcpy(terrasar->imagingMode, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.imagingMode")); strcpy(terrasar->elevationBeamConfiguration, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.elevationBeamConfiguration")); strcpy(terrasar->imageDataType, xml_get_string_value(doc, "level1Product.productInfo.imageDataInfo.imageDataType")); terrasar->imageDataDepth = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.imageDataDepth"); strcpy(terrasar->imageDataFormat, xml_get_string_value(doc, "level1Product.productInfo.imageDataInfo.imageDataFormat")); strcpy(terrasar->azimuthTimeUTC, xml_get_string_value(doc, "level1Product.productInfo.sceneInfo.sceneCenterCoord.azimuthTimeUTC")); terrasar->absOrbit = xml_get_int_value(doc, "level1Product.productInfo.missionInfo.absOrbit"); strcpy(terrasar->orbitDirection, xml_get_string_value(doc, "level1Product.productInfo.missionInfo.orbitDirection")); terrasar->numberOfLayers = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.numberOfLayers"); strcpy(terrasar->polarisationMode, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationMode")); if (strcmp_case(terrasar->polarisationMode, "SINGLE") == 0) strcpy(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[0]")); else if (strcmp_case(terrasar->polarisationMode, "DUAL") == 0) { strcpy(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[0]")); strcat(terrasar->bands, ","); strcat(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[1]")); } else if (strcmp_case(terrasar->polarisationMode, "TWIN") == 0) { strcpy(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[0]")); strcat(terrasar->bands, ","); strcat(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[1]")); } else if (strcmp_case(terrasar->polarisationMode, "QUAD") == 0) { strcpy(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[0]")); strcat(terrasar->bands, ","); strcat(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[1]")); strcat(terrasar->bands, ","); strcat(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[2]")); strcat(terrasar->bands, ","); strcat(terrasar->bands, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.polarisationList.polLayer[3]")); } terrasar->numberOfRows = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.numberOfRows"); terrasar->numberOfColumns = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.numberOfColumns"); strcpy(terrasar->projection, xml_get_string_value(doc, "level1Product.productInfo.productVariantInfo.projection")); if (strcmp_case(terrasar->projection, "GROUNDRANGE") == 0) terrasar->rangeResolution = xml_get_double_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster." "groundRangeResolution"); if (strcmp_case(terrasar->projection, "SLANTRANGE") == 0) terrasar->rangeResolution = xml_get_double_value(doc, "level1Product.productSpecific.complexImageInfo.projectedSpacingRange." "slantRange"); // FIXME: cover MAP case terrasar->azimuthResolution = xml_get_double_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.azimuthResolution"); terrasar->sceneCenterCoordLat = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCenterCoord.lat"); terrasar->sceneCenterCoordLon = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCenterCoord.lon"); strcpy(terrasar->lookDirection, xml_get_string_value(doc, "level1Product.productInfo.acquisitionInfo.lookDirection")); terrasar->azimuthLooks = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.azimuthLooks"); terrasar->rangeLooks = xml_get_int_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.rangeLooks"); strcpy(terrasar->imageCoordinateType, xml_get_string_value(doc, "level1Product.productSpecific.complexImageInfo.imageCoordinateType")); terrasar->rowSpacing = xml_get_double_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.rowSpacing"); terrasar->columnSpacing = xml_get_double_value(doc, "level1Product.productInfo.imageDataInfo.imageRaster.columnSpacing"); terrasar->rangeTimeFirst = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.rangeTime.firstPixel"); terrasar->rangeTimeLast = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.rangeTime.lastPixel"); terrasar->centerFrequency = xml_get_double_value(doc, "level1Product.instrument.radarParameters.centerFrequency"); terrasar->prf = xml_get_double_value(doc, "level1Product.instrument.settings.settingRecord.PRF"); terrasar->totalProcessedAzimuthBandwidth = xml_get_double_value(doc, "level1Product.processing.processingParameter." "totalProcessedAzimuthBandwidth"); // chirp rate ??? terrasar->pulseLength = xml_get_double_value(doc, "level1Product.processing.processingParameter.rangeCompression.chirps." "referenceChirp.pulseLength"); terrasar->rsf = xml_get_double_value(doc, "level1Product.instrument.settings.RSF"); // pitch, roll, yaw ??? // read Doppler values terrasar->doppler = meta_doppler_init(); terrasar->doppler->type = tsx_doppler; numDopplerEstimates = xml_get_int_value(doc, "level1Product.processing.doppler.dopplerCentroid[0]." "numberOfDopplerRecords"); tsx = tsx_doppler_init(numDopplerEstimates); terrasar->doppler->tsx = tsx; strcpy(str, xml_get_string_value(doc, "level1Product.processing.doppler.dopplerCentroid[0].dopplerEstimate[0]." "timeUTC")); date_terrasar2date(str, &imgDopplerDate, &imgDopplerTime); tsx->year = imgDopplerDate.year; date_ymd2jd(&imgDopplerDate, &julianDate); tsx->julDay = julianDate.jd; tsx->second = date_hms2sec(&imgDopplerTime); for (ii=0; ii<numDopplerEstimates; ii++) { strcpy(timeStr, xml_get_string_value(doc, "level1Product.processing.doppler.dopplerCentroid[0]." "dopplerEstimate[%d].timeUTC", ii)); date_terrasar2date(timeStr, &date, &time); tsx->dop[ii].time = time_difference(&date, &time, &imgDopplerDate, &imgDopplerTime); tsx->dop[ii].first_range_time = xml_get_double_value(doc, "level1Product.processing.doppler.dopplerCentroid[0]." "dopplerEstimate[%d].combinedDoppler.validityRangeMin", ii); tsx->dop[ii].reference_time = xml_get_double_value(doc, "level1Product.processing.doppler.dopplerCentroid[0]." "dopplerEstimate[%d].combinedDoppler.referencePoint", ii); tsx->dop[ii].poly_degree = xml_get_double_value(doc, "level1Product.processing.doppler.dopplerCentroid[0]." "dopplerEstimate[%d].combinedDoppler.polynomialDegree", ii); tsx->dop[ii].coefficient = (double *) MALLOC(sizeof(double) * (tsx->dop[ii].poly_degree+1)); for (kk=0; kk<=tsx->dop[ii].poly_degree; kk++) tsx->dop[ii].coefficient[kk] = xml_get_double_value(doc, "level1Product.processing.doppler.dopplerCentroid[0]." "dopplerEstimate[%d].combinedDoppler.coefficient[%d]", ii, kk); } // read state vectors strcpy(terrasar->sceneStart, xml_get_string_value(doc, "level1Product.productInfo.sceneInfo.start.timeUTC")); date_terrasar2date(terrasar->sceneStart, &imgStartDate, &imgStartTime); strcpy(terrasar->sceneStop, xml_get_string_value(doc, "level1Product.productInfo.sceneInfo.stop.timeUTC")); numStateVectors = xml_get_int_value(doc, "level1Product.platform.orbit.orbitHeader.numStateVectors"); terrasar->state_vectors = meta_state_vectors_init(numStateVectors); terrasar->state_vectors->year = imgStartDate.year; date_ymd2jd(&imgStartDate, &julianDate); terrasar->state_vectors->julDay = julianDate.jd; terrasar->state_vectors->second = date_hms2sec(&imgStartTime); for (ii=0; ii<numStateVectors; ii++) { sprintf(str, "level1Product.platform.orbit.stateVec[%d].timeUTC", ii); strcpy(timeStr, xml_get_string_value(doc, str)); date_terrasar2date(timeStr, &date, &time); terrasar->state_vectors->vecs[ii].time = time_difference(&date, &time, &imgStartDate, &imgStartTime); sprintf(str, "level1Product.platform.orbit.stateVec[%d].posX", ii); terrasar->state_vectors->vecs[ii].vec.pos.x = xml_get_double_value(doc, str); sprintf(str, "level1Product.platform.orbit.stateVec[%d].posY", ii); terrasar->state_vectors->vecs[ii].vec.pos.y = xml_get_double_value(doc, str); sprintf(str, "level1Product.platform.orbit.stateVec[%d].posZ", ii); terrasar->state_vectors->vecs[ii].vec.pos.z = xml_get_double_value(doc, str); sprintf(str, "level1Product.platform.orbit.stateVec[%d].velX", ii); terrasar->state_vectors->vecs[ii].vec.vel.x = xml_get_double_value(doc, str); sprintf(str, "level1Product.platform.orbit.stateVec[%d].velY", ii); terrasar->state_vectors->vecs[ii].vec.vel.y = xml_get_double_value(doc, str); sprintf(str, "level1Product.platform.orbit.stateVec[%d].velZ", ii); terrasar->state_vectors->vecs[ii].vec.vel.z = xml_get_double_value(doc, str); } // read location information terrasar->sceneCornerCoord1Lat = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[0].lat"); terrasar->sceneCornerCoord1Lon = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[0].lon"); terrasar->sceneCornerCoord2Lat = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[1].lat"); terrasar->sceneCornerCoord2Lon = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[1].lon"); terrasar->sceneCornerCoord3Lat = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[2].lat"); terrasar->sceneCornerCoord3Lon = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[2].lon"); terrasar->sceneCornerCoord4Lat = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[3].lat"); terrasar->sceneCornerCoord4Lon = xml_get_double_value(doc, "level1Product.productInfo.sceneInfo.sceneCornerCoord[3].lon"); // read calibration information char calFlag[15]; strcpy(calFlag, xml_get_string_value(doc, "level1Product.productInfo.productVariantInfo.radiometricCorrection")); if (strcmp_case(calFlag, "CALIBRATED") == 0) terrasar->cal_factor = xml_get_double_value(doc, "level1Product.calibration.calibrationConstant.calFactor"); xmlFreeDoc(doc); xmlCleanupParser(); return terrasar; }
radarsat2_meta *read_radarsat2_meta_ext(const char *dataFile, int cal) { int ii, numStateVectors, numDopplerEstimates; ymd_date imgStartDate, date; hms_time imgStartTime, time; julian_date julianDate; char timeStr[30], str[150]; radarsat2_doppler_params *r2_doppler; radarsat2_meta *radarsat2 = radarsat2_meta_init(); if (!fileExists(dataFile)) asfPrintError("Metadata file (%s) does not exist!\n", dataFile); char *path = (char *) MALLOC(sizeof(char)*512); char *file = (char *) MALLOC(sizeof(char)*128); split_dir_and_file(dataFile, path, file); xmlDoc *doc = xmlReadFile(dataFile, NULL, 0); if (!doc) asfPrintError("Could not parse file %s\n", dataFile); strcpy(radarsat2->satellite, xml_get_string_value(doc, "product.sourceAttributes.satellite")); strcpy(radarsat2->sensor, xml_get_string_value(doc, "product.sourceAttributes.sensor")); strcpy(radarsat2->beamModeMnemonic, xml_get_string_value(doc, "product.sourceAttributes.beamModeMnemonic")); strcpy(radarsat2->acquisitionType, xml_get_string_value(doc, "product.sourceAttributes.radarParameters.acquisitionType")); strcpy(radarsat2->productType, xml_get_string_value(doc, "product.imageGenerationParameters.generalProcessingInformation." "productType")); strcpy(radarsat2->dataType, xml_get_string_value(doc, "product.imageAttributes.rasterAttributes.dataType")); strcpy(radarsat2->processingFacility, xml_get_string_value(doc, "product.imageGenerationParameters.generalProcessingInformation." "processingFacility")); strcpy(radarsat2->zeroDopplerAzimuthTime, xml_get_string_value(doc, "product.imageGenerationParameters.slantRangeToGroundRange." "zeroDopplerAzimuthTime")); strcpy(radarsat2->softwareVersion, xml_get_string_value(doc, "product.imageGenerationParameters.generalProcessingInformation." "softwareVersion")); radarsat2->bitsPerSample = xml_get_int_value(doc, "product.productInfo.imageDataInfo.imageDataDepth"); //radarsat2->absOrbit = //xml_get_int_value(doc, "product.productInfo.missionInfo.absOrbit"); strcpy(radarsat2->passDirection, xml_get_string_value(doc, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "passDirection")); // Number of bands needs to be derived from polarizations string int band_count = 0; char *attribute = (char *) MALLOC(sizeof(char)*128); char *fileName = (char *) MALLOC(sizeof(char)*512); strcpy(radarsat2->polarizations, xml_get_string_value(doc, "product.sourceAttributes.radarParameters.polarizations")); for (ii=0; ii<strlen(radarsat2->polarizations)-1; ii++) if (radarsat2->polarizations[ii] == ' ') radarsat2->polarizations[ii] = ','; if (strstr(radarsat2->polarizations, "HH")) band_count++; if (strstr(radarsat2->polarizations, "VV")) band_count++; if (strstr(radarsat2->polarizations, "HV")) band_count++; if (strstr(radarsat2->polarizations, "VH")) band_count++; radarsat2->band_count = band_count; strcpy(radarsat2->filename, ""); strcpy(radarsat2->bands, ""); // Park the filenames in the basename field of the metadata and replace // it with the directory name once we are done with importing the data for (ii=0; ii<band_count; ii++) { sprintf(str, "product.imageAttributes.fullResolutionImageData[%d].pole", ii); strcpy(attribute, xml_get_string_attribute(doc, str)); sprintf(str, "product.imageAttributes.fullResolutionImageData[%d]", ii); strcpy(fileName, xml_get_string_value(doc, str)); if (ii == 0) { sprintf(radarsat2->filename, "%s", fileName); sprintf(radarsat2->bands, "AMP-%s,PHASE-%s", uc(attribute), uc(attribute)); } else { strcat(radarsat2->filename, ","); strcat(radarsat2->filename, fileName); strcat(radarsat2->bands, ","); sprintf(str, "AMP-%s,PHASE-%s", uc(attribute), uc(attribute)); strcat(radarsat2->bands, str); } } FREE(fileName); FREE(attribute); radarsat2->numberOfLines = xml_get_int_value(doc, "product.imageAttributes.rasterAttributes.numberOfLines"); radarsat2->numberOfSamplesPerLine = xml_get_int_value(doc, "product.imageAttributes.rasterAttributes.numberOfSamplesPerLine"); radarsat2->sampledPixelSpacing = xml_get_double_value(doc, "product.imageAttributes.rasterAttributes.sampledPixelSpacing"); radarsat2->sampledLineSpacing = xml_get_double_value(doc, "product.imageAttributes.rasterAttributes.sampledLineSpacing"); radarsat2->semiMajorAxis = xml_get_double_value(doc, "product.imageAttributes.geographicInformation." "referenceEllipsoidParameters.semiMajorAxis"); radarsat2->semiMinorAxis = xml_get_double_value(doc, "product.imageAttributes.geographicInformation." "referenceEllipsoidParameters.semiMinorAxis"); strcpy(radarsat2->lineTimeOrdering, xml_get_string_value(doc, "product.imageAttributes.rasterAttributes.lineTimeOrdering")); strcpy(radarsat2->pixelTimeOrdering, xml_get_string_value(doc, "product.imageAttributes.rasterAttributes.pixelTimeOrdering")); strcpy(radarsat2->antennaPointing, xml_get_string_value(doc, "product.sourceAttributes.radarParameters.antennaPointing")); radarsat2->numberOfAzimuthLooks = xml_get_int_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "numberOfAzimuthLooks"); radarsat2->numberOfRangeLooks = xml_get_int_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "numberOfRangeLooks"); radarsat2->slantRangeNearEdge = xml_get_double_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "slantRangeNearEdge"); radarsat2->radarCenterFrequency = xml_get_double_value(doc, "product.sourceAttributes.radarParameters.radarCenterFrequency"); radarsat2->pulseRepetitionFrequency = xml_get_double_value(doc, "product.sourceAttributes.radarParameters.pulseRepetitionFrequency"); radarsat2->satelliteHeight = xml_get_double_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "satelliteHeight"); radarsat2->totalProcessedAzimuthBandwidth = xml_get_double_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "totalProcessedAzimuthBandwidth"); // chirp rate ??? radarsat2->pulseLength = xml_get_double_value(doc, "product.sourceAttributes.radarParameters.pulseLength"); radarsat2->adcSamplingRate = xml_get_double_value(doc, "product.sourceAttributes.radarParameters.adcSamplingRate"); // pitch, roll, yaw ??? // read Doppler values radarsat2->doppler = meta_doppler_init(); radarsat2->doppler->type = radarsat2_doppler; char *dopplerCentroidStr; dopplerCentroidStr = (char *) MALLOC(sizeof(char)*512); strcpy(dopplerCentroidStr, xml_get_string_value(doc, "product.imageGenerationParameters.dopplerCentroid." "dopplerCentroidCoefficients")); numDopplerEstimates = getNumParamsInString(dopplerCentroidStr); r2_doppler = radarsat2_doppler_init(numDopplerEstimates); radarsat2->doppler->r2 = r2_doppler; r2_doppler->ref_time_centroid = xml_get_double_value(doc, "product.imageGenerationParameters.dopplerCentroid." "dopplerCentroidReferenceTime"); r2_doppler->ref_time_rate = xml_get_double_value(doc, "product.imageGenerationParameters.dopplerRateValues." "dopplerRateReferenceTime"); char *dopplerRateStr; dopplerRateStr = (char *) MALLOC(sizeof(char)*512); strcpy(dopplerRateStr, xml_get_string_value(doc, "product.imageGenerationParameters.dopplerRateValues." "dopplerRateValuesCoefficients")); r2_doppler->time_first_sample = xml_get_double_value(doc, "product.imageGenerationParameters.slantRangeToGroundRange." "slantRangeTimeToFirstRangeSample"); char *p, *q; p = dopplerCentroidStr; for (ii=0; ii<numDopplerEstimates; ii++) { if (ii == 0) q = p; else { if (strchr(p, ' ')) { q = strchr(p, ' '); q++; } } sscanf(q, "%lf", &r2_doppler->centroid[ii]); p = q; } FREE(dopplerCentroidStr); p = dopplerRateStr; for (ii=0; ii<numDopplerEstimates; ii++) { if (ii == 0) q = p; else { if (strchr(p, ' ')) { q = strchr(p, ' '); q++; } } sscanf(q, "%lf", &r2_doppler->rate[ii]); p = q; } FREE(dopplerRateStr); // read state vectors strcpy(radarsat2->zeroDopplerTimeFirstLine, xml_get_string_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "zeroDopplerTimeFirstLine")); date_terrasar2date(radarsat2->zeroDopplerTimeFirstLine, &imgStartDate, &imgStartTime); strcpy(radarsat2->zeroDopplerTimeLastLine, xml_get_string_value(doc, "product.imageGenerationParameters.sarProcessingInformation." "zeroDopplerTimeLastLine")); // Accommodate data stored in reverse time if (strcmp_case(radarsat2->lineTimeOrdering, "DECREASING") == 0) date_terrasar2date(radarsat2->zeroDopplerTimeLastLine, &imgStartDate, &imgStartTime); // FIXME: determine numStateVector from data - count the entries //numStateVectors = xml_get_int_value(doc, // "product.platform.orbit.orbitHeader.numStateVectors"); numStateVectors = 5; radarsat2->state_vectors = meta_state_vectors_init(numStateVectors); radarsat2->state_vectors->year = imgStartDate.year; date_ymd2jd(&imgStartDate, &julianDate); radarsat2->state_vectors->julDay = julianDate.jd; radarsat2->state_vectors->second = date_hms2sec(&imgStartTime); for (ii=0; ii<numStateVectors; ii++) { sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].timeStamp", ii); strcpy(timeStr, xml_get_string_value(doc, str)); date_terrasar2date(timeStr, &date, &time); radarsat2->state_vectors->vecs[ii].time = time_difference(&date, &time, &imgStartDate, &imgStartTime); sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].xPosition", ii); radarsat2->state_vectors->vecs[ii].vec.pos.x = xml_get_double_value(doc, str); sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].yPosition", ii); radarsat2->state_vectors->vecs[ii].vec.pos.y = xml_get_double_value(doc, str); sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].zPosition", ii); radarsat2->state_vectors->vecs[ii].vec.pos.z = xml_get_double_value(doc, str); sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].xVelocity", ii); radarsat2->state_vectors->vecs[ii].vec.vel.x = xml_get_double_value(doc, str); sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].yVelocity", ii); radarsat2->state_vectors->vecs[ii].vec.vel.y = xml_get_double_value(doc, str); sprintf(str, "product.sourceAttributes.orbitAndAttitude.orbitInformation." "stateVector[%d].zVelocity", ii); radarsat2->state_vectors->vecs[ii].vec.vel.z = xml_get_double_value(doc, str); } // read location information from the tie points ii = 0; int line=-99, pixel=-99, found=TRUE; while (found) { sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].imageCoordinate.line", ii); line = (int) xml_get_double_value(doc, str); sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].imageCoordinate.pixel", ii); pixel = (int) xml_get_double_value(doc, str); if (line < 0 || pixel < 0) found = FALSE; if (found) { if (line == 0 && pixel == 0) { sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "latitude", ii); radarsat2->sceneCornerCoord1Lat = xml_get_double_value(doc, str); sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "longitude", ii); radarsat2->sceneCornerCoord1Lon = xml_get_double_value(doc, str); } if (line == 0 && pixel == radarsat2->numberOfSamplesPerLine-1) { sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "latitude", ii); radarsat2->sceneCornerCoord2Lat = xml_get_double_value(doc, str); sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "longitude", ii); radarsat2->sceneCornerCoord2Lon = xml_get_double_value(doc, str); } if (line == radarsat2->numberOfLines-1 && pixel == 0) { sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "latitude", ii); radarsat2->sceneCornerCoord3Lat = xml_get_double_value(doc, str); sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "longitude", ii); radarsat2->sceneCornerCoord3Lon = xml_get_double_value(doc, str); } if (line == radarsat2->numberOfLines-1 && pixel == radarsat2->numberOfSamplesPerLine-1) { sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "latitude", ii); radarsat2->sceneCornerCoord4Lat = xml_get_double_value(doc, str); sprintf(str, "product.imageAttributes.geographicInformation." "geolocationGrid.imageTiePoint[%d].geodeticCoordinate." "longitude", ii); radarsat2->sceneCornerCoord4Lon = xml_get_double_value(doc, str); } } ii++; } // Read calibration information if (cal) { double sample_count = radarsat2->numberOfSamplesPerLine; attribute = (char *) MALLOC(sizeof(char)*128); fileName = (char *) MALLOC(sizeof(char)*512); for (ii=0; ii<3; ii++) { sprintf(str, "product.imageAttributes.lookupTable[%d].incidenceAngleCorrection", ii); strcpy(attribute, xml_get_string_attribute(doc, str)); sprintf(str, "product.imageAttributes.lookupTable[%d]", ii); if (strlen(path) > 0) sprintf(fileName, "%s%s", path, xml_get_string_value(doc, str)); else strcpy(fileName, xml_get_string_value(doc, str)); if (strcmp_case(attribute, "Beta Nought") == 0) radarsat2->gains_beta = read_radarsat2_lut(fileName, sample_count); else if (strcmp_case(attribute, "Sigma Nought") == 0) radarsat2->gains_sigma = read_radarsat2_lut(fileName, sample_count); else if (strcmp_case(attribute, "Gamma") == 0) radarsat2->gains_gamma = read_radarsat2_lut(fileName, sample_count); } FREE(attribute); FREE(fileName); } xmlFreeDoc(doc); xmlCleanupParser(); return radarsat2; }
/** * Return status of the noll_prob->cmd for the formula * pform /\ not(\/ nform_i) * by looking at the entailment * pform ==> \/ nform_i * * @return 1 if satisfiable, (i.e. invalid entailment) * 0 if not satisfiable (i.e., valid entailment) * */ int noll_entl_solve (void) { int res = 0; #ifndef NDEBUG noll_entl_fprint (stdout); fflush (stdout); #endif /* * Special case of sat solving, when no negative formula */ if (noll_entl_is_sat ()) return noll_sat_solve (noll_prob->pform); /* * Test special (syntactic) cases of entailment, * before normalizing the formulas */ if (noll_option_get_verb () > 0) fprintf (stdout, " > check special cases\n"); res = noll_entl_solve_special (true); if (res != -1) return res; if (noll_option_get_verb () > 0) { fprintf (stdout, " not a special case for check-%ssat!\n", (noll_prob->cmd == NOLL_FORM_SAT) ? "" : "un"); fflush (stdout); } struct timeval tvBegin, tvEnd, tvDiff; gettimeofday (&tvBegin, NULL); /* * Compute typing infos */ if (noll_option_get_verb () > 0) fprintf (stdout, " > typing formulas\n"); noll_entl_type (); #ifndef NDEBUG fprintf (stdout, "\n*** noll_entl_solve: after typing problem:\n"); noll_records_array_fprint (stdout, "records:"); noll_fields_array_fprint (stdout, "fields:"); noll_pred_array_fprint (stdout, preds_array, "predicates:"); fflush (stdout); #endif /* * Normalize both formulas (which also test satisfiability) */ if (noll_option_get_verb () > 0) fprintf (stdout, " > normalizing formulas\n"); noll_entl_normalize (); /* * Test the satisfiability of pform /\ not(\/_i nform) */ /* * Special cases, not covered by graph homeomorphism */ res = noll_entl_solve_special (false); if (res != -1) goto check_end; /* * If both formulas are not empty, * translate formulas to graphs. */ if (noll_option_get_verb () > 0) fprintf (stdout, " > translation to graphs\n"); res = noll_entl_to_graph (); if (res == 0) { // entailment invalid, so sat problem res = 1; goto check_end; } /* * Check graph homeomorphism */ if (noll_option_get_verb () > 0) fprintf (stdout, " > check graph homeomorphism\n"); /* build homeomorphism from right to left */ res = noll_entl_to_hom (); /* sharing constraints in pos_graph are updated and tested! */ switch (res) { case 0: { // homeomorphism not found, // so entailment invalid, // so sat problem res = 1; break; } case 1: { // homeomorphism found // so entailment valid // so unsat problem res = 0; break; } default: assert (res == -1); break; } /* * FIN */ check_end: gettimeofday (&tvEnd, NULL); time_difference (&tvDiff, &tvEnd, &tvBegin); printf ("\nTotal time (sec): %ld.%06ld\n\n", (long int) tvDiff.tv_sec, (long int) tvDiff.tv_usec); /* * Free the allocated memory * (only graphs, formulas will be deallocated at the end) */ noll_entl_free_aux (); return res; }
meta_parameters *iso2meta(iso_meta *iso) { int ii; meta_parameters *meta = raw_init(); char str[30]; // Convenience pointers iso_generalHeader *header = iso->generalHeader; iso_productComponents *comps = iso->productComponents; iso_productInfo *info = iso->productInfo; iso_productSpecific *spec = iso->productSpecific; iso_setup *setup = iso->setup; iso_processing *proc = iso->processing; iso_instrument *inst = iso->instrument; iso_platform *platform = iso->platform; iso_productQuality *quality = iso->productQuality; meta->meta_version = 3.5; // General block for (ii=0; ii<comps->numAnnotations; ii++) if (comps->annotation[ii].type == MAIN_TYPE) strncpy(meta->general->basename, comps->annotation[ii].file.name, 256); strcpy(meta->general->sensor, header->mission); strcpy(meta->general->sensor_name, info->sensor); strcpy(meta->general->mode, info->elevationBeamConfiguration); strcpy(meta->general->receiving_station, info->receivingStation); strcpy(meta->general->processor, header->generationSystem); if (info->imageDataType == DETECTED_DATA_TYPE && info->imageDataDepth == 8) meta->general->data_type = ASF_BYTE; else if (info->imageDataType == DETECTED_DATA_TYPE && info->imageDataDepth == 16) meta->general->data_type = INTEGER16; else if (info->imageDataType == DETECTED_DATA_TYPE && info->imageDataDepth == 32) // assumption here is that we are not dealing with INTERGER32 meta->general->data_type = REAL32; else if (info->imageDataType == DETECTED_DATA_TYPE && info->imageDataDepth == 64) meta->general->data_type = REAL64; else if (info->imageDataType == COMPLEX_DATA_TYPE && info->imageDataDepth == 8) meta->general->data_type = COMPLEX_BYTE; else if (info->imageDataType == COMPLEX_DATA_TYPE && info->imageDataDepth == 16) meta->general->data_type = COMPLEX_INTEGER16; else if (info->imageDataType == COMPLEX_DATA_TYPE && info->imageDataDepth == 32) // assumption here is that we are not dealing with COMPLEX_INTEGER32 meta->general->data_type = COMPLEX_REAL32; else if (info->imageDataType == COMPLEX_DATA_TYPE && info->imageDataDepth == 64) meta->general->data_type = COMPLEX_REAL64; if (info->imageDataType == RAW_DATA_TYPE) meta->general->image_data_type = RAW_IMAGE; else if (info->imageDataType == COMPLEX_DATA_TYPE) meta->general->image_data_type = COMPLEX_IMAGE; else if (info->imageDataType == DETECTED_DATA_TYPE) meta->general->image_data_type = AMPLITUDE_IMAGE; // more detailed mapping of imageDataType will probably need pixelValueID // context if (strcmp_case(info->pixelValueID, "RADAR BRIGHTNESS") == 0) meta->general->radiometry = r_AMP; // dealing with any form of calibration not implemented yet dateTime2str(info->sceneCenterCoord.azimuthTimeUTC, meta->general->acquisition_date); meta->general->orbit = info->absOrbit; if (info->orbitDirection == ASCENDING) meta->general->orbit_direction = 'A'; else if (info->orbitDirection == DESCENDING) meta->general->orbit_direction = 'D'; meta->general->frame = setup->frameID; meta->general->band_count = comps->numLayers; strcpy(meta->general->bands, polLayer2str(comps->imageData[0].polLayer)); for (ii=1; ii<comps->numLayers; ii++) { sprintf(str, ", %s", polLayer2str(comps->imageData[ii].polLayer)); strcat(meta->general->bands, str); } meta->general->line_count = info->numberOfRows; meta->general->sample_count = info->numberOfColumns; meta->general->start_line = info->startRow; meta->general->start_sample = info->startColumn; meta->general->x_pixel_size = info->groundRangeResolution; meta->general->y_pixel_size = info->azimuthResolution; meta->general->center_latitude = info->sceneCenterCoord.lat; meta->general->center_longitude = info->sceneCenterCoord.lon; spheroid_type_t spheroid = WGS84_SPHEROID; // FIXME: needs to know reference spheroid_axes_lengths(spheroid, &meta->general->re_major, &meta->general->re_minor); meta->general->bit_error_rate = quality->imageDataQuality[0].bitErrorRate; meta->general->missing_lines = quality->imageDataQuality[0].missingLines; meta->general->no_data = (float) quality->imageDataQuality[0].noData; // SAR block meta->sar = meta_sar_init(); if (info->projection == SLANTRANGE_PROJ) meta->sar->image_type = 'S'; else if (info->projection == GROUNDRANGE_PROJ) meta->sar->image_type = 'G'; else if (info->projection == MAP_PROJ) meta->sar->image_type = 'P'; if (setup->lookDirection == RIGHT_LOOK) meta->sar->look_direction = 'R'; else if (setup->lookDirection == LEFT_LOOK) meta->sar->look_direction = 'L'; meta->sar->azimuth_look_count = info->azimuthLooks; meta->sar->range_look_count = info->rangeLooks; if (spec->imageCoordinateType == RAW_COORD) meta->sar->deskewed = FALSE; else if (spec->imageCoordinateType == ZERODOPPLER) meta->sar->deskewed = TRUE; meta->general->line_scaling = info->rowScaling; meta->general->sample_scaling = info->columnScaling; meta->sar->range_time_per_pixel = info->columnSpacing; meta->sar->azimuth_time_per_pixel = info->rowSpacing; meta->sar->slant_shift = spec->slantRangeShift; //meta->sar->slant_range_first_pixel = info->rangeTimeFirstPixel * SPD_LIGHT; meta->sar->slant_range_first_pixel = spec->projectedSpacingSlantRange; meta->sar->wavelength = SPD_LIGHT / inst->centerFrequency; meta->sar->prf = spec->commonPRF; meta->sar->earth_radius = info->earthRadius; meta->sar->satellite_height = info->satelliteHeight; // meta->sar->satellite_binary_time; // meta->sar->satellite_clock_time; for (ii=0; ii<=proc->doppler[0].polynomialDegree; ii++) meta->sar->range_doppler_coefficients[ii] = proc->doppler[0].coefficient[ii]; meta->sar->azimuth_doppler_coefficients[0] = proc->doppler[0].coefficient[0]; // meta->sar->chirp_rate // meta->sar->pulse_duration meta->sar->range_sampling_rate = spec->commonRSF; if (info->polarizationMode == SINGLE_POL) strcpy(meta->sar->polarization, "SINGLE"); else if (info->polarizationMode == DUAL_POL) strcpy(meta->sar->polarization, "DUAL"); else if (info->polarizationMode == QUAD_POL) strcpy(meta->sar->polarization, "QUAD"); meta->sar->multilook = proc->multiLookedFlag; meta->sar->pitch = info->pitch; meta->sar->roll = info->roll; meta->sar->yaw = info->yaw; meta->sar->incid_a[0] = info->sceneCenterCoord.incidenceAngle; meta->sar->heading_angle = info->headingAngle; meta->sar->chirp_rate = proc->processingParameter[0].chirpRate; meta->sar->pulse_duration = proc->processingParameter[0].pulseDuration; // meta->projection // meta->transform // meta->airsar // meta->uavsar // meta->statistics int numVectors = platform->numStateVectors; meta->state_vectors = meta_state_vectors_init(numVectors); meta->state_vectors->vector_count = numVectors; ymd_date ymdStart, ymdSV; julian_date jd; hms_time hmsStart, hmsSV; ymdStart.year = info->startTimeUTC.year; ymdStart.month = info->startTimeUTC.month; ymdStart.day = info->startTimeUTC.day; hmsStart.hour = info->startTimeUTC.hour; hmsStart.min = info->startTimeUTC.min; hmsStart.sec = info->startTimeUTC.second; meta->state_vectors->year = info->startTimeUTC.year; date_ymd2jd(&ymdStart, &jd); meta->state_vectors->julDay = jd.jd; meta->state_vectors->second = date_hms2sec(&hmsStart); for (ii=0; ii<numVectors; ii++) { ymdSV.year = platform->stateVec[ii].timeUTC.year; ymdSV.month = platform->stateVec[ii].timeUTC.month; ymdSV.day = platform->stateVec[ii].timeUTC.day; hmsSV.hour = platform->stateVec[ii].timeUTC.hour; hmsSV.min = platform->stateVec[ii].timeUTC.min; hmsSV.sec = platform->stateVec[ii].timeUTC.second; meta->state_vectors->vecs[ii].time = time_difference(&ymdSV, &hmsSV, &ymdStart, &hmsStart); meta->state_vectors->vecs[ii].vec.pos.x = platform->stateVec[ii].posX; meta->state_vectors->vecs[ii].vec.pos.y = platform->stateVec[ii].posY; meta->state_vectors->vecs[ii].vec.pos.z = platform->stateVec[ii].posZ; meta->state_vectors->vecs[ii].vec.vel.x = platform->stateVec[ii].velX; meta->state_vectors->vecs[ii].vec.vel.y = platform->stateVec[ii].velY; meta->state_vectors->vecs[ii].vec.vel.z = platform->stateVec[ii].velZ; } if (meta->sar->azimuth_time_per_pixel > 0) meta->sar->time_shift = 0.0; else meta->sar->time_shift = meta->state_vectors->vecs[numVectors-1].time; if (meta->sar->yaw == 0 || !meta_is_valid_double(meta->sar->yaw)) { meta->sar->yaw = meta_yaw(meta, meta->general->line_count/2.0, meta->general->sample_count/2.0); } /* // few calculations need state vectors meta->sar->earth_radius = meta_get_earth_radius(meta, line_count/2, sample_count/2); // meta->sar->earth_radius_pp meta->sar->satellite_height = meta_get_sat_height(meta, meta->general->line_count/2, meta->general->sample_count/2); meta->sar->incid_a[0] = meta_incid(meta, line_count/2, sample_count/2)*R2D; */ // Location block meta_get_corner_coords(meta); /* meta->location = meta_location_init(); for (ii=0; ii<4; ii++) { if (info->sceneCornerCoord[ii].refRow == 0 && info->sceneCornerCoord[ii].refColumn == 0) { meta->location->lat_start_near_range = info->sceneCornerCoord[ii].lat; meta->location->lon_start_near_range = info->sceneCornerCoord[ii].lon; } else if (info->sceneCornerCoord[ii].refRow == 0 && info->sceneCornerCoord[ii].refColumn == sample_count) { meta->location->lat_start_far_range = info->sceneCornerCoord[ii].lat; meta->location->lon_start_far_range = info->sceneCornerCoord[ii].lon; } else if (info->sceneCornerCoord[ii].refRow == line_count && info->sceneCornerCoord[ii].refColumn == 0) { meta->location->lat_end_near_range = info->sceneCornerCoord[ii].lat; meta->location->lon_end_near_range = info->sceneCornerCoord[ii].lon; } else if (info->sceneCornerCoord[ii].refRow == line_count && info->sceneCornerCoord[ii].refColumn == sample_count) { meta->location->lat_end_far_range = info->sceneCornerCoord[ii].lat; meta->location->lon_end_far_range = info->sceneCornerCoord[ii].lon; } } */ return meta; }
static void *consumer_read_ahead_thread( void *arg ) { // The argument is the consumer mlt_consumer self = arg; // Get the properties of the consumer mlt_properties properties = MLT_CONSUMER_PROPERTIES( self ); // Get the width and height int width = mlt_properties_get_int( properties, "width" ); int height = mlt_properties_get_int( properties, "height" ); // See if video is turned off int video_off = mlt_properties_get_int( properties, "video_off" ); int preview_off = mlt_properties_get_int( properties, "preview_off" ); int preview_format = mlt_properties_get_int( properties, "preview_format" ); // Get the audio settings mlt_audio_format afmt = mlt_audio_s16; const char *format = mlt_properties_get( properties, "mlt_audio_format" ); if ( format ) { if ( !strcmp( format, "none" ) ) afmt = mlt_audio_none; else if ( !strcmp( format, "s32" ) ) afmt = mlt_audio_s32; else if ( !strcmp( format, "s32le" ) ) afmt = mlt_audio_s32le; else if ( !strcmp( format, "float" ) ) afmt = mlt_audio_float; else if ( !strcmp( format, "f32le" ) ) afmt = mlt_audio_f32le; else if ( !strcmp( format, "u8" ) ) afmt = mlt_audio_u8; } int counter = 0; double fps = mlt_properties_get_double( properties, "fps" ); int channels = mlt_properties_get_int( properties, "channels" ); int frequency = mlt_properties_get_int( properties, "frequency" ); int samples = 0; void *audio = NULL; // See if audio is turned off int audio_off = mlt_properties_get_int( properties, "audio_off" ); // Get the maximum size of the buffer int buffer = mlt_properties_get_int( properties, "buffer" ) + 1; // General frame variable mlt_frame frame = NULL; uint8_t *image = NULL; // Time structures struct timeval ante; // Average time for get_frame and get_image int count = 0; int skipped = 0; int64_t time_process = 0; int skip_next = 0; mlt_position pos = 0; mlt_position start_pos = 0; mlt_position last_pos = 0; int frame_duration = mlt_properties_get_int( properties, "frame_duration" ); int drop_max = mlt_properties_get_int( properties, "drop_max" ); if ( preview_off && preview_format != 0 ) self->format = preview_format; // Get the first frame frame = mlt_consumer_get_frame( self ); if ( frame ) { // Get the image of the first frame if ( !video_off ) { mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL ); mlt_frame_get_image( frame, &image, &self->format, &width, &height, 0 ); } if ( !audio_off ) { samples = mlt_sample_calculator( fps, frequency, counter++ ); mlt_frame_get_audio( frame, &audio, &afmt, &frequency, &channels, &samples ); } // Mark as rendered mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 ); last_pos = start_pos = pos = mlt_frame_get_position( frame ); } // Get the starting time (can ignore the times above) gettimeofday( &ante, NULL ); // Continue to read ahead while ( self->ahead ) { // Put the current frame into the queue pthread_mutex_lock( &self->queue_mutex ); while( self->ahead && mlt_deque_count( self->queue ) >= buffer ) pthread_cond_wait( &self->queue_cond, &self->queue_mutex ); mlt_deque_push_back( self->queue, frame ); pthread_cond_broadcast( &self->queue_cond ); pthread_mutex_unlock( &self->queue_mutex ); // Get the next frame frame = mlt_consumer_get_frame( self ); // If there's no frame, we're probably stopped... if ( frame == NULL ) continue; pos = mlt_frame_get_position( frame ); // Increment the counter used for averaging processing cost count ++; // All non-normal playback frames should be shown if ( mlt_properties_get_int( MLT_FRAME_PROPERTIES( frame ), "_speed" ) != 1 ) { #ifdef DEINTERLACE_ON_NOT_NORMAL_SPEED mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "consumer_deinterlace", 1 ); #endif // Indicate seeking or trick-play start_pos = pos; } // If skip flag not set or frame-dropping disabled if ( !skip_next || self->real_time == -1 ) { if ( !video_off ) { // Reset width/height - could have been changed by previous mlt_frame_get_image width = mlt_properties_get_int( properties, "width" ); height = mlt_properties_get_int( properties, "height" ); // Get the image mlt_events_fire( MLT_CONSUMER_PROPERTIES( self ), "consumer-frame-render", frame, NULL ); mlt_frame_get_image( frame, &image, &self->format, &width, &height, 0 ); } // Indicate the rendered image is available. mlt_properties_set_int( MLT_FRAME_PROPERTIES( frame ), "rendered", 1 ); // Reset consecutively-skipped counter skipped = 0; } else // Skip image processing { // Increment the number of consecutively-skipped frames skipped++; // If too many (1 sec) consecutively-skipped frames if ( skipped > drop_max ) { // Reset cost tracker time_process = 0; count = 1; mlt_log_verbose( self, "too many frames dropped - forcing next frame\n" ); } } // Always process audio if ( !audio_off ) { samples = mlt_sample_calculator( fps, frequency, counter++ ); mlt_frame_get_audio( frame, &audio, &afmt, &frequency, &channels, &samples ); } // Get the time to process this frame int64_t time_current = time_difference( &ante ); // If the current time is not suddenly some large amount if ( time_current < time_process / count * 20 || !time_process || count < 5 ) { // Accumulate the cost for processing this frame time_process += time_current; } else { mlt_log_debug( self, "current %"PRId64" threshold %"PRId64" count %d\n", time_current, (int64_t) (time_process / count * 20), count ); // Ignore the cost of this frame's time count--; } // Determine if we started, resumed, or seeked if ( pos != last_pos + 1 ) start_pos = pos; last_pos = pos; // Do not skip the first 20% of buffer at start, resume, or seek if ( pos - start_pos <= buffer / 5 + 1 ) { // Reset cost tracker time_process = 0; count = 1; } // Reset skip flag skip_next = 0; // Only consider skipping if the buffer level is low (or really small) if ( mlt_deque_count( self->queue ) <= buffer / 5 + 1 ) { // Skip next frame if average cost exceeds frame duration. if ( time_process / count > frame_duration ) skip_next = 1; if ( skip_next ) mlt_log_debug( self, "avg usec %"PRId64" (%"PRId64"/%d) duration %d\n", time_process/count, time_process, count, frame_duration); } } // Remove the last frame mlt_frame_close( frame ); return NULL; }
/** * g_file_monitor_emit_event: * @monitor: a #GFileMonitor. * @child: a #GFile. * @other_file: a #GFile. * @event_type: a set of #GFileMonitorEvent flags. * * Emits the #GFileMonitor::changed signal if a change * has taken place. Should be called from file monitor * implementations only. * * The signal will be emitted from an idle handler (in the <link * linkend="g-main-context-push-thread-default">thread-default main * context</link>). **/ void g_file_monitor_emit_event (GFileMonitor *monitor, GFile *child, GFile *other_file, GFileMonitorEvent event_type) { guint32 time_now, since_last; gboolean emit_now; RateLimiter *limiter; g_return_if_fail (G_IS_FILE_MONITOR (monitor)); g_return_if_fail (G_IS_FILE (child)); limiter = g_hash_table_lookup (monitor->priv->rate_limiter, child); if (event_type != G_FILE_MONITOR_EVENT_CHANGED) { if (limiter) { rate_limiter_send_delayed_change_now (monitor, limiter, get_time_msecs ()); if (event_type == G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT) limiter->send_virtual_changes_done_at = 0; else rate_limiter_send_virtual_changes_done_now (monitor, limiter); update_rate_limiter_timeout (monitor, 0); } emit_in_idle (monitor, child, other_file, event_type); } else { /* Changed event, rate limit */ time_now = get_time_msecs (); emit_now = TRUE; if (limiter) { since_last = time_difference (limiter->last_sent_change_time, time_now); if (since_last < monitor->priv->rate_limit_msec) { /* We ignore this change, but arm a timer so that we can fire it later if we don't get any other events (that kill this timeout) */ emit_now = FALSE; if (limiter->send_delayed_change_at == 0) { limiter->send_delayed_change_at = time_now + monitor->priv->rate_limit_msec; update_rate_limiter_timeout (monitor, limiter->send_delayed_change_at); } } } if (limiter == NULL) limiter = new_limiter (monitor, child); if (emit_now) { emit_in_idle (monitor, child, other_file, event_type); limiter->last_sent_change_time = time_now; limiter->send_delayed_change_at = 0; /* Set a timeout of 2*rate limit so that we can clear out the change from the hash eventualy */ update_rate_limiter_timeout (monitor, time_now + 2 * monitor->priv->rate_limit_msec); } /* Schedule a virtual change done. This is removed if we get a real one, and postponed if we get more change events. */ limiter->send_virtual_changes_done_at = time_now + DEFAULT_VIRTUAL_CHANGES_DONE_DELAY_SECS * 1000; update_rate_limiter_timeout (monitor, limiter->send_virtual_changes_done_at); } }
int noll_sat_solve (noll_form_t * form) { /* check that form is exactly the positive formula */ assert (noll_prob->pform == form); /* * Special case: null or unsat input formula */ if (form == NULL || form->kind == NOLL_FORM_UNSAT) { if (noll_option_get_verb () > 0) fprintf (stdout, " unsat formula!\n"); if (noll_option_is_diag ()) fprintf (stdout, "[diag] unsat at input!\n"); return 0; } struct timeval tvBegin, tvEnd, tvDiff; gettimeofday (&tvBegin, NULL); /* * Compute typing infos */ if (noll_option_get_verb () > 0) fprintf (stdout, " > typing formula\n"); noll_sat_type (); #ifndef NDEBUG fprintf (stdout, "\n*** noll_sat_solve: after typing problem:\n"); noll_records_array_fprint (stdout, "records:"); noll_fields_array_fprint (stdout, "fields:"); noll_pred_array_fprint (stdout, preds_array, "predicates:"); fflush (stdout); #endif noll_prob->pabstr = noll_normalize (form, "f-out.txt", true, false); /* * FIN */ check_end: gettimeofday (&tvEnd, NULL); time_difference (&tvDiff, &tvEnd, &tvBegin); printf ("\nTotal time (sec): %ld.%06ld\n\n", (long int) tvDiff.tv_sec, (long int) tvDiff.tv_usec); int res = 1; if (form->kind == NOLL_FORM_UNSAT) { if (noll_option_get_verb () > 0) fprintf (stdout, " unsat formula!\n"); if (noll_option_is_diag ()) noll_sat_diag_unsat (form, noll_prob->pabstr); res = 0; } else { // else, form->kind is sat if (noll_option_get_verb () > 0) fprintf (stdout, " sat formula!\n"); if (noll_option_is_diag ()) noll_sat_diag_sat (form, noll_prob->pabstr); } /* * Free the allocated memory * (only boolean abstraction, formulas will be deallocated at the end) */ noll_sat_free_aux (form); return res; }
/* Stop accounting * * Here we will request the resource information at the end of the period * we want to account. Using the reference (begin) values we retrieved in * the module_acccounting_start() function we can now determine the resource * usage of this request. */ static int module_accounting_stop(request_rec *r) { // {{{ /* printf("Module accounting stop\n"); */ struct timeval end_time; struct rusage end_own_usage; struct rusage end_child_usage; acc_data *data; /* Resolve the internal redirect request */ request_rec *initial; request_rec *last; /* Determine the main request */ initial = r; while (initial->main) initial = initial->main; last = initial; /* Determine the first request */ while (initial->prev) initial = initial->prev; /* Determine the last request */ while (last->next) last = last->next; /* Get the reference (begin) data */ if ((data = (acc_data*) apr_table_get(initial->notes, notes_key_internal)) == NULL) { /* Internal data missing ?!? */ ACC_LOG_REQ_ERROR("Failed to fetch internal data!"); return DECLINED; } /* Request resource information at this point */ /* Try waiting for children */ wait4(-1, NULL, WNOHANG, NULL); /* What's the time since epoch? */ if (gettimeofday(&(end_time), NULL) == -1) { /* ERROR */ ACC_LOG_REQ_ERROR("Request for (end) time of day failed"); } /* Get the accumelated resource usage of this process */ if (getrusage(RUSAGE_SELF, &(end_own_usage)) == -1) { /* ERROR */ ACC_LOG_REQ_ERROR("Request for (end) resource usage failed"); } /* Get the accumelated resource usage for childeren of this process */ if (getrusage(RUSAGE_CHILDREN, &(end_child_usage)) == -1) { /* ERROR */ ACC_LOG_REQ_ERROR("Request for children's (end) resource usage failed"); } /* Debug */ // {{{ ACC_LOG_DEBUG_TIME( "accounting_stop:data->begin_time", data->begin_time ); ACC_LOG_DEBUG_TIME( "accounting_stop:data->begin_own_usage.ru_utime", data->begin_own_usage.ru_utime ); ACC_LOG_DEBUG_TIME( "accounting_stop:data->begin_own_usage.ru_stime", data->begin_own_usage.ru_stime ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:data->begin_own_usage.ru_inblock", data->begin_own_usage.ru_inblock ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:data->begin_own_usage.ru_oublock", data->begin_own_usage.ru_oublock ); ACC_LOG_DEBUG_TIME( "accounting_stop:data->begin_child_usage.ru_utime", data->begin_child_usage.ru_utime ); ACC_LOG_DEBUG_TIME( "accounting_stop:data->begin_child_usage.ru_stime", data->begin_child_usage.ru_stime ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:data->begin_child_usage.ru_inblock", data->begin_child_usage.ru_inblock ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:data->begin_child_usage.ru_oublock", data->begin_child_usage.ru_oublock ); ACC_LOG_DEBUG_TIME( "accounting_stop:end_time", end_time ); ACC_LOG_DEBUG_TIME( "accounting_stop:end_own_usage.ru_utime", end_own_usage.ru_utime ); ACC_LOG_DEBUG_TIME( "accounting_stop:end_own_usage.ru_stime", end_own_usage.ru_stime ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:end_own_usage.ru_inblock", end_own_usage.ru_inblock ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:end_own_usage.ru_oublock", end_own_usage.ru_oublock ); ACC_LOG_DEBUG_TIME( "accounting_stop:end_child_usage.ru_utime", end_child_usage.ru_utime ); ACC_LOG_DEBUG_TIME( "accounting_stop:end_child_usage.ru_stime", end_child_usage.ru_stime ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:end_child_usage.ru_inblock", end_child_usage.ru_inblock ); ACC_LOG_DEBUG_BLOCKS( "accounting_stop:end_child_usage.ru_oublock", end_child_usage.ru_oublock ); // }}} /* Set the time difference between start and stop */ apr_table_setn( last->notes, notes_key_time, apr_psprintf( last->pool, "%ld", time_difference( last, &(data->begin_time), &(end_time) ) ) ); /* Set the accumilated user time */ apr_table_setn( last->notes, notes_key_utime, apr_psprintf( last->pool, "%ld", time_difference( last, &(data->begin_own_usage.ru_utime), &(end_own_usage.ru_utime) ) ) ); /* Set the accumilated system time */ apr_table_setn( last->notes, notes_key_stime, apr_psprintf( last->pool, "%ld", time_difference( last, &(data->begin_own_usage.ru_stime), &(end_own_usage.ru_stime) ) ) ); /* apr_table_setn( last->notes, notes_key_stime, apr_psprintf( last->pool, "%ld", end_own_usage.ru_stime.tv_usec ) ); */ /* Set the accumulated inblocks */ apr_table_setn( last->notes, notes_key_inblock, apr_psprintf( last->pool, "%ld", block_difference( last, data->begin_own_usage.ru_inblock, end_own_usage.ru_inblock ) ) ); /* Set the accumulated oublocks */ apr_table_setn( last->notes, notes_key_oublock, apr_psprintf( last->pool, "%ld", block_difference( last, data->begin_own_usage.ru_oublock, end_own_usage.ru_oublock ) ) ); /* Set the child accumilated user time */ apr_table_setn( last->notes, notes_key_cutime, apr_psprintf( last->pool, "%ld", time_difference( last, &(data->begin_child_usage.ru_utime), &(end_child_usage.ru_utime) ) ) ); /* Set the child accumilated system time */ apr_table_setn( last->notes, notes_key_cstime, apr_psprintf( last->pool, "%ld", time_difference( last, &(data->begin_child_usage.ru_stime), &(end_child_usage.ru_stime) ) ) ); /* Set the child accumulated inblocks */ apr_table_setn( last->notes, notes_key_cinblock, apr_psprintf( last->pool, "%ld", block_difference( last, data->begin_child_usage.ru_inblock, end_child_usage.ru_inblock ) ) ); /* Set the child accumulated oublocks */ apr_table_setn( last->notes, notes_key_coublock, apr_psprintf( last->pool, "%ld", block_difference( last, data->begin_child_usage.ru_oublock, end_child_usage.ru_oublock ) ) ); /* We're not a final handler */ return DECLINED; } // }}}
int main(int argc, char** argv){ int noOfRows = 5; int noOfCols = 1000; int love = 0; if(argc > 1){ noOfCols = getNoOfColsForMB(atoi(argv[1])); } if(argc > 2){ love = atoi(argv[2]); } if(argc > 3){ noOfRows = atoi(argv[3]); } double **rows = malloc(sizeof(double*) * noOfRows); for(int c = 0; c < noOfRows; c++){ rows[c] = malloc(sizeof(double) * noOfCols); for(int d = 0; d < noOfCols; d++){ rows[c][d] = getRandomNumber(); } } struct timeval start; struct timeval stop; struct timeval difference; gettimeofday(&start, NULL); double totalSum = 0.0; int cids[2]; int ptr = 0; if(love){ cids[0] = mchain(); cids[1] = mchain(); } for(int row = 1; row < noOfRows -1; row++){ if(love){ brk_mchain(cids[ptr]); if(row > 1){ hate(rows[row - 2], noOfCols*sizeof(double)); } mlink(cids[ptr], rows[row], noOfCols*sizeof(double)); ptr += 1; ptr = ptr%2; } for(int col = 1; col < noOfCols -1; col++){ double sum = 0.0; for(int i = -1; i < 2; i++){ for(int j = -1; j < 2; j++){ sum += rows[row + i][col + j] * (1.0/9.0); } } rows[row][col] = sum; totalSum += sum; } } gettimeofday(&stop, NULL); time_difference(&difference, &stop, &start); printf("Done.\n"); printf("Time: %ds %dus\n", difference.tv_sec, difference.tv_usec); return 0; }