repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
davepallot/OSKAR
|
oskar/mem/oskar_mem_write_fits_cube.h
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_MEM_WRITE_FITS_CUBE_H_
#define OSKAR_MEM_WRITE_FITS_CUBE_H_
/**
* @file oskar_mem_write_fits_cube.h
*/
#include <oskar_global.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief
* Writes pixel data to a FITS image file.
*
* @details
* Writes pixel data to a FITS image file (or two files, for complex data).
*
* Can be called multiple times with the same \p root_name to write
* one plane at a time.
*
* Set \p i_plane to -1 if \p data contains the entire cube.
*
* @param[in] data Array of values to write.
* @param[in] root_name Root name of FITS file to write.
* @param[in] width Image width, in pixels.
* @param[in] height Image height, in pixels.
* @param[in] num_planes Number of image planes in the file.
* @param[in] i_plane Image plane index to write (-1 = all).
* @param[in,out] status Status return code.
*/
OSKAR_EXPORT
void oskar_mem_write_fits_cube(oskar_Mem* data, const char* root_name,
int width, int height, int num_planes, int i_plane, int* status);
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_MEM_WRITE_FITS_CUBE_H_ */
|
davepallot/OSKAR
|
oskar/telescope/station/oskar_evaluate_element_weights_dft_cuda.h
|
/*
* Copyright (c) 2012-2018, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_EVALUATE_ELEMENT_WEIGHTS_DFT_CUDA_H_
#define OSKAR_EVALUATE_ELEMENT_WEIGHTS_DFT_CUDA_H_
/**
* @file oskar_evaluate_element_weights_dft_cuda.h
*/
#include <oskar_global.h>
#include <utility/oskar_vector_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief
* Generates geometric DFT beamforming weights using CUDA (single precision).
*
* @details
* This function produces the complex DFT beamforming weights for the
* given element positions and beam direction.
*
* The wavelength used to compute the supplied wavenumber must be in the
* same units as the input positions.
*
* Note that all pointers refer to device memory.
*
* @param[in] num_elements Number of antenna elements.
* @param[in] d_x Input element x positions.
* @param[in] d_y Input element y positions.
* @param[in] d_y Input element z positions.
* @param[in] wavenumber Wavenumber (2 pi / wavelength).
* @param[in] x_beam Beam direction cosine x-component.
* @param[in] y_beam Beam direction cosine y-component.
* @param[in] z_beam Beam direction cosine z-component.
* @param[out] weights Array of complex DFT weights (length num_elements).
*/
OSKAR_EXPORT
void oskar_evaluate_element_weights_dft_cuda_f(int num_elements,
const float* d_x, const float* d_y, const float* d_z,
float wavenumber, float x_beam, float y_beam, float z_beam,
float2* d_weights);
/**
* @brief
* Generates geometric DFT beamforming weights using CUDA (double precision).
*
* @details
* This function produces the complex DFT beamforming weights for the
* given element positions and beam direction.
*
* The wavelength used to compute the supplied wavenumber must be in the
* same units as the input positions.
*
* Note that all pointers refer to device memory.
*
* @param[in] num_elements Number of antenna elements.
* @param[in] d_x Input element x positions.
* @param[in] d_y Input element y positions.
* @param[in] d_y Input element z positions.
* @param[in] wavenumber Wavenumber (2 pi / wavelength).
* @param[in] x_beam Beam direction cosine x-component.
* @param[in] y_beam Beam direction cosine y-component.
* @param[in] z_beam Beam direction cosine z-component.
* @param[out] weights Array of complex DFT weights (length num_elements).
*/
OSKAR_EXPORT
void oskar_evaluate_element_weights_dft_cuda_d(int num_elements,
const double* d_x, const double* d_y, const double* d_z,
double wavenumber, double x_beam, double y_beam, double z_beam,
double2* d_weights);
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_EVALUATE_ELEMENT_WEIGHTS_DFT_CUDA_H_ */
|
davepallot/OSKAR
|
oskar/imager/src/oskar_imager_rotate_coords.c
|
<reponame>davepallot/OSKAR<filename>oskar/imager/src/oskar_imager_rotate_coords.c
/*
* Copyright (c) 2016-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "imager/private_imager.h"
#include "imager/oskar_imager.h"
#ifdef __cplusplus
extern "C" {
#endif
void oskar_imager_rotate_coords(const oskar_Imager* h, size_t num_coords,
const oskar_Mem* uu_in, const oskar_Mem* vv_in, const oskar_Mem* ww_in,
oskar_Mem* uu_out, oskar_Mem* vv_out, oskar_Mem* ww_out)
{
#ifdef OSKAR_OS_WIN
int i;
const int num = (const int) num_coords;
#else
size_t i;
const size_t num = num_coords;
#endif
const double *M = h->M;
if (oskar_mem_precision(uu_in) == OSKAR_SINGLE)
{
float *uu_o, *vv_o, *ww_o;
const float *uu_i, *vv_i, *ww_i;
uu_i = (const float*)oskar_mem_void_const(uu_in);
vv_i = (const float*)oskar_mem_void_const(vv_in);
ww_i = (const float*)oskar_mem_void_const(ww_in);
uu_o = (float*)oskar_mem_void(uu_out);
vv_o = (float*)oskar_mem_void(vv_out);
ww_o = (float*)oskar_mem_void(ww_out);
#pragma omp parallel for private(i)
for (i = 0; i < num; ++i)
{
double s0, s1, s2, t0, t1, t2;
s0 = uu_i[i]; s1 = vv_i[i]; s2 = ww_i[i];
t0 = M[0] * s0 + M[1] * s1 + M[2] * s2;
t1 = M[3] * s0 + M[4] * s1 + M[5] * s2;
t2 = M[6] * s0 + M[7] * s1 + M[8] * s2;
uu_o[i] = t0; vv_o[i] = t1; ww_o[i] = t2;
}
}
else
{
double *uu_o, *vv_o, *ww_o;
const double *uu_i, *vv_i, *ww_i;
uu_i = (const double*)oskar_mem_void_const(uu_in);
vv_i = (const double*)oskar_mem_void_const(vv_in);
ww_i = (const double*)oskar_mem_void_const(ww_in);
uu_o = (double*)oskar_mem_void(uu_out);
vv_o = (double*)oskar_mem_void(vv_out);
ww_o = (double*)oskar_mem_void(ww_out);
#pragma omp parallel for private(i)
for (i = 0; i < num; ++i)
{
double s0, s1, s2, t0, t1, t2;
s0 = uu_i[i]; s1 = vv_i[i]; s2 = ww_i[i];
t0 = M[0] * s0 + M[1] * s1 + M[2] * s2;
t1 = M[3] * s0 + M[4] * s1 + M[5] * s2;
t2 = M[6] * s0 + M[7] * s1 + M[8] * s2;
uu_o[i] = t0; vv_o[i] = t1; ww_o[i] = t2;
}
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/telescope/src/oskar_telescope_accessors.c
|
<filename>oskar/telescope/src/oskar_telescope_accessors.c
/*
* Copyright (c) 2013-2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "telescope/private_telescope.h"
#include "telescope/oskar_telescope.h"
#include "math/oskar_cmath.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Properties and metadata. */
int oskar_telescope_precision(const oskar_Telescope* model)
{
return model->precision;
}
int oskar_telescope_mem_location(const oskar_Telescope* model)
{
return model->mem_location;
}
double oskar_telescope_lon_rad(const oskar_Telescope* model)
{
return model->lon_rad;
}
double oskar_telescope_lat_rad(const oskar_Telescope* model)
{
return model->lat_rad;
}
double oskar_telescope_alt_metres(const oskar_Telescope* model)
{
return model->alt_metres;
}
double oskar_telescope_polar_motion_x_rad(const oskar_Telescope* model)
{
return model->pm_x_rad;
}
double oskar_telescope_polar_motion_y_rad(const oskar_Telescope* model)
{
return model->pm_y_rad;
}
int oskar_telescope_phase_centre_coord_type(const oskar_Telescope* model)
{
return model->phase_centre_coord_type;
}
double oskar_telescope_phase_centre_ra_rad(const oskar_Telescope* model)
{
return model->phase_centre_ra_rad;
}
double oskar_telescope_phase_centre_dec_rad(const oskar_Telescope* model)
{
return model->phase_centre_dec_rad;
}
double oskar_telescope_channel_bandwidth_hz(const oskar_Telescope* model)
{
return model->channel_bandwidth_hz;
}
double oskar_telescope_time_average_sec(const oskar_Telescope* model)
{
return model->time_average_sec;
}
double oskar_telescope_uv_filter_min(const oskar_Telescope* model)
{
return model->uv_filter_min;
}
double oskar_telescope_uv_filter_max(const oskar_Telescope* model)
{
return model->uv_filter_max;
}
int oskar_telescope_uv_filter_units(const oskar_Telescope* model)
{
return model->uv_filter_units;
}
int oskar_telescope_pol_mode(const oskar_Telescope* model)
{
return model->pol_mode;
}
int oskar_telescope_num_baselines(const oskar_Telescope* model)
{
return ((model->num_stations * (model->num_stations - 1)) / 2);
}
int oskar_telescope_num_stations(const oskar_Telescope* model)
{
return model->num_stations;
}
int oskar_telescope_identical_stations(const oskar_Telescope* model)
{
return model->identical_stations;
}
int oskar_telescope_allow_station_beam_duplication(
const oskar_Telescope* model)
{
return model->allow_station_beam_duplication;
}
int oskar_telescope_enable_numerical_patterns(const oskar_Telescope* model)
{
return model->enable_numerical_patterns;
}
int oskar_telescope_max_station_size(const oskar_Telescope* model)
{
return model->max_station_size;
}
int oskar_telescope_max_station_depth(const oskar_Telescope* model)
{
return model->max_station_depth;
}
/* Station models. */
oskar_Station* oskar_telescope_station(oskar_Telescope* model, int i)
{
return model->station[i];
}
const oskar_Station* oskar_telescope_station_const(
const oskar_Telescope* model, int i)
{
return model->station[i];
}
/* Coordinate arrays. */
oskar_Mem* oskar_telescope_station_measured_x_offset_ecef_metres(
oskar_Telescope* model)
{
return model->station_measured_x_offset_ecef_metres;
}
const oskar_Mem* oskar_telescope_station_measured_x_offset_ecef_metres_const(
const oskar_Telescope* model)
{
return model->station_measured_x_offset_ecef_metres;
}
oskar_Mem* oskar_telescope_station_measured_y_offset_ecef_metres(
oskar_Telescope* model)
{
return model->station_measured_y_offset_ecef_metres;
}
const oskar_Mem* oskar_telescope_station_measured_y_offset_ecef_metres_const(
const oskar_Telescope* model)
{
return model->station_measured_y_offset_ecef_metres;
}
oskar_Mem* oskar_telescope_station_measured_z_offset_ecef_metres(
oskar_Telescope* model)
{
return model->station_measured_z_offset_ecef_metres;
}
const oskar_Mem* oskar_telescope_station_measured_z_offset_ecef_metres_const(
const oskar_Telescope* model)
{
return model->station_measured_z_offset_ecef_metres;
}
oskar_Mem* oskar_telescope_station_measured_x_enu_metres(oskar_Telescope* model)
{
return model->station_measured_x_enu_metres;
}
const oskar_Mem* oskar_telescope_station_measured_x_enu_metres_const(
const oskar_Telescope* model)
{
return model->station_measured_x_enu_metres;
}
oskar_Mem* oskar_telescope_station_measured_y_enu_metres(oskar_Telescope* model)
{
return model->station_measured_y_enu_metres;
}
const oskar_Mem* oskar_telescope_station_measured_y_enu_metres_const(
const oskar_Telescope* model)
{
return model->station_measured_y_enu_metres;
}
oskar_Mem* oskar_telescope_station_measured_z_enu_metres(oskar_Telescope* model)
{
return model->station_measured_z_enu_metres;
}
const oskar_Mem* oskar_telescope_station_measured_z_enu_metres_const(
const oskar_Telescope* model)
{
return model->station_measured_z_enu_metres;
}
oskar_Mem* oskar_telescope_station_true_x_offset_ecef_metres(
oskar_Telescope* model)
{
return model->station_true_x_offset_ecef_metres;
}
const oskar_Mem* oskar_telescope_station_true_x_offset_ecef_metres_const(
const oskar_Telescope* model)
{
return model->station_true_x_offset_ecef_metres;
}
oskar_Mem* oskar_telescope_station_true_y_offset_ecef_metres(
oskar_Telescope* model)
{
return model->station_true_y_offset_ecef_metres;
}
const oskar_Mem* oskar_telescope_station_true_y_offset_ecef_metres_const(
const oskar_Telescope* model)
{
return model->station_true_y_offset_ecef_metres;
}
oskar_Mem* oskar_telescope_station_true_z_offset_ecef_metres(
oskar_Telescope* model)
{
return model->station_true_z_offset_ecef_metres;
}
const oskar_Mem* oskar_telescope_station_true_z_offset_ecef_metres_const(
const oskar_Telescope* model)
{
return model->station_true_z_offset_ecef_metres;
}
oskar_Mem* oskar_telescope_station_true_x_enu_metres(oskar_Telescope* model)
{
return model->station_true_x_enu_metres;
}
const oskar_Mem* oskar_telescope_station_true_x_enu_metres_const(
const oskar_Telescope* model)
{
return model->station_true_x_enu_metres;
}
oskar_Mem* oskar_telescope_station_true_y_enu_metres(oskar_Telescope* model)
{
return model->station_true_y_enu_metres;
}
const oskar_Mem* oskar_telescope_station_true_y_enu_metres_const(
const oskar_Telescope* model)
{
return model->station_true_y_enu_metres;
}
oskar_Mem* oskar_telescope_station_true_z_enu_metres(oskar_Telescope* model)
{
return model->station_true_z_enu_metres;
}
const oskar_Mem* oskar_telescope_station_true_z_enu_metres_const(
const oskar_Telescope* model)
{
return model->station_true_z_enu_metres;
}
int oskar_telescope_noise_enabled(const oskar_Telescope* model)
{
return model->noise_enabled;
}
unsigned int oskar_telescope_noise_seed(const oskar_Telescope* model)
{
return model->noise_seed;
}
/* Setters. */
void oskar_telescope_set_allow_station_beam_duplication(oskar_Telescope* model,
int value)
{
model->allow_station_beam_duplication = value;
}
void oskar_telescope_set_enable_noise(oskar_Telescope* model,
int value, unsigned int seed)
{
model->noise_enabled = value;
model->noise_seed = seed;
}
void oskar_telescope_set_enable_numerical_patterns(oskar_Telescope* model,
int value)
{
model->enable_numerical_patterns = value;
}
static void oskar_telescope_set_gaussian_station_beam_p(oskar_Station* station,
double fwhm_rad, double ref_freq_hz)
{
oskar_station_set_gaussian_beam_values(station, fwhm_rad, ref_freq_hz);
if (oskar_station_has_child(station))
{
int i, num_elements;
num_elements = oskar_station_num_elements(station);
for (i = 0; i < num_elements; ++i)
{
oskar_telescope_set_gaussian_station_beam_p(
oskar_station_child(station, i), fwhm_rad, ref_freq_hz);
}
}
}
void oskar_telescope_set_gaussian_station_beam_width(oskar_Telescope* model,
double fwhm_deg, double ref_freq_hz)
{
int i;
for (i = 0; i < model->num_stations; ++i)
{
oskar_telescope_set_gaussian_station_beam_p(model->station[i],
fwhm_deg * M_PI / 180.0, ref_freq_hz);
}
}
void oskar_telescope_set_noise_freq_file(oskar_Telescope* model,
const char* filename, int* status)
{
int i;
if (*status) return;
for (i = 0; i < model->num_stations; ++i)
{
oskar_mem_load_ascii(filename, 1, status,
oskar_station_noise_freq_hz(model->station[i]), "");
}
}
void oskar_telescope_set_noise_freq(oskar_Telescope* model,
double start_hz, double inc_hz, int num_channels, int* status)
{
int i;
oskar_Mem* noise_freq_hz;
noise_freq_hz = oskar_mem_create(model->precision, OSKAR_CPU,
num_channels, status);
if (*status) return;
if (model->precision == OSKAR_DOUBLE)
{
double* f = oskar_mem_double(noise_freq_hz, status);
for (i = 0; i < num_channels; ++i) f[i] = start_hz + i * inc_hz;
}
else
{
float* f = oskar_mem_float(noise_freq_hz, status);
for (i = 0; i < num_channels; ++i) f[i] = start_hz + i * inc_hz;
}
/* Set noise frequency for all top-level stations. */
for (i = 0; i < model->num_stations; ++i)
{
oskar_Mem* t;
t = oskar_station_noise_freq_hz(model->station[i]);
oskar_mem_realloc(t, num_channels, status);
oskar_mem_copy(t, noise_freq_hz, status);
}
oskar_mem_free(noise_freq_hz, status);
}
void oskar_telescope_set_noise_rms_file(oskar_Telescope* model,
const char* filename, int* status)
{
int i;
if (*status) return;
for (i = 0; i < model->num_stations; ++i)
{
oskar_mem_load_ascii(filename, 1, status,
oskar_station_noise_rms_jy(model->station[i]), "");
}
}
void oskar_telescope_set_noise_rms(oskar_Telescope* model,
double start, double end, int* status)
{
int i, j, num_channels;
double inc;
oskar_Station* s;
oskar_Mem *noise_rms_jy, *h;
/* Set noise RMS for all top-level stations. */
if (*status) return;
for (i = 0; i < model->num_stations; ++i)
{
s = model->station[i];
h = oskar_station_noise_rms_jy(s);
num_channels = (int)oskar_mem_length(oskar_station_noise_freq_hz(s));
if (num_channels == 0)
{
*status = OSKAR_ERR_OUT_OF_RANGE;
return;
}
oskar_mem_realloc(h, num_channels, status);
noise_rms_jy = oskar_mem_create(model->precision, OSKAR_CPU,
num_channels, status);
inc = (end - start) / (double)num_channels;
if (model->precision == OSKAR_DOUBLE)
{
double* r = oskar_mem_double(noise_rms_jy, status);
for (j = 0; j < num_channels; ++j) r[j] = start + j * inc;
}
else
{
float* r = oskar_mem_float(noise_rms_jy, status);
for (j = 0; j < num_channels; ++j) r[j] = start + j * inc;
}
oskar_mem_copy(h, noise_rms_jy, status);
oskar_mem_free(noise_rms_jy, status);
}
}
void oskar_telescope_set_position(oskar_Telescope* model,
double longitude_rad, double latitude_rad, double altitude_metres)
{
model->lon_rad = longitude_rad;
model->lat_rad = latitude_rad;
model->alt_metres = altitude_metres;
}
void oskar_telescope_set_polar_motion(oskar_Telescope* model,
double pm_x_rad, double pm_y_rad)
{
int i;
model->pm_x_rad = pm_x_rad;
model->pm_y_rad = pm_y_rad;
/* Set for all stations, too. */
for (i = 0; i < model->num_stations; ++i)
{
oskar_station_set_polar_motion(model->station[i], pm_x_rad, pm_y_rad);
}
}
static void oskar_telescope_set_station_phase_centre(oskar_Station* station,
int coord_type, double ra_rad, double dec_rad)
{
oskar_station_set_phase_centre(station, coord_type, ra_rad, dec_rad);
if (oskar_station_has_child(station))
{
int i, num_elements;
num_elements = oskar_station_num_elements(station);
for (i = 0; i < num_elements; ++i)
{
oskar_telescope_set_station_phase_centre(
oskar_station_child(station, i),
coord_type, ra_rad, dec_rad);
}
}
}
void oskar_telescope_set_phase_centre(oskar_Telescope* model,
int coord_type, double ra_rad, double dec_rad)
{
int i;
model->phase_centre_coord_type = coord_type;
model->phase_centre_ra_rad = ra_rad;
model->phase_centre_dec_rad = dec_rad;
for (i = 0; i < model->num_stations; ++i)
{
oskar_telescope_set_station_phase_centre(model->station[i],
coord_type, ra_rad, dec_rad);
}
}
void oskar_telescope_set_channel_bandwidth(oskar_Telescope* model,
double bandwidth_hz)
{
model->channel_bandwidth_hz = bandwidth_hz;
}
void oskar_telescope_set_time_average(oskar_Telescope* model,
double time_average_sec)
{
model->time_average_sec = time_average_sec;
}
void oskar_telescope_set_station_ids(oskar_Telescope* model)
{
int i, counter = 0;
for (i = 0; i < model->num_stations; ++i)
oskar_station_set_unique_ids(model->station[i], &counter);
}
static void oskar_telescope_set_station_type_p(oskar_Station* station, int type)
{
oskar_station_set_station_type(station, type);
if (oskar_station_has_child(station))
{
int i, num_elements;
num_elements = oskar_station_num_elements(station);
for (i = 0; i < num_elements; ++i)
{
oskar_telescope_set_station_type_p(
oskar_station_child(station, i), type);
}
}
}
void oskar_telescope_set_station_type(oskar_Telescope* model, const char* type,
int* status)
{
int i, t;
if (*status) return;
if (!strncmp(type, "A", 1) || !strncmp(type, "a", 1))
t = OSKAR_STATION_TYPE_AA;
else if (!strncmp(type, "G", 1) || !strncmp(type, "g", 1))
t = OSKAR_STATION_TYPE_GAUSSIAN_BEAM;
else if (!strncmp(type, "I", 1) || !strncmp(type, "i", 1))
t = OSKAR_STATION_TYPE_ISOTROPIC;
else if (!strncmp(type, "V", 1) || !strncmp(type, "v", 1))
t = OSKAR_STATION_TYPE_VLA_PBCOR;
else
{
*status = OSKAR_ERR_INVALID_ARGUMENT;
return;
}
for (i = 0; i < model->num_stations; ++i)
oskar_telescope_set_station_type_p(model->station[i], t);
}
void oskar_telescope_set_uv_filter(oskar_Telescope* model,
double uv_filter_min, double uv_filter_max, const char* units,
int* status)
{
if (!strncmp(units, "M", 1) || !strncmp(units, "m", 1))
model->uv_filter_units = OSKAR_METRES;
else if (!strncmp(units, "W", 1) || !strncmp(units, "w", 1))
model->uv_filter_units = OSKAR_WAVELENGTHS;
else
{
*status = OSKAR_ERR_INVALID_ARGUMENT;
return;
}
model->uv_filter_min = uv_filter_min;
model->uv_filter_max = uv_filter_max;
}
void oskar_telescope_set_pol_mode(oskar_Telescope* model, const char* mode,
int* status)
{
if (*status) return;
if (!strncmp(mode, "S", 1) || !strncmp(mode, "s", 1))
model->pol_mode = OSKAR_POL_MODE_SCALAR;
else if (!strncmp(mode, "F", 1) || !strncmp(mode, "f", 1))
model->pol_mode = OSKAR_POL_MODE_FULL;
else
*status = OSKAR_ERR_INVALID_ARGUMENT;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/settings/oskar_SettingsTree.h
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2015-2017, The University of Oxford
* All rights reserved.
*
* This file is part of the OSKAR package.
* Contact: oskar at oerc.ox.ac.uk
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_SETTINGS_TREE_H_
#define OSKAR_SETTINGS_TREE_H_
#include <settings/oskar_settings_macros.h>
#ifdef __cplusplus
namespace oskar {
/*
* Forward declarations only - don't include any other headers in this file!
*
* We shouldn't use std::string in interfaces because of ABI
* incompatibilities with different versions of the C++ "standard" library.
*
* (This caused various "unresolved symbol" errors in the Python
* interface, for example.)
*
* For methods which we expect will be called from elsewhere,
* use const char* instead, as this does work.
*/
class SettingsDependency;
class SettingsDependencyGroup;
class SettingsFileHandler;
class SettingsItem;
class SettingsKey;
class SettingsNode;
class SettingsValue;
struct SettingsTreePrivate;
/**
* @brief Settings container for use with OSKAR applications.
*
* @details
* High level representation of a tree of OSKAR application settings in memory.
* Each node in the tree consists of a SettingsNode, which is a
* specialisation of a SettingsItem.
*
* By attaching a file handler with the method @fn set_file_handler settings
* can be read from a settings file.
*
* Settings within the tree are addressed with a key which takes the form of a
* delimited string using the separator specified in the constructor.
*/
class OSKAR_SETTINGS_EXPORT SettingsTree
{
public:
/*! Constructor */
SettingsTree(char key_separator = '/');
/*! Destructor */
~SettingsTree();
/*! Adds a dependency to the current setting. */
/*!
* Adds a dependency to the current setting based on the value of
* another setting specified by the @p dependency_key. Settings are
* enabled or disabled based on their dependencies. A dependency is
* satisfied if the value of the setting at the key specified by
* @p dependency_key evaluated with the specified @p condition found to be
* True. A setting can have multiple dependencies by calling this function
* multiple times and the combination of multiple dependencies can be
* controlled though the functions @p begin_dependency_group and
* @p end_dependency_group.
*
* Allowed conditions are: EQ, NE, GT, GE, LT, LE.
*
* @param dependency_key Full settings key which the current key is
* dependent on.
* @param value The required value for the dependency to be
* satisfied.
* @param condition The condition logic to be satisfied. Default "EQ".
* @return True if successfully added, otherwise false.
*/
bool add_dependency(const char* dependency_key,
const char* value,
const char* condition = "EQ");
/*! Records a setting key-value pair that failed to validate on load. */
/*!
* When loading a file, if a key is unknown, it can be recorded by calling
* this method. This is used by the file handler classes.
*
* @param key The unknown settings key.
* @param value The unknown settings value.
*/
void add_failed(const char* key, const char* value);
/*! Add a setting to the tree, specified by a key and optional meta-data. */
/*!
* Adds a setting to the tree at the position defined by the specified
* @p key modified by the current group prefix.
*
* @param key The settings key.
* @param label Brief label given to the setting.
* @param description A more detailed description of the setting.
* @param type_name String name of the settings type. This should be the
* name of type handled by the SettingsValue class.
* @param type_default String containing the default value for the type.
* @param type_parameters String containing any initialisation parameters
* for the type.
* @param required If true, mark the setting as required.
* @param priority Priority level (importance) of the setting.
*
* @return True if successfully added, otherwise false.
*/
bool add_setting(const char* key,
const char* label = 0,
const char* description = 0,
const char* type_name = 0,
const char* type_default = 0,
const char* type_parameters = 0,
bool required = false,
int priority = 0);
/*! Begin a logical group of dependencies for the current setting. */
/*!
* @param logic Combination logic of dependencies in the group
* ("AND" or "OR"). Default "AND".
* @return True if successful, otherwise false.
*/
bool begin_dependency_group(const char* logic = "AND");
/*! Add a new entry to the end of the current settings key group prefix. */
/*!
* Convenience method for working with settings keys. When working with
* settings through accessor methods which take a key as the first
* argument, the specified key will be prefixed with the set of groups
* registered though this function.
*
* @param name Name of the group to add.
*/
void begin_group(const char* name);
/*! Clears the tree, removing all items. */
void clear();
/*! Clears the current settings key group prefix. */
/*!
* Convenience method to clear the current settings group, if set using
* @fn begin_group.
*/
void clear_group();
/*! Returns true if a setting with the specified key exists in the tree. */
bool contains(const char* key) const;
/*! Returns true if dependencies of the specified key are satisfied. */
bool dependencies_satisfied(const char* key) const;
/*! Closes the current logical group of dependencies. */
void end_dependency_group();
/*! Removes the last level from the current settings key group prefix. */
/*!
* Convenience method for working with settings keys to be used in
* conjunction with @fn begin_group.
*/
void end_group();
/*! Return the i-th key that failed to load. */
const char* failed_key(int i) const;
/*! Return the value of the i-th key that failed to load. */
const char* failed_key_value(int i) const;
/*! Return a pointer to the file handler, if one has been set. */
const SettingsFileHandler* file_handler() const;
/*! Return a pointer to the file handler, if one has been set. */
SettingsFileHandler* file_handler();
/*! Return the file name path of the associated settings file. */
const char* file_name() const;
/*! Return the first letter of the setting with the given key.
*
* @param key The settings key.
* @param status Status return code.
*/
char first_letter(const char* key, int* status) const;
/*! Deletes the settings tree. */
static void free(SettingsTree* h);
/*! Returns the current group prefix. */
/*!
* Returns the current group prefix defined by the @fn begin_group and
* @fn end_group functions.
*
* @return The group prefix string.
*/
const char* group_prefix() const;
/*! Returns true for required settings with satisfied dependencies. */
bool is_critical(const char* key) const;
/*! Returns true if the setting has been changed from its default value. */
bool is_modified() const;
/*! Return a pointer to SettingsItem object at the specified @p key. */
/*!
* Method to give access to the item at the specified @p key.
* Note the settings key given to this function will be modified by the
* current group prefix.
*
* @param key The settings key.
* @return SettingsItem pointer.
*/
const SettingsItem* item(const char* key) const;
/*! Loads settings values from a settings file. */
/*!
* Loads values from a settings file into the settings tree. This function
* requires that a SettingsFileHandler has already been specified via the
* @fn set_file_handler method. If the @p file_name is specified it will
* be used, however if left empty (the default argument) the existing
* settings file will be used if previously specified.
*
* @param file_name Settings file path name from which to load.
* @return True if successful, otherwise false.
*/
bool load(const char* file_name = 0);
/*! Returns the number of keys that failed to load. */
int num_failed_keys() const;
/*! Returns the total number of settings items in the tree. */
int num_items() const;
/*! Returns the number of settings items in the tree which have a value. */
int num_settings() const;
/*! Utility method which prints a formatted summary of the settings tree. */
void print() const;
/*! Returns the root node of the settings tree. */
const SettingsNode* root_node() const;
/*! Saves the settings tree to a settings file. */
/*!
* Saves the settings tree to a settings file. This function requires
* that a SettingsFileHandler has already been specified via the
* @fn set_file_handler method. If the @p file_name is specified
* it will be used, however if left empty (the default argument) the
* existing setting file will be used if it has previously been specified.
*
* @param file_name File name of the settings file.
* @return True if successful, otherwise false.
*/
bool save(const char* file_name = 0) const;
/*! Returns the key separator character. */
char separator() const;
/*! Return a pointer to SettingsValue object at the specified @p key. */
/*!
* Method to give access to the value of the item at the specified @p key.
* Note the settings key given to this function will be modified by the
* current group prefix.
*
* @param key The settings key.
* @return SettingsValue pointer.
*/
const SettingsValue* settings_value(const char* key) const;
/*! Set the setting at the specified @p key to its default value. */
/*!
* Sets the setting at the specified key to its default value.
* The current group prefix will be prepended to the key.
*
* @param key Settings key.
* @param write If true and a SettingsFileHandler has been set, update
* the settings file on setting the value.
* @return True is successful, otherwise false.
*/
bool set_default(const char* key, bool write = true);
/*! Set all of the settings in the tree to their default value. */
void set_defaults();
/*! Attach a settings file handler. */
/*!
* Assign a settings file handler which will give the SettingsTree object
* the ability to read and write settings files.
* Note that ownership of the handler *IS* transferred to this object.
*
* @param handler SettingsFileHandler object to attach.
* @param name Path of the settings file to use.
*/
void set_file_handler(SettingsFileHandler* handler, const char* name = 0);
/*! Set or update the file name path of the associated settings file. */
void set_file_name(const char* name);
/*! Set the value of the setting at the specified @p key. */
/*!
* Sets the value of the setting at the specified key. The current group
* prefix will be prepended to the key.
*
* @param key Settings key.
* @param value Value of the setting.
* @param write If true and a SettingsFileHandler has been set, update
* the settings file on setting the value.
* @return True is successful, otherwise false.
*/
bool set_value(const char* key, const char* value, bool write = true);
bool starts_with(const char* key, const char* str, int* status) const;
double to_double(const char* key, int* status) const;
const double* to_double_list(const char* key, int* size, int* status) const;
int to_int(const char* key, int* status) const;
const int* to_int_list(const char* key, int* size, int* status) const;
const char* to_string(const char* key, int* status) const;
const char* const* to_string_list(const char* key, int* size,
int* status) const;
/*! Returns the value of a specified key. */
/*!
* Operator to give access to the string value of the item at the
* specified @p key.
* Note the settings key given to this function will be modified by the
* current group prefix.
*
* @param key The settings key.
* @return The settings value as a string.
*/
const char* operator[](const char* key) const;
private:
SettingsTree(const SettingsTree&);
bool dependencies_satisfied_(const SettingsDependencyGroup* group) const;
bool dependency_satisfied_(const SettingsDependency* dep) const;
const SettingsNode* find_(const SettingsNode* node,
const SettingsKey& full_key, int depth) const;
SettingsNode* find_(SettingsNode* node,
const SettingsKey& full_key, int depth);
bool is_critical_(const SettingsNode* node) const;
bool parent_dependencies_satisfied_(const SettingsNode*) const;
void print_(const SettingsNode* node, int depth = 0) const;
void set_defaults_(SettingsNode* node);
private:
mutable bool modified_;
SettingsTreePrivate* p;
};
} /* namespace oskar */
#endif /* __cplusplus */
#endif /* OSKAR_SETTINGS_TREE_H_ */
|
davepallot/OSKAR
|
oskar/telescope/station/src/oskar_evaluate_station_beam.c
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2013-2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "telescope/station/oskar_evaluate_station_beam.h"
#include "telescope/station/oskar_evaluate_station_beam_aperture_array.h"
#include "telescope/station/oskar_evaluate_station_beam_gaussian.h"
#include "telescope/station/oskar_evaluate_vla_beam_pbcor.h"
#include "convert/oskar_convert_relative_directions_to_enu_directions.h"
#include "convert/oskar_convert_enu_directions_to_relative_directions.h"
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
static void evaluate_station_beam_relative_directions(oskar_Mem* beam_pattern,
int np, const oskar_Mem* l, const oskar_Mem* m, const oskar_Mem* n,
const oskar_Station* station, oskar_StationWork* work,
int time_index, double frequency_hz, double GAST, int* status);
static void evaluate_station_beam_enu_directions(oskar_Mem* beam_pattern,
int np, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z,
const oskar_Station* station, oskar_StationWork* work,
int time_index, double frequency_hz, double GAST, int* status);
static void compute_enu_directions(oskar_Mem* x, oskar_Mem* y, oskar_Mem* z,
int np, const oskar_Mem* l, const oskar_Mem* m,
const oskar_Mem* n, const oskar_Station* station, double GAST,
int* status);
static void compute_relative_directions(oskar_Mem* l, oskar_Mem* m,
oskar_Mem* n, int np, const oskar_Mem* x, const oskar_Mem* y,
const oskar_Mem* z, const oskar_Station* station, double GAST,
int* status);
void oskar_evaluate_station_beam(oskar_Mem* beam_pattern, int num_points,
int coord_type, oskar_Mem* x, oskar_Mem* y, oskar_Mem* z,
double norm_ra_rad, double norm_dec_rad, const oskar_Station* station,
oskar_StationWork* work, int time_index, double frequency_hz,
double GAST, int* status)
{
int normalise_final_beam;
oskar_Mem* out;
/* Check if safe to proceed. */
if (*status) return;
/* Set default output beam array. */
out = beam_pattern;
/* Check that the arrays have enough space to add an extra source at the
* end (for normalisation). We don't want to reallocate here, since that
* will be slow to do each time: must simply ensure that we pass input
* arrays that are large enough.
* The normalisation doesn't need to happen if the station has an
* isotropic beam. */
normalise_final_beam = oskar_station_normalise_final_beam(station) &&
(oskar_station_type(station) != OSKAR_STATION_TYPE_ISOTROPIC);
if (normalise_final_beam)
{
double c_x = 0.0, c_y = 0.0, c_z = 1.0;
/* Increment number of points. */
num_points++;
/* Check the input arrays are big enough to hold the new source. */
if ((int)oskar_mem_length(x) < num_points ||
(int)oskar_mem_length(y) < num_points ||
(int)oskar_mem_length(z) < num_points)
{
*status = OSKAR_ERR_DIMENSION_MISMATCH;
return;
}
/* Set output beam array to work buffer. */
out = oskar_station_work_normalised_beam(work, beam_pattern, status);
/* Get the beam direction in the appropriate coordinate system. */
/* (Direction cosines are already set to the interferometer phase
* centre for relative directions.) */
if (coord_type == OSKAR_ENU_DIRECTIONS)
{
double t_x, t_y, t_z, ha0;
ha0 = (GAST + oskar_station_lon_rad(station)) - norm_ra_rad;
oskar_convert_relative_directions_to_enu_directions_d(
&t_x, &t_y, &t_z, 1, &c_x, &c_y, &c_z, ha0, norm_dec_rad,
oskar_station_lat_rad(station));
c_x = t_x;
c_y = t_y;
c_z = t_z;
}
/* Add the extra normalisation source to the end of the arrays. */
oskar_mem_set_element_real(x, num_points-1, c_x, status);
oskar_mem_set_element_real(y, num_points-1, c_y, status);
oskar_mem_set_element_real(z, num_points-1, c_z, status);
}
/* Evaluate the station beam for the given directions. */
if (coord_type == OSKAR_ENU_DIRECTIONS)
{
evaluate_station_beam_enu_directions(out, num_points, x, y, z,
station, work, time_index, frequency_hz, GAST, status);
}
else if (coord_type == OSKAR_RELATIVE_DIRECTIONS)
{
evaluate_station_beam_relative_directions(out, num_points, x, y, z,
station, work, time_index, frequency_hz, GAST, status);
}
else
{
*status = OSKAR_ERR_INVALID_ARGUMENT;
}
/* Scale beam pattern by value of the last source if required. */
if (normalise_final_beam)
{
double amp = 0.0;
/* Get the last element of the vector and convert to amplitude. */
if (oskar_mem_is_matrix(out))
{
double4c val;
val = oskar_mem_get_element_matrix(out, num_points-1, status);
/*
* Scale by square root of "Stokes I" autocorrelation:
* sqrt(0.5 * [sum of resultant diagonal]).
*
* We have
* [ Xa Xb ] [ Xa* Xc* ] = [ Xa Xa* + Xb Xb* (don't care) ]
* [ Xc Xd ] [ Xb* Xd* ] [ (don't care) Xc Xc* + Xd Xd* ]
*
* Stokes I is completely real, so need only evaluate the real
* part of all the multiplies. Because of the conjugate terms,
* these become re*re + im*im.
*
* Need the square root because we only want the normalised value
* for the beam itself (in isolation), not its actual
* autocorrelation!
*/
amp = val.a.x * val.a.x + val.a.y * val.a.y +
val.b.x * val.b.x + val.b.y * val.b.y +
val.c.x * val.c.x + val.c.y * val.c.y +
val.d.x * val.d.x + val.d.y * val.d.y;
amp = sqrt(0.5 * amp);
}
else
{
double2 val;
val = oskar_mem_get_element_complex(out, num_points-1, status);
/* Scale by voltage. */
amp = sqrt(val.x * val.x + val.y * val.y);
}
/* Scale beam array by normalisation value. */
oskar_mem_scale_real(out, 1.0/amp, status);
/* Copy output beam data. */
oskar_mem_copy_contents(beam_pattern, out, 0, 0, num_points-1, status);
}
}
static void evaluate_station_beam_relative_directions(oskar_Mem* beam_pattern,
int np, const oskar_Mem* l, const oskar_Mem* m, const oskar_Mem* n,
const oskar_Station* station, oskar_StationWork* work,
int time_index, double frequency_hz, double GAST, int* status)
{
oskar_Mem *x, *y, *z; /* ENU direction cosines */
if (*status) return;
/* ENU directions are needed for horizon clip in all cases */
x = oskar_station_work_enu_direction_x(work);
y = oskar_station_work_enu_direction_y(work);
z = oskar_station_work_enu_direction_z(work);
compute_enu_directions(x, y, z, np, l, m, n, station, GAST, status);
switch (oskar_station_type(station))
{
case OSKAR_STATION_TYPE_AA:
{
oskar_evaluate_station_beam_aperture_array(beam_pattern, station,
np, x, y, z, GAST, frequency_hz, work, time_index, status);
break;
}
case OSKAR_STATION_TYPE_ISOTROPIC:
{
oskar_mem_set_value_real(beam_pattern, 1.0, 0, np, status);
break;
}
case OSKAR_STATION_TYPE_GAUSSIAN_BEAM:
{
double fwhm, f0;
fwhm = oskar_station_gaussian_beam_fwhm_rad(station);
f0 = oskar_station_gaussian_beam_reference_freq_hz(station);
fwhm *= f0 / frequency_hz;
oskar_evaluate_station_beam_gaussian(beam_pattern, np, l, m, z,
fwhm, status);
break;
}
case OSKAR_STATION_TYPE_VLA_PBCOR:
{
oskar_evaluate_vla_beam_pbcor(beam_pattern, np, l, m, frequency_hz,
status);
break;
}
default:
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
break;
}
};
}
static void evaluate_station_beam_enu_directions(oskar_Mem* beam_pattern,
int np, const oskar_Mem* x, const oskar_Mem* y, const oskar_Mem* z,
const oskar_Station* station, oskar_StationWork* work,
int time_index, double frequency_hz, double GAST, int* status)
{
if (*status) return;
switch (oskar_station_type(station))
{
case OSKAR_STATION_TYPE_AA:
{
oskar_evaluate_station_beam_aperture_array(beam_pattern, station,
np, x, y, z, GAST, frequency_hz, work, time_index, status);
break;
}
case OSKAR_STATION_TYPE_ISOTROPIC:
{
oskar_mem_set_value_real(beam_pattern, 1.0, 0, np, status);
break;
}
case OSKAR_STATION_TYPE_GAUSSIAN_BEAM:
{
oskar_Mem *l, *m, *n; /* Relative direction cosines */
double fwhm, f0;
l = oskar_station_work_enu_direction_x(work);
m = oskar_station_work_enu_direction_y(work);
n = oskar_station_work_enu_direction_z(work);
compute_relative_directions(l, m, n, np, x, y, z, station, GAST,
status);
fwhm = oskar_station_gaussian_beam_fwhm_rad(station);
f0 =oskar_station_gaussian_beam_reference_freq_hz(station);
fwhm *= f0 / frequency_hz;
oskar_evaluate_station_beam_gaussian(beam_pattern, np, l, m, z,
fwhm, status);
break;
}
case OSKAR_STATION_TYPE_VLA_PBCOR:
{
oskar_Mem *l, *m, *n; /* Relative direction cosines */
l = oskar_station_work_enu_direction_x(work);
m = oskar_station_work_enu_direction_y(work);
n = oskar_station_work_enu_direction_z(work);
compute_relative_directions(l, m, n, np, x, y, z, station, GAST,
status);
oskar_evaluate_vla_beam_pbcor(beam_pattern, np, l, m, frequency_hz,
status);
break;
}
default:
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
break;
}
};
}
static void compute_enu_directions(oskar_Mem* x, oskar_Mem* y, oskar_Mem* z,
int np, const oskar_Mem* l, const oskar_Mem* m, const oskar_Mem* n,
const oskar_Station* station, double GAST, int* status)
{
double ha0, dec0, lat;
int pointing_coord_type;
if (*status) return;
/* Resize work arrays if needed */
if ((int)oskar_mem_length(x) < np) oskar_mem_realloc(x, np, status);
if ((int)oskar_mem_length(y) < np) oskar_mem_realloc(y, np, status);
if ((int)oskar_mem_length(z) < np) oskar_mem_realloc(z, np, status);
if (*status) return;
/* Obtain ra0, dec0 of phase centre */
lat = oskar_station_lat_rad(station);
pointing_coord_type = oskar_station_beam_coord_type(station);
if (pointing_coord_type == OSKAR_SPHERICAL_TYPE_EQUATORIAL)
{
double ra0;
ra0 = oskar_station_beam_lon_rad(station);
ha0 = (GAST + oskar_station_lon_rad(station)) - ra0;
dec0 = oskar_station_beam_lat_rad(station);
}
else if (pointing_coord_type == OSKAR_SPHERICAL_TYPE_AZEL)
{
/* TODO convert from az0, el0 to ha0, dec0 */
ha0 = 0.0;
dec0 = 0.0;
*status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE;
return;
}
else
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
return;
}
/* Convert from phase-centre-relative to ENU directions. */
oskar_convert_relative_directions_to_enu_directions(
x, y, z, np, l, m, n, ha0, dec0, lat, status);
}
static void compute_relative_directions(oskar_Mem* l, oskar_Mem* m,
oskar_Mem* n, int np, const oskar_Mem* x, const oskar_Mem* y,
const oskar_Mem* z, const oskar_Station* station, double GAST,
int* status)
{
double ha0, dec0, lat;
int pointing_coord_type;
if (*status) return;
/* Resize work arrays if needed */
if ((int)oskar_mem_length(l) < np) oskar_mem_realloc(l, np, status);
if ((int)oskar_mem_length(m) < np) oskar_mem_realloc(m, np, status);
if ((int)oskar_mem_length(n) < np) oskar_mem_realloc(n, np, status);
if (*status) return;
/* Obtain ra0, dec0 of phase centre */
lat = oskar_station_lat_rad(station);
pointing_coord_type = oskar_station_beam_coord_type(station);
if (pointing_coord_type == OSKAR_SPHERICAL_TYPE_EQUATORIAL)
{
double ra0;
ra0 = oskar_station_beam_lon_rad(station);
ha0 = (GAST + oskar_station_lon_rad(station)) - ra0;
dec0 = oskar_station_beam_lat_rad(station);
}
else if (pointing_coord_type == OSKAR_SPHERICAL_TYPE_AZEL)
{
/* TODO convert from az0, el0 to ha0, dec0 */
ha0 = 0.0;
dec0 = 0.0;
*status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE;
return;
}
else
{
*status = OSKAR_ERR_SETTINGS_TELESCOPE;
return;
}
/* Convert from ENU to phase-centre-relative directions. */
oskar_convert_enu_directions_to_relative_directions(
l, m, n, np, x, y, z, ha0, dec0, lat, status);
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/utility/src/oskar_get_error_string.c
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2011-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "utility/oskar_get_error_string.h"
#include "binary/oskar_binary.h"
#include "settings/oskar_settings_macros.h"
#ifdef OSKAR_HAVE_CUDA
#include <cuda_runtime_api.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
const char* oskar_get_error_string(int error)
{
/* If the error code is positive, get the CUDA error string
* (OSKAR error codes are negative). */
#ifdef OSKAR_HAVE_CUDA
if (error > 0)
return cudaGetErrorString((cudaError_t)error);
#endif
/* Return a string describing the OSKAR error code. */
switch (error)
{
case OSKAR_ERR_EOF: return "end of file";
case OSKAR_ERR_FILE_IO: return "file I/O error";
case OSKAR_ERR_INVALID_ARGUMENT: return "invalid function argument";
case OSKAR_ERR_FUNCTION_NOT_AVAILABLE: return "functionality not available";
case OSKAR_ERR_OUT_OF_RANGE: return "out of range";
case OSKAR_ERR_MEMORY_ALLOC_FAILURE: return "memory allocation failure";
case OSKAR_ERR_MEMORY_NOT_ALLOCATED: return "memory not allocated";
case OSKAR_ERR_TYPE_MISMATCH: return "data type mismatch";
case OSKAR_ERR_LOCATION_MISMATCH: return "data location mismatch";
case OSKAR_ERR_DIMENSION_MISMATCH: return "data dimension mismatch";
case OSKAR_ERR_VALUE_MISMATCH: return "coordinate/value mismatch";
case OSKAR_ERR_BAD_DATA_TYPE: return "unsupported data type";
case OSKAR_ERR_BAD_LOCATION: return "unsupported data location";
case OSKAR_ERR_BAD_UNITS: return "invalid units";
case OSKAR_ERR_CUDA_NOT_AVAILABLE: return "CUDA not available";
case OSKAR_ERR_OPENCL_NOT_AVAILABLE: return "OpenCL not available";
case OSKAR_ERR_COMPUTE_DEVICES: return "compute device not found";
/* The following enumerators are under review... */
case OSKAR_ERR_SPLINE_COEFF_FAIL: return "spline fitting failed";
case OSKAR_ERR_SPLINE_EVAL_FAIL: return "spline evaluation failed";
case OSKAR_ERR_ELLIPSE_FIT_FAILED: return "ellipse fitting failed";
case OSKAR_ERR_SETTINGS_TELESCOPE: return "telescope settings error";
case OSKAR_ERR_SETUP_FAIL: return "set up failed";
case OSKAR_ERR_SETUP_FAIL_SKY: return "sky model set up failed";
case OSKAR_ERR_SETUP_FAIL_TELESCOPE:
return "telescope model set up failed";
case OSKAR_ERR_SETUP_FAIL_TELESCOPE_ENTRIES_MISMATCH:
return "the number of station directories is inconsistent "
"with the telescope layout file";
case OSKAR_ERR_SETUP_FAIL_TELESCOPE_CONFIG_FILE_MISSING:
return "a configuration file is missing from the "
"telescope model directory tree";
case OSKAR_ERR_BAD_SKY_FILE: return "bad OSKAR sky model file";
case OSKAR_ERR_BAD_POINTING_FILE: return "bad pointing file";
case OSKAR_ERR_BAD_COORD_FILE: return "bad coordinate file";
case OSKAR_ERR_BAD_GSM_FILE: return "bad Global Sky Model file";
/* OSKAR binary file errors. */
case OSKAR_ERR_BINARY_OPEN_FAIL: return "binary file open failed";
case OSKAR_ERR_BINARY_SEEK_FAIL: return "binary file seek failed";
case OSKAR_ERR_BINARY_READ_FAIL: return "binary file read failed";
case OSKAR_ERR_BINARY_WRITE_FAIL: return "binary file write failed";
case OSKAR_ERR_BINARY_NOT_OPEN_FOR_READ:
return "binary file not open for read";
case OSKAR_ERR_BINARY_NOT_OPEN_FOR_WRITE:
return "binary file not open for write";
case OSKAR_ERR_BINARY_FILE_INVALID: return "not an OSKAR binary file";
case OSKAR_ERR_BINARY_FORMAT_BAD: return "incompatible binary format";
case OSKAR_ERR_BINARY_ENDIAN_MISMATCH: return "incompatible byte ordering";
case OSKAR_ERR_BINARY_VERSION_UNKNOWN: return "unknown binary format version";
case OSKAR_ERR_BINARY_TYPE_UNKNOWN: return "unknown binary data type";
case OSKAR_ERR_BINARY_INT_UNKNOWN: return "unknown integer format";
case OSKAR_ERR_BINARY_FLOAT_UNKNOWN: return "unknown float format";
case OSKAR_ERR_BINARY_DOUBLE_UNKNOWN: return "unknown double format";
case OSKAR_ERR_BINARY_MEMORY_NOT_ALLOCATED:
return "allocated memory is not big enough for binary chunk";
case OSKAR_ERR_BINARY_TAG_NOT_FOUND: return "data tag not found in file";
case OSKAR_ERR_BINARY_TAG_TOO_LONG: return "binary tag name too long";
case OSKAR_ERR_BINARY_TAG_OUT_OF_RANGE:return "binary tag out of range";
case OSKAR_ERR_BINARY_CRC_FAIL: return "CRC code mismatch";
/* OSKAR settings errors. */
case OSKAR_ERR_SETTINGS_NO_VALUE:
return "setting not found";
case OSKAR_ERR_SETTINGS_INT_CONVERSION_FAIL:
return "settings int conversion failure";
case OSKAR_ERR_SETTINGS_UNSIGNED_INT_CONVERSION_FAIL:
return "settings unsigned int conversion failure";
case OSKAR_ERR_SETTINGS_DOUBLE_CONVERSION_FAIL:
return "settings double conversion failure";
case OSKAR_ERR_SETTINGS_INT_LIST_CONVERSION_FAIL:
return "settings int list conversion failure";
case OSKAR_ERR_SETTINGS_DOUBLE_LIST_CONVERSION_FAIL:
return "settings double list conversion failure";
case OSKAR_ERR_SETTINGS_STRING_LIST_CONVERSION_FAIL:
return "settings string list conversion failure";
default:
break;
};
return "unknown error.";
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/vis/src/oskar_vis_block_resize.c
|
/*
* Copyright (c) 2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "vis/private_vis_block.h"
#include "vis/oskar_vis_block.h"
#ifdef __cplusplus
extern "C" {
#endif
void oskar_vis_block_resize(oskar_VisBlock* vis, int num_times,
int num_channels, int num_stations, int* status)
{
int num_autocorr = 0, num_xcorr = 0, num_baselines = 0, num_coords = 0;
/* Check if safe to proceed. */
if (*status) return;
/* Set dimensions. */
if (vis->has_cross_correlations)
num_baselines = num_stations * (num_stations - 1) / 2;
vis->dim_start_size[2] = num_times;
vis->dim_start_size[3] = num_channels;
vis->dim_start_size[4] = num_baselines;
vis->dim_start_size[5] = num_stations;
num_coords = num_times * num_baselines;
num_xcorr = num_times * num_baselines * num_channels;
if (vis->has_auto_correlations)
num_autocorr = num_channels * num_times * num_stations;
/* Resize arrays as required. */
oskar_mem_realloc(vis->baseline_uu_metres, num_coords, status);
oskar_mem_realloc(vis->baseline_vv_metres, num_coords, status);
oskar_mem_realloc(vis->baseline_ww_metres, num_coords, status);
oskar_mem_realloc(vis->auto_correlations, num_autocorr, status);
oskar_mem_realloc(vis->cross_correlations, num_xcorr, status);
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/mem/src/oskar_mem_accessors.c
|
<reponame>davepallot/OSKAR<filename>oskar/mem/src/oskar_mem_accessors.c
/*
* Copyright (c) 2013-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "mem/oskar_mem.h"
#include "mem/private_mem.h"
#ifdef __cplusplus
extern "C" {
#endif
int oskar_mem_allocated(const oskar_Mem* mem)
{
return mem->data ? 1 : 0;
}
#ifdef OSKAR_HAVE_OPENCL
cl_mem* oskar_mem_cl_buffer(oskar_Mem* mem, int* status)
{
if (mem->location & OSKAR_CL)
return &mem->buffer;
else
{
*status = OSKAR_ERR_LOCATION_MISMATCH;
return 0;
}
}
const cl_mem* oskar_mem_cl_buffer_const(const oskar_Mem* mem, int* status)
{
if (mem->location & OSKAR_CL)
return &mem->buffer;
else
{
*status = OSKAR_ERR_LOCATION_MISMATCH;
return 0;
}
}
#endif
size_t oskar_mem_length(const oskar_Mem* mem)
{
return mem->num_elements;
}
int oskar_mem_location(const oskar_Mem* mem)
{
return mem->location;
}
int oskar_mem_type(const oskar_Mem* mem)
{
return mem->type;
}
int oskar_mem_precision(const oskar_Mem* mem)
{
return oskar_type_precision(mem->type);
}
int oskar_mem_is_double(const oskar_Mem* mem)
{
return oskar_type_is_double(mem->type);
}
int oskar_mem_is_single(const oskar_Mem* mem)
{
return oskar_type_is_single(mem->type);
}
int oskar_mem_is_complex(const oskar_Mem* mem)
{
return oskar_type_is_complex(mem->type);
}
int oskar_mem_is_real(const oskar_Mem* mem)
{
return oskar_type_is_real(mem->type);
}
int oskar_mem_is_matrix(const oskar_Mem* mem)
{
return oskar_type_is_matrix(mem->type);
}
int oskar_mem_is_scalar(const oskar_Mem* mem)
{
return oskar_type_is_scalar(mem->type);
}
/* Pointer conversion functions. */
void* oskar_mem_void(oskar_Mem* mem)
{
return (void*) mem->data;
}
const void* oskar_mem_void_const(const oskar_Mem* mem)
{
return (const void*) mem->data;
}
char* oskar_mem_char(oskar_Mem* mem)
{
return (char*) mem->data;
}
const char* oskar_mem_char_const(const oskar_Mem* mem)
{
return (const char*) mem->data;
}
int* oskar_mem_int(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_INT)
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (int*) mem->data;
}
const int* oskar_mem_int_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_INT)
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const int*) mem->data;
}
float* oskar_mem_float(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_SINGLE)
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (float*) mem->data;
}
const float* oskar_mem_float_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_SINGLE)
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const float*) mem->data;
}
float2* oskar_mem_float2(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_SINGLE ||
!oskar_type_is_complex(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (float2*) mem->data;
}
const float2* oskar_mem_float2_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_SINGLE ||
!oskar_type_is_complex(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const float2*) mem->data;
}
float4c* oskar_mem_float4c(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_SINGLE ||
!oskar_type_is_complex(mem->type) ||
!oskar_type_is_matrix(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (float4c*) mem->data;
}
const float4c* oskar_mem_float4c_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_SINGLE ||
!oskar_type_is_complex(mem->type) ||
!oskar_type_is_matrix(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const float4c*) mem->data;
}
double* oskar_mem_double(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_DOUBLE)
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (double*) mem->data;
}
const double* oskar_mem_double_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_DOUBLE)
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const double*) mem->data;
}
double2* oskar_mem_double2(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_DOUBLE ||
!oskar_type_is_complex(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (double2*) mem->data;
}
const double2* oskar_mem_double2_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_DOUBLE ||
!oskar_type_is_complex(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const double2*) mem->data;
}
double4c* oskar_mem_double4c(oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_DOUBLE ||
!oskar_type_is_complex(mem->type) ||
!oskar_type_is_matrix(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (double4c*) mem->data;
}
const double4c* oskar_mem_double4c_const(const oskar_Mem* mem, int* status)
{
/* Check for type mismatch. */
if (oskar_type_precision(mem->type) != OSKAR_DOUBLE ||
!oskar_type_is_complex(mem->type) ||
!oskar_type_is_matrix(mem->type))
*status = OSKAR_ERR_TYPE_MISMATCH;
/* Cast the pointer. */
return (const double4c*) mem->data;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/interferometer/oskar_jones_accessors.h
|
/*
* Copyright (c) 2013-2014, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_JONES_ACCESSORS_H_
#define OSKAR_JONES_ACCESSORS_H_
/**
* @file oskar_jones_accessors.h
*/
#include <oskar_global.h>
#include <mem/oskar_mem.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief
* Returns the number of sources in the Jones matrix block.
*
* @details
* Returns the number of sources in the Jones matrix block.
*
* @param[in] jones Pointer to data structure.
*
* @return The number of stations.
*/
OSKAR_EXPORT
int oskar_jones_num_sources(const oskar_Jones* jones);
/**
* @brief
* Returns the number of stations in the Jones matrix block.
*
* @details
* Returns the number of stations in the Jones matrix block.
*
* @param[in] jones Pointer to data structure.
*
* @return The number of stations.
*/
OSKAR_EXPORT
int oskar_jones_num_stations(const oskar_Jones* jones);
/**
* @brief
* Returns the enumerated data type of the Jones matrix block.
*
* @details
* Returns the enumerated data type of the Jones matrix block.
*
* @param[in] jones Pointer to data structure.
*
* @return The enumerated data type.
*/
OSKAR_EXPORT
int oskar_jones_type(const oskar_Jones* jones);
/**
* @brief
* Returns the enumerated location of the Jones matrix block.
*
* @details
* Returns the enumerated location (OSKAR_CPU or OSKAR_GPU)
* of the Jones matrix block.
*
* @param[in] jones Pointer to data structure.
*
* @return The enumerated location.
*/
OSKAR_EXPORT
int oskar_jones_mem_location(const oskar_Jones* jones);
/**
* @brief
* Returns a pointer to the matrix block memory.
*
* @details
* Returns a pointer to the matrix block memory.
*
* @param[in] jones Pointer to data structure.
*
* @return A pointer to the memory structure.
*/
OSKAR_EXPORT
oskar_Mem* oskar_jones_mem(oskar_Jones* jones);
/**
* @brief
* Returns a read-only pointer to the matrix block memory.
*
* @details
* Returns a read-only pointer to the matrix block memory.
*
* @param[in] jones Pointer to data structure.
*
* @return A pointer to the memory structure.
*/
OSKAR_EXPORT
const oskar_Mem* oskar_jones_mem_const(const oskar_Jones* jones);
/**
* @brief
* Returns a pointer to the matrix block as a float2.
*
* @details
* Returns a pointer to the matrix block as a float2.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
float2* oskar_jones_float2(oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a const float2.
*
* @details
* Returns a pointer to the matrix block as a const float2.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
const float2* oskar_jones_float2_const(const oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a float4c.
*
* @details
* Returns a pointer to the matrix block as a float4c.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
float4c* oskar_jones_float4c(oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a const float4c.
*
* @details
* Returns a pointer to the matrix block as a const float4c.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
const float4c* oskar_jones_float4c_const(const oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a double2.
*
* @details
* Returns a pointer to the matrix block as a double2.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
double2* oskar_jones_double2(oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a const double2.
*
* @details
* Returns a pointer to the matrix block as a const double2.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
const double2* oskar_jones_double2_const(const oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a double4c.
*
* @details
* Returns a pointer to the matrix block as a double4c.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
double4c* oskar_jones_double4c(oskar_Jones* jones, int* status);
/**
* @brief
* Returns a pointer to the matrix block as a const double4c.
*
* @details
* Returns a pointer to the matrix block as a const double4c.
*
* @param[in] jones Pointer to data structure.
* @param[in,out] status Status return code.
*
* @return A pointer of the requested type.
*/
OSKAR_EXPORT
const double4c* oskar_jones_double4c_const(const oskar_Jones* jones,
int* status);
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_JONES_ACCESSORS_H_ */
|
davepallot/OSKAR
|
oskar/convert/src/oskar_convert_station_uvw_to_baseline_uvw.c
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2013-2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "convert/oskar_convert_station_uvw_to_baseline_uvw.h"
#include "convert/oskar_convert_station_uvw_to_baseline_uvw_cuda.h"
#include "utility/oskar_device_utils.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
void oskar_convert_station_uvw_to_baseline_uvw_f(int num_stations,
const float* u, const float* v, const float* w, float* uu,
float* vv, float* ww)
{
int s1, s2, b; /* Station and baseline indices. */
for (s1 = 0, b = 0; s1 < num_stations; ++s1)
{
for (s2 = s1 + 1; s2 < num_stations; ++s2, ++b)
{
uu[b] = u[s2] - u[s1];
vv[b] = v[s2] - v[s1];
ww[b] = w[s2] - w[s1];
}
}
}
/* Double precision. */
void oskar_convert_station_uvw_to_baseline_uvw_d(int num_stations,
const double* u, const double* v, const double* w, double* uu,
double* vv, double* ww)
{
int s1, s2, b; /* Station and baseline indices. */
for (s1 = 0, b = 0; s1 < num_stations; ++s1)
{
for (s2 = s1 + 1; s2 < num_stations; ++s2, ++b)
{
uu[b] = u[s2] - u[s1];
vv[b] = v[s2] - v[s1];
ww[b] = w[s2] - w[s1];
}
}
}
/* Wrapper. */
void oskar_convert_station_uvw_to_baseline_uvw(const oskar_Mem* u,
const oskar_Mem* v, const oskar_Mem* w, oskar_Mem* uu, oskar_Mem* vv,
oskar_Mem* ww, int* status)
{
int type, location, num_stations, num_baselines;
/* Check if safe to proceed. */
if (*status) return;
/* Get data type, location and size. */
type = oskar_mem_type(u);
location = oskar_mem_location(u);
num_stations = (int)oskar_mem_length(u);
num_baselines = num_stations * (num_stations - 1) / 2;
/* Check that the data locations match. */
if (oskar_mem_location(v) != location ||
oskar_mem_location(w) != location ||
oskar_mem_location(uu) != location ||
oskar_mem_location(vv) != location ||
oskar_mem_location(ww) != location)
{
*status = OSKAR_ERR_LOCATION_MISMATCH;
return;
}
/* Check that the data dimensions are OK. */
if ((int)oskar_mem_length(v) < num_stations ||
(int)oskar_mem_length(w) < num_stations ||
(int)oskar_mem_length(uu) < num_baselines ||
(int)oskar_mem_length(vv) < num_baselines ||
(int)oskar_mem_length(ww) < num_baselines)
{
*status = OSKAR_ERR_DIMENSION_MISMATCH;
return;
}
if (location == OSKAR_CPU)
{
if (type == OSKAR_SINGLE)
{
oskar_convert_station_uvw_to_baseline_uvw_f(num_stations,
oskar_mem_float_const(u, status),
oskar_mem_float_const(v, status),
oskar_mem_float_const(w, status),
oskar_mem_float(uu, status),
oskar_mem_float(vv, status),
oskar_mem_float(ww, status));
}
else if (type == OSKAR_DOUBLE)
{
oskar_convert_station_uvw_to_baseline_uvw_d(num_stations,
oskar_mem_double_const(u, status),
oskar_mem_double_const(v, status),
oskar_mem_double_const(w, status),
oskar_mem_double(uu, status),
oskar_mem_double(vv, status),
oskar_mem_double(ww, status));
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
}
else if (location == OSKAR_GPU)
{
#ifdef OSKAR_HAVE_CUDA
if (type == OSKAR_SINGLE)
{
oskar_convert_station_uvw_to_baseline_uvw_cuda_f(num_stations,
oskar_mem_float_const(u, status),
oskar_mem_float_const(v, status),
oskar_mem_float_const(w, status),
oskar_mem_float(uu, status),
oskar_mem_float(vv, status),
oskar_mem_float(ww, status));
}
else if (type == OSKAR_DOUBLE)
{
oskar_convert_station_uvw_to_baseline_uvw_cuda_d(num_stations,
oskar_mem_double_const(u, status),
oskar_mem_double_const(v, status),
oskar_mem_double_const(w, status),
oskar_mem_double(uu, status),
oskar_mem_double(vv, status),
oskar_mem_double(ww, status));
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
oskar_device_check_error(status);
#else
*status = OSKAR_ERR_CUDA_NOT_AVAILABLE;
#endif
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/sky/private_sky_scale_flux_with_frequency_inline.h
|
<filename>oskar/sky/private_sky_scale_flux_with_frequency_inline.h
/*
* Copyright (c) 2014, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <oskar_global.h>
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
#define C0 299792458.0
#define C0f 299792458.0f
/* Single precision. */
OSKAR_INLINE
void oskar_scale_flux_with_frequency_inline_f(const float frequency,
float* I, float* Q, float* U, float* V, float* ref_freq,
const float sp_index, const float rm)
{
float freq0_, sin_b, cos_b;
/* Get reference frequency, spectral index and rotation measure. */
freq0_ = *ref_freq;
if (freq0_ == 0.0f)
return;
/* Compute rotation factors, sin(2 beta) and cos(2 beta). */
{
float delta_lambda_squared;
/* Compute delta_lambda_squared using factorised difference of two
* squares. (Numerically superior than an explicit difference.)
* This is (lambda^2 - lambda0^2) */
{
float lambda, lambda0;
lambda = C0f / frequency;
lambda0 = C0f / freq0_;
delta_lambda_squared = (lambda - lambda0) * (lambda + lambda0);
}
/* Compute sin(2 beta) and cos(2 beta). */
{
float b;
b = 2.0f * rm * delta_lambda_squared;
#ifdef __CUDACC__
sincosf(b, &sin_b, &cos_b);
#else
sin_b = sinf(b);
cos_b = cosf(b);
#endif
}
}
/* Set new values and update reference frequency. */
{
float scale, Q_, U_;
/* Compute spectral index scaling factor. */
scale = powf(frequency / freq0_, sp_index);
Q_ = scale * *Q;
U_ = scale * *U;
*I *= scale;
*V *= scale;
*Q = Q_ * cos_b - U_ * sin_b;
*U = Q_ * sin_b + U_ * cos_b;
*ref_freq = frequency;
}
}
/* Double precision. */
OSKAR_INLINE
void oskar_scale_flux_with_frequency_inline_d(const double frequency,
double* I, double* Q, double* U, double* V, double* ref_freq,
const double sp_index, const double rm)
{
double freq0_, sin_b, cos_b;
/* Get reference frequency, spectral index and rotation measure. */
freq0_ = *ref_freq;
if (freq0_ == 0.0)
return;
/* Compute rotation factors, sin(2 beta) and cos(2 beta). */
{
double delta_lambda_squared;
/* Compute delta_lambda_squared using factorised difference of two
* squares. (Numerically superior than an explicit difference.)
* This is (lambda^2 - lambda0^2) */
{
double lambda, lambda0;
lambda = C0 / frequency;
lambda0 = C0 / freq0_;
delta_lambda_squared = (lambda - lambda0) * (lambda + lambda0);
}
/* Compute sin(2 beta) and cos(2 beta). */
{
double b;
b = 2.0 * rm * delta_lambda_squared;
#ifdef __CUDACC__
sincos(b, &sin_b, &cos_b);
#else
sin_b = sin(b);
cos_b = cos(b);
#endif
}
}
/* Set new values and update reference frequency. */
{
double scale, Q_, U_;
/* Compute spectral index scaling factor. */
scale = pow(frequency / freq0_, sp_index);
Q_ = scale * *Q;
U_ = scale * *U;
*I *= scale;
*V *= scale;
*Q = Q_ * cos_b - U_ * sin_b;
*U = Q_ * sin_b + U_ * cos_b;
*ref_freq = frequency;
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/log/oskar_log_value.h
|
/*
* Copyright (c) 2012-2014, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_LOG_VALUE_H_
#define OSKAR_LOG_VALUE_H_
/**
* @file oskar_log_value.h
*/
#include <oskar_global.h>
#include <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief
* Writes a key-value pair to the log.
*
* @details
* This function writes a key-value pair to the log, where the value is
* written starting at a fixed column offset from the start of the entry.
*
* The separation of the key and value is specified by the log width parameter
* which is set by the oskar_log_set_value_width() method. The default
* width for value messages places the value of the message is determined
* by the OSKAR_LOG_DEFAULT_VALUE_WIDTH macro in the oskar_log.h header.
*
* Value log entries have a depth which, if positive, will indent the message
* by 2 spaces per depth value and prefix the message with a list bullet.
*
* If the depth value is set to -1 the list bullet will be omitted and
* no indent is applied.
*
* Log entries are created with a priority code which is used to determine
* which log are printed in the log and also sets a letter code with which
* the message is tagged.
*
* The priority code takes one of the following values:
* - 'E' : Error
* - 'W' : Warning
* - 'M' : Message
* - 'D' : Debug
*
* @param[in,out] log Pointer to a log structure.
* @param[in] Depth List depth of the log entry.
* @param[in] priority Priority of nesting of log entry.
* @param[in] prefix String prefix (key).
* @param[in] format Format string for printf().
*/
OSKAR_EXPORT
void oskar_log_value(oskar_Log* log, char priority, int depth,
const char* prefix, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_LOG_VALUE_H_ */
|
davepallot/OSKAR
|
oskar/vis/oskar_vis_header_accessors.h
|
/*
* Copyright (c) 2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_VIS_HEADER_ACCESSORS_H_
#define OSKAR_VIS_HEADER_ACCESSORS_H_
/**
* @file oskar_vis_header_accessors.h
*/
#include <oskar_global.h>
#include <mem/oskar_mem.h>
#ifdef __cplusplus
extern "C" {
#endif
OSKAR_EXPORT
oskar_Mem* oskar_vis_header_telescope_path(oskar_VisHeader* vis);
OSKAR_EXPORT
const oskar_Mem* oskar_vis_header_telescope_path_const(
const oskar_VisHeader* vis);
OSKAR_EXPORT
oskar_Mem* oskar_vis_header_settings(oskar_VisHeader* vis);
OSKAR_EXPORT
const oskar_Mem* oskar_vis_header_settings_const(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_num_tags_per_block(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_write_auto_correlations(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_write_cross_correlations(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_amp_type(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_coord_precision(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_max_times_per_block(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_max_channels_per_block(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_num_channels_total(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_num_times_total(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_num_stations(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_pol_type(const oskar_VisHeader* vis);
OSKAR_EXPORT
int oskar_vis_header_phase_centre_coord_type(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_phase_centre_ra_deg(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_phase_centre_dec_deg(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_freq_start_hz(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_freq_inc_hz(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_channel_bandwidth_hz(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_time_start_mjd_utc(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_time_inc_sec(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_time_average_sec(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_telescope_lon_deg(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_telescope_lat_deg(const oskar_VisHeader* vis);
OSKAR_EXPORT
double oskar_vis_header_telescope_alt_metres(const oskar_VisHeader* vis);
OSKAR_EXPORT
oskar_Mem* oskar_vis_header_station_x_offset_ecef_metres(oskar_VisHeader* vis);
OSKAR_EXPORT
const oskar_Mem* oskar_vis_header_station_x_offset_ecef_metres_const(
const oskar_VisHeader* vis);
OSKAR_EXPORT
oskar_Mem* oskar_vis_header_station_y_offset_ecef_metres(oskar_VisHeader* vis);
OSKAR_EXPORT
const oskar_Mem* oskar_vis_header_station_y_offset_ecef_metres_const(
const oskar_VisHeader* vis);
OSKAR_EXPORT
oskar_Mem* oskar_vis_header_station_z_offset_ecef_metres(oskar_VisHeader* vis);
OSKAR_EXPORT
const oskar_Mem* oskar_vis_header_station_z_offset_ecef_metres_const(
const oskar_VisHeader* vis);
/* Setters. */
OSKAR_EXPORT
void oskar_vis_header_set_freq_start_hz(oskar_VisHeader* vis, double value);
OSKAR_EXPORT
void oskar_vis_header_set_freq_inc_hz(oskar_VisHeader* vis, double value);
OSKAR_EXPORT
void oskar_vis_header_set_channel_bandwidth_hz(oskar_VisHeader* vis,
double value);
OSKAR_EXPORT
void oskar_vis_header_set_time_start_mjd_utc(oskar_VisHeader* vis,
double value);
OSKAR_EXPORT
void oskar_vis_header_set_time_inc_sec(oskar_VisHeader* vis, double value);
OSKAR_EXPORT
void oskar_vis_header_set_time_average_sec(oskar_VisHeader* vis, double value);
OSKAR_EXPORT
void oskar_vis_header_set_phase_centre(oskar_VisHeader* vis,
int coord_type, double ra_deg, double dec_deg);
OSKAR_EXPORT
void oskar_vis_header_set_telescope_centre(oskar_VisHeader* vis,
double lon_deg, double lat_deg, double alt_metres);
OSKAR_EXPORT
void oskar_vis_header_set_pol_type(oskar_VisHeader* vis, int value,
int* status);
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_VIS_HEADER_ACCESSORS_H_ */
|
davepallot/OSKAR
|
oskar/imager/src/oskar_imager_rotate_vis.c
|
/*
* Copyright (c) 2016-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "math/oskar_cmath.h"
#include "imager/private_imager.h"
#include "imager/oskar_imager.h"
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void oskar_imager_rotate_vis(const oskar_Imager* h, size_t num_vis,
const oskar_Mem* uu_in, const oskar_Mem* vv_in, const oskar_Mem* ww_in,
oskar_Mem* amps)
{
#ifdef OSKAR_OS_WIN
int i;
const int num = (const int) num_vis;
#else
size_t i;
const size_t num = num_vis;
#endif
const double delta_l = h->delta_l;
const double delta_m = h->delta_m;
const double delta_n = h->delta_n;
const double twopi = 2.0 * M_PI;
if (oskar_mem_precision(amps) == OSKAR_DOUBLE)
{
const double *u, *v, *w;
double2* a;
u = (const double*)oskar_mem_void_const(uu_in);
v = (const double*)oskar_mem_void_const(vv_in);
w = (const double*)oskar_mem_void_const(ww_in);
a = (double2*)oskar_mem_void(amps);
#pragma omp parallel for private(i)
for (i = 0; i < num; ++i)
{
double arg, phase_re, phase_im, re, im;
arg = twopi * (u[i] * delta_l + v[i] * delta_m + w[i] * delta_n);
phase_re = cos(arg);
phase_im = sin(arg);
re = a[i].x * phase_re - a[i].y * phase_im;
im = a[i].x * phase_im + a[i].y * phase_re;
a[i].x = re;
a[i].y = im;
}
}
else
{
const float *u, *v, *w;
float2* a;
u = (const float*)oskar_mem_void_const(uu_in);
v = (const float*)oskar_mem_void_const(vv_in);
w = (const float*)oskar_mem_void_const(ww_in);
a = (float2*)oskar_mem_void(amps);
#pragma omp parallel for private(i)
for (i = 0; i < num; ++i)
{
double arg, phase_re, phase_im, re, im;
arg = twopi * (u[i] * delta_l + v[i] * delta_m + w[i] * delta_n);
phase_re = cos(arg);
phase_im = sin(arg);
re = a[i].x * phase_re - a[i].y * phase_im;
im = a[i].x * phase_im + a[i].y * phase_re;
a[i].x = (float) re;
a[i].y = (float) im;
}
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/mem/oskar_mem_multiply_cuda.h
|
/*
* Copyright (c) 2013-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_MEM_MULTIPLY_CUDA_H_
#define OSKAR_MEM_MULTIPLY_CUDA_H_
#include <oskar_global.h>
#include <utility/oskar_vector_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
OSKAR_EXPORT
void oskar_mem_multiply_cuda_rr_r_f(int num, float* d_c,
const float* d_a, const float* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_cc_c_f(int num, float2* d_c,
const float2* d_a, const float2* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_cc_m_f(int num, float4c* d_c,
const float2* d_a, const float2* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_cm_m_f(int num, float4c* d_c,
const float2* d_a, const float4c* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_mm_m_f(int num, float4c* d_c,
const float4c* d_a, const float4c* d_b);
/* Double precision. */
OSKAR_EXPORT
void oskar_mem_multiply_cuda_rr_r_d(int num, double* d_c,
const double* d_a, const double* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_cc_c_d(int num, double2* d_c,
const double2* d_a, const double2* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_cc_m_d(int num, double4c* d_c,
const double2* d_a, const double2* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_cm_m_d(int num, double4c* d_c,
const double2* d_a, const double4c* d_b);
OSKAR_EXPORT
void oskar_mem_multiply_cuda_mm_m_d(int num, double4c* d_c,
const double4c* d_a, const double4c* d_b);
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_MEM_MULTIPLY_CUDA_H_ */
|
davepallot/OSKAR
|
oskar/splines/src/oskar_splines_evaluate.c
|
<filename>oskar/splines/src/oskar_splines_evaluate.c
/*
* Copyright (c) 2012-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "splines/oskar_dierckx_bispev.h"
#include "splines/oskar_dierckx_bispev_bicubic_cuda.h"
#include "splines/oskar_splines.h"
#include "utility/oskar_device_utils.h"
#ifdef __cplusplus
extern "C" {
#endif
void oskar_splines_evaluate(oskar_Mem* output, int offset, int stride,
const oskar_Splines* spline, int num_points, const oskar_Mem* x,
const oskar_Mem* y, int* status)
{
int nx, ny, type, location;
/* Check if safe to proceed. */
if (*status) return;
/* Check type. */
type = oskar_splines_precision(spline);
if (type != oskar_mem_type(x) || type != oskar_mem_type(y))
{
*status = OSKAR_ERR_TYPE_MISMATCH;
return;
}
/* Check that all arrays are co-located. */
location = oskar_splines_mem_location(spline);
if (location != oskar_mem_location(output) ||
location != oskar_mem_location(x) ||
location != oskar_mem_location(y))
{
*status = OSKAR_ERR_LOCATION_MISMATCH;
return;
}
/* Get number of knots. */
nx = oskar_splines_num_knots_x_theta(spline);
ny = oskar_splines_num_knots_y_phi(spline);
/* Check data type. */
if (type == OSKAR_SINGLE)
{
const float *tx, *ty, *coeff, *x_, *y_;
float *out;
tx = oskar_mem_float_const(
oskar_splines_knots_x_theta_const(spline), status);
ty = oskar_mem_float_const(
oskar_splines_knots_y_phi_const(spline), status);
coeff = oskar_mem_float_const(
oskar_splines_coeff_const(spline), status);
x_ = oskar_mem_float_const(x, status);
y_ = oskar_mem_float_const(y, status);
out = oskar_mem_float(output, status) + offset;
/* Check if data are in CPU memory. */
if (location == OSKAR_CPU)
{
int i;
if (nx == 0 || ny == 0 || !tx || !ty || !coeff)
{
for (i = 0; i < num_points; ++i)
{
out[i * stride] = 0.0f;
}
}
else
{
/* Set up workspace. */
float x1, y1, wrk[8];
int iwrk1[2], kwrk1 = 2, lwrk = 8, err = 0;
/* Evaluate surface at the points. */
for (i = 0; i < num_points; ++i)
{
x1 = x_[i];
y1 = y_[i];
oskar_dierckx_bispev_f(tx, nx, ty, ny, coeff, 3, 3,
&x1, 1, &y1, 1, &out[i * stride],
wrk, lwrk, iwrk1, kwrk1, &err);
if (err != 0)
{
*status = OSKAR_ERR_SPLINE_EVAL_FAIL;
return;
}
}
}
}
else if (location == OSKAR_GPU)
{
#ifdef OSKAR_HAVE_CUDA
oskar_dierckx_bispev_bicubic_cuda_f(tx, nx, ty, ny, coeff,
num_points, x_, y_, stride, out);
oskar_device_check_error(status);
#else
*status = OSKAR_ERR_CUDA_NOT_AVAILABLE;
#endif
}
else
*status = OSKAR_ERR_BAD_LOCATION;
}
else if (type == OSKAR_DOUBLE)
{
const double *tx, *ty, *coeff, *x_, *y_;
double *out;
tx = oskar_mem_double_const(
oskar_splines_knots_x_theta_const(spline), status);
ty = oskar_mem_double_const(
oskar_splines_knots_y_phi_const(spline), status);
coeff = oskar_mem_double_const(
oskar_splines_coeff_const(spline), status);
x_ = oskar_mem_double_const(x, status);
y_ = oskar_mem_double_const(y, status);
out = oskar_mem_double(output, status) + offset;
/* Check if data are in CPU memory. */
if (location == OSKAR_CPU)
{
int i;
if (nx == 0 || ny == 0 || !tx || !ty || !coeff)
{
for (i = 0; i < num_points; ++i)
{
out[i * stride] = 0.0;
}
}
else
{
/* Set up workspace. */
double x1, y1, wrk[8];
int iwrk1[2], kwrk1 = 2, lwrk = 8, err = 0;
/* Evaluate surface at the points. */
for (i = 0; i < num_points; ++i)
{
x1 = x_[i];
y1 = y_[i];
oskar_dierckx_bispev_d(tx, nx, ty, ny, coeff, 3, 3,
&x1, 1, &y1, 1, &out[i * stride],
wrk, lwrk, iwrk1, kwrk1, &err);
if (err != 0)
{
*status = OSKAR_ERR_SPLINE_EVAL_FAIL;
return;
}
}
}
}
else if (location == OSKAR_GPU)
{
#ifdef OSKAR_HAVE_CUDA
oskar_dierckx_bispev_bicubic_cuda_d(tx, nx, ty, ny, coeff,
num_points, x_, y_, stride, out);
oskar_device_check_error(status);
#else
*status = OSKAR_ERR_CUDA_NOT_AVAILABLE;
#endif
}
else
*status = OSKAR_ERR_BAD_LOCATION;
}
else
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/correlate/src/oskar_auto_correlate_omp.c
|
/*
* Copyright (c) 2015-2018, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "correlate/private_correlate_functions_inline.h"
#include "correlate/oskar_auto_correlate_omp.h"
#include "math/oskar_add_inline.h"
#include "math/oskar_kahan_sum.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
void oskar_auto_correlate_omp_f(const int num_sources, const int num_stations,
const float4c* jones, const float* source_I, const float* source_Q,
const float* source_U, const float* source_V, float4c* vis)
{
int s;
#pragma omp parallel for private(s)
for (s = 0; s < num_stations; ++s)
{
int i;
float4c m1, m2, sum, guard;
const float4c *const jones_station = &jones[s * num_sources];
OSKAR_CLEAR_COMPLEX_MATRIX(float, sum)
OSKAR_CLEAR_COMPLEX_MATRIX(float, guard)
for (i = 0; i < num_sources; ++i)
{
/* Construct source brightness matrix. */
OSKAR_CONSTRUCT_B(float, m2,
source_I[i], source_Q[i], source_U[i], source_V[i])
/* Multiply first Jones matrix with source brightness matrix. */
OSKAR_LOAD_MATRIX(m1, jones_station[i])
OSKAR_MUL_COMPLEX_MATRIX_HERMITIAN_IN_PLACE(float2, m1, m2);
/* Multiply result with second (Hermitian transposed) Jones matrix. */
OSKAR_LOAD_MATRIX(m2, jones_station[i])
OSKAR_MUL_COMPLEX_MATRIX_CONJUGATE_TRANSPOSE_IN_PLACE(float2, m1, m2);
/* Accumulate. */
OSKAR_KAHAN_SUM_COMPLEX_MATRIX(float, sum, m1, guard)
}
/* Blank non-Hermitian values. */
sum.a.y = 0.0f; sum.d.y = 0.0f;
OSKAR_ADD_COMPLEX_MATRIX_IN_PLACE(vis[s], sum);
}
}
/* Double precision. */
void oskar_auto_correlate_omp_d(const int num_sources, const int num_stations,
const double4c* jones, const double* source_I, const double* source_Q,
const double* source_U, const double* source_V, double4c* vis)
{
int s;
#pragma omp parallel for private(s)
for (s = 0; s < num_stations; ++s)
{
int i;
double4c m1, m2, sum;
const double4c *const jones_station = &jones[s * num_sources];
OSKAR_CLEAR_COMPLEX_MATRIX(double, sum)
for (i = 0; i < num_sources; ++i)
{
/* Construct source brightness matrix. */
OSKAR_CONSTRUCT_B(double, m2,
source_I[i], source_Q[i], source_U[i], source_V[i])
/* Multiply first Jones matrix with source brightness matrix. */
OSKAR_LOAD_MATRIX(m1, jones_station[i])
OSKAR_MUL_COMPLEX_MATRIX_HERMITIAN_IN_PLACE(double2, m1, m2);
/* Multiply result with second (Hermitian transposed) Jones matrix. */
OSKAR_LOAD_MATRIX(m2, jones_station[i])
OSKAR_MUL_COMPLEX_MATRIX_CONJUGATE_TRANSPOSE_IN_PLACE(double2, m1, m2);
/* Accumulate. */
OSKAR_ADD_COMPLEX_MATRIX_IN_PLACE(sum, m1)
}
/* Blank non-Hermitian values. */
sum.a.y = 0.0; sum.d.y = 0.0;
OSKAR_ADD_COMPLEX_MATRIX_IN_PLACE(vis[s], sum);
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/convert/src/oskar_convert_ecef_to_station_uvw.c
|
<filename>oskar/convert/src/oskar_convert_ecef_to_station_uvw.c
/*
* Copyright (c) 2013-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "convert/oskar_convert_ecef_to_station_uvw.h"
#include "convert/oskar_convert_ecef_to_station_uvw_cuda.h"
#include "utility/oskar_device_utils.h"
#include "convert/private_convert_ecef_to_station_uvw_inline.h"
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
void oskar_convert_ecef_to_station_uvw_f(int num_stations, const float* x,
const float* y, const float* z, double ha0_rad, double dec0_rad,
float* u, float* v, float* w)
{
int i;
double sin_ha0, cos_ha0, sin_dec0, cos_dec0;
/* Precompute trig. */
sin_ha0 = sin(ha0_rad);
cos_ha0 = cos(ha0_rad);
sin_dec0 = sin(dec0_rad);
cos_dec0 = cos(dec0_rad);
/* Loop over points. */
for (i = 0; i < num_stations; ++i)
{
double ut, vt, wt;
oskar_convert_ecef_to_station_uvw_inline_d(x[i], y[i], z[i],
sin_ha0, cos_ha0, sin_dec0, cos_dec0, &ut, &vt, &wt);
u[i] = (float)ut;
v[i] = (float)vt;
w[i] = (float)wt;
}
}
/* Double precision. */
void oskar_convert_ecef_to_station_uvw_d(int num_stations, const double* x,
const double* y, const double* z, double ha0_rad, double dec0_rad,
double* u, double* v, double* w)
{
int i;
double sin_ha0, cos_ha0, sin_dec0, cos_dec0;
/* Precompute trig. */
sin_ha0 = sin(ha0_rad);
cos_ha0 = cos(ha0_rad);
sin_dec0 = sin(dec0_rad);
cos_dec0 = cos(dec0_rad);
/* Loop over points. */
for (i = 0; i < num_stations; ++i)
{
oskar_convert_ecef_to_station_uvw_inline_d(x[i], y[i], z[i], sin_ha0,
cos_ha0, sin_dec0, cos_dec0, &u[i], &v[i], &w[i]);
}
}
/* Wrapper. */
void oskar_convert_ecef_to_station_uvw(int num_stations, const oskar_Mem* x,
const oskar_Mem* y, const oskar_Mem* z, double ra0_rad,
double dec0_rad, double gast, oskar_Mem* u, oskar_Mem* v,
oskar_Mem* w, int* status)
{
int type, location;
double ha0_rad;
/* Check if safe to proceed. */
if (*status) return;
/* Get data type and location of the input coordinates. */
type = oskar_mem_type(x);
location = oskar_mem_location(x);
/* Check that the memory is allocated. */
if (!oskar_mem_allocated(u) || !oskar_mem_allocated(v) ||
!oskar_mem_allocated(w) || !oskar_mem_allocated(x) ||
!oskar_mem_allocated(y) || !oskar_mem_allocated(z))
{
*status = OSKAR_ERR_MEMORY_NOT_ALLOCATED;
return;
}
/* Check that the data dimensions are OK. */
if ((int)oskar_mem_length(u) < num_stations ||
(int)oskar_mem_length(v) < num_stations ||
(int)oskar_mem_length(w) < num_stations ||
(int)oskar_mem_length(x) < num_stations ||
(int)oskar_mem_length(y) < num_stations ||
(int)oskar_mem_length(z) < num_stations)
{
*status = OSKAR_ERR_DIMENSION_MISMATCH;
return;
}
/* Check that the data are in the right location. */
if (oskar_mem_location(y) != location ||
oskar_mem_location(z) != location ||
oskar_mem_location(u) != location ||
oskar_mem_location(v) != location ||
oskar_mem_location(w) != location)
{
*status = OSKAR_ERR_BAD_LOCATION;
return;
}
/* Check that the data is of the right type. */
if (oskar_mem_type(y) != type || oskar_mem_type(z) != type ||
oskar_mem_type(u) != type || oskar_mem_type(v) != type ||
oskar_mem_type(w) != type)
{
*status = OSKAR_ERR_TYPE_MISMATCH;
return;
}
/* Evaluate Greenwich Hour Angle of phase centre. */
ha0_rad = gast - ra0_rad;
/* Evaluate station u,v,w coordinates. */
if (location == OSKAR_GPU)
{
#ifdef OSKAR_HAVE_CUDA
if (type == OSKAR_SINGLE)
{
oskar_convert_ecef_to_station_uvw_cuda_f(num_stations,
oskar_mem_float_const(x, status),
oskar_mem_float_const(y, status),
oskar_mem_float_const(z, status),
(float)ha0_rad, (float)dec0_rad,
oskar_mem_float(u, status),
oskar_mem_float(v, status),
oskar_mem_float(w, status));
}
else if (type == OSKAR_DOUBLE)
{
oskar_convert_ecef_to_station_uvw_cuda_d(num_stations,
oskar_mem_double_const(x, status),
oskar_mem_double_const(y, status),
oskar_mem_double_const(z, status),
ha0_rad, dec0_rad,
oskar_mem_double(u, status),
oskar_mem_double(v, status),
oskar_mem_double(w, status));
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
oskar_device_check_error(status);
#else
*status = OSKAR_ERR_CUDA_NOT_AVAILABLE;
#endif
}
else if (location == OSKAR_CPU)
{
if (type == OSKAR_SINGLE)
{
oskar_convert_ecef_to_station_uvw_f(num_stations,
oskar_mem_float_const(x, status),
oskar_mem_float_const(y, status),
oskar_mem_float_const(z, status),
(float)ha0_rad, (float)dec0_rad,
oskar_mem_float(u, status),
oskar_mem_float(v, status),
oskar_mem_float(w, status));
}
else if (type == OSKAR_DOUBLE)
{
oskar_convert_ecef_to_station_uvw_d(num_stations,
oskar_mem_double_const(x, status),
oskar_mem_double_const(y, status),
oskar_mem_double_const(z, status),
ha0_rad, dec0_rad,
oskar_mem_double(u, status),
oskar_mem_double(v, status),
oskar_mem_double(w, status));
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
}
else
{
*status = OSKAR_ERR_BAD_LOCATION;
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/interferometer/src/oskar_evaluate_jones_Z.c
|
<gh_stars>1-10
/*
* Copyright (c) 2013-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "interferometer/oskar_evaluate_jones_Z.h"
#include "convert/oskar_convert_relative_directions_to_enu_directions.h"
#include "convert/oskar_convert_offset_ecef_to_ecef.h"
#include "telescope/station/oskar_evaluate_pierce_points.h"
#include "sky/oskar_evaluate_tec_tid.h"
#include <math.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
static void oskar_evaluate_TEC(oskar_WorkJonesZ* work, int num_pp,
const oskar_SettingsIonosphere* settings,
double gast, int* status);
static void evaluate_station_ECEF_coords(
double* station_x, double* station_y, double* station_z,
int stationID, const oskar_Telescope* telescope);
static void evaluate_jones_Z_station(oskar_Mem* Z_station,
double wavelength, const oskar_Mem* TEC, const oskar_Mem* hor_z,
double min_elevation, int num_pp, int* status);
void oskar_evaluate_jones_Z(oskar_Jones* Z, const oskar_Sky* sky,
const oskar_Telescope* telescope,
const oskar_SettingsIonosphere* settings, double gast,
double frequency_hz, oskar_WorkJonesZ* work, int* status)
{
int i, num_sources, num_stations;
/* Station position in ECEF frame */
double station_x, station_y, station_z, wavelength;
oskar_Mem *Z_station;
int type;
oskar_Sky* sky_cpu; /* Copy of the sky model on the CPU */
/* Check if safe to proceed. */
if (*status) return;
/* Check data types. */
type = oskar_sky_precision(sky);
if (oskar_telescope_precision(telescope) != type ||
oskar_jones_type(Z) != (type | OSKAR_COMPLEX) ||
oskar_work_jones_z_type(work) != type)
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
return;
}
/* For now, this function requires data is on the CPU .. check this. */
/* Resize the work array (if needed) */
num_stations = oskar_telescope_num_stations(telescope);
num_sources = oskar_sky_num_sources(sky);
oskar_work_jones_z_resize(work, num_sources, status);
/* Copy the sky model to the CPU. */
sky_cpu = oskar_sky_create_copy(sky, OSKAR_CPU, status);
Z_station = oskar_mem_create_alias(0, 0, 0, status);
wavelength = 299792458.0 / frequency_hz;
/* Evaluate the ionospheric phase screen for each station at each
* source pierce point. */
for (i = 0; i < num_stations; ++i)
{
double last, lon, lat;
const oskar_Station* station;
station = oskar_telescope_station_const(telescope, i);
lon = oskar_station_lon_rad(station);
lat = oskar_station_lat_rad(station);
last = gast + lon;
/* Evaluate horizontal x,y,z source positions (for which to evaluate
* pierce points) */
oskar_convert_relative_directions_to_enu_directions(
work->hor_x, work->hor_y, work->hor_z, num_sources,
oskar_sky_l_const(sky_cpu), oskar_sky_m_const(sky_cpu),
oskar_sky_n_const(sky_cpu), last - oskar_sky_reference_ra_rad(sky_cpu),
oskar_sky_reference_dec_rad(sky_cpu), lat, status);
/* Obtain station coordinates in the ECEF frame. */
evaluate_station_ECEF_coords(&station_x, &station_y, &station_z, i,
telescope);
/* Obtain the pierce points. */
/* FIXME(BM) this is current hard-coded to TID height screen 0
* this fix is only needed to support multiple screen heights. */
oskar_evaluate_pierce_points(work->pp_lon, work->pp_lat,
work->pp_rel_path, station_x, station_y,
station_z, settings->TID[0].height_km * 1000., num_sources,
work->hor_x, work->hor_y, work->hor_z, status);
/* Evaluate TEC values for the pierce points */
oskar_evaluate_TEC(work, num_sources, settings, gast, status);
/* Get a pointer to the Jones matrices for the station */
oskar_jones_get_station_pointer(Z_station, Z, i, status);
/* Populate the Jones matrix with ionospheric phase */
evaluate_jones_Z_station(Z_station, wavelength,
work->total_TEC, work->hor_z, settings->min_elevation,
num_sources, status);
}
oskar_sky_free(sky_cpu, status);
oskar_mem_free(Z_station, status);
}
/* Evaluate the TEC value for each pierce point - note: at the moment this is
* just the accumulation of one or more TID screens.
* TODO convert this to a stand-alone function.
*/
static void oskar_evaluate_TEC(oskar_WorkJonesZ* work, int num_pp,
const oskar_SettingsIonosphere* settings,
double gast, int* status)
{
int i;
/* FIXME(BM) For now limit number of screens to 1, this can be removed
* if a TEC model which is valid for multiple screens is implemented
*/
if (settings->num_TID_screens > 1)
*status = OSKAR_ERR_INVALID_ARGUMENT;
oskar_mem_set_value_real(work->total_TEC, 0.0, 0, 0, status);
/* Loop over TID screens to evaluate TEC values */
for (i = 0; i < settings->num_TID_screens; ++i)
{
oskar_mem_set_value_real(work->screen_TEC, 0.0, 0, 0, status);
/* Evaluate TEC values for the screen */
oskar_evaluate_tec_tid(work->screen_TEC, num_pp, work->pp_lon,
work->pp_lat, work->pp_rel_path, settings->TEC0,
&settings->TID[i], gast);
/* Accumulate into total TEC */
/* FIXME(BM) addition is not physical for more than one TEC screen in
* the way TIDs are currently evaluated as TEC0 is added into both
* screens.
*/
oskar_mem_add(work->total_TEC, work->total_TEC, work->screen_TEC,
oskar_mem_length(work->total_TEC), status);
}
}
static void evaluate_station_ECEF_coords(
double* station_x, double* station_y, double* station_z,
int stationID, const oskar_Telescope* telescope)
{
double st_x, st_y, st_z;
double lon, lat, alt;
const oskar_Station* station;
const void *x_, *y_, *z_;
x_ = oskar_mem_void_const(
oskar_telescope_station_true_x_offset_ecef_metres_const(telescope));
y_ = oskar_mem_void_const(
oskar_telescope_station_true_y_offset_ecef_metres_const(telescope));
z_ = oskar_mem_void_const(
oskar_telescope_station_true_z_offset_ecef_metres_const(telescope));
station = oskar_telescope_station_const(telescope, stationID);
lon = oskar_station_lon_rad(station);
lat = oskar_station_lat_rad(station);
alt = oskar_station_alt_metres(station);
if (oskar_mem_type(
oskar_telescope_station_true_x_offset_ecef_metres_const(telescope)) ==
OSKAR_DOUBLE)
{
st_x = ((const double*)x_)[stationID];
st_y = ((const double*)y_)[stationID];
st_z = ((const double*)z_)[stationID];
}
else
{
st_x = (double)((const float*)x_)[stationID];
st_y = (double)((const float*)y_)[stationID];
st_z = (double)((const float*)z_)[stationID];
}
oskar_convert_offset_ecef_to_ecef(1, &st_x, &st_y, &st_z, lon, lat, alt,
station_x, station_y, station_z);
}
static void evaluate_jones_Z_station(oskar_Mem* Z_station,
double wavelength, const oskar_Mem* TEC, const oskar_Mem* hor_z,
double min_elevation, int num_pp, int* status)
{
int i, type;
double arg;
/* Check if safe to proceed. */
if (*status) return;
type = oskar_mem_type(Z_station);
if (type == OSKAR_DOUBLE_COMPLEX)
{
double2* Z = oskar_mem_double2(Z_station, status);
for (i = 0; i < num_pp; ++i)
{
/* Initialise as an unit scalar Z = (1 + 0i) i.e. no phase change */
Z[i].x = 1.0;
Z[i].y = 0.0;
/* If the pierce point is below the minimum specified elevation
* don't evaluate a phase */
if (asin((oskar_mem_double_const(hor_z, status))[i]) <
min_elevation)
continue;
arg = wavelength * 25. * oskar_mem_double_const(TEC, status)[i];
/* Z phase == exp(i * lambda * 25 * tec) */
Z[i].x = cos(arg);
Z[i].y = sin(arg);
}
}
else if (type == OSKAR_SINGLE_COMPLEX)
{
float2* Z = oskar_mem_float2(Z_station, status);
for (i = 0; i < num_pp; ++i)
{
/* Initialise as an unit scalar Z = (1 + 0i) i.e. no phase change */
Z[i].x = 1.0;
Z[i].y = 0.0;
/* If the pierce point is below the minimum specified elevation
* don't evaluate a phase */
if (asin((oskar_mem_float_const(hor_z, status))[i]) <
min_elevation)
continue;
arg = wavelength * 25. * oskar_mem_float_const(TEC, status)[i];
/* Z phase == exp(i * lambda * 25 * tec) */
Z[i].x = cos(arg);
Z[i].y = sin(arg);
}
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/settings/types/oskar_DoubleRangeExt.h
|
<gh_stars>1-10
/*
* Copyright (c) 2015, The University of Oxford
* All rights reserved.
*
* This file is part of the OSKAR package.
* Contact: oskar at oerc.ox.ac.uk
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_SETTINGS_TYPE_DOUBLERANGEEXT_H_
#define OSKAR_SETTINGS_TYPE_DOUBLERANGEEXT_H_
/**
* @file oskar_DoubleRangeExt.h
*/
#include "settings/types/oskar_AbstractSettingsType.h"
#include "settings/extern/ttl/var/variant.hpp"
namespace oskar {
/**
* @class DoubleRangeExt
*
* @brief
* Ranged double value.
*
* @details
* Initialised with a CSV list consisting of the minimum and
* maximum range and the extended string values.
*
* The range of the allowed value is inclusive.
*
* e.g. a range of 3.0,10.0,min,max allows any double x, in the range
* 3.0 >= x >= 10.0. For numbers less < 3.0 the string 'min' will be used and
* for numbers > 10.0 the string 'max' will be used.
*
* Values outside the range are set to the extended string value or
* the closest extreme of the range if the extreme value string for that side
* of the range is not set.
*
* By default the range is initialised to a full range of allowed double
* values (i.e. from -DBL_MAX to DBL_MAX), with a value of 0.0 and no extended
* string values.
*/
class DoubleRangeExt : public AbstractSettingsType
{
public:
typedef ttl::var::variant<double, std::string> Value;
enum Format { AUTO, EXPONENT };
OSKAR_SETTINGS_EXPORT DoubleRangeExt();
OSKAR_SETTINGS_EXPORT virtual ~DoubleRangeExt();
OSKAR_SETTINGS_EXPORT bool init(const char* s);
OSKAR_SETTINGS_EXPORT bool set_default(const char* value);
OSKAR_SETTINGS_EXPORT bool set_value(const char* value);
OSKAR_SETTINGS_EXPORT bool is_default() const;
OSKAR_SETTINGS_EXPORT double value() const;
OSKAR_SETTINGS_EXPORT double min() const;
OSKAR_SETTINGS_EXPORT double max() const;
OSKAR_SETTINGS_EXPORT const char* ext_min() const;
OSKAR_SETTINGS_EXPORT const char* ext_max() const;
OSKAR_SETTINGS_EXPORT bool operator==(const DoubleRangeExt& other) const;
OSKAR_SETTINGS_EXPORT bool operator>(const DoubleRangeExt& other) const;
private:
bool from_string_(Value& value, const std::string& s) const;
std::string to_string_(const Value& value) const;
double min_, max_;
std::string ext_min_, ext_max_;
Format format_;
Value default_, value_;
};
} /* namespace oskar */
#endif /* OSKAR_SETTINGS_TYPE_DOUBLERANGEEXT_H_ */
|
davepallot/OSKAR
|
oskar/telescope/src/oskar_telescope_analyse.c
|
/*
* Copyright (c) 2012-2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "telescope/private_telescope.h"
#include "telescope/oskar_telescope.h"
#include "telescope/station/oskar_station_analyse.h"
#include "telescope/station/oskar_station_different.h"
#ifdef __cplusplus
extern "C" {
#endif
static void max_station_size_and_depth(const oskar_Station* s,
int* max_elements, int* max_depth, int depth)
{
int i, num_elements;
num_elements = oskar_station_num_elements(s);
*max_elements = num_elements > *max_elements ? num_elements : *max_elements;
*max_depth = depth > *max_depth ? depth : *max_depth;
if (oskar_station_has_child(s))
{
for (i = 0; i < num_elements; ++i)
{
max_station_size_and_depth(oskar_station_child_const(s, i),
max_elements, max_depth, depth + 1);
}
}
}
static void set_child_station_locations(oskar_Station* s,
const oskar_Station* parent)
{
if (parent)
{
oskar_station_set_position(s,
oskar_station_lon_rad(parent),
oskar_station_lat_rad(parent),
oskar_station_alt_metres(parent));
}
/* Recursively set data for child stations. */
if (oskar_station_has_child(s))
{
int i, num_elements;
num_elements = oskar_station_num_elements(s);
for (i = 0; i < num_elements; ++i)
set_child_station_locations(oskar_station_child(s, i), s);
}
}
void oskar_telescope_analyse(oskar_Telescope* model, int* status)
{
int i = 0, finished_identical_station_check = 0, num_stations;
/* Check if safe to proceed. */
if (*status) return;
/* Set default flags. */
model->identical_stations = 1;
/* Recursively find the maximum number of elements in any station. */
num_stations = model->num_stations;
model->max_station_size = 0;
for (i = 0; i < num_stations; ++i)
{
set_child_station_locations(oskar_telescope_station(model, i), 0);
max_station_size_and_depth(oskar_telescope_station_const(model, i),
&model->max_station_size, &model->max_station_depth, 1);
}
/* Recursively analyse each station. */
for (i = 0; i < num_stations; ++i)
{
oskar_station_analyse(oskar_telescope_station(model, i),
&finished_identical_station_check, status);
}
/* Check if safe to proceed. */
if (*status) return;
/* Check if we need to examine every station. */
if (finished_identical_station_check)
{
model->identical_stations = 0;
}
else
{
/* Check if the stations are different. */
for (i = 1; i < num_stations; ++i)
{
if (oskar_station_different(oskar_telescope_station(model, 0),
oskar_telescope_station(model, i), status))
{
model->identical_stations = 0;
break;
}
}
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/vis/src/oskar_vis_header_create.c
|
<reponame>davepallot/OSKAR<filename>oskar/vis/src/oskar_vis_header_create.c<gh_stars>1-10
/*
* Copyright (c) 2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "vis/private_vis_header.h"
#include "vis/oskar_vis_header.h"
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
oskar_VisHeader* oskar_vis_header_create(int amp_type, int coord_precision,
int max_times_per_block, int num_times_total,
int max_channels_per_block, int num_channels_total, int num_stations,
int write_autocorr, int write_crosscor, int* status)
{
oskar_VisHeader* hdr = 0;
/* Check if safe to proceed. */
if (*status) return 0;
/* Check type. */
if (!oskar_type_is_complex(amp_type))
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
return 0;
}
/* Allocate the structure. */
hdr = (oskar_VisHeader*) malloc(sizeof(oskar_VisHeader));
if (!hdr)
{
*status = OSKAR_ERR_MEMORY_ALLOC_FAILURE;
return 0;
}
hdr->amp_type = amp_type;
hdr->coord_precision = coord_precision;
/* Set number of tags per block in the binary file. */
/* This must be updated if the number of fields written to file from
* the oskar_VisBlock structure is changed. */
hdr->num_tags_per_block = 1;
if (write_crosscor) hdr->num_tags_per_block += 4;
if (write_autocorr) hdr->num_tags_per_block += 1;
/* Set dimensions. */
hdr->max_times_per_block = max_times_per_block;
hdr->num_times_total = num_times_total;
hdr->max_channels_per_block = max_channels_per_block;
hdr->num_channels_total = num_channels_total;
hdr->num_stations = num_stations;
/* Set default polarisation type. */
if (oskar_type_is_matrix(amp_type))
hdr->pol_type = OSKAR_VIS_POL_TYPE_LINEAR_XX_XY_YX_YY;
else
hdr->pol_type = OSKAR_VIS_POL_TYPE_STOKES_I;
/* Initialise meta-data. */
hdr->write_autocorr = write_autocorr;
hdr->write_crosscorr = write_crosscor;
hdr->freq_start_hz = 0.0;
hdr->freq_inc_hz = 0.0;
hdr->channel_bandwidth_hz = 0.0;
hdr->time_start_mjd_utc = 0.0;
hdr->time_inc_sec = 0.0;
hdr->time_average_sec = 0.0;
hdr->phase_centre_type = 0;
hdr->phase_centre_deg[0] = 0.0;
hdr->phase_centre_deg[1] = 0.0;
hdr->telescope_centre_lon_deg = 0.0;
hdr->telescope_centre_lat_deg = 0.0;
hdr->telescope_centre_alt_m = 0.0;
/* Initialise CPU memory. */
hdr->telescope_path = oskar_mem_create(OSKAR_CHAR, OSKAR_CPU, 0, status);
hdr->settings = oskar_mem_create(OSKAR_CHAR, OSKAR_CPU, 0, status);
hdr->station_x_offset_ecef_metres = oskar_mem_create(coord_precision,
OSKAR_CPU, num_stations, status);
hdr->station_y_offset_ecef_metres = oskar_mem_create(coord_precision,
OSKAR_CPU, num_stations, status);
hdr->station_z_offset_ecef_metres = oskar_mem_create(coord_precision,
OSKAR_CPU, num_stations, status);
/* Return handle to structure. */
return hdr;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/imager/src/private_imager_select_data.c
|
/*
* Copyright (c) 2016-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "imager/private_imager.h"
#include "imager/oskar_imager.h"
#include "imager/private_imager_select_data.h"
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
#define C0 299792458.0
static
void copy_vis_pol(size_t num_rows, int num_channels, int num_pols,
int c, int p, const oskar_Mem* vis_in, const oskar_Mem* weight_in,
oskar_Mem* vis_out, oskar_Mem* weight_out, size_t out_offset,
int* status);
void oskar_imager_select_data(
const oskar_Imager* h,
size_t num_rows,
int start_chan,
int end_chan,
int num_pols,
const oskar_Mem* uu_in,
const oskar_Mem* vv_in,
const oskar_Mem* ww_in,
const oskar_Mem* vis_in,
const oskar_Mem* weight_in,
const oskar_Mem* time_in,
double im_freq_hz,
int im_pol,
size_t* num_out,
oskar_Mem* uu_out,
oskar_Mem* vv_out,
oskar_Mem* ww_out,
oskar_Mem* vis_out,
oskar_Mem* weight_out,
oskar_Mem* time_out,
int* status)
{
int i, c, p, num_channels;
double inv_wavelength;
const double s = 0.05;
const double df = h->freq_inc_hz != 0.0 ? h->freq_inc_hz : 1.0;
const double f0 = h->vis_freq_start_hz;
/* Initialise. */
if (*status) return;
*num_out = 0;
/* Override pol_offset if required. */
p = h->pol_offset;
if (h->im_type == OSKAR_IMAGE_TYPE_STOKES ||
h->im_type == OSKAR_IMAGE_TYPE_LINEAR)
p = im_pol;
if (num_pols == 1) p = 0;
/* Check whether using frequency snapshots or frequency synthesis. */
num_channels = 1 + end_chan - start_chan;
if (h->chan_snaps)
{
/* Get the channel for the image and check if out of range. */
c = (int) round((im_freq_hz - f0) / df);
if (c < start_chan || c > end_chan) return;
if (fabs((im_freq_hz - f0) - c * df) > s * df) return;
/* Copy the baseline coordinates in wavelengths. */
inv_wavelength = (f0 + c * df) / C0;
oskar_mem_copy_contents(uu_out, uu_in, 0, 0, num_rows, status);
oskar_mem_copy_contents(vv_out, vv_in, 0, 0, num_rows, status);
oskar_mem_copy_contents(ww_out, ww_in, 0, 0, num_rows, status);
oskar_mem_scale_real(uu_out, inv_wavelength, status);
oskar_mem_scale_real(vv_out, inv_wavelength, status);
oskar_mem_scale_real(ww_out, inv_wavelength, status);
/* Copy visibility data and weights if present. */
copy_vis_pol(num_rows, num_channels, num_pols,
c - start_chan, p, vis_in, weight_in,
vis_out, weight_out, 0, status);
/* Copy time centroids if present. */
if (time_in && time_out)
{
if (oskar_mem_length(time_out) < num_rows)
oskar_mem_realloc(time_out, num_rows, status);
oskar_mem_copy_contents(time_out, time_in, 0, 0, num_rows, status);
}
*num_out += num_rows;
}
else /* Frequency synthesis */
{
oskar_Mem *uu_, *vv_, *ww_;
uu_ = oskar_mem_create_alias(0, 0, 0, status);
vv_ = oskar_mem_create_alias(0, 0, 0, status);
ww_ = oskar_mem_create_alias(0, 0, 0, status);
for (i = 0; i < h->num_sel_freqs; ++i)
{
c = (int) round((h->sel_freqs[i] - f0) / df);
if (c < start_chan || c > end_chan) continue;
if (fabs((h->sel_freqs[i] - f0) - c * df) > s * df) continue;
/* Copy the baseline coordinates in wavelengths. */
inv_wavelength = (f0 + c * df) / C0;
oskar_mem_set_alias(uu_, uu_out, *num_out, num_rows, status);
oskar_mem_set_alias(vv_, vv_out, *num_out, num_rows, status);
oskar_mem_set_alias(ww_, ww_out, *num_out, num_rows, status);
oskar_mem_copy_contents(uu_, uu_in, 0, 0, num_rows, status);
oskar_mem_copy_contents(vv_, vv_in, 0, 0, num_rows, status);
oskar_mem_copy_contents(ww_, ww_in, 0, 0, num_rows, status);
oskar_mem_scale_real(uu_, inv_wavelength, status);
oskar_mem_scale_real(vv_, inv_wavelength, status);
oskar_mem_scale_real(ww_, inv_wavelength, status);
/* Copy visibility data and weights if present. */
copy_vis_pol(num_rows, num_channels, num_pols,
c - start_chan, p, vis_in, weight_in,
vis_out, weight_out, *num_out, status);
/* Copy time centroids if present. */
if (time_in && time_out)
{
if (oskar_mem_length(time_out) < num_rows * h->num_sel_freqs)
oskar_mem_realloc(time_out, num_rows * h->num_sel_freqs,
status);
oskar_mem_copy_contents(time_out, time_in, *num_out, 0,
num_rows, status);
}
*num_out += num_rows;
}
oskar_mem_free(uu_, status);
oskar_mem_free(vv_, status);
oskar_mem_free(ww_, status);
}
}
void copy_vis_pol(size_t num_rows, int num_channels, int num_pols,
int c, int p, const oskar_Mem* vis_in, const oskar_Mem* weight_in,
oskar_Mem* vis_out, oskar_Mem* weight_out, size_t out_offset,
int* status)
{
size_t r;
if (*status) return;
if (oskar_mem_precision(vis_out) == OSKAR_SINGLE)
{
float* w_out;
const float* w_in;
w_out = oskar_mem_float(weight_out, status) + out_offset;
w_in = oskar_mem_float_const(weight_in, status);
for (r = 0; r < num_rows; ++r)
w_out[r] = w_in[num_pols * r + p];
if (vis_in)
{
float2* v_out;
const float2* v_in;
v_out = oskar_mem_float2(vis_out, status) + out_offset;
v_in = oskar_mem_float2_const(vis_in, status);
for (r = 0; r < num_rows; ++r)
v_out[r] = v_in[num_pols * (num_channels * r + c) + p];
}
}
else
{
double* w_out;
const double* w_in;
w_out = oskar_mem_double(weight_out, status) + out_offset;
w_in = oskar_mem_double_const(weight_in, status);
for (r = 0; r < num_rows; ++r)
w_out[r] = w_in[num_pols * r + p];
if (vis_in)
{
double2* v_out;
const double2* v_in;
v_out = oskar_mem_double2(vis_out, status) + out_offset;
v_in = oskar_mem_double2_const(vis_in, status);
for (r = 0; r < num_rows; ++r)
v_out[r] = v_in[num_pols * (num_channels * r + c) + p];
}
}
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/sky/src/oskar_sky_from_image.c
|
<filename>oskar/sky/src/oskar_sky_from_image.c
/*
* Copyright (c) 2016-2018, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sky/oskar_sky.h"
#include "convert/oskar_convert_relative_directions_to_lon_lat.h"
#include "math/oskar_cmath.h"
#ifdef __cplusplus
extern "C" {
#endif
static void set_pixel(oskar_Sky* sky, int i, int x, int y, double val,
const double crval[2], const double crpix[2], const double cdelt[2],
double image_freq_hz, double spectral_index, int* status);
oskar_Sky* oskar_sky_from_image(int precision, const oskar_Mem* image,
const int image_size[2], const double image_crval_deg[2],
const double image_crpix[2], double image_cellsize_deg,
double image_freq_hz, double spectral_index, int* status)
{
int i, type, x, y;
double crval[2], cdelt[2], val;
oskar_Sky* sky = 0;
/* Check if safe to proceed. */
if (*status) return 0;
/* Check pixel size has been defined. */
if (image_cellsize_deg == 0.0)
{
*status = OSKAR_ERR_OUT_OF_RANGE;
fprintf(stderr, "Unknown image pixel size. "
"(Ensure all WCS headers are present.)\n");
return 0;
}
/* Get reference pixels and reference values in radians. */
crval[0] = image_crval_deg[0] * M_PI / 180.0;
crval[1] = image_crval_deg[1] * M_PI / 180.0;
/* Compute sine of pixel deltas for inverse orthographic projection. */
cdelt[0] = -sin(image_cellsize_deg * M_PI / 180.0);
cdelt[1] = -cdelt[0];
/* Create a sky model. */
sky = oskar_sky_create(precision, OSKAR_CPU, 0, status);
/* Store the image pixels. */
type = oskar_mem_precision(image);
if (type == OSKAR_SINGLE)
{
const float *img = oskar_mem_float_const(image, status);
for (y = 0, i = 0; y < image_size[1]; ++y)
{
for (x = 0; x < image_size[0]; ++x)
{
/* Check pixel value. */
val = (double) (img[image_size[0] * y + x]);
if (val == 0.0)
continue;
set_pixel(sky, i++, x, y, val, crval, image_crpix, cdelt,
image_freq_hz, spectral_index, status);
}
}
}
else
{
const double *img = oskar_mem_double_const(image, status);
for (y = 0, i = 0; y < image_size[1]; ++y)
{
for (x = 0; x < image_size[0]; ++x)
{
/* Check pixel value. */
val = img[image_size[0] * y + x];
if (val == 0.0)
continue;
set_pixel(sky, i++, x, y, val, crval, image_crpix, cdelt,
image_freq_hz, spectral_index, status);
}
}
}
/* Return the sky model. */
oskar_sky_resize(sky, i, status);
return sky;
}
static void set_pixel(oskar_Sky* sky, int i, int x, int y, double val,
const double crval[2], const double crpix[2], const double cdelt[2],
double image_freq_hz, double spectral_index, int* status)
{
double ra, dec, l, m;
/* Convert pixel positions to RA and Dec values. */
l = cdelt[0] * (x + 1 - crpix[0]);
m = cdelt[1] * (y + 1 - crpix[1]);
oskar_convert_relative_directions_to_lon_lat_2d_d(1,
&l, &m, crval[0], crval[1], &ra, &dec);
/* Store pixel data in sky model. */
if (oskar_sky_num_sources(sky) <= i)
oskar_sky_resize(sky, i + 1000, status);
oskar_sky_set_source(sky, i, ra, dec, val, 0.0, 0.0, 0.0,
image_freq_hz, spectral_index, 0.0, 0.0, 0.0, 0.0, status);
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/convert/private_convert_enu_directions_to_cirs_relative_directions_inline.h
|
<gh_stars>1-10
/*
* Copyright (c) 2014, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_PRIVATE_CONVERT_ENU_DIRECTIONS_TO_CIRS_RELATIVE_DIRECTIONS_INLINE_H_
#define OSKAR_PRIVATE_CONVERT_ENU_DIRECTIONS_TO_CIRS_RELATIVE_DIRECTIONS_INLINE_H_
#include <oskar_global.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
OSKAR_INLINE
void oskar_convert_enu_directions_to_cirs_relative_directions_inline_f(
float x, float y, float z, const float sin_lat,
const float cos_lat, const float sin_ha0, const float cos_ha0,
const float sin_dec0, const float cos_dec0, const float local_pm_x,
const float local_pm_y, const float diurnal_aberration,
float* l, float* m, float* n)
{
float f, w, x2, y2, z2, t1, t2;
/* ENU directions to Cartesian -HA,Dec. */
/* This is the first (latitude) stage of the original transformation:
* rotate by -phi about x.
* INTERNAL: Axes are then permuted so that x -> Y, y -> Z and z -> X.
* X towards local meridian, Z towards NCP, Y towards local east. */
y2 = x;
z2 = y * cos_lat + z * sin_lat;
x2 = -y * sin_lat + z * cos_lat;
/* Diurnal aberration. */
f = 1.0f + diurnal_aberration * y2;
x = f * x2;
y = f * (y2 - diurnal_aberration);
z = f * z2;
/* Polar motion, permuting axes back to ENU directions. */
w = local_pm_x * x - local_pm_y * y + z;
z2 = x - local_pm_x * w;
x2 = y + local_pm_y * w;
y2 = w - (local_pm_x * local_pm_x + local_pm_y * local_pm_y) * z;
/* ENU directions to CIRS relative directions. */
/* This is the final two stages of the original transformation:
* rotate by ha0 around y, then by dec0 around x. */
t1 = x2 * sin_ha0;
t2 = z2 * cos_ha0;
*l = x2 * cos_ha0 + z2 * sin_ha0;
*m = t1 * sin_dec0 + y2 * cos_dec0 - t2 * sin_dec0;
*n = -t1 * cos_dec0 + y2 * sin_dec0 + t2 * cos_dec0;
}
/* Double precision. */
OSKAR_INLINE
void oskar_convert_enu_directions_to_cirs_relative_directions_inline_d(
double x, double y, double z, const double sin_lat,
const double cos_lat, const double sin_ha0, const double cos_ha0,
const double sin_dec0, const double cos_dec0, const double local_pm_x,
const double local_pm_y, const double diurnal_aberration,
double* l, double* m, double* n)
{
double f, w, x2, y2, z2, t1, t2;
/* ENU directions to Cartesian -HA,Dec. */
/* This is the first (latitude) stage of the original transformation:
* rotate by -phi about x.
* INTERNAL: Axes are then permuted so that x -> Y, y -> Z and z -> X.
* X towards local meridian, Z towards NCP, Y towards local east. */
y2 = x;
z2 = y * cos_lat + z * sin_lat;
x2 = -y * sin_lat + z * cos_lat;
/* Diurnal aberration. */
f = 1.0 + diurnal_aberration * y2;
x = f * x2;
y = f * (y2 - diurnal_aberration);
z = f * z2;
/* Polar motion, permuting axes back to ENU directions. */
w = local_pm_x * x - local_pm_y * y + z;
z2 = x - local_pm_x * w;
x2 = y + local_pm_y * w;
y2 = w - (local_pm_x * local_pm_x + local_pm_y * local_pm_y) * z;
/* ENU directions to CIRS relative directions. */
/* This is the final two stages of the original transformation:
* rotate by ha0 around y, then by dec0 around x. */
t1 = x2 * sin_ha0;
t2 = z2 * cos_ha0;
*l = x2 * cos_ha0 + z2 * sin_ha0;
*m = t1 * sin_dec0 + y2 * cos_dec0 - t2 * sin_dec0;
*n = -t1 * cos_dec0 + y2 * sin_dec0 + t2 * cos_dec0;
}
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_PRIVATE_CONVERT_ENU_DIRECTIONS_TO_CIRS_RELATIVE_DIRECTIONS_INLINE_H_ */
|
davepallot/OSKAR
|
oskar/log/src/oskar_log_free.c
|
<filename>oskar/log/src/oskar_log_free.c
/*
* Copyright (c) 2012-2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "oskar_version.h"
#include "log/private_log.h"
#include "log/oskar_log.h"
#include "log/oskar_log_file_exists.h"
#include "log/oskar_log_system_clock_string.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
void oskar_log_free(oskar_Log* log)
{
/* Print closing message. */
oskar_log_section(log, 'M', "OSKAR-%s ending at %s.",
OSKAR_VERSION_STR, oskar_log_system_clock_string(0));
/* If log is NULL, there's nothing more to do. */
if (!log) return;
/* Close the file. */
if (log->file) fclose(log->file);
/* If flag is set to delete, then remove the log file. */
if (!log->keep_file && log->name)
{
if (oskar_log_file_exists(log->name))
remove(log->name);
}
/* Free memory for the log data. */
free(log->name);
free(log->code);
free(log->offset);
free(log->length);
free(log->timestamp);
/* Free the structure itself. */
free(log);
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/utility/src/oskar_device_utils.c
|
<reponame>davepallot/OSKAR<filename>oskar/utility/src/oskar_device_utils.c<gh_stars>0
/*
* Copyright (c) 2012-2018, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "utility/oskar_device_utils.h"
#include <stdlib.h>
#include <string.h>
#ifdef OSKAR_HAVE_CUDA
#include <cuda_runtime_api.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
void oskar_device_check_error(int* status)
{
if (*status) return;
#ifdef OSKAR_HAVE_CUDA
*status = (int) cudaPeekAtLastError();
#endif
}
int oskar_device_compute_capability(void)
{
int version = 0;
#ifdef OSKAR_HAVE_CUDA
int major = 0, minor = 0, device = 0;
cudaGetDevice(&device);
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, device);
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, device);
version = 10 * major + minor;
#endif
return version;
}
int oskar_device_count(int *status)
{
int num = 0;
if (*status) return 0;
#ifdef OSKAR_HAVE_CUDA
if (cudaGetDeviceCount(&num) != cudaSuccess)
num = 0;
#endif
return num;
}
void oskar_device_mem_info(size_t* mem_free, size_t* mem_total)
{
if (!mem_free || !mem_total) return;
#ifdef OSKAR_HAVE_CUDA
cudaMemGetInfo(mem_free, mem_total);
#else
(void) mem_free;
(void) mem_total;
#endif
}
char* oskar_device_name(int device_id)
{
char* name = 0;
#ifdef OSKAR_HAVE_CUDA
struct cudaDeviceProp device_prop;
#endif
if (device_id < 0) return 0;
#ifdef OSKAR_HAVE_CUDA
cudaGetDeviceProperties(&device_prop, device_id);
name = (char*) calloc(1 + strlen(device_prop.name), sizeof(char));
strcpy(name, device_prop.name);
#endif
return name;
}
void oskar_device_reset(void)
{
#ifdef OSKAR_HAVE_CUDA
cudaDeviceReset();
#endif
}
void oskar_device_set(int id, int* status)
{
if (*status || id < 0) return;
#ifdef OSKAR_HAVE_CUDA
*status = (int) cudaSetDevice(id);
#endif
}
void oskar_device_synchronize(void)
{
#ifdef OSKAR_HAVE_CUDA
cudaDeviceSynchronize();
#endif
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/sky/src/oskar_sky_save.c
|
/*
* Copyright (c) 2012-2015, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sky/oskar_sky.h"
#include "math/oskar_cmath.h"
#include <stdio.h>
#define RAD2DEG 180.0/M_PI
#define RAD2ARCSEC RAD2DEG * 3600.0
#ifdef __cplusplus
extern "C" {
#endif
void oskar_sky_save(const char* filename, const oskar_Sky* sky, int* status)
{
int s, type, num_sources;
FILE* file;
/* Check if safe to proceed. */
if (*status) return;
/* Check sky model is in CPU memory. */
if (oskar_sky_mem_location(sky) != OSKAR_CPU)
{
*status = OSKAR_ERR_BAD_LOCATION;
return;
}
/* Open the output file. */
file = fopen(filename, "w");
if (!file)
{
*status = OSKAR_ERR_FILE_IO;
return;
}
/* Get the data type and number of sources. */
type = oskar_sky_precision(sky);
num_sources = oskar_sky_num_sources(sky);
/* Print a helpful header. */
fprintf(file, "# Number of sources: %i\n", num_sources);
fprintf(file, "# RA (deg), Dec (deg), I (Jy), Q (Jy), U (Jy), V (Jy), "
"Ref. freq. (Hz), Spectral index, Rotation measure (rad/m^2), "
"FWHM major (arcsec), FWHM minor (arcsec), Position angle (deg)\n");
/* Print out sky model in ASCII format. */
if (type == OSKAR_DOUBLE)
{
const double *ra_, *dec_, *I_, *Q_, *U_, *V_, *ref_, *sp_, *rm_;
const double *maj_, *min_, *pa_;
ra_ = oskar_mem_double_const(oskar_sky_ra_rad_const(sky), status);
dec_ = oskar_mem_double_const(oskar_sky_dec_rad_const(sky), status);
I_ = oskar_mem_double_const(oskar_sky_I_const(sky), status);
Q_ = oskar_mem_double_const(oskar_sky_Q_const(sky), status);
U_ = oskar_mem_double_const(oskar_sky_U_const(sky), status);
V_ = oskar_mem_double_const(oskar_sky_V_const(sky), status);
ref_ = oskar_mem_double_const(oskar_sky_reference_freq_hz_const(sky), status);
sp_ = oskar_mem_double_const(oskar_sky_spectral_index_const(sky), status);
rm_ = oskar_mem_double_const(oskar_sky_rotation_measure_rad_const(sky), status);
maj_ = oskar_mem_double_const(oskar_sky_fwhm_major_rad_const(sky), status);
min_ = oskar_mem_double_const(oskar_sky_fwhm_minor_rad_const(sky), status);
pa_ = oskar_mem_double_const(oskar_sky_position_angle_rad_const(sky), status);
for (s = 0; s < num_sources; ++s)
{
fprintf(file, "% 11.6f,% 11.6f,% 12.6e,% 12.6e,% 12.6e,% 12.6e,"
"% 12.6e,% 12.6e,% 12.6e,% 12.6e,% 12.6e,% 11.6f\n",
ra_[s] * RAD2DEG, dec_[s] * RAD2DEG,
I_[s], Q_[s], U_[s], V_[s], ref_[s], sp_[s], rm_[s],
maj_[s] * RAD2ARCSEC, min_[s] * RAD2ARCSEC,
pa_[s] * RAD2DEG);
}
}
else if (type == OSKAR_SINGLE)
{
const float *ra_, *dec_, *I_, *Q_, *U_, *V_, *ref_, *sp_, *rm_;
const float *maj_, *min_, *pa_;
ra_ = oskar_mem_float_const(oskar_sky_ra_rad_const(sky), status);
dec_ = oskar_mem_float_const(oskar_sky_dec_rad_const(sky), status);
I_ = oskar_mem_float_const(oskar_sky_I_const(sky), status);
Q_ = oskar_mem_float_const(oskar_sky_Q_const(sky), status);
U_ = oskar_mem_float_const(oskar_sky_U_const(sky), status);
V_ = oskar_mem_float_const(oskar_sky_V_const(sky), status);
ref_ = oskar_mem_float_const(oskar_sky_reference_freq_hz_const(sky), status);
sp_ = oskar_mem_float_const(oskar_sky_spectral_index_const(sky), status);
rm_ = oskar_mem_float_const(oskar_sky_rotation_measure_rad_const(sky), status);
maj_ = oskar_mem_float_const(oskar_sky_fwhm_major_rad_const(sky), status);
min_ = oskar_mem_float_const(oskar_sky_fwhm_minor_rad_const(sky), status);
pa_ = oskar_mem_float_const(oskar_sky_position_angle_rad_const(sky), status);
for (s = 0; s < num_sources; ++s)
{
fprintf(file, "% 11.6f,% 11.6f,% 12.6e,% 12.6e,% 12.6e,% 12.6e,"
"% 12.6e,% 12.6e,% 12.6e,% 12.6e,% 12.6e,% 11.6f\n",
ra_[s] * RAD2DEG, dec_[s] * RAD2DEG,
I_[s], Q_[s], U_[s], V_[s], ref_[s], sp_[s], rm_[s],
maj_[s] * RAD2ARCSEC, min_[s] * RAD2ARCSEC,
pa_[s] * RAD2DEG);
}
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
}
fclose(file);
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/imager/src/private_imager_update_plane_dft.c
|
/*
* Copyright (c) 2016-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include "imager/private_imager.h"
#include "imager/private_imager_update_plane_dft.h"
#include "imager/oskar_imager.h"
#include "math/oskar_cmath.h"
#include "math/oskar_dft_c2r.h"
#include "utility/oskar_device_utils.h"
#include "utility/oskar_thread.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
static void* run_blocks(void* arg);
struct ThreadArgs
{
oskar_Imager* h;
oskar_Mem* plane;
int thread_id, num_vis;
};
typedef struct ThreadArgs ThreadArgs;
void oskar_imager_update_plane_dft(oskar_Imager* h, size_t num_vis,
const oskar_Mem* uu, const oskar_Mem* vv, const oskar_Mem* ww,
const oskar_Mem* amps, const oskar_Mem* weight, oskar_Mem* plane,
double* plane_norm, int* status)
{
size_t i, num_pixels, num_threads;
oskar_Thread** threads = 0;
ThreadArgs* args = 0;
if (*status) return;
/* Check the image plane. */
num_pixels = (size_t) h->image_size;
num_pixels *= num_pixels;
if (oskar_mem_precision(plane) != h->imager_prec)
*status = OSKAR_ERR_TYPE_MISMATCH;
if (oskar_mem_is_complex(plane) || oskar_mem_is_matrix(plane))
*status = OSKAR_ERR_BAD_DATA_TYPE;
if (oskar_mem_length(plane) < num_pixels)
oskar_mem_realloc(plane, num_pixels, status);
if (*status) return;
/* Copy visibility data to each device. */
num_threads = (size_t) (h->num_devices);
for (i = 0; i < num_threads; ++i)
{
if (i < (size_t) (h->num_gpus))
oskar_device_set(h->gpu_ids[i], status);
oskar_mem_copy(h->d[i].uu, uu, status);
oskar_mem_copy(h->d[i].vv, vv, status);
oskar_mem_copy(h->d[i].amp, amps, status);
oskar_mem_copy(h->d[i].weight, weight, status);
if (h->algorithm == OSKAR_ALGORITHM_DFT_3D)
oskar_mem_copy(h->d[i].ww, ww, status);
}
/* Set up worker threads. */
threads = (oskar_Thread**) calloc(num_threads, sizeof(oskar_Thread*));
args = (ThreadArgs*) calloc(num_threads, sizeof(ThreadArgs));
for (i = 0; i < num_threads; ++i)
{
args[i].h = h;
args[i].thread_id = (int) i;
args[i].num_vis = (int) num_vis;
args[i].plane = plane;
}
/* Set status code. */
h->status = *status;
/* Start the worker threads. */
h->i_block = 0;
for (i = 0; i < num_threads; ++i)
threads[i] = oskar_thread_create(run_blocks, (void*)&args[i], 0);
/* Wait for worker threads to finish. */
for (i = 0; i < num_threads; ++i)
{
oskar_thread_join(threads[i]);
oskar_thread_free(threads[i]);
}
free(threads);
free(args);
/* Get status code. */
*status = h->status;
/* Update normalisation. */
if (oskar_mem_precision(weight) == OSKAR_DOUBLE)
{
const double* w;
w = oskar_mem_double_const(weight, status);
for (i = 0; i < num_vis; ++i) *plane_norm += w[i];
}
else
{
const float* w;
w = oskar_mem_float_const(weight, status);
for (i = 0; i < num_vis; ++i) *plane_norm += w[i];
}
}
static void* run_blocks(void* arg)
{
oskar_Imager* h;
oskar_Mem *t, *plane;
DeviceData* d;
size_t max_block_size, num_pixels;
const size_t smallest = 1024, largest = 65536;
int i_block, thread_id, num_blocks, num_vis;
int *status;
/* Get thread function arguments. */
h = ((ThreadArgs*)arg)->h;
thread_id = ((ThreadArgs*)arg)->thread_id;
num_vis = ((ThreadArgs*)arg)->num_vis;
plane = ((ThreadArgs*)arg)->plane;
status = &(h->status);
/* Set the device used by the thread. */
d = &h->d[thread_id];
if (thread_id < h->num_gpus)
oskar_device_set(h->gpu_ids[thread_id], status);
#ifdef _OPENMP
/* Disable nested parallelism. */
omp_set_nested(0);
omp_set_num_threads(1);
#endif
/* Pointer to output block. */
t = oskar_mem_create_alias(0, 0, 0, status);
/* Calculate the maximum pixel block size, and number of blocks. */
num_pixels = h->image_size * h->image_size;
max_block_size = num_pixels / h->num_devices;
max_block_size = ((max_block_size + smallest - 1) / smallest) * smallest;
if (max_block_size > largest) max_block_size = largest;
if (max_block_size < smallest) max_block_size = smallest;
num_blocks = (int) ((num_pixels + max_block_size - 1) / max_block_size);
/* Loop until all blocks are done. */
for (;;)
{
size_t block_size, block_start;
/* Get a unique block index. */
oskar_mutex_lock(h->mutex);
i_block = (h->i_block)++;
oskar_mutex_unlock(h->mutex);
if ((i_block >= num_blocks) || *status) break;
/* Calculate the block size. */
block_start = i_block * max_block_size;
block_size = num_pixels - block_start;
if (block_size > max_block_size) block_size = max_block_size;
/* Copy the l,m,n positions for the block. */
if (oskar_mem_length(d->l) < block_size)
oskar_mem_realloc(d->l, block_size, status);
oskar_mem_copy_contents(d->l, h->l, 0, block_start,
block_size, status);
if (oskar_mem_length(d->m) < block_size)
oskar_mem_realloc(d->m, block_size, status);
oskar_mem_copy_contents(d->m, h->m, 0, block_start,
block_size, status);
if (h->algorithm == OSKAR_ALGORITHM_DFT_3D)
{
if (oskar_mem_length(d->n) < block_size)
oskar_mem_realloc(d->n, block_size, status);
oskar_mem_copy_contents(d->n, h->n, 0, block_start,
block_size, status);
}
/* Run DFT for the block. */
oskar_dft_c2r(num_vis, 2.0 * M_PI, d->uu, d->vv, d->ww,
d->amp, d->weight, (int) block_size,
d->l, d->m, d->n, d->block_dev, status);
/* Copy data to the host and add to existing pixels. */
oskar_mem_copy(d->block_cpu, d->block_dev, status);
oskar_mem_set_alias(t, plane, block_start, block_size, status);
oskar_mem_add(t, t, d->block_cpu, block_size, status);
}
oskar_mem_free(t, status);
return 0;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/math/src/oskar_evaluate_image_lm_grid.c
|
/*
* Copyright (c) 2012-2016, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "math/oskar_evaluate_image_lm_grid.h"
#include "math/oskar_linspace.h"
#include <math.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
/* oskar_Mem wrapper */
void oskar_evaluate_image_lm_grid(oskar_Mem* l, oskar_Mem* m, int nl, int nm,
double fov_lon, double fov_lat, int* status)
{
int type, loc;
if (*status) return;
type = oskar_mem_type(l);
if (oskar_mem_type(m) != type) {
*status = OSKAR_ERR_TYPE_MISMATCH;
return;
}
loc = oskar_mem_location(l);
if (oskar_mem_location(m) != loc) {
*status = OSKAR_ERR_LOCATION_MISMATCH;
return;
}
if (loc == OSKAR_CPU)
{
if (type == OSKAR_DOUBLE)
{
double* l_ = oskar_mem_double(l, status);
double* m_ = oskar_mem_double(m, status);
oskar_evaluate_image_lm_grid_d(nl, nm, fov_lon, fov_lat, l_, m_);
}
else if (type == OSKAR_SINGLE)
{
float* l_ = oskar_mem_float(l, status);
float* m_ = oskar_mem_float(m, status);
oskar_evaluate_image_lm_grid_f(nl, nm, (float)fov_lon,
(float)fov_lat, l_, m_);
}
else
{
*status = OSKAR_ERR_BAD_DATA_TYPE;
return;
}
}
else if (loc == OSKAR_GPU)
{
/* There is currently no need for a GPU version of this function */
*status = OSKAR_ERR_BAD_LOCATION;
return;
}
else
{
*status = OSKAR_ERR_BAD_LOCATION;
return;
}
}
/* Single precision. */
void oskar_evaluate_image_lm_grid_f(int num_l, int num_m,
float fov_lon, float fov_lat, float* grid_l, float* grid_m)
{
int i, j, p;
float l_max, m_max, *l, *m, r;
/* Allocate temporary memory for vectors. */
l = malloc(num_l * sizeof(float));
m = malloc(num_m * sizeof(float));
/* Set up the grid boundaries. */
l_max = sin(0.5 * fov_lon);
m_max = sin(0.5 * fov_lat);
/* Create the axis vectors. */
oskar_linspace_f(l, l_max, -l_max, num_l); /* FITS convention. */
oskar_linspace_f(m, -m_max, m_max, num_m);
/* Slowest varying is m, fastest varying is l. */
for (j = 0, p = 0; j < num_m; ++j)
{
for (i = 0; i < num_l; ++i, ++p)
{
r = sqrtf(l[i]*l[i] + m[j]*m[j]);
if (r > 1.0f)
{
grid_l[p] = sqrtf(-1.0f); /* NAN */
grid_m[p] = sqrtf(-1.0f); /* NAN */
}
else
{
grid_l[p] = l[i];
grid_m[p] = m[j];
}
}
}
/* Free temporary memory. */
free(l);
free(m);
}
/* Double precision. */
void oskar_evaluate_image_lm_grid_d(int num_l, int num_m,
double fov_lon, double fov_lat, double* grid_l, double* grid_m)
{
int i, j, p;
double l_max, m_max, *l, *m, r;
/* Allocate temporary memory for vectors. */
l = malloc(num_l * sizeof(double));
m = malloc(num_m * sizeof(double));
/* Set up the grid boundaries. */
l_max = sin(0.5 * fov_lon);
m_max = sin(0.5 * fov_lat);
/* Create the axis vectors. */
oskar_linspace_d(l, l_max, -l_max, num_l); /* FITS convention. */
oskar_linspace_d(m, -m_max, m_max, num_m);
/* Slowest varying is m, fastest varying is l. */
for (j = 0, p = 0; j < num_m; ++j)
{
for (i = 0; i < num_l; ++i, ++p)
{
r = sqrt(l[i]*l[i] + m[j]*m[j]);
if (r > 1.0)
{
grid_l[p] = sqrtf(-1.0f); /* NAN */
grid_m[p] = sqrtf(-1.0f); /* NAN */
}
else
{
grid_l[p] = l[i];
grid_m[p] = m[j];
}
}
}
/* Free temporary memory. */
free(l);
free(m);
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/convert/oskar_convert_ecef_to_station_uvw_cuda.h
|
<reponame>davepallot/OSKAR<filename>oskar/convert/oskar_convert_ecef_to_station_uvw_cuda.h
/*
* Copyright (c) 2013-2014, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OSKAR_CONVERT_ECEF_TO_STATION_UVW_CUDA_H_
#define OSKAR_CONVERT_ECEF_TO_STATION_UVW_CUDA_H_
/**
* @file oskar_convert_ecef_to_station_uvw_cuda.h
*/
#include <oskar_global.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief
* Transforms station (x,y,z) coordinates to (u,v,w) coordinates using CUDA
* (single precision).
*
* @details
* Given the hour angle and declination of the phase tracking centre, this CUDA
* function transforms the station (x,y,z) coordinates to (u,v,w) coordinates.
*
* @param[in] num_stations The size of the station coordinate arrays.
* @param[in] d_x Input station x coordinates (ECEF or related frame).
* @param[in] d_y Input station y coordinates (ECEF or related frame).
* @param[in] d_z Input station z coordinates (ECEF or related frame).
* @param[in] ha0_rad The Hour Angle of the phase centre, in radians.
* @param[in] dec0_rad The Declination of the phase centre, in radians.
* @param[out] d_u Output station u coordinates.
* @param[out] d_v Output station v coordinates.
* @param[out] d_w Output station w coordinates.
*/
OSKAR_EXPORT
void oskar_convert_ecef_to_station_uvw_cuda_f(int num_stations,
const float* d_x, const float* d_y, const float* d_z,
float ha0_rad, float dec0_rad, float* d_u, float* d_v, float* d_w);
/**
* @brief
* Transforms station (x,y,z) coordinates to (u,v,w) coordinates using CUDA
* (double precision).
*
* @details
* Given the hour angle and declination of the phase tracking centre, this CUDA
* function transforms the station (x,y,z) coordinates to (u,v,w) coordinates.
*
* @param[in] num_stations The size of the station coordinate arrays.
* @param[in] d_x Input station x coordinates (ECEF or related frame).
* @param[in] d_y Input station y coordinates (ECEF or related frame).
* @param[in] d_z Input station z coordinates (ECEF or related frame).
* @param[in] ha0_rad The Hour Angle of the phase centre, in radians.
* @param[in] dec0_rad The Declination of the phase centre, in radians.
* @param[out] d_u Output station u coordinates.
* @param[out] d_v Output station v coordinates.
* @param[out] d_w Output station w coordinates.
*/
OSKAR_EXPORT
void oskar_convert_ecef_to_station_uvw_cuda_d(int num_stations,
const double* d_x, const double* d_y, const double* d_z,
double ha0_rad, double dec0_rad, double* d_u, double* d_v, double* d_w);
#ifdef __CUDACC__
/* Kernels. */
__global__
void oskar_convert_ecef_to_station_uvw_cudak_f(const int num_stations,
const float* restrict x, const float* restrict y,
const float* restrict z, const float sin_ha0,
const float cos_ha0, const float sin_dec0, const float cos_dec0,
float* restrict u, float* restrict v, float* restrict w);
__global__
void oskar_convert_ecef_to_station_uvw_cudak_d(const int num_stations,
const double* restrict x, const double* restrict y,
const double* restrict z, const double sin_ha0,
const double cos_ha0, const double sin_dec0, const double cos_dec0,
double* restrict u, double* restrict v, double* restrict w);
#endif /* __CUDACC__ */
#ifdef __cplusplus
}
#endif
#endif /* OSKAR_CONVERT_ECEF_TO_STATION_UVW_CUDA_H_ */
|
davepallot/OSKAR
|
oskar/utility/src/oskar_getline.c
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2011-2013, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "utility/oskar_getline.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
int oskar_getline(char** lineptr, size_t* n, FILE* stream)
{
/* Initialise the byte counter. */
size_t size = 0;
int c;
/* Check if buffer is empty. */
if (*n == 0 || *lineptr == 0)
{
*n = 80;
*lineptr = (char*)malloc(*n);
if (*lineptr == 0)
return OSKAR_ERR_MEMORY_ALLOC_FAILURE;
}
/* Read in the line. */
for (;;)
{
/* Get the character. */
c = getc(stream);
/* Check if end-of-file or end-of-line has been reached. */
if (c == EOF || c == '\n')
break;
/* Allocate space for size+1 bytes (including NULL terminator). */
if (size + 1 >= *n)
{
void *t;
/* Double the length of the buffer. */
*n = 2 * *n + 1;
t = realloc(*lineptr, *n);
if (!t)
return OSKAR_ERR_MEMORY_ALLOC_FAILURE;
*lineptr = (char*)t;
}
/* Store the character. */
(*lineptr)[size++] = c;
}
/* Add a NULL terminator. */
(*lineptr)[size] = '\0';
/* Return the number of characters read, or EOF as appropriate. */
if (c == EOF && size == 0)
return OSKAR_ERR_EOF;
return (int) size;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
oskar/mem/src/oskar_mem_set_value_real.c
|
<reponame>davepallot/OSKAR
/*
* Copyright (c) 2012-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "mem/oskar_mem.h"
#include "mem/oskar_mem_set_value_real_cuda.h"
#include "mem/private_mem.h"
#include "utility/oskar_cl_utils.h"
#ifdef __cplusplus
extern "C" {
#endif
void oskar_mem_set_value_real(oskar_Mem* mem, double val,
size_t offset, size_t length, int* status)
{
size_t i, n;
int type, location;
/* Check if safe to proceed. */
if (*status) return;
/* Get the data type, location, and number of elements. */
type = mem->type;
location = mem->location;
n = length;
if (offset == 0 && length == 0)
{
n = mem->num_elements;
}
if (location == OSKAR_CPU)
{
switch (type)
{
case OSKAR_DOUBLE:
{
double *v;
v = (double*)(mem->data) + offset;
for (i = 0; i < n; ++i) v[i] = val;
break;
}
case OSKAR_DOUBLE_COMPLEX:
{
double2 *v;
v = (double2*)(mem->data) + offset;
for (i = 0; i < n; ++i)
{
v[i].x = val;
v[i].y = 0.0;
}
break;
}
case OSKAR_DOUBLE_COMPLEX_MATRIX:
{
double4c d;
double4c *v;
v = (double4c*)(mem->data) + offset;
for (i = 0; i < n; ++i)
{
d.a.x = val;
d.a.y = 0.0;
d.b.x = 0.0;
d.b.y = 0.0;
d.c.x = 0.0;
d.c.y = 0.0;
d.d.x = val;
d.d.y = 0.0;
v[i] = d;
}
break;
}
case OSKAR_SINGLE:
{
float *v;
v = (float*)(mem->data) + offset;
for (i = 0; i < n; ++i) v[i] = (float)val;
break;
}
case OSKAR_SINGLE_COMPLEX:
{
float2 *v;
v = (float2*)(mem->data) + offset;
for (i = 0; i < n; ++i)
{
v[i].x = (float)val;
v[i].y = 0.0f;
}
break;
}
case OSKAR_SINGLE_COMPLEX_MATRIX:
{
float4c d;
float4c *v;
v = (float4c*)(mem->data) + offset;
for (i = 0; i < n; ++i)
{
d.a.x = (float)val;
d.a.y = 0.0f;
d.b.x = 0.0f;
d.b.y = 0.0f;
d.c.x = 0.0f;
d.c.y = 0.0f;
d.d.x = (float)val;
d.d.y = 0.0f;
v[i] = d;
}
break;
}
default:
*status = OSKAR_ERR_BAD_DATA_TYPE;
break;
}
}
else if (location == OSKAR_GPU)
{
#ifdef OSKAR_HAVE_CUDA
switch (type)
{
case OSKAR_DOUBLE:
oskar_mem_set_value_real_cuda_r_d((int)n,
(double*)(mem->data) + offset, val);
break;
case OSKAR_DOUBLE_COMPLEX:
oskar_mem_set_value_real_cuda_c_d((int)n,
(double2*)(mem->data) + offset, val);
break;
case OSKAR_DOUBLE_COMPLEX_MATRIX:
oskar_mem_set_value_real_cuda_m_d((int)n,
(double4c*)(mem->data) + offset, val);
break;
case OSKAR_SINGLE:
oskar_mem_set_value_real_cuda_r_f((int)n,
(float*)(mem->data) + offset, (float)val);
break;
case OSKAR_SINGLE_COMPLEX:
oskar_mem_set_value_real_cuda_c_f((int)n,
(float2*)(mem->data) + offset, (float)val);
break;
case OSKAR_SINGLE_COMPLEX_MATRIX:
oskar_mem_set_value_real_cuda_m_f((int)n,
(float4c*)(mem->data) + offset, (float)val);
break;
default:
*status = OSKAR_ERR_BAD_DATA_TYPE;
break;
}
#else
*status = OSKAR_ERR_CUDA_NOT_AVAILABLE;
#endif
}
else if (location & OSKAR_CL)
{
#ifdef OSKAR_HAVE_OPENCL
cl_device_type dev_type;
cl_event event;
cl_kernel k = 0;
cl_int is_gpu, error, n_in, off;
cl_uint arg = 0;
/* Get the appropriate kernel. */
/*
* NOTE: Don't use clEnqueueFillBuffer(),
* as this is currently broken on macOS.
*/
clGetDeviceInfo(oskar_cl_device_id(),
CL_DEVICE_TYPE, sizeof(cl_device_type), &dev_type, NULL);
is_gpu = dev_type & CL_DEVICE_TYPE_GPU;
const size_t local_size = is_gpu ? 256 : 128;
switch (type)
{
case OSKAR_DOUBLE:
k = oskar_cl_kernel("mem_set_value_real_r_double");
break;
case OSKAR_DOUBLE_COMPLEX:
k = oskar_cl_kernel("mem_set_value_real_c_double");
break;
case OSKAR_DOUBLE_COMPLEX_MATRIX:
k = oskar_cl_kernel("mem_set_value_real_m_double");
break;
case OSKAR_SINGLE:
k = oskar_cl_kernel("mem_set_value_real_r_float");
break;
case OSKAR_SINGLE_COMPLEX:
k = oskar_cl_kernel("mem_set_value_real_c_float");
break;
case OSKAR_SINGLE_COMPLEX_MATRIX:
k = oskar_cl_kernel("mem_set_value_real_m_float");
break;
default:
*status = OSKAR_ERR_BAD_DATA_TYPE;
break;
}
/* Set kernel arguments. */
if (k)
{
n_in = (cl_int) (mem->num_elements);
off = (cl_int) offset;
error = clSetKernelArg(k, arg++, sizeof(cl_int), &n_in);
error |= clSetKernelArg(k, arg++, sizeof(cl_mem),
oskar_mem_cl_buffer_const(mem, status));
error |= clSetKernelArg(k, arg++, sizeof(cl_int), &off);
if (oskar_mem_precision(mem) == OSKAR_SINGLE)
{
cl_float v = (cl_float) val;
error |= clSetKernelArg(k, arg++, sizeof(cl_float), &v);
}
else
{
cl_double v = (cl_double) val;
error |= clSetKernelArg(k, arg++, sizeof(cl_double), &v);
}
if (!*status && error != CL_SUCCESS)
*status = OSKAR_ERR_INVALID_ARGUMENT;
if (!*status)
{
/* Launch kernel on current command queue. */
const size_t global_size = ((n + local_size - 1) /
local_size) * local_size;
error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1,
NULL, &global_size, &local_size, 0, NULL, &event);
if (error != CL_SUCCESS)
*status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE;
}
}
else
{
*status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE;
}
#else
*status = OSKAR_ERR_OPENCL_NOT_AVAILABLE;
#endif
}
else
*status = OSKAR_ERR_BAD_LOCATION;
}
#ifdef __cplusplus
}
#endif
|
davepallot/OSKAR
|
python/oskar/src/oskar_imager_lib.c
|
/*
* Copyright (c) 2014-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <Python.h>
#include <oskar.h>
#include <stdlib.h>
#include <string.h>
/* http://docs.scipy.org/doc/numpy-dev/reference/c-api.deprecations.html */
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
static const char module_doc[] =
"This module provides an interface to the OSKAR imager.";
static const char name[] = "oskar_Imager";
static void* get_handle(PyObject* capsule, const char* name)
{
void* h = 0;
if (!PyCapsule_CheckExact(capsule))
{
PyErr_SetString(PyExc_RuntimeError, "Object is not a PyCapsule.");
return 0;
}
if (!(h = PyCapsule_GetPointer(capsule, name)))
{
PyErr_Format(PyExc_RuntimeError, "Capsule is not of type %s.", name);
return 0;
}
return h;
}
static void imager_free(PyObject* capsule)
{
int status = 0;
oskar_imager_free((oskar_Imager*) get_handle(capsule, name), &status);
}
static int numpy_type_from_oskar(int type)
{
switch (type)
{
case OSKAR_INT: return NPY_INT;
case OSKAR_SINGLE: return NPY_FLOAT;
case OSKAR_DOUBLE: return NPY_DOUBLE;
case OSKAR_SINGLE_COMPLEX: return NPY_CFLOAT;
case OSKAR_DOUBLE_COMPLEX: return NPY_CDOUBLE;
}
return 0;
}
static int oskar_type_from_numpy(PyArrayObject* arr)
{
switch (PyArray_TYPE(arr))
{
case NPY_INT: return OSKAR_INT;
case NPY_FLOAT: return OSKAR_SINGLE;
case NPY_DOUBLE: return OSKAR_DOUBLE;
case NPY_CFLOAT: return OSKAR_SINGLE_COMPLEX;
case NPY_CDOUBLE: return OSKAR_DOUBLE_COMPLEX;
}
return 0;
}
static PyObject* algorithm(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("s", oskar_imager_algorithm(h));
}
static PyObject* capsule_name(PyObject* self, PyObject* args)
{
PyObject *capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!PyCapsule_CheckExact(capsule))
{
PyErr_SetString(PyExc_RuntimeError, "Object is not a PyCapsule.");
return 0;
}
return Py_BuildValue("s", PyCapsule_GetName(capsule));
}
static PyObject* cellsize(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_cellsize(h));
}
static PyObject* channel_snapshots(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int flag = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
flag = oskar_imager_channel_snapshots(h);
return Py_BuildValue("O", flag ? Py_True : Py_False);
}
static PyObject* check_init(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
Py_BEGIN_ALLOW_THREADS
oskar_imager_check_init(h, &status);
Py_END_ALLOW_THREADS
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_check_init() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* coords_only(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int flag;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
flag = oskar_imager_coords_only(h);
return Py_BuildValue("O", flag ? Py_True : Py_False);
}
static PyObject* create(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0, prec = 0;
const char* type;
if (!PyArg_ParseTuple(args, "s", &type)) return 0;
prec = (type[0] == 'S' || type[0] == 's') ? OSKAR_SINGLE : OSKAR_DOUBLE;
h = oskar_imager_create(prec, &status);
capsule = PyCapsule_New((void*)h, name, (PyCapsule_Destructor)imager_free);
return Py_BuildValue("N", capsule); /* Don't increment refcount. */
}
static oskar_Mem** create_cube(oskar_Imager* h, int plane_size, int plane_type,
PyObject* dict, const char* key, int num_planes, int* status)
{
oskar_Mem *alias_tmp, **cube_c;
PyArrayObject *cube;
int i, plane_elem;
npy_intp dims[3];
/* Create a Python array to hold the images. */
plane_elem = plane_size * plane_size;
dims[0] = num_planes;
dims[1] = plane_size;
dims[2] = plane_size;
cube = (PyArrayObject*)PyArray_SimpleNew(3, dims,
numpy_type_from_oskar(plane_type));
if (!cube) return 0;
/* Store the array in the dictionary. */
PyDict_SetItemString(dict, key, (PyObject*)cube);
/* Create the array of pointers to each plane for the imager. */
alias_tmp = oskar_mem_create_alias_from_raw(PyArray_DATA(cube),
plane_type, OSKAR_CPU, PyArray_SIZE(cube), status);
cube_c = calloc(num_planes, sizeof(oskar_Mem*));
for (i = 0; i < num_planes; ++i)
cube_c[i] = oskar_mem_create_alias(alias_tmp,
i * plane_elem, plane_elem, status);
oskar_mem_free(alias_tmp, status);
return cube_c;
}
static PyObject* fft_on_gpu(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("O", oskar_imager_fft_on_gpu(h) ? Py_True : Py_False);
}
static PyObject* finalise(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *capsule = 0, *dict = 0;
oskar_Mem **grids_c = 0, **images_c = 0;
int i = 0, return_images = 0, return_grids = 0, status = 0;
if (!PyArg_ParseTuple(args, "Oii",
&capsule, &return_images, &return_grids))
return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
/* Create a dictionary to return any outputs. */
dict = PyDict_New();
/* Check if we need to return images. */
if (return_images > 0)
{
images_c = create_cube(h, oskar_imager_image_size(h),
oskar_imager_precision(h), dict, "images", return_images,
&status);
if (!images_c) goto fail;
}
/* Check if we need to return grids. */
if (return_grids > 0)
{
grids_c = create_cube(h, oskar_imager_plane_size(h),
oskar_imager_plane_type(h), dict, "grids", return_grids,
&status);
if (!grids_c) goto fail;
}
/* Finalise. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_finalise(h, return_images, images_c,
return_grids, grids_c, &status);
Py_END_ALLOW_THREADS
/* Free handles. */
if (grids_c)
{
for (i = 0; i < return_grids; ++i)
oskar_mem_free(grids_c[i], &status);
free(grids_c);
grids_c = 0;
}
if (images_c)
{
for (i = 0; i < return_images; ++i)
oskar_mem_free(images_c[i], &status);
free(images_c);
images_c = 0;
}
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_finalise() failed with code %d (%s).",
status, oskar_get_error_string(status));
goto fail;
}
return Py_BuildValue("N", dict); /* Don't increment refcount. */
fail:
Py_XDECREF(dict);
if (grids_c)
{
for (i = 0; i < return_grids; ++i)
oskar_mem_free(grids_c[i], &status);
free(grids_c);
grids_c = 0;
}
if (images_c)
{
for (i = 0; i < return_images; ++i)
oskar_mem_free(images_c[i], &status);
free(images_c);
images_c = 0;
}
return 0;
}
static PyObject* finalise_plane(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *obj[] = {0, 0};
PyArrayObject* plane = 0;
oskar_Mem* plane_c = 0;
int status = 0;
double plane_norm = 0.0;
if (!PyArg_ParseTuple(args, "OOd", &obj[0], &obj[1], &plane_norm))
return 0;
if (!(h = (oskar_Imager*) get_handle(obj[0], name))) return 0;
/* Get the supplied plane. */
plane = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_OUT_ARRAY);
if (!plane) goto fail;
plane_c = oskar_mem_create_alias_from_raw(PyArray_DATA(plane),
oskar_type_from_numpy(plane), OSKAR_CPU,
PyArray_SIZE(plane), &status);
/* Finalise the plane. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_finalise_plane(h, plane_c, plane_norm, &status);
Py_END_ALLOW_THREADS
oskar_mem_free(plane_c, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_finalise_plane() failed with code %d (%s).",
status, oskar_get_error_string(status));
goto fail;
}
Py_XDECREF(plane);
return Py_BuildValue("");
fail:
Py_XDECREF(plane);
return 0;
}
static PyObject* fov(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_fov(h));
}
static PyObject* freq_max_hz(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_freq_max_hz(h));
}
static PyObject* freq_min_hz(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_freq_min_hz(h));
}
static PyObject* generate_w_kernels_on_gpu(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("O",
oskar_imager_generate_w_kernels_on_gpu(h) ? Py_True : Py_False);
}
static PyObject* image_size(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("i", oskar_imager_image_size(h));
}
static PyObject* image_type(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("s", oskar_imager_image_type(h));
}
static PyObject* input_file(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *capsule = 0, *list = 0;
int i, num_files = 0;
char* const* files;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
/* Return the input file name or list of input file names. */
num_files = oskar_imager_num_input_files(h);
files = oskar_imager_input_files(h);
if (num_files == 0) return Py_BuildValue("");
if (num_files == 1) return Py_BuildValue("s", files[0]);
list = PyList_New(num_files);
for (i = 0; i < num_files; ++i)
{
PyList_SetItem(list, i, Py_BuildValue("s", files[i]));
}
return Py_BuildValue("N", list);
}
static PyObject* ms_column(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("s", oskar_imager_ms_column(h));
}
static PyObject* num_w_planes(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("i", oskar_imager_num_w_planes(h));
}
static PyObject* output_root(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("s", oskar_imager_output_root(h));
}
static PyObject* plane_size(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("i", oskar_imager_plane_size(h));
}
static PyObject* reset_cache(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_reset_cache(h, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_reset_cache() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* rotate_coords(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *obj[] = {0, 0, 0, 0};
oskar_Mem *uu_c, *vv_c, *ww_c;
PyArrayObject *uu = 0, *vv = 0, *ww = 0;
int status = 0;
size_t num_coords;
/* Parse inputs. */
if (!PyArg_ParseTuple(args, "OOOO", &obj[0], &obj[1], &obj[2], &obj[3]))
return 0;
if (!(h = (oskar_Imager*) get_handle(obj[0], name))) return 0;
/* Make sure input objects are arrays. Convert if required. */
uu = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_INOUT_ARRAY);
vv = (PyArrayObject*) PyArray_FROM_OF(obj[2], NPY_ARRAY_INOUT_ARRAY);
ww = (PyArrayObject*) PyArray_FROM_OF(obj[3], NPY_ARRAY_INOUT_ARRAY);
if (!uu || !vv || !ww)
goto fail;
/* Check dimensions. */
num_coords = (size_t) PyArray_SIZE(uu);
if (num_coords != (size_t) PyArray_SIZE(vv) ||
num_coords != (size_t) PyArray_SIZE(ww))
{
PyErr_SetString(PyExc_RuntimeError, "Data dimension mismatch.");
goto fail;
}
/* Pointers to arrays. */
uu_c = oskar_mem_create_alias_from_raw(PyArray_DATA(uu),
oskar_type_from_numpy(uu), OSKAR_CPU, num_coords, &status);
vv_c = oskar_mem_create_alias_from_raw(PyArray_DATA(vv),
oskar_type_from_numpy(vv), OSKAR_CPU, num_coords, &status);
ww_c = oskar_mem_create_alias_from_raw(PyArray_DATA(ww),
oskar_type_from_numpy(ww), OSKAR_CPU, num_coords, &status);
/* Rotate the baseline coordinates. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_rotate_coords(h,
num_coords, uu_c, vv_c, ww_c, uu_c, vv_c, ww_c);
Py_END_ALLOW_THREADS
oskar_mem_free(uu_c, &status);
oskar_mem_free(vv_c, &status);
oskar_mem_free(ww_c, &status);
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
return Py_BuildValue("");
fail:
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
return 0;
}
static PyObject* rotate_vis(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *obj[] = {0, 0, 0, 0, 0};
oskar_Mem *uu_c, *vv_c, *ww_c, *amp_c;
PyArrayObject *uu = 0, *vv = 0, *ww = 0, *amp = 0;
int status = 0;
size_t num_vis;
/* Parse inputs. */
if (!PyArg_ParseTuple(args, "OOOOO", &obj[0], &obj[1], &obj[2], &obj[3],
&obj[4]))
return 0;
if (!(h = (oskar_Imager*) get_handle(obj[0], name))) return 0;
/* Make sure input objects are arrays. Convert if required. */
uu = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_IN_ARRAY);
vv = (PyArrayObject*) PyArray_FROM_OF(obj[2], NPY_ARRAY_IN_ARRAY);
ww = (PyArrayObject*) PyArray_FROM_OF(obj[3], NPY_ARRAY_IN_ARRAY);
amp = (PyArrayObject*) PyArray_FROM_OF(obj[4], NPY_ARRAY_INOUT_ARRAY);
if (!uu || !vv || !ww || !amp)
goto fail;
/* Check dimensions. */
num_vis = (size_t) PyArray_SIZE(amp);
if (num_vis != (size_t) PyArray_SIZE(uu) ||
num_vis != (size_t) PyArray_SIZE(vv) ||
num_vis != (size_t) PyArray_SIZE(ww))
{
PyErr_SetString(PyExc_RuntimeError, "Data dimension mismatch.");
goto fail;
}
/* Pointers to arrays. */
uu_c = oskar_mem_create_alias_from_raw(PyArray_DATA(uu),
oskar_type_from_numpy(uu), OSKAR_CPU, num_vis, &status);
vv_c = oskar_mem_create_alias_from_raw(PyArray_DATA(vv),
oskar_type_from_numpy(vv), OSKAR_CPU, num_vis, &status);
ww_c = oskar_mem_create_alias_from_raw(PyArray_DATA(ww),
oskar_type_from_numpy(ww), OSKAR_CPU, num_vis, &status);
amp_c = oskar_mem_create_alias_from_raw(PyArray_DATA(amp),
oskar_type_from_numpy(amp), OSKAR_CPU, num_vis, &status);
/* Phase-rotate the visibility amplitudes. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_rotate_vis(h, num_vis, uu_c, vv_c, ww_c, amp_c);
Py_END_ALLOW_THREADS
oskar_mem_free(uu_c, &status);
oskar_mem_free(vv_c, &status);
oskar_mem_free(ww_c, &status);
oskar_mem_free(amp_c, &status);
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amp);
return Py_BuildValue("");
fail:
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amp);
return 0;
}
static PyObject* run(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *capsule = 0, *dict = 0;
oskar_Mem **grids_c = 0, **images_c = 0;
int i = 0, return_images = 0, return_grids = 0, status = 0;
if (!PyArg_ParseTuple(args, "Oii",
&capsule, &return_images, &return_grids))
return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
/* Create a dictionary to return any outputs. */
dict = PyDict_New();
/* Check if we need to return images. */
if (return_images > 0)
{
images_c = create_cube(h, oskar_imager_image_size(h),
oskar_imager_precision(h), dict, "images", return_images,
&status);
if (!images_c) goto fail;
}
/* Check if we need to return grids. */
if (return_grids > 0)
{
grids_c = create_cube(h, oskar_imager_plane_size(h),
oskar_imager_plane_type(h), dict, "grids", return_grids,
&status);
if (!grids_c) goto fail;
}
/* Run the imager. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_run(h, return_images, images_c,
return_grids, grids_c, &status);
Py_END_ALLOW_THREADS
/* Free handles. */
if (grids_c)
{
for (i = 0; i < return_grids; ++i)
oskar_mem_free(grids_c[i], &status);
free(grids_c);
grids_c = 0;
}
if (images_c)
{
for (i = 0; i < return_images; ++i)
oskar_mem_free(images_c[i], &status);
free(images_c);
images_c = 0;
}
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_run() failed with code %d (%s).",
status, oskar_get_error_string(status));
goto fail;
}
return Py_BuildValue("N", dict); /* Don't increment refcount. */
fail:
Py_XDECREF(dict);
if (grids_c)
{
for (i = 0; i < return_grids; ++i)
oskar_mem_free(grids_c[i], &status);
free(grids_c);
grids_c = 0;
}
if (images_c)
{
for (i = 0; i < return_images; ++i)
oskar_mem_free(images_c[i], &status);
free(images_c);
images_c = 0;
}
return 0;
}
static PyObject* scale_norm_with_num_input_files(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("O",
oskar_imager_scale_norm_with_num_input_files(h) ?
Py_True : Py_False);
}
static PyObject* set_algorithm(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0;
const char* type = 0;
if (!PyArg_ParseTuple(args, "Os", &capsule, &type)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_algorithm(h, type, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_set_algorithm() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* set_cellsize(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double cellsize = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &cellsize)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_cellsize(h, cellsize);
return Py_BuildValue("");
}
static PyObject* set_channel_snapshots(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int value = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_channel_snapshots(h, value);
return Py_BuildValue("");
}
static PyObject* set_coords_only(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int flag = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &flag)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_coords_only(h, flag);
return Py_BuildValue("");
}
static PyObject* set_default_direction(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_default_direction(h);
return Py_BuildValue("");
}
static PyObject* set_direction(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double ra = 0.0, dec = 0.0;
if (!PyArg_ParseTuple(args, "Odd", &capsule, &ra, &dec)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_direction(h, ra, dec);
return Py_BuildValue("");
}
static PyObject* set_fft_on_gpu(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int value = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_fft_on_gpu(h, value);
return Py_BuildValue("");
}
static PyObject* set_fov(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double fov = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &fov)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_fov(h, fov);
return Py_BuildValue("");
}
static PyObject* set_freq_max_hz(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double value = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_freq_max_hz(h, value);
return Py_BuildValue("");
}
static PyObject* set_freq_min_hz(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double value = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_freq_min_hz(h, value);
return Py_BuildValue("");
}
static PyObject* set_generate_w_kernels_on_gpu(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int value = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_generate_w_kernels_on_gpu(h, value);
return Py_BuildValue("");
}
static PyObject* set_grid_kernel(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0, support = 0, oversample = 0;
const char* type = 0;
if (!PyArg_ParseTuple(args, "Osii", &capsule, &type, &support, &oversample))
return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_grid_kernel(h, type, support, oversample, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_set_grid_kernel() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* set_image_size(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int size = 0, status = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &size)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_image_size(h, size, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_set_image_size() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* set_image_type(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0;
const char* type = 0;
if (!PyArg_ParseTuple(args, "Os", &capsule, &type)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_image_type(h, type, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_set_image_type() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* set_input_file(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *capsule = 0, *list = 0;
int status = 0;
if (!PyArg_ParseTuple(args, "OO", &capsule, &list)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
/* Check to see if the list is really a list, or a string. */
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(list))
#else
if (PyString_Check(list))
#endif
{
#if PY_MAJOR_VERSION >= 3
const char* file = PyUnicode_AsUTF8(list);
#else
const char* file = PyString_AsString(list);
#endif
oskar_imager_set_input_files(h, 1, &file, &status);
return Py_BuildValue("i", status);
}
else if (PyList_Check(list))
{
int i, num_files;
const char** files = 0;
num_files = (int) PyList_Size(list);
files = (const char**) calloc(num_files, sizeof(const char*));
for (i = 0; i < num_files; ++i)
{
#if PY_MAJOR_VERSION >= 3
files[i] = PyUnicode_AsUTF8(PyList_GetItem(list, i));
#else
files[i] = PyString_AsString(PyList_GetItem(list, i));
#endif
}
oskar_imager_set_input_files(h, num_files, files, &status);
free(files);
return Py_BuildValue("i", status);
}
else
{
PyErr_SetString(PyExc_RuntimeError,
"Argument must be a string or list of strings.");
return 0;
}
}
static PyObject* set_ms_column(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0;
const char* column = 0;
if (!PyArg_ParseTuple(args, "Os", &capsule, &column)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_ms_column(h, column, &status);
return Py_BuildValue("i", status);
}
static PyObject* set_num_w_planes(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int num = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &num)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_num_w_planes(h, num);
return Py_BuildValue("");
}
static PyObject* set_output_root(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
const char* filename = 0;
if (!PyArg_ParseTuple(args, "Os", &capsule, &filename)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_output_root(h, filename);
return Py_BuildValue("");
}
static PyObject* set_scale_norm_with_num_input_files(PyObject* self,
PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int value = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_scale_norm_with_num_input_files(h, value);
return Py_BuildValue("");
}
static PyObject* set_size(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int size = 0, status = 0;
if (!PyArg_ParseTuple(args, "Oi", &capsule, &size)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_size(h, size, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_set_size() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* set_time_max_utc(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double value = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_time_max_utc(h, value);
return Py_BuildValue("");
}
static PyObject* set_time_min_utc(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double value = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_time_min_utc(h, value);
return Py_BuildValue("");
}
static PyObject* set_uv_filter_max(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double value = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_uv_filter_max(h, value);
return Py_BuildValue("");
}
static PyObject* set_uv_filter_min(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double value = 0.0;
if (!PyArg_ParseTuple(args, "Od", &capsule, &value)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_uv_filter_min(h, value);
return Py_BuildValue("");
}
static PyObject* set_vis_frequency(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int num = 0;
double ref = 0.0, inc = 0.0;
if (!PyArg_ParseTuple(args, "Oddi", &capsule, &ref, &inc, &num)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_vis_frequency(h, ref, inc, num);
return Py_BuildValue("");
}
static PyObject* set_vis_phase_centre(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
double ra = 0.0, dec = 0.0;
if (!PyArg_ParseTuple(args, "Odd", &capsule, &ra, &dec)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_vis_phase_centre(h, ra, dec);
return Py_BuildValue("");
}
static PyObject* set_weighting(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
int status = 0;
const char* type = 0;
if (!PyArg_ParseTuple(args, "Os", &capsule, &type)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
oskar_imager_set_weighting(h, type, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_set_weighting() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* size(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("i", oskar_imager_size(h));
}
static PyObject* time_max_utc(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_time_max_utc(h));
}
static PyObject* time_min_utc(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_time_min_utc(h));
}
static PyObject* update(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *obj[] = {0, 0, 0, 0, 0, 0, 0};
oskar_Mem *uu_c, *vv_c, *ww_c, *amp_c = 0, *weight_c, *time_centroid_c = 0;
PyArrayObject *uu = 0, *vv = 0, *ww = 0, *amps = 0;
PyArrayObject *weight = 0, *time_centroid = 0;
int start_chan = 0, end_chan = 0, num_pols = 1, status = 0;
size_t num_rows, num_weights;
/* Parse inputs. */
if (!PyArg_ParseTuple(args, "OOOOOOOiii", &obj[0],
&obj[1], &obj[2], &obj[3], &obj[4], &obj[5], &obj[6],
&start_chan, &end_chan, &num_pols))
return 0;
if (!(h = (oskar_Imager*) get_handle(obj[0], name))) return 0;
/* Make sure input objects are arrays. Convert if required. */
uu = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_IN_ARRAY);
vv = (PyArrayObject*) PyArray_FROM_OF(obj[2], NPY_ARRAY_IN_ARRAY);
ww = (PyArrayObject*) PyArray_FROM_OF(obj[3], NPY_ARRAY_IN_ARRAY);
if (!uu || !vv || !ww) goto fail;
/* Check if visibility amplitudes are present. */
if (obj[4] != Py_None)
{
amps = (PyArrayObject*) PyArray_FROM_OF(obj[4], NPY_ARRAY_IN_ARRAY);
if (!amps) goto fail;
/* Check visibility data are complex. */
if (!PyArray_ISCOMPLEX(amps))
{
PyErr_SetString(PyExc_RuntimeError,
"Input visibility data must be complex.");
goto fail;
}
}
/* Check if weights are present. */
if (obj[5] != Py_None)
{
weight = (PyArrayObject*) PyArray_FROM_OF(obj[5], NPY_ARRAY_IN_ARRAY);
if (!weight) goto fail;
}
/* Check if time centroid values are present. */
if (obj[6] != Py_None)
{
time_centroid = (PyArrayObject*) PyArray_FROM_OTF(obj[6],
NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);
if (!time_centroid) goto fail;
}
/* Check if visibilities are required but not present. */
if (!oskar_imager_coords_only(h) && !amps)
{
PyErr_SetString(PyExc_RuntimeError, "Visibility data not present and "
"imager not in coordinate-only mode.");
goto fail;
}
/* Check number of polarisations. */
if (num_pols != 1 && num_pols != 4)
{
PyErr_SetString(PyExc_ValueError,
"Unknown number of polarisations. Must be 1 or 4.");
goto fail;
}
/* Get dimensions. */
num_rows = (size_t) PyArray_SIZE(uu);
if (num_rows != (size_t) PyArray_SIZE(vv) ||
num_rows != (size_t) PyArray_SIZE(ww))
{
PyErr_SetString(PyExc_RuntimeError,
"Coordinate data dimension mismatch.");
goto fail;
}
num_weights = num_rows * num_pols;
/* Pointers to input arrays. */
uu_c = oskar_mem_create_alias_from_raw(PyArray_DATA(uu),
oskar_type_from_numpy(uu), OSKAR_CPU, num_rows, &status);
vv_c = oskar_mem_create_alias_from_raw(PyArray_DATA(vv),
oskar_type_from_numpy(vv), OSKAR_CPU, num_rows, &status);
ww_c = oskar_mem_create_alias_from_raw(PyArray_DATA(ww),
oskar_type_from_numpy(ww), OSKAR_CPU, num_rows, &status);
if (amps)
{
int vis_type;
size_t num_vis;
vis_type = oskar_type_from_numpy(amps);
num_vis = num_rows * (1 + end_chan - start_chan);
if (num_pols == 4) vis_type |= OSKAR_MATRIX;
amp_c = oskar_mem_create_alias_from_raw(PyArray_DATA(amps),
vis_type, OSKAR_CPU, num_vis, &status);
}
if (weight)
{
weight_c = oskar_mem_create_alias_from_raw(PyArray_DATA(weight),
oskar_type_from_numpy(weight), OSKAR_CPU, num_weights, &status);
}
else
{
/* Set weights to 1 if not supplied. */
weight_c = oskar_mem_create(oskar_imager_precision(h), OSKAR_CPU,
num_weights, &status);
oskar_mem_set_value_real(weight_c, 1.0, 0, num_weights, &status);
}
if (time_centroid)
{
time_centroid_c = oskar_mem_create_alias_from_raw(
PyArray_DATA(time_centroid),
oskar_type_from_numpy(time_centroid),
OSKAR_CPU, num_rows, &status);
}
/* Update the imager with the supplied visibility data. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_update(h, num_rows, start_chan, end_chan, num_pols,
uu_c, vv_c, ww_c, amp_c, weight_c, time_centroid_c, &status);
Py_END_ALLOW_THREADS
oskar_mem_free(uu_c, &status);
oskar_mem_free(vv_c, &status);
oskar_mem_free(ww_c, &status);
oskar_mem_free(amp_c, &status);
oskar_mem_free(weight_c, &status);
oskar_mem_free(time_centroid_c, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_update() failed with code %d (%s).", status,
oskar_get_error_string(status));
goto fail;
}
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amps);
Py_XDECREF(weight);
Py_XDECREF(time_centroid);
return Py_BuildValue("");
fail:
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amps);
Py_XDECREF(weight);
Py_XDECREF(time_centroid);
return 0;
}
static PyObject* update_from_block(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
oskar_VisBlock* block = 0;
oskar_VisHeader* header = 0;
PyObject *obj[] = {0, 0, 0};
int status = 0;
/* Parse inputs. */
if (!PyArg_ParseTuple(args, "OOO", &obj[0], &obj[1], &obj[2]))
return 0;
if (!(h = (oskar_Imager*) get_handle(obj[0], name))) return 0;
if (!(header = (oskar_VisHeader*) get_handle(obj[1], "oskar_VisHeader")))
return 0;
if (!(block = (oskar_VisBlock*) get_handle(obj[2], "oskar_VisBlock")))
return 0;
/* Update the imager with the supplied visibility data. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_update_from_block(h, header, block, &status);
Py_END_ALLOW_THREADS
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_update_from_block() failed with code %d (%s).",
status, oskar_get_error_string(status));
return 0;
}
return Py_BuildValue("");
}
static PyObject* update_plane(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject *obj[] = {0, 0, 0, 0, 0, 0, 0, 0};
oskar_Mem *uu_c = 0, *vv_c = 0, *ww_c = 0, *amp_c = 0, *weight_c = 0;
oskar_Mem *plane_c = 0, *weights_grid_c = 0;
PyArrayObject *uu = 0, *vv = 0, *ww = 0, *amps = 0, *weight = 0;
PyArrayObject *plane = 0, *weights_grid = 0;
double plane_norm = 0.0;
int status = 0;
size_t num_vis;
/* Parse inputs:
* capsule, uu, vv, ww, amps, weight, plane, plane_norm, weights_grid. */
if (!PyArg_ParseTuple(args, "OOOOOOOdO", &obj[0],
&obj[1], &obj[2], &obj[3], &obj[4], &obj[5], &obj[6], &plane_norm,
&obj[7]))
return 0;
if (!(h = (oskar_Imager*) get_handle(obj[0], name))) return 0;
/* Make sure required input objects are arrays. Convert if required. */
uu = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_IN_ARRAY);
vv = (PyArrayObject*) PyArray_FROM_OF(obj[2], NPY_ARRAY_IN_ARRAY);
ww = (PyArrayObject*) PyArray_FROM_OF(obj[3], NPY_ARRAY_IN_ARRAY);
if (!uu || !vv || !ww) goto fail;
/* Check if visibility amplitudes are present. */
if (obj[4] != Py_None)
{
amps = (PyArrayObject*) PyArray_FROM_OF(obj[4], NPY_ARRAY_IN_ARRAY);
if (!amps) goto fail;
/* Check visibility data are complex. */
if (!PyArray_ISCOMPLEX(amps))
{
PyErr_SetString(PyExc_RuntimeError,
"Input visibility data must be complex.");
goto fail;
}
}
/* Check if weights are present. */
if (obj[5] != Py_None)
{
weight = (PyArrayObject*) PyArray_FROM_OF(obj[5], NPY_ARRAY_IN_ARRAY);
if (!weight) goto fail;
}
/* Check if visibility grid is present. */
if (obj[6] != Py_None)
{
plane = (PyArrayObject*) PyArray_FROM_OF(obj[6], NPY_ARRAY_IN_ARRAY);
if (!plane) goto fail;
}
/* Check if weights grid is present. */
if (obj[7] != Py_None)
{
weights_grid = (PyArrayObject*) PyArray_FROM_OF(obj[7],
NPY_ARRAY_IN_ARRAY);
if (!weights_grid) goto fail;
}
/* Check if visibilities are required but not present. */
if (!oskar_imager_coords_only(h) && (!amps || !plane))
{
PyErr_SetString(PyExc_RuntimeError, "Visibility data not present and "
"imager not in coordinate-only mode.");
goto fail;
}
/* Check dimensions. */
num_vis = (size_t) PyArray_SIZE(uu);
if (num_vis != (size_t) PyArray_SIZE(vv) ||
num_vis != (size_t) PyArray_SIZE(ww) ||
(amps && num_vis != (size_t) PyArray_SIZE(amps)) ||
(weight && num_vis != (size_t) PyArray_SIZE(weight)))
{
PyErr_SetString(PyExc_RuntimeError, "Input data dimension mismatch.");
goto fail;
}
/* Pointers to input arrays. */
uu_c = oskar_mem_create_alias_from_raw(PyArray_DATA(uu),
oskar_type_from_numpy(uu), OSKAR_CPU, num_vis, &status);
vv_c = oskar_mem_create_alias_from_raw(PyArray_DATA(vv),
oskar_type_from_numpy(vv), OSKAR_CPU, num_vis, &status);
ww_c = oskar_mem_create_alias_from_raw(PyArray_DATA(ww),
oskar_type_from_numpy(ww), OSKAR_CPU, num_vis, &status);
if (amps)
{
amp_c = oskar_mem_create_alias_from_raw(PyArray_DATA(amps),
oskar_type_from_numpy(amps), OSKAR_CPU, num_vis, &status);
}
if (weight)
{
weight_c = oskar_mem_create_alias_from_raw(PyArray_DATA(weight),
oskar_type_from_numpy(weight), OSKAR_CPU, num_vis, &status);
}
else
{
/* Set weights to 1 if not supplied. */
weight_c = oskar_mem_create(oskar_imager_precision(h), OSKAR_CPU,
num_vis, &status);
oskar_mem_set_value_real(weight_c, 1.0, 0, num_vis, &status);
}
if (plane)
{
plane_c = oskar_mem_create_alias_from_raw(PyArray_DATA(plane),
oskar_type_from_numpy(plane), OSKAR_CPU,
(size_t) PyArray_SIZE(plane), &status);
}
if (weights_grid)
{
weights_grid_c = oskar_mem_create_alias_from_raw(
PyArray_DATA(weights_grid),
oskar_type_from_numpy(weights_grid), OSKAR_CPU,
(size_t) PyArray_SIZE(weights_grid), &status);
}
/* Update the plane. */
Py_BEGIN_ALLOW_THREADS
oskar_imager_update_plane(h, num_vis, uu_c, vv_c, ww_c, amp_c,
weight_c, plane_c, &plane_norm, weights_grid_c, &status);
Py_END_ALLOW_THREADS
/* Clean up. */
oskar_mem_free(uu_c, &status);
oskar_mem_free(vv_c, &status);
oskar_mem_free(ww_c, &status);
oskar_mem_free(amp_c, &status);
oskar_mem_free(weight_c, &status);
oskar_mem_free(plane_c, &status);
oskar_mem_free(weights_grid_c, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"oskar_imager_update_plane() failed with code %d (%s).",
status, oskar_get_error_string(status));
goto fail;
}
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amps);
Py_XDECREF(weight);
Py_XDECREF(plane);
Py_XDECREF(weights_grid);
return Py_BuildValue("d", plane_norm);
fail:
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amps);
Py_XDECREF(weight);
Py_XDECREF(plane);
Py_XDECREF(weights_grid);
return 0;
}
static PyObject* uv_filter_max(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_uv_filter_max(h));
}
static PyObject* uv_filter_min(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("d", oskar_imager_uv_filter_min(h));
}
static PyObject* weighting(PyObject* self, PyObject* args)
{
oskar_Imager* h = 0;
PyObject* capsule = 0;
if (!PyArg_ParseTuple(args, "O", &capsule)) return 0;
if (!(h = (oskar_Imager*) get_handle(capsule, name))) return 0;
return Py_BuildValue("s", oskar_imager_weighting(h));
}
static PyObject* make_image(PyObject* self, PyObject* args)
{
oskar_Imager* h;
PyObject *obj[] = {0, 0, 0, 0, 0};
PyArrayObject *uu = 0, *vv = 0, *ww = 0, *amps = 0, *weight = 0, *im = 0;
size_t num_cells, num_pixels, num_vis;
int plane_size = 0, size = 0;
int dft = 0, status = 0, type = 0, wproj = 0, uniform = 0, wprojplanes = -1;
double fov_deg = 0.0, norm = 0.0;
const char *weighting_type = 0, *algorithm_type = 0;
oskar_Mem *uu_c, *vv_c, *ww_c, *amp_c, *weight_c, *plane;
oskar_Mem *weights_grid = 0;
npy_intp dims[2];
/* Parse inputs. */
if (!PyArg_ParseTuple(args, "OOOOdissOi",
&obj[0], &obj[1], &obj[2], &obj[3], &fov_deg, &size,
&weighting_type, &algorithm_type, &obj[4], &wprojplanes))
return 0;
/* Make sure input objects are arrays. Convert if required. */
uu = (PyArrayObject*) PyArray_FROM_OF(obj[0], NPY_ARRAY_IN_ARRAY);
vv = (PyArrayObject*) PyArray_FROM_OF(obj[1], NPY_ARRAY_IN_ARRAY);
ww = (PyArrayObject*) PyArray_FROM_OF(obj[2], NPY_ARRAY_IN_ARRAY);
amps = (PyArrayObject*) PyArray_FROM_OF(obj[3], NPY_ARRAY_IN_ARRAY);
if (!uu || !vv || !ww || !amps) goto fail;
/* Check if weights are present. */
if (obj[4] != Py_None)
{
weight = (PyArrayObject*) PyArray_FROM_OF(obj[4], NPY_ARRAY_IN_ARRAY);
if (!weight) goto fail;
}
/* Check dimensions. */
num_pixels = size * size;
num_vis = (size_t) PyArray_SIZE(amps);
if (num_vis != (size_t) PyArray_SIZE(uu) ||
num_vis != (size_t) PyArray_SIZE(vv) ||
num_vis != (size_t) PyArray_SIZE(ww) ||
(weight && num_vis != (size_t) PyArray_SIZE(weight)))
{
PyErr_SetString(PyExc_RuntimeError, "Input data dimension mismatch.");
goto fail;
}
/* Get precision of complex visibility data. */
if (!PyArray_ISCOMPLEX(amps))
{
PyErr_SetString(PyExc_RuntimeError,
"Input visibility data must be complex.");
goto fail;
}
type = oskar_type_precision(oskar_type_from_numpy(amps));
/* Pointers to input/output arrays. */
uu_c = oskar_mem_create_alias_from_raw(PyArray_DATA(uu),
oskar_type_from_numpy(uu), OSKAR_CPU, num_vis, &status);
vv_c = oskar_mem_create_alias_from_raw(PyArray_DATA(vv),
oskar_type_from_numpy(vv), OSKAR_CPU, num_vis, &status);
ww_c = oskar_mem_create_alias_from_raw(PyArray_DATA(ww),
oskar_type_from_numpy(ww), OSKAR_CPU, num_vis, &status);
amp_c = oskar_mem_create_alias_from_raw(PyArray_DATA(amps),
oskar_type_from_numpy(amps), OSKAR_CPU, num_vis, &status);
if (weight)
{
weight_c = oskar_mem_create_alias_from_raw(PyArray_DATA(weight),
oskar_type_from_numpy(weight), OSKAR_CPU, num_vis, &status);
}
else
{
/* Set weights to 1 if not supplied. */
weight_c = oskar_mem_create(type, OSKAR_CPU, num_vis, &status);
oskar_mem_set_value_real(weight_c, 1.0, 0, num_vis, &status);
}
/* Allow threads. */
Py_BEGIN_ALLOW_THREADS
/* Create and set up the imager. */
h = oskar_imager_create(type, &status);
oskar_imager_set_fov(h, fov_deg);
oskar_imager_set_size(h, size, &status);
oskar_imager_set_algorithm(h, algorithm_type, &status);
oskar_imager_set_num_w_planes(h, wprojplanes);
oskar_imager_set_weighting(h, weighting_type, &status);
/* Check for DFT, W-projection or uniform weighting. */
if (!strncmp(algorithm_type, "DFT", 3) ||
!strncmp(algorithm_type, "dft", 3))
dft = 1;
if (!strncmp(algorithm_type, "W", 1) ||
!strncmp(algorithm_type, "w", 1))
wproj = 1;
if (!strncmp(weighting_type, "U", 1) ||
!strncmp(weighting_type, "u", 1))
uniform = 1;
/* Get the plane size. */
plane_size = oskar_imager_plane_size(h);
num_cells = plane_size * plane_size;
/* Supply the coordinates first, if required. */
if (wproj || uniform)
{
weights_grid = oskar_mem_create(type, OSKAR_CPU, num_cells, &status);
oskar_imager_set_coords_only(h, 1);
oskar_imager_update_plane(h, num_vis, uu_c, vv_c, ww_c, 0, weight_c,
0, 0, weights_grid, &status);
oskar_imager_set_coords_only(h, 0);
}
/* Initialise the algorithm. */
oskar_imager_check_init(h, &status);
/* Make the image. */
plane = oskar_mem_create((dft ? type : (type | OSKAR_COMPLEX)), OSKAR_CPU,
num_cells, &status);
oskar_imager_update_plane(h, num_vis, uu_c, vv_c, ww_c, amp_c, weight_c,
plane, &norm, weights_grid, &status);
oskar_imager_finalise_plane(h, plane, norm, &status);
oskar_imager_trim_image(h, plane, plane_size, size, &status);
/* Free temporaries. */
oskar_mem_free(uu_c, &status);
oskar_mem_free(vv_c, &status);
oskar_mem_free(ww_c, &status);
oskar_mem_free(amp_c, &status);
oskar_mem_free(weight_c, &status);
oskar_mem_free(weights_grid, &status);
oskar_imager_free(h, &status);
/* Disallow threads. */
Py_END_ALLOW_THREADS
/* Copy the data out. */
dims[0] = size;
dims[1] = size;
im = (PyArrayObject*)PyArray_SimpleNew(2, dims,
oskar_type_is_double(type) ? NPY_DOUBLE : NPY_FLOAT);
memcpy(PyArray_DATA(im), oskar_mem_void_const(plane),
num_pixels * oskar_mem_element_size(type));
oskar_mem_free(plane, &status);
/* Check for errors. */
if (status)
{
PyErr_Format(PyExc_RuntimeError,
"make_image() failed with code %d (%s).",
status, oskar_get_error_string(status));
goto fail;
}
/* Return image to the python workspace. */
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amps);
Py_XDECREF(weight);
return Py_BuildValue("N", im); /* Don't increment refcount. */
fail:
Py_XDECREF(uu);
Py_XDECREF(vv);
Py_XDECREF(ww);
Py_XDECREF(amps);
Py_XDECREF(weight);
Py_XDECREF(im);
return 0;
}
/* Method table. */
static PyMethodDef methods[] =
{
{"algorithm", (PyCFunction)algorithm, METH_VARARGS, "algorithm()"},
{"capsule_name", (PyCFunction)capsule_name,
METH_VARARGS, "capsule_name()"},
{"cellsize", (PyCFunction)cellsize, METH_VARARGS, "cellsize()"},
{"channel_snapshots", (PyCFunction)channel_snapshots,
METH_VARARGS, "channel_snapshots()"},
{"check_init", (PyCFunction)check_init, METH_VARARGS, "check_init()"},
{"coords_only", (PyCFunction)coords_only,
METH_VARARGS, "coords_only()"},
{"create", (PyCFunction)create, METH_VARARGS, "create(type)"},
{"fft_on_gpu", (PyCFunction)fft_on_gpu, METH_VARARGS, "fft_on_gpu()"},
{"finalise", (PyCFunction)finalise,
METH_VARARGS, "finalise(return_images, return_grids)"},
{"finalise_plane", (PyCFunction)finalise_plane,
METH_VARARGS, "finalise_plane(plane, plane_norm)"},
{"fov", (PyCFunction)fov, METH_VARARGS, "fov()"},
{"freq_max_hz", (PyCFunction)freq_max_hz,
METH_VARARGS, "freq_max_hz()"},
{"freq_min_hz", (PyCFunction)freq_min_hz,
METH_VARARGS, "freq_min_hz()"},
{"generate_w_kernels_on_gpu", (PyCFunction)generate_w_kernels_on_gpu,
METH_VARARGS, "generate_w_kernels_on_gpu()"},
{"image_size", (PyCFunction)image_size, METH_VARARGS, "image_size()"},
{"image_type", (PyCFunction)image_type, METH_VARARGS, "image_type()"},
{"input_file", (PyCFunction)input_file, METH_VARARGS, "input_file()"},
{"ms_column", (PyCFunction)ms_column, METH_VARARGS, "ms_column()"},
{"make_image", (PyCFunction)make_image, METH_VARARGS,
"make_image(uu, vv, ww, amp, weight, fov_deg, size)"},
{"num_w_planes", (PyCFunction)num_w_planes,
METH_VARARGS, "num_w_planes()"},
{"output_root", (PyCFunction)output_root,
METH_VARARGS, "output_root()"},
{"plane_size", (PyCFunction)plane_size, METH_VARARGS, "plane_size()"},
{"reset_cache", (PyCFunction)reset_cache,
METH_VARARGS, "reset_cache()"},
{"rotate_coords", (PyCFunction)rotate_coords,
METH_VARARGS, "rotate_coords(uu, vv, ww)"},
{"rotate_vis", (PyCFunction)rotate_vis,
METH_VARARGS, "rotate_vis(uu_in, vv_in, ww_in, amps)"},
{"run", (PyCFunction)run,
METH_VARARGS, "run(return_images, return_grids)"},
{"scale_norm_with_num_input_files",
(PyCFunction)scale_norm_with_num_input_files,
METH_VARARGS, "scale_norm_with_num_input_files()"},
{"set_algorithm", (PyCFunction)set_algorithm,
METH_VARARGS, "set_algorithm(type)"},
{"set_cellsize", (PyCFunction)set_cellsize,
METH_VARARGS, "set_cellsize(value)"},
{"set_channel_snapshots", (PyCFunction)set_channel_snapshots,
METH_VARARGS, "set_channel_snapshots(value)"},
{"set_coords_only", (PyCFunction)set_coords_only,
METH_VARARGS, "set_coords_only(flag)"},
{"set_default_direction", (PyCFunction)set_default_direction,
METH_VARARGS, "set_default_direction()"},
{"set_direction", (PyCFunction)set_direction,
METH_VARARGS, "set_direction(ra_deg, dec_deg)"},
{"set_fft_on_gpu", (PyCFunction)set_fft_on_gpu,
METH_VARARGS, "set_fft_on_gpu(value)"},
{"set_fov", (PyCFunction)set_fov, METH_VARARGS, "set_fov(value)"},
{"set_freq_max_hz", (PyCFunction)set_freq_max_hz,
METH_VARARGS, "set_freq_max_hz(value)"},
{"set_freq_min_hz", (PyCFunction)set_freq_min_hz,
METH_VARARGS, "set_freq_min_hz(value)"},
{"set_generate_w_kernels_on_gpu",
(PyCFunction)set_generate_w_kernels_on_gpu,
METH_VARARGS, "set_generate_w_kernels_on_gpu(value)"},
{"set_grid_kernel", (PyCFunction)set_grid_kernel,
METH_VARARGS, "set_grid_kernel(type, support, oversample)"},
{"set_image_size", (PyCFunction)set_image_size,
METH_VARARGS, "set_image_size(value)"},
{"set_image_type", (PyCFunction)set_image_type,
METH_VARARGS, "set_image_type(type)"},
{"set_input_file", (PyCFunction)set_input_file,
METH_VARARGS, "set_input_file(filename)"},
{"set_ms_column", (PyCFunction)set_ms_column,
METH_VARARGS, "set_ms_column(column)"},
{"set_num_w_planes", (PyCFunction)set_num_w_planes,
METH_VARARGS, "set_num_w_planes(value)"},
{"set_output_root", (PyCFunction)set_output_root,
METH_VARARGS, "set_output_root(filename)"},
{"set_scale_norm_with_num_input_files",
(PyCFunction)set_scale_norm_with_num_input_files,
METH_VARARGS, "set_scale_norm_with_num_input_files(value)"},
{"set_size", (PyCFunction)set_size, METH_VARARGS, "set_size(value)"},
{"set_time_max_utc", (PyCFunction)set_time_max_utc,
METH_VARARGS, "set_time_max_utc(value)"},
{"set_time_min_utc", (PyCFunction)set_time_min_utc,
METH_VARARGS, "set_time_min_utc(value)"},
{"set_uv_filter_max", (PyCFunction)set_uv_filter_max,
METH_VARARGS, "set_uv_filter_max(max_wavelengths)"},
{"set_uv_filter_min", (PyCFunction)set_uv_filter_min,
METH_VARARGS, "set_uv_filter_min(min_wavelengths)"},
{"set_vis_frequency", (PyCFunction)set_vis_frequency, METH_VARARGS,
"set_vis_frequency(ref_hz, inc_hz, num_channels)"},
{"set_vis_phase_centre", (PyCFunction)set_vis_phase_centre,
METH_VARARGS, "set_vis_phase_centre(ra_deg, dec_deg)"},
{"set_weighting", (PyCFunction)set_weighting,
METH_VARARGS, "set_weighting(type)"},
{"size", (PyCFunction)size, METH_VARARGS, "size()"},
{"time_max_utc", (PyCFunction)time_max_utc,
METH_VARARGS, "time_max_utc()"},
{"time_min_utc", (PyCFunction)time_min_utc,
METH_VARARGS, "time_min_utc()"},
{"update", (PyCFunction)update, METH_VARARGS,
"update(uu, vv, ww, amps, weight, time_centroid, "
"start_chan, end_chan, num_pols)"},
{"update_from_block", (PyCFunction)update_from_block,
METH_VARARGS, "update_from_block(vis_header, vis_block)"},
{"update_plane", (PyCFunction)update_plane, METH_VARARGS,
"update_plane(uu, vv, ww, amps, weight, plane, plane_norm)"},
{"uv_filter_max", (PyCFunction)uv_filter_max,
METH_VARARGS, "uv_filter_max()"},
{"uv_filter_min", (PyCFunction)uv_filter_min,
METH_VARARGS, "uv_filter_min()"},
{"weighting", (PyCFunction)weighting, METH_VARARGS, "weighting()"},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
static PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_imager_lib", /* m_name */
module_doc, /* m_doc */
-1, /* m_size */
methods /* m_methods */
};
#endif
static PyObject* moduleinit(void)
{
PyObject* m;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule3("_imager_lib", methods, module_doc);
#endif
return m;
}
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit__imager_lib(void)
{
import_array();
return moduleinit();
}
#else
/* The init function name has to match that of the compiled module
* with the pattern 'init<module name>'. This module is called '_imager_lib' */
PyMODINIT_FUNC init_imager_lib(void)
{
import_array();
moduleinit();
return;
}
#endif
|
Ramsubito/Task-Queue
|
Solution_Code/Motor2D/j1Player.h
|
<reponame>Ramsubito/Task-Queue<gh_stars>0
#ifndef _J1PLAYER_H__
#define _J1PLAYER_H__
#include "p2Point.h"
#include "SDL/include/SDL.h"
#include <queue>
#include "j1Entity.h"
class j1Player : public Entity
{
public:
j1Player(int x, int y, entity_type type);
virtual ~j1Player();
bool Awake();
bool Start();
bool PreUpdate();
void Move(float dt);
bool CleanUp();
};
#endif // !_J1PLAYER_H__
|
Ramsubito/Task-Queue
|
Solution_Code/Motor2D/j1Entity.h
|
#ifndef __J1ENTITY_H__
#define __J1ENTITY_H__
#include "j1App.h"
#include "j1Module.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "SDL/include/SDL.h"
#include <list>
#include <queue>
#define MAX_ENEMIES 5
class SDL_Texture;
enum entity_type
{
NO_TYPE,
PLAYER,
};
class Entity {
public:
Entity(int x, int y, entity_type type) {}
virtual void Move(float dt) {};
public:
iPoint pos;
iPoint speed;
entity_type type;
SDL_Rect rect;
};
class j1Entity : public j1Module {
private:
std::list<Entity*> entities;
public:
j1Entity();
virtual ~j1Entity();
public:
bool Awake();
bool Start();
bool PreUpdate();
bool Update(float dt);
bool CleanUp();
Entity* AddEntity(int x, int y, entity_type type);
SDL_Texture* test;
};
#endif // !__ENTITIES_H__
|
Ramsubito/Task-Queue
|
Handout_Task-Queue/Motor2D/j1TaskQueue.h
|
#ifndef _TASKQUEUE_H__
#define _TASKQUEUE_H__
#include "p2Point.h"
#include <queue>
#include "j1Module.h"
#include "j1Entity.h"
class Task {
public:
Task(Entity* ent) : entity(ent) {};
~Task() {};
Entity* entity;
virtual bool Action() { return true; };
virtual void InitTask() {};
};
class j1TaskQueue : public j1Module
{
public:
j1TaskQueue() {};
virtual ~j1TaskQueue() {};
bool Update(float dt);
bool CleanUp();
bool Enqueue(Task* task);
bool Do_Tasks();
public:
Task* Temp_Task = nullptr;
private:
std::queue<Task*> TaskQueue;
};
//Movement methods already added
class Go_Right : public Task
{
public:
Go_Right(Entity* entity) : Task(entity) {};
~Go_Right() {};
public:
iPoint Final_Position;
virtual void InitTask() {Final_Position.x = entity->pos.x + 100;};
bool Action();
};
class Go_Left : public Task
{
public:
Go_Left(Entity* entity) : Task(entity) {};
~Go_Left() {};
public:
iPoint Final_Position;
virtual void InitTask() { Final_Position.x = entity->pos.x - 100; };
bool Action();
};
class Go_Up : public Task
{
public:
Go_Up(Entity* entity) : Task(entity) {};
~Go_Up() {};
public:
iPoint Final_Position;
virtual void InitTask() { Final_Position.y = entity->pos.y - 100; };
bool Action();
};
class Go_Down : public Task
{
public:
Go_Down(Entity* entity) : Task(entity) { };
~Go_Down() {};
public:
iPoint Final_Position;
virtual void InitTask() { Final_Position.y = entity->pos.y +100; };
bool Action();
};
#endif // !_TASKMANAGER_H__
|
Maximus5/win32-darkmode
|
win32-darkmode/win32-darkmode.h
|
<reponame>Maximus5/win32-darkmode
#pragma once
#include <climits>
#include <cstdint>
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <CommCtrl.h>
#include <Uxtheme.h>
#include <WindowsX.h>
#include <Dwmapi.h>
#include <Vssym32.h>
#pragma comment(lib, "Comctl32.lib")
#pragma comment(lib, "Uxtheme.lib")
#pragma comment(lib, "Dwmapi.lib")
#include "resource.h"
#include "DarkMode.h"
#include "ListViewUtil.h"
|
Maximus5/win32-darkmode
|
win32-darkmode/DarkMode.h
|
<filename>win32-darkmode/DarkMode.h
#pragma once
#include "IatHook.h"
enum IMMERSIVE_HC_CACHE_MODE
{
IHCM_USE_CACHED_VALUE,
IHCM_REFRESH
};
// Insider 18334
enum PreferredAppMode
{
Default,
AllowDark,
ForceDark,
ForceLight,
Max
};
using fnRtlGetNtVersionNumbers = void (WINAPI *)(LPDWORD major, LPDWORD minor, LPDWORD build);
// 1809 17763
using fnShouldAppsUseDarkMode = bool (WINAPI *)(); // ordinal 132
using fnAllowDarkModeForWindow = bool (WINAPI *)(HWND hWnd, bool allow); // ordinal 133
using fnAllowDarkModeForApp = bool (WINAPI *)(bool allow); // ordinal 135, removed since 18334
using fnFlushMenuThemes = void (WINAPI *)(); // ordinal 136
using fnRefreshImmersiveColorPolicyState = void (WINAPI *)(); // ordinal 104
using fnIsDarkModeAllowedForWindow = bool (WINAPI *)(HWND hWnd); // ordinal 137
using fnGetIsImmersiveColorUsingHighContrast = bool (WINAPI *)(IMMERSIVE_HC_CACHE_MODE mode); // ordinal 106
using fnOpenNcThemeData = HTHEME(WINAPI *)(HWND hWnd, LPCWSTR pszClassList); // ordinal 49
// Insider 18290
using fnShouldSystemUseDarkMode = bool (WINAPI *)(); // ordinal 138
// Insider 18334
using fnSetPreferredAppMode = PreferredAppMode (WINAPI *)(PreferredAppMode appMode); // ordinal 135, since 18334
using fnIsDarkModeAllowedForApp = bool (WINAPI *)(); // ordinal 139
fnShouldAppsUseDarkMode _ShouldAppsUseDarkMode = nullptr;
fnAllowDarkModeForWindow _AllowDarkModeForWindow = nullptr;
fnAllowDarkModeForApp _AllowDarkModeForApp = nullptr;
fnFlushMenuThemes _FlushMenuThemes = nullptr;
fnRefreshImmersiveColorPolicyState _RefreshImmersiveColorPolicyState = nullptr;
fnIsDarkModeAllowedForWindow _IsDarkModeAllowedForWindow = nullptr;
fnGetIsImmersiveColorUsingHighContrast _GetIsImmersiveColorUsingHighContrast = nullptr;
fnOpenNcThemeData _OpenNcThemeData = nullptr;
// Insider 18290
fnShouldSystemUseDarkMode _ShouldSystemUseDarkMode = nullptr;
// Insider 18334
fnSetPreferredAppMode _SetPreferredAppMode = nullptr;
bool g_darkModeSupported = false;
bool g_darkModeEnabled = false;
DWORD g_buildNumber = 0;
bool AllowDarkModeForWindow(HWND hWnd, bool allow)
{
if (g_darkModeSupported)
return _AllowDarkModeForWindow(hWnd, allow);
return false;
}
bool IsHighContrast()
{
HIGHCONTRASTW highContrast = { sizeof(highContrast) };
if (SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(highContrast), &highContrast, FALSE))
return highContrast.dwFlags & HCF_HIGHCONTRASTON;
return false;
}
void RefreshTitleBarThemeColor(HWND hWnd)
{
BOOL dark = FALSE;
if (_IsDarkModeAllowedForWindow(hWnd) &&
_ShouldAppsUseDarkMode() &&
!IsHighContrast())
{
dark = TRUE;
}
DwmSetWindowAttribute(hWnd, 19, &dark, sizeof(dark));
}
bool IsColorSchemeChangeMessage(LPARAM lParam)
{
bool is = false;
if (lParam && CompareStringOrdinal(reinterpret_cast<LPCWCH>(lParam), -1, L"ImmersiveColorSet", -1, TRUE) == CSTR_EQUAL)
{
_RefreshImmersiveColorPolicyState();
is = true;
}
_GetIsImmersiveColorUsingHighContrast(IHCM_REFRESH);
return is;
}
bool IsColorSchemeChangeMessage(UINT message, LPARAM lParam)
{
if (message == WM_SETTINGCHANGE)
return IsColorSchemeChangeMessage(lParam);
return false;
}
void AllowDarkModeForApp(bool allow)
{
if (_AllowDarkModeForApp)
_AllowDarkModeForApp(allow);
else if (_SetPreferredAppMode)
_SetPreferredAppMode(allow ? AllowDark : Default);
}
void FixDarkScrollBar()
{
auto addr = FindDelayLoadThunkInModule(GetModuleHandleW(L"comctl32.dll"), "uxtheme.dll", 49); // OpenNcThemeData
if (addr)
{
DWORD oldProtect;
if (VirtualProtect(addr, sizeof(IMAGE_THUNK_DATA), PAGE_READWRITE, &oldProtect))
{
auto MyOpenThemeData = [](HWND hWnd, LPCWSTR classList) -> HTHEME {
if (wcscmp(classList, L"ScrollBar") == 0)
{
hWnd = nullptr;
classList = L"Explorer::ScrollBar";
}
return _OpenNcThemeData(hWnd, classList);
};
addr->u1.Function = reinterpret_cast<ULONG_PTR>(static_cast<fnOpenNcThemeData>(MyOpenThemeData));
VirtualProtect(addr, sizeof(IMAGE_THUNK_DATA), oldProtect, &oldProtect);
}
}
}
void InitDarkMode()
{
fnRtlGetNtVersionNumbers RtlGetNtVersionNumbers = reinterpret_cast<fnRtlGetNtVersionNumbers>(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetNtVersionNumbers"));
if (RtlGetNtVersionNumbers)
{
DWORD major, minor;
RtlGetNtVersionNumbers(&major, &minor, &g_buildNumber);
g_buildNumber &= ~0xF0000000;
if (major == 10 && minor == 0 && 17763 <= g_buildNumber && g_buildNumber <= 18343) // Windows 10 1809 10.0.17763 - Insider 10.0.18343
{
HMODULE hUxtheme = LoadLibraryExW(L"uxtheme.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (hUxtheme)
{
_OpenNcThemeData = reinterpret_cast<fnOpenNcThemeData>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(49)));
_RefreshImmersiveColorPolicyState = reinterpret_cast<fnRefreshImmersiveColorPolicyState>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(104)));
_GetIsImmersiveColorUsingHighContrast = reinterpret_cast<fnGetIsImmersiveColorUsingHighContrast>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(106)));
_ShouldAppsUseDarkMode = reinterpret_cast<fnShouldAppsUseDarkMode>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(132)));
_AllowDarkModeForWindow = reinterpret_cast<fnAllowDarkModeForWindow>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(133)));
auto ord135 = GetProcAddress(hUxtheme, MAKEINTRESOURCEA(135));
if (g_buildNumber == 18334)
_AllowDarkModeForApp = reinterpret_cast<fnAllowDarkModeForApp>(ord135);
else
_SetPreferredAppMode = reinterpret_cast<fnSetPreferredAppMode>(ord135);
//_FlushMenuThemes = reinterpret_cast<fnFlushMenuThemes>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(136)));
_IsDarkModeAllowedForWindow = reinterpret_cast<fnIsDarkModeAllowedForWindow>(GetProcAddress(hUxtheme, MAKEINTRESOURCEA(137)));
if (_OpenNcThemeData &&
_RefreshImmersiveColorPolicyState &&
_ShouldAppsUseDarkMode &&
_AllowDarkModeForWindow &&
(_AllowDarkModeForApp || _SetPreferredAppMode) &&
//_FlushMenuThemes &&
_IsDarkModeAllowedForWindow)
{
g_darkModeSupported = true;
AllowDarkModeForApp(true);
_RefreshImmersiveColorPolicyState();
g_darkModeEnabled = _ShouldAppsUseDarkMode() && !IsHighContrast();
FixDarkScrollBar();
}
}
}
}
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slae2.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* UPDATED: 08/16/2009 by BBandini - gcc 4.4.1 won't compile math function
when passed a constant; one mod: sqrt(x20)
instead of sqrt(2.0).
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slae2_(real *a, real *b, real *c, real *rt1, real *rt2)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAE2 computes the eigenvalues of a 2-by-2 symmetric matrix
[ A B ]
[ B C ].
On return, RT1 is the eigenvalue of larger absolute value, and RT2
is the eigenvalue of smaller absolute value.
Arguments
=========
A (input) REAL
The (1,1) element of the 2-by-2 matrix.
B (input) REAL
The (1,2) and (2,1) elements of the 2-by-2 matrix.
C (input) REAL
The (2,2) element of the 2-by-2 matrix.
RT1 (output) REAL
The eigenvalue of larger absolute value.
RT2 (output) REAL
The eigenvalue of smaller absolute value.
Further Details
===============
RT1 is accurate to a few ulps barring over/underflow.
RT2 may be inaccurate if there is massive cancellation in the
determinant A*C-B*B; higher precision or correctly rounded or
correctly truncated arithmetic would be needed to compute RT2
accurately in all cases.
Overflow is possible only if RT1 is within a factor of 5 of overflow.
Underflow is harmless if the input data is 0 or exceeds
underflow_threshold / macheps.
=====================================================================
Compute the eigenvalues */
/* System generated locals */
real r__1;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
static real acmn, acmx, ab, df, tb, sm, rt, adf;
sm = *a + *c;
df = *a - *c;
adf = dabs(df);
tb = *b + *b;
ab = dabs(tb);
if (dabs(*a) > dabs(*c)) {
acmx = *a;
acmn = *c;
} else {
acmx = *c;
acmn = *a;
}
if (adf > ab) {
/* Computing 2nd power */
r__1 = ab / adf;
rt = adf * sqrt(r__1 * r__1 + 1.f);
} else if (adf < ab) {
/* Computing 2nd power */
r__1 = adf / ab;
rt = ab * sqrt(r__1 * r__1 + 1.f);
} else {
/* Includes case AB=ADF=0 */
float x20 = 2.;
rt = ab * sqrt(x20);
}
if (sm < 0.f) {
*rt1 = (sm - rt) * .5f;
/* Order of execution important.
To get fully accurate smaller eigenvalue,
next line needs to be executed in higher precision. */
*rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b;
} else if (sm > 0.f) {
*rt1 = (sm + rt) * .5f;
/* Order of execution important.
To get fully accurate smaller eigenvalue,
next line needs to be executed in higher precision. */
*rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b;
} else {
/* Includes case RT1 = RT2 = 0 */
*rt1 = rt * .5f;
*rt2 = rt * -.5f;
}
return 0;
/* End of SLAE2 */
} /* slae2_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/ihead/readihdr.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IHEAD - IHead Image Utilities
FILE: READIHDR.C
AUTHOR: <NAME>
DATE: 04/26/1989
UPDATED: 03/14/2005 by MDG
Contains routines responsible for reading an IHead header
from an open file.
ROUTINES:
#cat: readihdr - reads the contents of an open file pointer into an
#cat: IHead structure.
***********************************************************************/
#include <stdio.h>
#include <ihead.h>
#include <util.h>
/************************************************************/
/* Readihdr() allocates and reads header information into an*/
/* ihead structure and returns the initialized structure. */
/* */
/* Modifications: */
/* 1/11/91 <NAME> */
/* check return codes */
/* declare malloc() */
/************************************************************/
IHEAD *readihdr(register FILE *fp)
{
IHEAD *head;
char lenstr[SHORT_CHARS];
int n, len;
n = fread(lenstr,1,SHORT_CHARS,fp);
if (n != SHORT_CHARS) {
(void) fprintf(stderr,"readihdr: fread returned %d (expected %d)\n",
n,SHORT_CHARS);
exit(1);
}
if (sscanf(lenstr,"%d",&len) != 1)
fatalerr("readihdr","cannot parse length field",(char *)NULL);
if (len != IHDR_SIZE)
fatalerr("readihdr","Record Sync Error: Header not found or old format.",
NULL);
head = (IHEAD *) malloc(sizeof(IHEAD));
if (head == (IHEAD *) NULL)
syserr("readihdr","malloc","head");
n = fread(head,1,len,fp);
if (n != len) {
(void) fprintf(stderr,"readihdr: fread returned %d (expected %d)\n",
n,len);
exit(1);
}
return head;
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/sormtr.c
|
<filename>library/src/main/cpp/nbis/commonnbis/src/lib/clapck/sormtr.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int sormtr_(char *side, char *uplo, char *trans, int *m,
int *n, real *a, int *lda, real *tau, real *c, int *ldc,
real *work, int *lwork, int *info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SORMTR overwrites the general real M-by-N matrix C with
SIDE = 'L' SIDE = 'R'
TRANS = 'N': Q * C C * Q
TRANS = 'T': Q**T * C C * Q**T
where Q is a real orthogonal matrix of order nq, with nq = m if
SIDE = 'L' and nq = n if SIDE = 'R'. Q is defined as the product of
nq-1 elementary reflectors, as returned by SSYTRD:
if UPLO = 'U', Q = H(nq-1) . . . H(2) H(1);
if UPLO = 'L', Q = H(1) H(2) . . . H(nq-1).
Arguments
=========
SIDE (input) CHARACTER*1
= 'L': apply Q or Q**T from the Left;
= 'R': apply Q or Q**T from the Right.
UPLO (input) CHARACTER*1
= 'U': Upper triangle of A contains elementary reflectors
from SSYTRD;
= 'L': Lower triangle of A contains elementary reflectors
from SSYTRD.
TRANS (input) CHARACTER*1
= 'N': No transpose, apply Q;
= 'T': Transpose, apply Q**T.
M (input) INTEGER
The number of rows of the matrix C. M >= 0.
N (input) INTEGER
The number of columns of the matrix C. N >= 0.
A (input) REAL array, dimension
(LDA,M) if SIDE = 'L'
(LDA,N) if SIDE = 'R'
The vectors which define the elementary reflectors, as
returned by SSYTRD.
LDA (input) INTEGER
The leading dimension of the array A.
LDA >= max(1,M) if SIDE = 'L'; LDA >= max(1,N) if SIDE = 'R'.
TAU (input) REAL array, dimension
(M-1) if SIDE = 'L'
(N-1) if SIDE = 'R'
TAU(i) must contain the scalar factor of the elementary
reflector H(i), as returned by SSYTRD.
C (input/output) REAL array, dimension (LDC,N)
On entry, the M-by-N matrix C.
On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q.
LDC (input) INTEGER
The leading dimension of the array C. LDC >= max(1,M).
WORK (workspace/output) REAL array, dimension (LWORK)
On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
LWORK (input) INTEGER
The dimension of the array WORK.
If SIDE = 'L', LWORK >= max(1,N);
if SIDE = 'R', LWORK >= max(1,M).
For optimum performance LWORK >= N*NB if SIDE = 'L', and
LWORK >= M*NB if SIDE = 'R', where NB is the optimal
blocksize.
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
=====================================================================
Test the input arguments
Parameter adjustments
Function Body */
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset, c_dim1, c_offset;
*/
int i__1;
/* Local variables */
static logical left;
extern logical lsame_(char *, char *);
static int iinfo, i1;
static logical upper;
static int i2, mi, ni, nq, nw;
extern /* Subroutine */ int xerbla_(char *, int *), sormql_(
char *, char *, int *, int *, int *, real *, int *
, real *, real *, int *, real *, int *, int *), sormqr_(char *, char *, int *, int *, int *,
real *, int *, real *, real *, int *, real *, int *,
int *);
#define TAU(I) tau[(I)-1]
#define WORK(I) work[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
#define C(I,J) c[(I)-1 + ((J)-1)* ( *ldc)]
*info = 0;
left = lsame_(side, "L");
upper = lsame_(uplo, "U");
/* NQ is the order of Q and NW is the minimum dimension of WORK */
if (left) {
nq = *m;
nw = *n;
} else {
nq = *n;
nw = *m;
}
if (! left && ! lsame_(side, "R")) {
*info = -1;
} else if (! upper && ! lsame_(uplo, "L")) {
*info = -2;
} else if (! lsame_(trans, "N") && ! lsame_(trans, "T")) {
*info = -3;
} else if (*m < 0) {
*info = -4;
} else if (*n < 0) {
*info = -5;
} else if (*lda < max(1,nq)) {
*info = -7;
} else if (*ldc < max(1,*m)) {
*info = -10;
} else if (*lwork < max(1,nw)) {
*info = -12;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SORMTR", &i__1);
return 0;
}
/* Quick return if possible */
if (*m == 0 || *n == 0 || nq == 1) {
WORK(1) = 1.f;
return 0;
}
if (left) {
mi = *m - 1;
ni = *n;
} else {
mi = *m;
ni = *n - 1;
}
if (upper) {
/* Q was determined by a call to SSYTRD with UPLO = 'U' */
i__1 = nq - 1;
sormql_(side, trans, &mi, &ni, &i__1, &A(1,2), lda, &
TAU(1), &C(1,1), ldc, &WORK(1), lwork, &iinfo);
} else {
/* Q was determined by a call to SSYTRD with UPLO = 'L' */
if (left) {
i1 = 2;
i2 = 1;
} else {
i1 = 1;
i2 = 2;
}
i__1 = nq - 1;
sormqr_(side, trans, &mi, &ni, &i__1, &A(2,1), lda, &TAU(1), &
C(i1,i2), ldc, &WORK(1), lwork, &iinfo);
}
return 0;
/* End of SORMTR */
} /* sormtr_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slatrd.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slatrd_(char *uplo, int *n, int *nb, real *a,
int *lda, real *e, real *tau, real *w, int *ldw)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLATRD reduces NB rows and columns of a real symmetric matrix A to
symmetric tridiagonal form by an orthogonal similarity
transformation Q' * A * Q, and returns the matrices V and W which are
needed to apply the transformation to the unreduced part of A.
If UPLO = 'U', SLATRD reduces the last NB rows and columns of a
matrix, of which the upper triangle is supplied;
if UPLO = 'L', SLATRD reduces the first NB rows and columns of a
matrix, of which the lower triangle is supplied.
This is an auxiliary routine called by SSYTRD.
Arguments
=========
UPLO (input) CHARACTER
Specifies whether the upper or lower triangular part of the
symmetric matrix A is stored:
= 'U': Upper triangular
= 'L': Lower triangular
N (input) INTEGER
The order of the matrix A.
NB (input) INTEGER
The number of rows and columns to be reduced.
A (input/output) REAL array, dimension (LDA,N)
On entry, the symmetric matrix A. If UPLO = 'U', the leading
n-by-n upper triangular part of A contains the upper
triangular part of the matrix A, and the strictly lower
triangular part of A is not referenced. If UPLO = 'L', the
leading n-by-n lower triangular part of A contains the lower
triangular part of the matrix A, and the strictly upper
triangular part of A is not referenced.
On exit:
if UPLO = 'U', the last NB columns have been reduced to
tridiagonal form, with the diagonal elements overwriting
the diagonal elements of A; the elements above the diagonal
with the array TAU, represent the orthogonal matrix Q as a
product of elementary reflectors;
if UPLO = 'L', the first NB columns have been reduced to
tridiagonal form, with the diagonal elements overwriting
the diagonal elements of A; the elements below the diagonal
with the array TAU, represent the orthogonal matrix Q as a
product of elementary reflectors.
See Further Details.
LDA (input) INTEGER
The leading dimension of the array A. LDA >= (1,N).
E (output) REAL array, dimension (N-1)
If UPLO = 'U', E(n-nb:n-1) contains the superdiagonal
elements of the last NB columns of the reduced matrix;
if UPLO = 'L', E(1:nb) contains the subdiagonal elements of
the first NB columns of the reduced matrix.
TAU (output) REAL array, dimension (N-1)
The scalar factors of the elementary reflectors, stored in
TAU(n-nb:n-1) if UPLO = 'U', and in TAU(1:nb) if UPLO = 'L'.
See Further Details.
W (output) REAL array, dimension (LDW,NB)
The n-by-nb matrix W required to update the unreduced part
of A.
LDW (input) INTEGER
The leading dimension of the array W. LDW >= max(1,N).
Further Details
===============
If UPLO = 'U', the matrix Q is represented as a product of elementary
reflectors
Q = H(n) H(n-1) . . . H(n-nb+1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(i:n) = 0 and v(i-1) = 1; v(1:i-1) is stored on exit in A(1:i-1,i),
and tau in TAU(i-1).
If UPLO = 'L', the matrix Q is represented as a product of elementary
reflectors
Q = H(1) H(2) . . . H(nb).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(1:i) = 0 and v(i+1) = 1; v(i+1:n) is stored on exit in A(i+1:n,i),
and tau in TAU(i).
The elements of the vectors v together form the n-by-nb matrix V
which is needed, with W, to apply the transformation to the unreduced
part of the matrix, using a symmetric rank-2k update of the form:
A := A - V*W' - W*V'.
The contents of A on exit are illustrated by the following examples
with n = 5 and nb = 2:
if UPLO = 'U': if UPLO = 'L':
( a a a v4 v5 ) ( d )
( a a v4 v5 ) ( 1 d )
( a 1 v5 ) ( v1 1 a )
( d 1 ) ( v1 v2 a a )
( d ) ( v1 v2 a a a )
where d denotes a diagonal element of the reduced matrix, a denotes
an element of the original matrix that is unchanged, and vi denotes
an element of the vector defining H(i).
=====================================================================
Quick return if possible
Parameter adjustments
Function Body */
/* Table of constant values */
static real c_b5 = -1.f;
static real c_b6 = 1.f;
static int c__1 = 1;
static real c_b16 = 0.f;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset, w_dim1, w_offset;
*/
int i__1, i__2, i__3;
/* Local variables */
extern doublereal sdot_(int *, real *, int *, real *, int *);
static int i;
static real alpha;
extern logical lsame_(char *, char *);
extern /* Subroutine */ int sscal_(int *, real *, real *, int *),
sgemv_(char *, int *, int *, real *, real *, int *,
real *, int *, real *, real *, int *), saxpy_(
int *, real *, real *, int *, real *, int *), ssymv_(
char *, int *, real *, real *, int *, real *, int *,
real *, real *, int *);
static int iw;
extern /* Subroutine */ int slarfg_(int *, real *, real *, int *,
real *);
#define E(I) e[(I)-1]
#define TAU(I) tau[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
#define W(I,J) w[(I)-1 + ((J)-1)* ( *ldw)]
if (*n <= 0) {
return 0;
}
if (lsame_(uplo, "U")) {
/* Reduce last NB columns of upper triangle */
i__1 = *n - *nb + 1;
for (i = *n; i >= *n-*nb+1; --i) {
iw = i - *n + *nb;
if (i < *n) {
/* Update A(1:i,i) */
i__2 = *n - i;
sgemv_("No transpose", &i, &i__2, &c_b5, &A(1,i+1), lda, &W(i,iw+1), ldw, &c_b6, &A(1,i), &c__1);
i__2 = *n - i;
sgemv_("No transpose", &i, &i__2, &c_b5, &W(1,iw+1), ldw, &A(i,i+1), lda, &c_b6, &A(1,i), &c__1);
}
if (i > 1) {
/* Generate elementary reflector H(i) to annihila
te
A(1:i-2,i) */
i__2 = i - 1;
slarfg_(&i__2, &A(i-1,i), &A(1,i), &
c__1, &TAU(i - 1));
E(i - 1) = A(i-1,i);
A(i-1,i) = 1.f;
/* Compute W(1:i-1,i) */
i__2 = i - 1;
ssymv_("Upper", &i__2, &c_b6, &A(1,1), lda, &A(1,i), &c__1, &c_b16, &W(1,iw), &
c__1);
if (i < *n) {
i__2 = i - 1;
i__3 = *n - i;
sgemv_("Transpose", &i__2, &i__3, &c_b6, &W(1,iw+1), ldw, &A(1,i), &c__1, &
c_b16, &W(i+1,iw), &c__1);
i__2 = i - 1;
i__3 = *n - i;
sgemv_("No transpose", &i__2, &i__3, &c_b5, &A(1,i+1), lda, &W(i+1,iw), &c__1,
&c_b6, &W(1,iw), &c__1);
i__2 = i - 1;
i__3 = *n - i;
sgemv_("Transpose", &i__2, &i__3, &c_b6, &A(1,i+1), lda, &A(1,i), &c__1, &
c_b16, &W(i+1,iw), &c__1);
i__2 = i - 1;
i__3 = *n - i;
sgemv_("No transpose", &i__2, &i__3, &c_b5, &W(1,iw+1), ldw, &W(i+1,iw), &c__1,
&c_b6, &W(1,iw), &c__1);
}
i__2 = i - 1;
sscal_(&i__2, &TAU(i - 1), &W(1,iw), &c__1);
i__2 = i - 1;
alpha = TAU(i - 1) * -.5f * sdot_(&i__2, &W(1,iw),
&c__1, &A(1,i), &c__1);
i__2 = i - 1;
saxpy_(&i__2, &alpha, &A(1,i), &c__1, &W(1,iw), &c__1);
}
/* L10: */
}
} else {
/* Reduce first NB columns of lower triangle */
i__1 = *nb;
for (i = 1; i <= *nb; ++i) {
/* Update A(i:n,i) */
i__2 = *n - i + 1;
i__3 = i - 1;
sgemv_("No transpose", &i__2, &i__3, &c_b5, &A(i,1), lda, &
W(i,1), ldw, &c_b6, &A(i,i), &c__1)
;
i__2 = *n - i + 1;
i__3 = i - 1;
sgemv_("No transpose", &i__2, &i__3, &c_b5, &W(i,1), ldw, &
A(i,1), lda, &c_b6, &A(i,i), &c__1)
;
if (i < *n) {
/* Generate elementary reflector H(i) to annihila
te
A(i+2:n,i) */
i__2 = *n - i;
/* Computing MIN */
i__3 = i + 2;
slarfg_(&i__2, &A(i+1,i), &A(min(i+2,*n),i), &c__1, &TAU(i));
E(i) = A(i+1,i);
A(i+1,i) = 1.f;
/* Compute W(i+1:n,i) */
i__2 = *n - i;
ssymv_("Lower", &i__2, &c_b6, &A(i+1,i+1),
lda, &A(i+1,i), &c__1, &c_b16, &W(i+1,i), &c__1);
i__2 = *n - i;
i__3 = i - 1;
sgemv_("Transpose", &i__2, &i__3, &c_b6, &W(i+1,1),
ldw, &A(i+1,i), &c__1, &c_b16, &W(1,i), &c__1);
i__2 = *n - i;
i__3 = i - 1;
sgemv_("No transpose", &i__2, &i__3, &c_b5, &A(i+1,1)
, lda, &W(1,i), &c__1, &c_b6, &W(i+1,i), &c__1);
i__2 = *n - i;
i__3 = i - 1;
sgemv_("Transpose", &i__2, &i__3, &c_b6, &A(i+1,1),
lda, &A(i+1,i), &c__1, &c_b16, &W(1,i), &c__1);
i__2 = *n - i;
i__3 = i - 1;
sgemv_("No transpose", &i__2, &i__3, &c_b5, &W(i+1,1)
, ldw, &W(1,i), &c__1, &c_b6, &W(i+1,i), &c__1);
i__2 = *n - i;
sscal_(&i__2, &TAU(i), &W(i+1,i), &c__1);
i__2 = *n - i;
alpha = TAU(i) * -.5f * sdot_(&i__2, &W(i+1,i), &
c__1, &A(i+1,i), &c__1);
i__2 = *n - i;
saxpy_(&i__2, &alpha, &A(i+1,i), &c__1, &W(i+1,i), &c__1);
}
/* L20: */
}
}
return 0;
/* End of SLATRD */
} /* slatrd_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slassq.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slassq_(int *n, real *x, int *incx, real *scale,
real *sumsq)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLASSQ returns the values scl and smsq such that
( scl**2 )*smsq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq,
where x( i ) = X( 1 + ( i - 1 )*INCX ). The value of sumsq is
assumed to be non-negative and scl returns the value
scl = max( scale, abs( x( i ) ) ).
scale and sumsq must be supplied in SCALE and SUMSQ and
scl and smsq are overwritten on SCALE and SUMSQ respectively.
The routine makes only one pass through the vector x.
Arguments
=========
N (input) INTEGER
The number of elements to be used from the vector X.
X (input) REAL
The vector for which a scaled sum of squares is computed.
x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n.
INCX (input) INTEGER
The increment between successive values of the vector X.
INCX > 0.
SCALE (input/output) REAL
On entry, the value scale in the equation above.
On exit, SCALE is overwritten with scl , the scaling factor
for the sum of squares.
SUMSQ (input/output) REAL
On entry, the value sumsq in the equation above.
On exit, SUMSQ is overwritten with smsq , the basic sum of
squares from which scl has been factored out.
=====================================================================
Parameter adjustments
Function Body */
/* System generated locals */
int i__1, i__2;
real r__1;
/* Local variables */
static real absxi;
static int ix;
#define X(I) x[(I)-1]
if (*n > 0) {
i__1 = (*n - 1) * *incx + 1;
i__2 = *incx;
for (ix = 1; *incx < 0 ? ix >= (*n-1)**incx+1 : ix <= (*n-1)**incx+1; ix += *incx) {
if (X(ix) != 0.f) {
absxi = (r__1 = X(ix), dabs(r__1));
if (*scale < absxi) {
/* Computing 2nd power */
r__1 = *scale / absxi;
*sumsq = *sumsq * (r__1 * r__1) + 1;
*scale = absxi;
} else {
/* Computing 2nd power */
r__1 = absxi / *scale;
*sumsq += r__1 * r__1;
}
}
/* L10: */
}
}
return 0;
/* End of SLASSQ */
} /* slassq_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slartg.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slartg_(real *f, real *g, real *cs, real *sn, real *r)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SLARTG generate a plane rotation so that
[ CS SN ] . [ F ] = [ R ] where CS**2 + SN**2 = 1.
[ -SN CS ] [ G ] [ 0 ]
This is a slower, more accurate version of the BLAS1 routine SROTG,
with the following other differences:
F and G are unchanged on return.
If G=0, then CS=1 and SN=0.
If F=0 and (G .ne. 0), then CS=0 and SN=1 without doing any
floating point operations (saves work in SBDSQR when
there are zeros on the diagonal).
If F exceeds G in magnitude, CS will be positive.
Arguments
=========
F (input) REAL
The first component of vector to be rotated.
G (input) REAL
The second component of vector to be rotated.
CS (output) REAL
The cosine of the rotation.
SN (output) REAL
The sine of the rotation.
R (output) REAL
The nonzero component of the rotated vector.
=====================================================================
*/
/* Initialized data */
static logical first = TRUE_;
/* System generated locals */
int i__1;
real r__1, r__2;
/* Builtin functions */
double log(doublereal), pow_ri(real *, int *), sqrt(doublereal);
/* Local variables */
static int i;
static real scale;
static int count;
static real f1, g1, safmn2, safmx2;
extern doublereal slamch_(char *);
static real safmin, eps;
if (first) {
first = FALSE_;
safmin = slamch_("S");
eps = slamch_("E");
r__1 = slamch_("B");
i__1 = (int) (log(safmin / eps) / log(slamch_("B")) / 2.f);
safmn2 = pow_ri(&r__1, &i__1);
safmx2 = 1.f / safmn2;
}
if (*g == 0.f) {
*cs = 1.f;
*sn = 0.f;
*r = *f;
} else if (*f == 0.f) {
*cs = 0.f;
*sn = 1.f;
*r = *g;
} else {
f1 = *f;
g1 = *g;
/* Computing MAX */
r__1 = dabs(f1), r__2 = dabs(g1);
scale = dmax(r__1,r__2);
if (scale >= safmx2) {
count = 0;
L10:
++count;
f1 *= safmn2;
g1 *= safmn2;
/* Computing MAX */
r__1 = dabs(f1), r__2 = dabs(g1);
scale = dmax(r__1,r__2);
if (scale >= safmx2) {
goto L10;
}
/* Computing 2nd power */
r__1 = f1;
/* Computing 2nd power */
r__2 = g1;
*r = sqrt(r__1 * r__1 + r__2 * r__2);
*cs = f1 / *r;
*sn = g1 / *r;
i__1 = count;
for (i = 1; i <= count; ++i) {
*r *= safmx2;
/* L20: */
}
} else if (scale <= safmn2) {
count = 0;
L30:
++count;
f1 *= safmx2;
g1 *= safmx2;
/* Computing MAX */
r__1 = dabs(f1), r__2 = dabs(g1);
scale = dmax(r__1,r__2);
if (scale <= safmn2) {
goto L30;
}
/* Computing 2nd power */
r__1 = f1;
/* Computing 2nd power */
r__2 = g1;
*r = sqrt(r__1 * r__1 + r__2 * r__2);
*cs = f1 / *r;
*sn = g1 / *r;
i__1 = count;
for (i = 1; i <= count; ++i) {
*r *= safmn2;
/* L40: */
}
} else {
/* Computing 2nd power */
r__1 = f1;
/* Computing 2nd power */
r__2 = g1;
*r = sqrt(r__1 * r__1 + r__2 * r__2);
*cs = f1 / *r;
*sn = g1 / *r;
}
if (dabs(*f) > dabs(*g) && *cs < 0.f) {
*cs = -(doublereal)(*cs);
*sn = -(doublereal)(*sn);
*r = -(doublereal)(*r);
}
}
return 0;
/* End of SLARTG */
} /* slartg_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/thresh.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: THRESH.C
AUTHORS: <NAME>
DATE: 09/21/2004
Contains routine to binarize an image but storing the results
as a char (1 byte per pixel).
***********************************************************************
ROUTINES:
#cat: thresh_charimage - takes a character image and thresholds it based
#cat: a specified factor, overwriting the input image.
***********************************************************************/
/************************************************************/
void thresh_charimage(unsigned char *adata, const int aw, const int ah,
const int thresh, const int pixflag)
{
int len, i;
unsigned char *aptr;
aptr = adata;
len = aw * ah;
for(i = 0; i < len; i++){
if(pixflag == 0)
*aptr = (thresh>(*aptr)) ? 1 : 0;
else
*aptr = (thresh>(*aptr)) ? 0 : 1;
aptr++;
}
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/ssytrd.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int ssytrd_(char *uplo, int *n, real *a, int *lda,
real *d, real *e, real *tau, real *work, int *lwork, int *
info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SSYTRD reduces a real symmetric matrix A to real symmetric
tridiagonal form T by an orthogonal similarity transformation:
Q**T * A * Q = T.
Arguments
=========
UPLO (input) CHARACTER*1
= 'U': Upper triangle of A is stored;
= 'L': Lower triangle of A is stored.
N (input) INTEGER
The order of the matrix A. N >= 0.
A (input/output) REAL array, dimension (LDA,N)
On entry, the symmetric matrix A. If UPLO = 'U', the leading
N-by-N upper triangular part of A contains the upper
triangular part of the matrix A, and the strictly lower
triangular part of A is not referenced. If UPLO = 'L', the
leading N-by-N lower triangular part of A contains the lower
triangular part of the matrix A, and the strictly upper
triangular part of A is not referenced.
On exit, if UPLO = 'U', the diagonal and first superdiagonal
of A are overwritten by the corresponding elements of the
tridiagonal matrix T, and the elements above the first
superdiagonal, with the array TAU, represent the orthogonal
matrix Q as a product of elementary reflectors; if UPLO
= 'L', the diagonal and first subdiagonal of A are over-
written by the corresponding elements of the tridiagonal
matrix T, and the elements below the first subdiagonal, with
the array TAU, represent the orthogonal matrix Q as a product
of elementary reflectors. See Further Details.
LDA (input) INTEGER
The leading dimension of the array A. LDA >= max(1,N).
D (output) REAL array, dimension (N)
The diagonal elements of the tridiagonal matrix T:
D(i) = A(i,i).
E (output) REAL array, dimension (N-1)
The off-diagonal elements of the tridiagonal matrix T:
E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'.
TAU (output) REAL array, dimension (N-1)
The scalar factors of the elementary reflectors (see Further
Details).
WORK (workspace/output) REAL array, dimension (LWORK)
On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
LWORK (input) INTEGER
The dimension of the array WORK. LWORK >= 1.
For optimum performance LWORK >= N*NB, where NB is the
optimal blocksize.
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
Further Details
===============
If UPLO = 'U', the matrix Q is represented as a product of elementary
reflectors
Q = H(n-1) . . . H(2) H(1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in
A(1:i-1,i+1), and tau in TAU(i).
If UPLO = 'L', the matrix Q is represented as a product of elementary
reflectors
Q = H(1) H(2) . . . H(n-1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i),
and tau in TAU(i).
The contents of A on exit are illustrated by the following examples
with n = 5:
if UPLO = 'U': if UPLO = 'L':
( d e v2 v3 v4 ) ( d )
( d e v3 v4 ) ( e d )
( d e v4 ) ( v1 e d )
( d e ) ( v1 v2 e d )
( d ) ( v1 v2 v3 e d )
where d and e denote diagonal and off-diagonal elements of T, and vi
denotes an element of the vector defining H(i).
=====================================================================
Test the input parameters
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__1 = 1;
static int c_n1 = -1;
static int c__3 = 3;
static int c__2 = 2;
static real c_b22 = -1.f;
static real c_b23 = 1.f;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset;
*/
int i__1, i__2, i__3;
/* Local variables */
static int i, j;
extern logical lsame_(char *, char *);
static int nbmin, iinfo;
static logical upper;
static int nb, kk;
extern /* Subroutine */ int ssytd2_(char *, int *, real *, int *,
real *, real *, real *, int *), ssyr2k_(char *, char *
, int *, int *, real *, real *, int *, real *,
int *, real *, real *, int *);
static int nx;
extern /* Subroutine */ int xerbla_(char *, int *);
extern int ilaenv_(int *, char *, char *, int *, int *,
int *, int *, ftnlen, ftnlen);
extern /* Subroutine */ int slatrd_(char *, int *, int *, real *,
int *, real *, real *, real *, int *);
static int ldwork, iws;
#define D(I) d[(I)-1]
#define E(I) e[(I)-1]
#define TAU(I) tau[(I)-1]
#define WORK(I) work[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
*info = 0;
upper = lsame_(uplo, "U");
if (! upper && ! lsame_(uplo, "L")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*lda < max(1,*n)) {
*info = -4;
} else if (*lwork < 1) {
*info = -9;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SSYTRD", &i__1);
return 0;
}
/* Quick return if possible */
if (*n == 0) {
WORK(1) = 1.f;
return 0;
}
/* Determine the block size. */
nb = ilaenv_(&c__1, "SSYTRD", uplo, n, &c_n1, &c_n1, &c_n1, 6L, 1L);
nx = *n;
iws = 1;
if (nb > 1 && nb < *n) {
/* Determine when to cross over from blocked to unblocked code
(last block is always handled by unblocked code).
Computing MAX */
i__1 = nb, i__2 = ilaenv_(&c__3, "SSYTRD", uplo, n, &c_n1, &c_n1, &
c_n1, 6L, 1L);
nx = max(i__1,i__2);
if (nx < *n) {
/* Determine if workspace is large enough for blocked co
de. */
ldwork = *n;
iws = ldwork * nb;
if (*lwork < iws) {
/* Not enough workspace to use optimal NB: deter
mine the
minimum value of NB, and reduce NB or force us
e of
unblocked code by setting NX = N.
Computing MAX */
i__1 = *lwork / ldwork;
nb = max(i__1,1);
nbmin = ilaenv_(&c__2, "SSYTRD", uplo, n, &c_n1, &c_n1, &c_n1,
6L, 1L);
if (nb < nbmin) {
nx = *n;
}
}
} else {
nx = *n;
}
} else {
nb = 1;
}
if (upper) {
/* Reduce the upper triangle of A.
Columns 1:kk are handled by the unblocked method. */
kk = *n - (*n - nx + nb - 1) / nb * nb;
i__1 = kk + 1;
i__2 = -nb;
for (i = *n - nb + 1; -nb < 0 ? i >= kk+1 : i <= kk+1; i += -nb) {
/* Reduce columns i:i+nb-1 to tridiagonal form and form
the
matrix W which is needed to update the unreduced part
of
the matrix */
i__3 = i + nb - 1;
slatrd_(uplo, &i__3, &nb, &A(1,1), lda, &E(1), &TAU(1), &
WORK(1), &ldwork);
/* Update the unreduced submatrix A(1:i-1,1:i-1), using
an
update of the form: A := A - V*W' - W*V' */
i__3 = i - 1;
ssyr2k_(uplo, "No transpose", &i__3, &nb, &c_b22, &A(1,i), lda, &WORK(1), &ldwork, &c_b23, &A(1,1), lda);
/* Copy superdiagonal elements back into A, and diagonal
elements into D */
i__3 = i + nb - 1;
for (j = i; j <= i+nb-1; ++j) {
A(j-1,j) = E(j - 1);
D(j) = A(j,j);
/* L10: */
}
/* L20: */
}
/* Use unblocked code to reduce the last or only block */
ssytd2_(uplo, &kk, &A(1,1), lda, &D(1), &E(1), &TAU(1), &iinfo);
} else {
/* Reduce the lower triangle of A */
i__2 = *n - nx;
i__1 = nb;
for (i = 1; nb < 0 ? i >= *n-nx : i <= *n-nx; i += nb) {
/* Reduce columns i:i+nb-1 to tridiagonal form and form
the
matrix W which is needed to update the unreduced part
of
the matrix */
i__3 = *n - i + 1;
slatrd_(uplo, &i__3, &nb, &A(i,i), lda, &E(i), &TAU(i),
&WORK(1), &ldwork);
/* Update the unreduced submatrix A(i+ib:n,i+ib:n), usin
g
an update of the form: A := A - V*W' - W*V' */
i__3 = *n - i - nb + 1;
ssyr2k_(uplo, "No transpose", &i__3, &nb, &c_b22, &A(i+nb,i), lda, &WORK(nb + 1), &ldwork, &c_b23, &A(i+nb,i+nb), lda);
/* Copy subdiagonal elements back into A, and diagonal
elements into D */
i__3 = i + nb - 1;
for (j = i; j <= i+nb-1; ++j) {
A(j+1,j) = E(j);
D(j) = A(j,j);
/* L30: */
}
/* L40: */
}
/* Use unblocked code to reduce the last or only block */
i__1 = *n - i + 1;
ssytd2_(uplo, &i__1, &A(i,i), lda, &D(i), &E(i), &TAU(i), &
iinfo);
}
WORK(1) = (real) iws;
return 0;
/* End of SSYTRD */
} /* ssytrd_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/rgb_ycc.c
|
<filename>library/src/main/cpp/nbis/imgtools/src/lib/image/rgb_ycc.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: RGB_YCC.C
AUTHOR: <NAME>
DATE: 02/15/2001
UPDATED: 03/15/2005 by MDG
Contains routines responsible for converting between RGB
and YCbCr image colorspace.
ROUTINES:
#cat: rgb2ycc_mem - takes an RGB pixmap and converts it to the YCbCr
#cat: colorspace.
#cat: rgb2ycc_intrlv_mem - takes an interleaved RGB pixmap and converts
#cat: it to the YCbCr colorspace.
#cat: rgb2ycc_nonintrlv_mem - takes a non-interleaved RGB pixmap and
#cat: converts it to the YCbCr colorspace.
#cat: downsample_cmpnts - takes a non-interleaved pixmap and downsamples
#cat: component planes based on specified factors.
#cat: window_avr_plane - downsamples a component plane by replacing adjacent
#cat: windows of specified dimension with the average
#cat: component value in each window.
#cat: avr_window - computes the averate component value in a window
#cat: of specified location and dimension.
#cat: ycc2rgb_mem - takes a YCbCr pixmap and converts it to the RGB
#cat: colorspace.
#cat: ycc2rgb_intrlv_mem - takes an interleaved YCbCr pixmap and converts
#cat: it to the RGB colorspace.
#cat: ycc2rgb_nonintrlv_mem - takes a non-interleaved YCbCr pixmap and
#cat: converts it to the RGB colorspace.
#cat: upsample_cmpnts - takes a non-interleaved pixmap and upsample
#cat: component planes based on specified factors.
#cat: window_fill_plane - upsamples a component plane by replicating a
#cat: single value into an output window of specifiec
#cat: dimension in an expanded output plane.
#cat: fill_window - replicates a component value in a window of specified
#cat: location and dimension.
#cat: test_evenmult_sampfctrs - ensures smaller downsample factors are
#cat: an even multiple of the maximum component downsample
#cat: factor.
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <rgb_ycc.h>
/*****************************************************************/
int rgb2ycc_mem(unsigned char **odata, int *olen, unsigned char *idata,
const int width, const int height, const int depth,
const int intrlvflag)
{
int ret;
if(intrlvflag){
if((ret = rgb2ycc_intrlv_mem(odata, olen, idata, width, height, depth)))
return(ret);
}
else{
if((ret = rgb2ycc_nonintrlv_mem(odata, olen, idata,
width, height, depth)))
return(ret);
}
return(0);
}
/*****************************************************************/
int rgb2ycc_intrlv_mem(unsigned char **oodata, int *oolen,
unsigned char *idata,
const int width, const int height, const int depth)
{
int i, num_pix, olen;
unsigned char *r_ptr, *g_ptr, *b_ptr;
unsigned char *y_ptr, *cb_ptr, *cr_ptr;
unsigned char *odata;
double dy, dcb, dcr;
int iy, icb, icr;
/* If image has empty dimension, then done ... */
if((width == 0) || (height == 0))
return(0);
if(depth != 24){
fprintf(stderr, "ERROR : rgb2ycc_intrlv_mem : depth = %d != 24\n",
depth);
return(-2);
}
num_pix = width * height;
olen = num_pix * (depth>>3);
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : rgb2ycc_intrlv_mem : malloc : odata\n");
return(-3);
}
for(i = 0,
r_ptr = idata,
g_ptr = idata+1,
b_ptr = idata+2,
y_ptr = odata,
cb_ptr = odata+1,
cr_ptr = odata+2;
i < num_pix;
i++,
r_ptr+=3,
g_ptr+=3,
b_ptr+=3,
y_ptr+=3,
cb_ptr+=3,
cr_ptr+=3){
/* Compute float Y,Cb,Cr. */
dy = (( 0.299 * (*r_ptr)) +
( 0.587 * (*g_ptr)) +
( 0.114 * (*b_ptr)));
dcb = ((-0.1687 * (*r_ptr)) +
(-0.3313 * (*g_ptr)) +
( 0.5 * (*b_ptr)) +
128.0);
dcr = (( 0.5 * (*r_ptr)) +
(-0.4177 * (*g_ptr)) +
(-0.0813 * (*b_ptr)) +
128.0);
/* Round to integer Y,Cb,Cr. */
iy = sround(dy);
icb = sround(dcb);
icr = sround(dcr);
/* Limit Y,Cb,Cr to [0..255]. */
iy = (iy < 0) ? 0 : ((iy > 255) ? 255 : iy);
icb = (icb < 0) ? 0 : ((icb > 255) ? 255 : icb);
icr = (icr < 0) ? 0 : ((icr > 255) ? 255 : icr);
/* Store uchar Y,Cb,Cr. */
*y_ptr = iy;
*cb_ptr = icb;
*cr_ptr = icr;
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
int rgb2ycc_nonintrlv_mem(unsigned char **oodata, int *oolen,
unsigned char *idata,
const int width, const int height, const int depth)
{
int i, num_pix, olen;
unsigned char *r_ptr, *g_ptr, *b_ptr;
unsigned char *y_ptr, *cb_ptr, *cr_ptr;
unsigned char *odata;
double dy, dcb, dcr;
int iy, icb, icr;
/* If image has empty dimension, then done ... */
if((width == 0) || (height == 0))
return(0);
if(depth != 24){
fprintf(stderr, "ERROR : rgb2ycc_nonintrlv_mem : depth = %d != 24\n",
depth);
return(-2);
}
num_pix = width * height;
olen = num_pix * (depth>>3);
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : rgb2ycc_nonintrlv_mem : malloc : odata\n");
return(-3);
}
r_ptr = idata;
g_ptr = r_ptr+num_pix;
b_ptr = g_ptr+num_pix;
y_ptr = odata;
cb_ptr = y_ptr+num_pix;
cr_ptr = cb_ptr+num_pix;
for(i = 0; i < num_pix; i++){
/* Compute float Y,Cb,Cr. */
dy = (( 0.299 * (*r_ptr)) +
( 0.587 * (*g_ptr)) +
( 0.114 * (*b_ptr)));
dcb = ((-0.1687 * (*r_ptr)) +
(-0.3313 * (*g_ptr)) +
( 0.5 * (*b_ptr)) +
128.0);
dcr = (( 0.5 * (*r_ptr)) +
(-0.4177 * (*g_ptr)) +
(-0.0813 * (*b_ptr)) +
128.0);
/* Round to integer Y,Cb,Cr. */
iy = sround(dy);
icb = sround(dcb);
icr = sround(dcr);
/* Limit Y,Cb,Cr to [0..255]. */
iy = (iy < 0) ? 0 : ((iy > 255) ? 255 : iy);
icb = (icb < 0) ? 0 : ((icb > 255) ? 255 : icb);
icr = (icr < 0) ? 0 : ((icr > 255) ? 255 : icr);
/* Store uchar Y,Cb,Cr. */
*y_ptr = iy;
*cb_ptr = icb;
*cr_ptr = icr;
r_ptr++;
g_ptr++;
b_ptr++;
y_ptr++;
cb_ptr++;
cr_ptr++;
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
int downsample_cmpnts(unsigned char **oodata, int *oolen,
unsigned char *idata,
const int width, const int height, const int depth,
int *hor_sampfctr, int *vrt_sampfctr, const int n_cmpnts)
{
int i, sampling, max_olen, olen, ow, oh;
int iplane_size, oplane_size;
unsigned char *odata, *iptr, *optr;
int max_hor, max_vrt;
int win_hor[MAX_CMPNTS], win_vrt[MAX_CMPNTS];
if(n_cmpnts <= 1){
fprintf(stderr, "ERROR : downsample_cmpnts : ");
fprintf(stderr, "# of components = %d < 2\n", n_cmpnts);
return(-2);
}
if(!test_evenmult_sampfctrs(&max_hor, &max_vrt,
hor_sampfctr, vrt_sampfctr, n_cmpnts)){
fprintf(stderr, "ERROR : downsample_cmpnts : ");
fprintf(stderr, "sample factors must be even multiples\n");
return(-3);
}
sampling = 0;
for(i = 0; i < n_cmpnts; i++){
win_hor[i] = max_hor / hor_sampfctr[i];
win_vrt[i] = max_vrt / vrt_sampfctr[i];
if((win_hor[i] != 1) || (win_vrt[i] != 1))
sampling = 1;
}
max_olen = width * height * n_cmpnts;
odata = (unsigned char *)malloc(max_olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : downsample_cmpnts : malloc : odata\n");
return(-4);
}
/* If no downsampling to be done, then memcpy entire input image */
/* and return, rather than do all the pixel addressing and assignments. */
if(!sampling){
memcpy(odata, idata, max_olen);
*oodata = odata;
*oolen = max_olen;
return(0);
}
/* Foreach component plane ... */
iptr = idata;
iplane_size = width * height;
optr = odata;
olen = 0;
for(i = 0; i < n_cmpnts; i++){
window_avr_plane(optr, &ow, &oh, win_hor[i], win_vrt[i],
iptr, width, height);
iptr += iplane_size;
oplane_size = ow * oh;
optr += oplane_size;
olen += oplane_size;
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
void window_avr_plane(unsigned char *odata, int *oow, int *ooh,
const int win_w, const int win_h,
unsigned char *idata, const int iw, const int ih)
{
int ox, oy, ow, oh;
unsigned char *siptr, *wiptr, *optr;
int ivrt_offset, last_win_w, last_win_h;
ow = (int)ceil(iw / (double)win_w);
oh = (int)ceil(ih / (double)win_h);
last_win_w = iw % win_w;
if(last_win_w == 0)
last_win_w = win_w;
last_win_h = ih % win_h;
if(last_win_h == 0)
last_win_h = win_h;
ivrt_offset = win_h * iw;
siptr = idata;
optr = odata;
for(oy = 0; oy < oh-1; oy++){
wiptr = siptr;
for(ox = 0; ox < ow-1; ox++){
*optr++ = avr_window(wiptr, win_w, win_h, iw, ih);
wiptr += win_w;
}
*optr++ = avr_window(wiptr, last_win_w, win_h, iw, ih);
siptr += ivrt_offset;
}
wiptr = siptr;
for(ox = 0; ox < ow-1; ox++){
*optr++ = avr_window(wiptr, win_w, last_win_h, iw, ih);
wiptr += win_w;
}
*optr++ = avr_window(wiptr, last_win_w, last_win_h, iw, ih);
*oow = ow;
*ooh = oh;
return;
}
/*****************************************************************/
int avr_window(unsigned char *wptr, const int win_w, const int win_h,
const int img_w, const int img_h)
{
unsigned char *pptr, *sptr;
int x, y;
int win_sum, win_num;
int win_avr;
win_num = win_w * win_h;
win_sum = 0;
sptr = wptr;
for(y = 0; y < win_h; y++){
pptr = sptr;
for(x = 0; x < win_w; x++){
win_sum += *pptr++;
}
sptr += img_w;
}
win_avr = (int)((win_sum / (double)win_num) + 0.5);
return(win_avr);
}
/*****************************************************************/
int ycc2rgb_mem(unsigned char **odata, int *olen, unsigned char *idata,
const int width, const int height, const int depth,
const int intrlvflag)
{
int ret;
if(intrlvflag){
if((ret = ycc2rgb_intrlv_mem(odata, olen, idata, width, height, depth)))
return(ret);
}
else{
if((ret = ycc2rgb_nonintrlv_mem(odata, olen, idata,
width, height, depth)))
return(ret);
}
return(0);
}
/*****************************************************************/
int ycc2rgb_intrlv_mem(unsigned char **oodata, int *oolen,
unsigned char *idata,
const int width, const int height, const int depth)
{
int i, num_pix, olen;
unsigned char *y_ptr, *cb_ptr, *cr_ptr;
unsigned char *r_ptr, *g_ptr, *b_ptr;
unsigned char *odata;
double dr, dg, db;
int ir, ig, ib;
/* If image has empty dimension, then done ... */
if((width == 0) || (height == 0))
return(0);
if(depth != 24){
fprintf(stderr, "ERROR : ycc2rgb_intrlv_mem : depth = %d != 24\n",
depth);
return(-2);
}
num_pix = width * height;
olen = num_pix * (depth>>3);
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : ycc2rgb_intrlv_mem : malloc : odata\n");
return(-3);
}
for(i = 0,
y_ptr = idata,
cb_ptr = idata+1,
cr_ptr = idata+2,
r_ptr = odata,
g_ptr = odata+1,
b_ptr = odata+2;
i < num_pix;
i++,
y_ptr+=3,
cb_ptr+=3,
cr_ptr+=3,
r_ptr+=3,
g_ptr+=3,
b_ptr+=3){
/* Compute float R,G,B. */
dr = ((*y_ptr) + ( 1.402 * ((*cr_ptr) - 128.0)));
dg = ((*y_ptr) + (-0.34414 * ((*cb_ptr) - 128.0)) +
(-0.71414 * ((*cr_ptr) - 128.0)));
db = ((*y_ptr) + ( 1.772 * ((*cb_ptr) - 128.0)));
/* Compute integer R,G,B. */
ir = sround(dr);
ig = sround(dg);
ib = sround(db);
/* Limit R,G,B to [0..255]. */
ir = (ir < 0) ? 0 : ((ir > 255) ? 255 : ir);
ig = (ig < 0) ? 0 : ((ig > 255) ? 255 : ig);
ib = (ib < 0) ? 0 : ((ib > 255) ? 255 : ib);
/* Store uchar R,G,B. */
*r_ptr = ir;
*g_ptr = ig;
*b_ptr = ib;
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
int ycc2rgb_nonintrlv_mem(unsigned char **oodata, int *oolen,
unsigned char *idata,
const int width, const int height, const int depth)
{
int i, num_pix, olen;
unsigned char *y_ptr, *cb_ptr, *cr_ptr;
unsigned char *r_ptr, *g_ptr, *b_ptr;
unsigned char *odata;
double dr, dg, db;
int ir, ig, ib;
/* If image has empty dimension, then done ... */
if((width == 0) || (height == 0))
return(0);
if(depth != 24){
fprintf(stderr, "ERROR : ycc2rgb_nonintrlv_mem : depth = %d != 24\n",
depth);
return(-2);
}
num_pix = width * height;
olen = num_pix * (depth>>3);
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : ycc2rgb_nonintrlv_mem : malloc : odata\n");
return(-3);
}
y_ptr = idata;
cb_ptr = y_ptr+num_pix;
cr_ptr = cb_ptr+num_pix;
r_ptr = odata;
g_ptr = r_ptr+num_pix;
b_ptr = g_ptr+num_pix;
for(i = 0; i < num_pix; i++){
/* Compute float R,G,B. */
dr = ((*y_ptr) + ( 1.402 * ((*cr_ptr) - 128.0)));
dg = ((*y_ptr) + (-0.34414 * ((*cb_ptr) - 128.0)) +
(-0.71414 * ((*cr_ptr) - 128.0)));
db = ((*y_ptr) + ( 1.772 * ((*cb_ptr) - 128.0)));
/* Compute integer R,G,B. */
ir = sround(dr);
ig = sround(dg);
ib = sround(db);
/* Limit R,G,B to [0..255]. */
ir = (ir < 0) ? 0 : ((ir > 255) ? 255 : ir);
ig = (ig < 0) ? 0 : ((ig > 255) ? 255 : ig);
ib = (ib < 0) ? 0 : ((ib > 255) ? 255 : ib);
/* Store uchar R,G,B. */
*r_ptr = ir;
*g_ptr = ig;
*b_ptr = ib;
y_ptr++;
cb_ptr++;
cr_ptr++;
r_ptr++;
g_ptr++;
b_ptr++;
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
int upsample_cmpnts(unsigned char **oodata, int *oolen,
unsigned char *idata,
const int width, const int height, const int depth,
int *hor_sampfctr, int *vrt_sampfctr, const int n_cmpnts)
{
int i, sampling, olen;
int iplane_size, oplane_size;
unsigned char *odata, *iptr, *optr;
int max_hor, max_vrt;
int win_hor[MAX_CMPNTS], win_vrt[MAX_CMPNTS];
int samp_width[MAX_CMPNTS], samp_height[MAX_CMPNTS];
if(n_cmpnts <= 1){
fprintf(stderr, "ERROR : upsample_cmpnts : ");
fprintf(stderr, "# of components = %d < 2\n", n_cmpnts);
return(-2);
}
if(!test_evenmult_sampfctrs(&max_hor, &max_vrt,
hor_sampfctr, vrt_sampfctr, n_cmpnts)){
fprintf(stderr, "ERROR : upsample_cmpnts : ");
fprintf(stderr, "sample factors must be even multiples\n");
return(-3);
}
sampling = 0;
for(i = 0; i < n_cmpnts; i++){
win_hor[i] = max_hor / hor_sampfctr[i];
win_vrt[i] = max_vrt / vrt_sampfctr[i];
if((win_hor[i] != 1) || (win_vrt[i] != 1))
sampling = 1;
/* Compute the pixel width & height of the component's input plane. */
samp_width[i] = (int)ceil(width *
(hor_sampfctr[i] / (double)max_hor));
samp_height[i] = (int)ceil(height *
(vrt_sampfctr[i] / (double)max_vrt));
}
olen = width * height * n_cmpnts;
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : upsample_cmpnts : malloc : odata\n");
return(-4);
}
/* If no upsampling to be done, then memcpy entire input image and */
/* return, rather than do all the pixel addressing and assignments. */
if(!sampling){
memcpy(odata, idata, olen);
*oodata = odata;
*oolen = olen;
return(0);
}
/* Foreach component plane ... */
iptr = idata;
optr = odata;
oplane_size = width * height;
for(i = 0; i < n_cmpnts; i++){
window_fill_plane(optr, width, height, win_hor[i], win_vrt[i],
iptr, samp_width[i], samp_height[i]);
iplane_size = samp_width[i] * samp_height[i];
iptr += iplane_size;
optr += oplane_size;
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
void window_fill_plane(unsigned char *odata, const int ow, const int oh,
const int win_w, const int win_h,
unsigned char *idata, const int iw, const int ih)
{
int ix, iy;
unsigned char *soptr, *woptr, *iptr;
int ovrt_offset, last_win_w, last_win_h;
last_win_w = ow % win_w;
if(last_win_w == 0)
last_win_w = win_w;
last_win_h = oh % win_h;
if(last_win_h == 0)
last_win_h = win_h;
ovrt_offset = win_h * ow;
soptr = odata;
iptr = idata;
for(iy = 0; iy < ih-1; iy++){
woptr = soptr;
for(ix = 0; ix < iw-1; ix++){
fill_window(*iptr, woptr, win_w, win_h, ow, oh);
iptr++;
woptr += win_w;
}
fill_window(*iptr, woptr, last_win_w, win_h, ow, oh);
iptr++;
soptr += ovrt_offset;
}
woptr = soptr;
for(ix = 0; ix < iw-1; ix++){
fill_window(*iptr, woptr, win_w, last_win_h, ow, oh);
iptr++;
woptr += win_w;
}
fill_window(*iptr, woptr, last_win_w, last_win_h, ow, oh);
return;
}
/*****************************************************************/
void fill_window(const unsigned char fillval, unsigned char *wptr,
const int win_w, const int win_h,
const int img_w, const int img_h)
{
unsigned char *pptr, *sptr;
int x, y;
sptr = wptr;
for(y = 0; y < win_h; y++){
pptr = sptr;
for(x = 0; x < win_w; x++){
*pptr++ = fillval;
}
sptr += img_w;
}
}
/*****************************************************************/
/* TRUE if even mulitples, FALSE if not. */
/*****************************************************************/
int test_evenmult_sampfctrs(int *omax_hor, int *omax_vrt,
int *hor_sampfctr, int *vrt_sampfctr, const int n_cmpnts)
{
int i, max_hor, max_vrt;
max_hor = -1;
max_vrt = -1;
for(i = 0; i < n_cmpnts; i++){
if(max_hor < hor_sampfctr[i])
max_hor = hor_sampfctr[i];
if(max_vrt < vrt_sampfctr[i])
max_vrt = vrt_sampfctr[i];
}
/* Test for non-even mulitple sample factors ... */
for(i = 0; i < n_cmpnts; i++){
if((max_hor % hor_sampfctr[i]) ||
(max_vrt % vrt_sampfctr[i])){
return(0);
}
}
*omax_hor = max_hor;
*omax_vrt = max_vrt;
return(1);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/dilate.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: DILATE.C
AUTHORS: <NAME>
DATE: 09/20/2004
UPDATED: 03/14/2005 by MDG
Contains routines to dilate a char image.
***********************************************************************
ROUTINES:
#cat: dilate_charimage - set false pixel to one if any of 4 neighbors is one
#cat: in a character image.
#cat: get_south8 - return value of char image pixel 1 below of current pixel
#cat: if defined else return (char)0
#cat: get_north8 - return value of char image pixel 1 above of current pixel
#cat: if defined else return (char)0
#cat: get_east8 - return value of char image pixel 1 right of current pixel
#cat: if defined else return (char)0
#cat: get_west8 - return value of char image pixel 1 left of current pixel
#cat: if defined else return (char)0
***********************************************************************/
#include <memory.h>
#include <memalloc.h>
#include <dilate.h>
/******************************************************************/
/* dilate a one bit per byte char image, inp. Result is out which */
/* must be disjoint with inp. The data in out before the call is */
/* irrelevant, and is zeroed and filled by this routine. iw and */
/* ih are the width and height of the image in pixels. Both inp */
/* and out point to iw*ih bytes */
/******************************************************************/
int dilate_charimage(unsigned char *inp, unsigned char **out, const int iw,
const int ih)
{
int row, col, ret;
unsigned char *itr, *otr;
if((ret = malloc_uchar_ret(out, iw*ih, "dilate_charimage out")))
return(ret);
itr = inp;
otr = *out;
memcpy(otr, inp, iw*ih);
/* for all pixels. set pixel if there is at least one true neighbor */
for ( row = 0 ; row < ih ; row++ )
for ( col = 0 ; col < iw ; col++ )
{
if (!*itr) /* pixel is already true, neighbors irrelevant */
{
/* more efficient with C's left to right evaluation of */
/* conjuctions. E N S functions not executed if W is false */
if (get_west8 ((char *)itr, col ) ||
get_east8 ((char *)itr, col, iw ) ||
get_north8((char *)itr, row, iw ) ||
get_south8((char *)itr, row, iw, ih))
*otr = 1;
}
itr++ ; otr++;
}
return(0);
}
/************************************************************************/
/* routines for accessing individual neighbors of pixel at (row,col) */
/* row and pixel are zero oriented. That is 0 <= row < ih and */
/* 0 <= col < iw. ptr points to the (row,col) element of the ih by iw */
/* sized char image which contains as many >bytes< as there are pixels */
/* in the image. */
/************************************************************************/
char get_south8(char *ptr, const int row, const int iw, const int ih)
{
if (row >= ih-1) /* catch case where image is undefined southwards */
return 0; /* use plane geometry and return false. */
return *(ptr+iw);
}
char get_north8(char *ptr, const int row, const int iw)
{
if (row < 1) /* catch case where image is undefined northwards */
return 0; /* use plane geometry and return false. */
return *(ptr-iw);
}
char get_east8(char *ptr, const int col, const int iw)
{
if (col >= iw-1) /* catch case where image is undefined eastwards */
return 0; /* use plane geometry and return false. */
return *(ptr+ 1);
}
char get_west8(char *ptr, const int col)
{
if (col < 1) /* catch case where image is undefined westwards */
return 0; /* use plane geometry and return false. */
return *(ptr- 1);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/img_io.c
|
<reponame>ThalesGroup/WSQForAndroid<filename>library/src/main/cpp/nbis/imgtools/src/lib/image/img_io.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: IMG_IO.C
AUTHORS: <NAME>
<NAME>
DATE: 01/16/2001
UPDATED: 03/15/2005 by MDG
UPDATED: 12/22/2008 by <NAME> - add read_raw()/read_ihead()
Contains routines responsible for alternatively reading/writing
pixmaps from/to an IHead or raw image file.
ROUTINES:
#cat: read_raw_from_filesize - reads a pixmap from an image file based
#cat: on the size of the file in bytes.
#cat: write_raw_from_memsize - writes a pimap to an image file given
#cat: a filled memory buffer.
#cat: read_ihead - reads a pixmap from an IHead image
#cat: read_raw - reads a pixmap from a raw image
#cat: read_raw_or_ihead_wsq - reads a pixmap from either an IHead or raw
#cat: image file based on a specified flag and tests the
#cat: pixmap's attributes to ensure WSQ compatability.
#cat: write_raw_or_ihead - writes a pixmap to either an IHead or
#cat: raw image file based on a specified flag.
***********************************************************************/
#include <img_io.h>
/***********************************************************************/
/* Reads a pixmap from image file based on the byte size of the file . */
/***********************************************************************/
int read_raw_from_filesize(char *ifile, unsigned char **odata, int *ofsize)
{
unsigned char *idata;
int ret, n, fsize;
FILE *infp;
if((ret = filesize(ifile)) < 0)
return(ret);
fsize = ret;
if((infp = fopen(ifile, "rb")) == (FILE *)NULL){
fprintf(stderr, "ERORR : read_raw_from_filesize : fopen : %s\n", ifile);
return(-2);
}
idata = (unsigned char *)malloc(fsize * sizeof(unsigned char));
if(idata == (unsigned char *)NULL){
fprintf(stderr, "ERORR : read_raw_from_filesize : malloc : idata\n");
return(-3);
}
n = fread(idata, sizeof(unsigned char), fsize, infp);
if(n != fsize){
fprintf(stderr, "ERORR : main : read_raw_from_filesize : ");
fprintf(stderr, "%d of %d bytes read from %s\n",
n, fsize, ifile);
return(-4);
}
fclose(infp);
*odata = idata;
*ofsize = fsize;
return(0);
}
/***********************************************************************/
/* Writes a pixmap to an image file given a filled memory buffer. */
/***********************************************************************/
int write_raw_from_memsize(char *ofile, unsigned char *odata, const int olen)
{
FILE *outfp;
int n;
if((outfp = fopen(ofile, "wb")) == NULL) {
fprintf(stderr, "ERROR: write_raw_from_memsize : fopen : %s\n", ofile);
return(-2);
}
if((n = fwrite(odata, 1, olen, outfp)) != olen){
fprintf(stderr, "ERROR: write_raw_from_memsize : fwrite : ");
/* Typo corrected on following line by MDG on 03-15-05 */
/* "%" with "%s" was missing */
fprintf(stderr, "only %d of %d bytes written from file %s\n",
n, olen, ofile);
return(-3);
}
fclose(outfp);
return(0);
}
/************************************************************/
/* Reads a pixmap from an IHead image file. */
/************************************************************/
int read_ihead(char *ifile, IHEAD **ohead, unsigned char **odata, int *owidth,
int *oheight, int *odepth)
{
IHEAD *ihead;
unsigned char *idata;
int width, height, depth;
/* Read the specified input file as an IHead image. */
ReadIheadRaster(ifile, &ihead, &idata, &width, &height, &depth);
/* Image must be 8-bit grayscale. */
if((depth != 8) && (depth != 24)){
free(ihead);
free(idata);
fprintf(stderr, "ERROR: read_ihead : ");
fprintf(stderr, "image depth = %d not 8 or 24\n", depth);
return(-2);
}
*ohead = ihead;
*odata = idata;
*owidth = width;
*oheight = height;
*odepth = depth;
return(0);
}
/************************************************************/
/* Reads a pixmap from a "raw" image file. */
/************************************************************/
int read_raw(char *ifile, unsigned char **odata, int *owidth, int *oheight,
int *odepth)
{
unsigned char *idata;
int width, height, depth;
int num_pix, img_siz;
FILE *infp;
/* Compute total number of pixels in input image. */
width = *owidth;
height = *oheight;
depth = *odepth;
if((depth != 8) && (depth != 24)){
fprintf(stderr, "ERROR: read_raw : ");
fprintf(stderr, "image depth = %d not 8 or 24\n", depth);
return(-3);
}
num_pix = width * height * (depth>>3);
/* Allocate the pixmap buffer. */
idata = (unsigned char *)malloc(num_pix*sizeof(unsigned char));
if(idata == (unsigned char *)NULL) {
fprintf(stderr,"ERROR : read_raw : malloc : idata\n");
return(-4);
}
/* Open the input image file for reading ... */
if((infp = fopen(ifile, "rb")) == (FILE *)NULL) {
fprintf(stderr, "ERROR: read_raw : %s\n", ifile);
return(-5);
}
/* Read the pixmap from the open file. */
img_siz = fread(idata, sizeof(unsigned char), num_pix, infp);
/* If anticipated number of pixels not read, then ERROR. */
if(img_siz != num_pix) {
free(idata);
fprintf(stderr, "ERROR : read_raw : fread : ");
fprintf(stderr, "only read %d of %d bytes\n",
img_siz, num_pix);
return(-6);
}
/* Close the file. */
fclose(infp);
*odata = idata;
*owidth = width;
*oheight = height;
*odepth = depth;
return(0);
}
/************************************************************/
/* Reads a pixmap from either an IHead or "raw" image file. */
/************************************************************/
int read_raw_or_ihead_wsq(const int iheadflag, char *ifile, IHEAD **ohead,
unsigned char **odata, int *owidth, int *oheight, int *odepth)
{
int ret, width, height;
/* If IHead image flagged ... */
if(iheadflag) {
if((ret = read_ihead(ifile, ohead, odata, owidth, oheight, odepth)))
return ret;
}
/* Otherwise, input image is a raw pixmap... */
else {
if((ret = read_raw(ifile, odata, owidth, oheight, odepth)))
return ret;
}
if(*odepth != 8){
fprintf(stderr, "ERROR: read_raw_or_ihead_wsq : ");
fprintf(stderr, "image depth = %d not 8\n", *odepth);
return(-2);
}
width = *owidth;
height = *oheight;
/* If image is too small ... */
if(width < MIN_IMG_DIM || height < MIN_IMG_DIM) {
if(iheadflag) {
free(*ohead);
}
free(*odata);
fprintf(stderr,
"ERROR: read_raw_or_ihead_wsq : Image must be at least %d X %d\n",
MIN_IMG_DIM, MIN_IMG_DIM);
fprintf(stderr,
" width = %d :: height = %d\n",
width, height);
return(-3);
}
return(0);
}
/************************************************************/
/* Writes a pixmap to either an IHead or "raw" image file. */
/************************************************************/
int write_raw_or_ihead(const int iheadflag, char *ofile,
unsigned char *odata, const int width, const int height,
const int depth, const int ppi)
{
FILE *outfp;
int n, olen;
IHEAD *ihead;
if((depth != 8) && (depth != 24)){
fprintf(stderr, "ERROR: write_raw_or_ihead : ");
fprintf(stderr, "image depth = %d not 8 or 24\n", depth);
return(-2);
}
outfp = fopen(ofile,"wb");
if (outfp == (FILE *)NULL) {
fprintf(stderr, "ERROR : write_raw_or_ihead : fopen : %s\n", ofile);
return(-3);
}
if(iheadflag){
ihead = (IHEAD *)malloc(sizeof(IHEAD));
if(ihead == (IHEAD *)NULL){
fprintf(stderr, "ERROR : write_raw_or_ihead : malloc : ihead\n");
return(-5);
}
nullihdr(ihead);
set_id(ihead, ofile);
set_created(ihead);
set_width(ihead, width);
set_height(ihead, height);
set_depth(ihead, depth);
set_density(ihead, ppi);
set_align(ihead, 8);
set_compression(ihead, 0);
set_complen(ihead, 0);
/* If grayscale ... */
if(depth == 8)
set_whitepix(ihead, 255);
/* Otherwise, RGB truecolor, so whitepix is ignored. */
else
set_whitepix(ihead, -1);
writeihdr(outfp, ihead);
free(ihead);
}
olen = width * height * (depth>>3);
n = fwrite(odata, 1, olen, outfp);
if (n != olen) {
fprintf(stderr, "ERROR : write_raw_or_ihead : fwrite : odata\n");
return(-5);
}
fclose(outfp);
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/util/bubble.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: FING - NIST Fingerprint Systems Utilities
FILE: BUBBLE.C
ALGORITHM: <NAME>
DATE: 09/20/2004
***********************************************************************
ROUTINES:
#cat: bubble_sort_int - sorts a list of integers into decreasing order with a
#cat: bubble sort. It is destructive to the integer list
#cat: passed to it.
***********************************************************************/
#include<swap.h>
/***************************************************************************/
void bubble_sort_int(int *pts, const int n)
{
int done = 0;
int i, p;
p = n;
while(!done){
done = 1;
for (i=1;i<p;i++){
if(pts[i-1] < pts[i]){
swap_int(pts[i-1], pts[i]);
done = 0;
}
}
p--;
}
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/wsq/tableio.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: WSQ - Grayscale Image Compression
FILE: TABLEIO.C
AUTHORS: <NAME>
<NAME>
DATE: 12/24/1999
UPDATED: 02/24/2005 by MDG
UPDATED: 03/08/2005 by MDG
Contains routines responsible for reading and writing the various
tables and blocks used by the WSQ encoder/decoder.
ROUTINES:
#cat: read_marker_wsq - Reads a specified WSQ marker from an open file.
#cat:
#cat: getc_marker_wsq - Reads a specified WSQ marker from a memory buffer.
#cat:
#cat: read_table_wsq - Reads a specified WSQ table from an open file.
#cat:
#cat: getc_table_wsq - Reads a specified WSQ table from a memory buffer.
#cat:
#cat: read_transform_table - Reads in a WSQ transform table from an
#cat: open file.
#cat: getc_transform_table - Reads in a WSQ transform table from a
#cat: memory buffer.
#cat: write_transform_table - Writes a WSQ transform table to an
#cat: open file.
#cat: putc_transform_table - Writes a WSQ transform table to a
#cat: memory buffer.
#cat: read_quantization_table - Reads a WSQ quantization table from an
#cat: open file.
#cat: getc_quantization_table - Reads a WSQ quantization table from a
#cat: memory buffer.
#cat: write_quantization_table - Writes a WSQ quantization table to an
#cat: open file.
#cat: putc_quantization_table - Writes a WSQ quantization table to a
#cat: memory buffer.
#cat: read_huffman_table_wsq - Reads a WSQ huffman table from an
#cat: open file.
#cat: getc_huffman_table_wsq - Reads a WSQ huffman table from a
#cat: memory buffer.
#cat: read_frame_header_wsq - Reads a WSQ Frame header from an open file.
#cat:
#cat: getc_frame_header_wsq - Reads a WSQ Frame header from a memory buffer.
#cat:
#cat: write_frame_header_wsq - Writes a WSQ Frame header to an open file.
#cat:
#cat: putc_frame_header_wsq - Writes a WSQ Frame header to a memory buffer.
#cat:
#cat: read_block_header - Reads a WSQ Block header from an open file.
#cat:
#cat: getc_block_header - Reads a WSQ Block header from a memory buffer.
#cat:
#cat: write_block_header - Writes a WSQ Block header to an open file.
#cat:
#cat: putc_block_header - Writes a WSQ Block header to a memory buffer.
#cat:
#cat: add_comment_wsq - Inserts a NISTCOM comment block into a
#cat: WSQ compressed datastream through an open file.
#cat: putc_nistcom_wsq - Inserts a NISTCOM comment block into a
#cat: WSQ compressed datastream through a memory buffer.
#cat: read_nistcom_wsq - Gets and returns the first NISTCOM comment block
#cat: in an open file.
#cat: getc_nistcom_wsq - Gets and returns the first NISTCOM comment block
#cat: in a memory buffer.
#cat: print_comments_wsq - Gets and prints the first NISTOCM comment block
#cat: in a WSQ compressed memory buffer to a specified
#cat: file pointer.
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wsq.h>
#include <computil.h>
#include <dataio.h>
#include <swap.h>
#include <defs.h>
#include <android/log.h>
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "tableio.c",__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "tableio.c",__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO , "tableio.c",__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN , "tableio.c",__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , "tableio.c",__VA_ARGS__)
/***********************************/
/* Routine to read in WSQ markers. */
/***********************************/
int read_marker_wsq(
unsigned short *omarker, /* marker read */
const int type, /* type of markers that could be found */
FILE *infp) /* input file */
{
int ret;
unsigned short marker; /* WSQ marker */
if((ret = read_ushort(&marker, infp)))
return(ret);
switch(type){
case SOI_WSQ:
if(marker != SOI_WSQ) {
fprintf(stderr,
"ERROR : read_marker_wsq : No SOI marker. {%u}\n", marker);
return(-70);
}
break;
case TBLS_N_SOF:
if(marker != DTT_WSQ && marker != DQT_WSQ && marker != DHT_WSQ
&& marker != SOF_WSQ && marker != COM_WSQ) {
fprintf(stderr,
"ERROR : read_marker_wsq : No SOF, Table, or comment markers.\n");
return(-71);
}
break;
case TBLS_N_SOB:
if(marker != DTT_WSQ && marker != DQT_WSQ && marker != DHT_WSQ
&& marker != SOB_WSQ && marker != COM_WSQ) {
fprintf(stderr,
"ERROR : read_marker_wsq : No SOB, Table, or comment markers.\n");
return(-72);
}
break;
case ANY_WSQ:
if((marker & 0xff00) != 0xff00){
fprintf(stderr,"ERROR : read_marker_wsq : no marker found {%04X}\n",
marker);
return(-73);
}
/* Added by MDG on 03-07-05 */
if((marker < SOI_WSQ) || (marker > COM_WSQ)){
fprintf(stderr,"ERROR : read_marker_wsq : {%04X} not a valid marker\n",
marker);
return(-74);
}
break;
default:
fprintf(stderr,
"ERROR : read_marker_wsq : Invalid marker -> {%4X}\n", marker);
return(-75);
}
*omarker = marker;
return(0);
}
/******************************************************/
/* Routine to read in WSQ markers from memory buffer. */
/******************************************************/
int getc_marker_wsq(
unsigned short *omarker, /* marker read */
const int type, /* type of markers that could be found */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned short marker; /* WSQ marker */
if((ret = getc_ushort(&marker, cbufptr, ebufptr)))
return(ret);
switch(type){
case SOI_WSQ:
if(marker != SOI_WSQ) {
LOGE("ERROR : getc_marker_wsq : No SOI marker. {%04X}", marker);
return(-88);
}
break;
case TBLS_N_SOF:
if(marker != DTT_WSQ && marker != DQT_WSQ && marker != DHT_WSQ
&& marker != SOF_WSQ && marker != COM_WSQ) {
fprintf(stderr,
"ERROR : getc_marker_wsq : No SOF, Table, or comment markers.\n");
return(-89);
}
break;
case TBLS_N_SOB:
if(marker != DTT_WSQ && marker != DQT_WSQ && marker != DHT_WSQ
&& marker != SOB_WSQ && marker != COM_WSQ) {
fprintf(stderr,
"ERROR : getc_marker_wsq : No SOB, Table, or comment markers.{%04X}\n",
marker);
return(-90);
}
break;
case ANY_WSQ:
if((marker & 0xff00) != 0xff00){
fprintf(stderr,"ERROR : getc_marker_wsq : no marker found {%04X}\n",
marker);
return(-91);
}
/* Added by MDG on 03-07-05 */
if((marker < SOI_WSQ) || (marker > COM_WSQ)){
fprintf(stderr,"ERROR : getc_marker_wsq : {%04X} not a valid marker\n",
marker);
return(-92);
}
break;
default:
fprintf(stderr,
"ERROR : getc_marker_wsq : Invalid marker -> {%4X}\n", marker);
return(-93);
}
*omarker = marker;
return(0);
}
/************************************/
/* Routine to read specified table. */
/************************************/
int read_table_wsq(
unsigned short marker, /* WSQ marker */
DTT_TABLE *dtt_table, /* transform table structure */
DQT_TABLE *dqt_table, /* quantization table structure */
DHT_TABLE *dht_table, /* huffman table structure */
FILE *infp) /* input file */
{
int ret;
unsigned char *comment;
switch(marker){
case DTT_WSQ:
if((ret = read_transform_table(dtt_table, infp)))
return(ret);
break;
case DQT_WSQ:
if((ret = read_quantization_table(dqt_table, infp)))
return(ret);
break;
case DHT_WSQ:
if((ret = read_huffman_table_wsq(dht_table, infp)))
return(ret);
break;
case COM_WSQ:
if((ret = read_comment(&comment, infp)))
return(ret);
#ifdef PRINT_COMMENT
fprintf(stderr, "COMMENT:\n%s\n\n", comment);
#endif
free(comment);
break;
default:
fprintf(stderr,"ERROR: read_table_wsq : Invalid table defined -> {%u}\n",
marker);
return(-75);
}
return(0);
}
/*******************************************************/
/* Routine to read specified table from memory buffer. */
/*******************************************************/
int getc_table_wsq(
unsigned short marker, /* WSQ marker */
DTT_TABLE *dtt_table, /* transform table structure */
DQT_TABLE *dqt_table, /* quantization table structure */
DHT_TABLE *dht_table, /* huffman table structure */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned char *comment;
switch(marker){
case DTT_WSQ:
if((ret = getc_transform_table(dtt_table, cbufptr, ebufptr)))
return(ret);
break;
case DQT_WSQ:
if((ret = getc_quantization_table(dqt_table, cbufptr, ebufptr)))
return(ret);
break;
case DHT_WSQ:
if((ret = getc_huffman_table_wsq(dht_table, cbufptr, ebufptr)))
return(ret);
break;
case COM_WSQ:
if((ret = getc_comment(&comment, cbufptr, ebufptr)))
return(ret);
#ifdef PRINT_COMMENT
fprintf(stderr, "COMMENT:\n%s\n\n", comment);
#endif
free(comment);
break;
default:
fprintf(stderr,"ERROR: getc_table_wsq : Invalid table defined -> {%u}\n",
marker);
return(-93);
}
return(0);
}
/**************************************************/
/* Routine to read in transform table parameters. */
/**************************************************/
int read_transform_table(
DTT_TABLE *dtt_table, /* transform table structure */
FILE *infp) /* input file */
{
int ret;
unsigned short hdr_size; /* header size */
float *a_lofilt, *a_hifilt; /* unexpanded filter coefficients */
unsigned char a_size; /* size of unexpanded coefficients */
unsigned int cnt, shrt_dat; /* counter and temp short data */
unsigned char scale, sign; /* scaling and sign parameters */
if(debug > 0)
fprintf(stderr, "Reading transform table.\n");
if((ret = read_ushort(&hdr_size, infp)))
return(ret);
if((ret = read_byte(&(dtt_table->hisz), infp)))
return(ret);
if((ret = read_byte(&(dtt_table->losz), infp)))
return(ret);
if(debug > 2) {
fprintf(stderr, "losize = %d\n", dtt_table->losz);
fprintf(stderr, "hisize = %d\n", dtt_table->hisz);
}
/* Added 02-24-05 by MDG */
/* If lofilt member previously allocated ... */
if(dtt_table->lofilt != (float *)NULL){
/* Deallocate the member prior to new allocation */
free(dtt_table->lofilt);
dtt_table->lofilt = (float *)NULL;
}
dtt_table->lofilt = (float *)calloc(dtt_table->losz,sizeof(float));
if(dtt_table->lofilt == (float *)NULL) {
fprintf(stderr,
"ERROR : read_transform_table : calloc : lofilt\n");
return(-76);
}
/* Added 02-24-05 by MDG */
/* If hifilt member previously allocated ... */
if(dtt_table->hifilt != (float *)NULL){
/* Deallocate the member prior to new allocation */
free(dtt_table->hifilt);
dtt_table->hifilt = (float *)NULL;
}
dtt_table->hifilt = (float *)calloc(dtt_table->hisz,sizeof(float));
if(dtt_table->hifilt == (float *)NULL) {
free(dtt_table->lofilt);
fprintf(stderr,
"ERROR : read_transform_table : calloc : hifilt\n");
return(-77);
}
if(dtt_table->hisz % 2)
a_size = (dtt_table->hisz + 1) / 2;
else
a_size = dtt_table->hisz / 2;
a_lofilt = (float *) calloc(a_size, sizeof(float));
if(a_lofilt == (float *)NULL) {
free(dtt_table->lofilt);
free(dtt_table->hifilt);
fprintf(stderr,
"ERROR : read_transform_table : calloc : a_lofilt\n");
return(-78);
}
a_size--;
for(cnt = 0; cnt <= a_size; cnt++) {
if((ret = read_byte(&sign, infp))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_lofilt);
return(ret);
}
if((ret = read_byte(&scale, infp))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_lofilt);
return(ret);
}
if((ret = read_uint(&shrt_dat, infp))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_lofilt);
return(ret);
}
a_lofilt[cnt] = (float)shrt_dat;
while(scale > 0) {
a_lofilt[cnt] /= 10.0;
scale--;
}
if(sign != 0)
a_lofilt[cnt] *= -1.0;
if(debug > 3)
fprintf(stderr, "lofilt[%d] = %.15f\n", cnt, a_lofilt[cnt]);
if(dtt_table->hisz % 2) {
dtt_table->hifilt[cnt + a_size] = (float)((float)int_sign(cnt)
* a_lofilt[cnt]);
if(cnt > 0)
dtt_table->hifilt[a_size - cnt] = dtt_table->hifilt[cnt + a_size];
}
else {
dtt_table->hifilt[cnt + a_size + 1] = (float)((float)int_sign(cnt)
* a_lofilt[cnt]);
dtt_table->hifilt[a_size - cnt] = -1.0 *
dtt_table->hifilt[cnt + a_size + 1];
}
}
free(a_lofilt);
if(dtt_table->losz % 2)
a_size = (dtt_table->losz + 1) / 2;
else
a_size = dtt_table->losz / 2;
a_hifilt = (float *) calloc(a_size, sizeof(float));
if(a_hifilt == (float *)NULL) {
free(dtt_table->lofilt);
free(dtt_table->hifilt);
fprintf(stderr,
"ERROR : read_transform_table : calloc : a_hifilt\n");
return(-79);
}
a_size--;
for(cnt = 0; cnt <= a_size; cnt++) {
if((ret = read_byte(&sign, infp))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_hifilt);
return(ret);
}
if((ret = read_byte(&scale, infp))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_hifilt);
return(ret);
}
if((ret = read_uint(&shrt_dat, infp))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_hifilt);
return(ret);
}
a_hifilt[cnt] = (float)shrt_dat;
while(scale > 0) {
a_hifilt[cnt] /= 10.0;
scale--;
}
if(sign != 0)
a_hifilt[cnt] *= -1.0;
if(debug > 2)
fprintf(stderr, "hifilt[%d] = %.15f\n", cnt, a_hifilt[cnt]);
if(dtt_table->losz % 2) {
dtt_table->lofilt[cnt + a_size] = (float)((float)int_sign(cnt)
* a_hifilt[cnt]);
if(cnt > 0)
dtt_table->lofilt[a_size - cnt] = dtt_table->lofilt[cnt + a_size];
}
else {
dtt_table->lofilt[cnt + a_size + 1] = (float)((float)int_sign(cnt+1)
* a_hifilt[cnt]);
dtt_table->lofilt[a_size - cnt] = dtt_table->lofilt[cnt + a_size + 1];
}
}
free(a_hifilt);
dtt_table->lodef = 1;
dtt_table->hidef = 1;
if(debug > 0)
fprintf(stderr, "Finished reading transform table.\n\n");
return(0);
}
/*********************************************************************/
/* Routine to read in transform table parameters from memory buffer. */
/*********************************************************************/
int getc_transform_table(
DTT_TABLE *dtt_table, /* transform table structure */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned short hdr_size; /* header size */
float *a_lofilt, *a_hifilt; /* unexpanded filter coefficients */
unsigned char a_size; /* size of unexpanded coefficients */
unsigned int cnt, shrt_dat; /* counter and temp short data */
unsigned char scale, sign; /* scaling and sign parameters */
if(debug > 0)
fprintf(stderr, "Reading transform table.\n");
if((ret = getc_ushort(&hdr_size, cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(&(dtt_table->hisz), cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(&(dtt_table->losz), cbufptr, ebufptr)))
return(ret);
if(debug > 2) {
fprintf(stderr, "losize = %d\n", dtt_table->losz);
fprintf(stderr, "hisize = %d\n", dtt_table->hisz);
}
/* Added 02-24-05 by MDG */
/* If lofilt member previously allocated ... */
if(dtt_table->lofilt != (float *)NULL){
/* Deallocate the member prior to new allocation */
free(dtt_table->lofilt);
dtt_table->lofilt = (float *)NULL;
}
dtt_table->lofilt = (float *)calloc(dtt_table->losz,sizeof(float));
if(dtt_table->lofilt == (float *)NULL) {
fprintf(stderr,
"ERROR : getc_transform_table : calloc : lofilt\n");
return(-94);
}
/* Added 02-24-05 by MDG */
/* If hifilt member previously allocated ... */
if(dtt_table->hifilt != (float *)NULL){
/* Deallocate the member prior to new allocation */
free(dtt_table->hifilt);
dtt_table->hifilt = (float *)NULL;
}
dtt_table->hifilt = (float *)calloc(dtt_table->hisz,sizeof(float));
if(dtt_table->hifilt == (float *)NULL) {
free(dtt_table->lofilt);
fprintf(stderr,
"ERROR : getc_transform_table : calloc : hifilt\n");
return(-95);
}
if(dtt_table->hisz % 2)
a_size = (dtt_table->hisz + 1) / 2;
else
a_size = dtt_table->hisz / 2;
a_lofilt = (float *) calloc(a_size, sizeof(float));
if(a_lofilt == (float *)NULL) {
free(dtt_table->lofilt);
free(dtt_table->hifilt);
fprintf(stderr,
"ERROR : getc_transform_table : calloc : a_lofilt\n");
return(-96);
}
a_size--;
for(cnt = 0; cnt <= a_size; cnt++) {
if((ret = getc_byte(&sign, cbufptr, ebufptr))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_lofilt);
return(ret);
}
if((ret = getc_byte(&scale, cbufptr, ebufptr))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_lofilt);
return(ret);
}
if((ret = getc_uint(&shrt_dat, cbufptr, ebufptr))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_lofilt);
return(ret);
}
a_lofilt[cnt] = (float)shrt_dat;
while(scale > 0) {
a_lofilt[cnt] /= 10.0;
scale--;
}
if(sign != 0)
a_lofilt[cnt] *= -1.0;
if(debug > 3)
fprintf(stderr, "lofilt[%d] = %.15f\n", cnt, a_lofilt[cnt]);
if(dtt_table->hisz % 2) {
dtt_table->hifilt[cnt + a_size] = (float)((float)int_sign(cnt)
* a_lofilt[cnt]);
if(cnt > 0)
dtt_table->hifilt[a_size - cnt] = dtt_table->hifilt[cnt + a_size];
}
else {
dtt_table->hifilt[cnt + a_size + 1] = (float)((float)int_sign(cnt)
* a_lofilt[cnt]);
dtt_table->hifilt[a_size - cnt] = -1.0 *
dtt_table->hifilt[cnt + a_size + 1];
}
}
free(a_lofilt);
if(dtt_table->losz % 2)
a_size = (dtt_table->losz + 1) / 2;
else
a_size = dtt_table->losz / 2;
a_hifilt = (float *) calloc(a_size, sizeof(float));
if(a_hifilt == (float *)NULL) {
free(dtt_table->lofilt);
free(dtt_table->hifilt);
fprintf(stderr,
"ERROR : getc_transform_table : calloc : a_hifilt\n");
return(-97);
}
a_size--;
for(cnt = 0; cnt <= a_size; cnt++) {
if((ret = getc_byte(&sign, cbufptr, ebufptr))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_hifilt);
return(ret);
}
if((ret = getc_byte(&scale, cbufptr, ebufptr))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_hifilt);
return(ret);
}
if((ret = getc_uint(&shrt_dat, cbufptr, ebufptr))){
free(dtt_table->lofilt);
free(dtt_table->hifilt);
free(a_hifilt);
return(ret);
}
a_hifilt[cnt] = (float)shrt_dat;
while(scale > 0) {
a_hifilt[cnt] /= 10.0;
scale--;
}
if(sign != 0)
a_hifilt[cnt] *= -1.0;
if(debug > 2)
fprintf(stderr, "hifilt[%d] = %.15f\n", cnt, a_hifilt[cnt]);
if(dtt_table->losz % 2) {
dtt_table->lofilt[cnt + a_size] = (float)((float)int_sign(cnt)
* a_hifilt[cnt]);
if(cnt > 0)
dtt_table->lofilt[a_size - cnt] = dtt_table->lofilt[cnt + a_size];
}
else {
dtt_table->lofilt[cnt + a_size + 1] = (float)((float)int_sign(cnt+1)
* a_hifilt[cnt]);
dtt_table->lofilt[a_size - cnt] = dtt_table->lofilt[cnt + a_size + 1];
}
}
free(a_hifilt);
dtt_table->lodef = 1;
dtt_table->hidef = 1;
if(debug > 0)
fprintf(stderr, "Finished reading transform table.\n\n");
return(0);
}
/********************************************/
/* Writes transform table to the open file. */
/********************************************/
int write_transform_table(
float *lofilt, /* filter coefficients */
const int losz,
float *hifilt,
const int hisz,
FILE *outfp) /* compressed file */
{
int ret;
unsigned int coef; /* filter coefficient indicator */
unsigned int int_dat; /* temp variable */
float dbl_tmp; /* temp variable */
char scale_ex, sign; /* exponent scaling and sign parameters */
if(debug > 0)
fprintf(stderr, "Writing transform table.\n");
if((ret = write_ushort(DTT_WSQ, outfp)))
return(ret);
if((ret = write_ushort(58, outfp))) /* table size */
return(ret);
/* number analysis lowpass coefficients */
if((ret = write_byte(losz, outfp)))
return(ret);
/* number analysis highpass coefficients */
if((ret = write_byte(hisz, outfp)))
return(ret);
for(coef = (losz>>1); coef < losz; coef++) {
dbl_tmp = lofilt[coef];
if(dbl_tmp >= 0.0) {
sign = 0;
}
else {
sign = 1;
dbl_tmp *= -1.0;
}
scale_ex = 0;
if(dbl_tmp == 0.0)
int_dat = 0;
else if(dbl_tmp < 4294967295.0) {
while(dbl_tmp < 4294967295.0) {
scale_ex += 1;
dbl_tmp *= 10.0;
}
scale_ex -= 1;
int_dat = (unsigned int)sround_uint(dbl_tmp / 10.0);
}
else {
dbl_tmp = lofilt[coef];
fprintf(stderr,
"ERROR: write_transform_table : lofilt[%d] to high at %f\n",
coef, dbl_tmp);
return(-80);
}
if(debug > 2) {
fprintf(stderr, "lo[%d] = %u\n", coef, int_dat);
fprintf(stderr, "lof[%d] = %0.15f\n", coef, lofilt[coef]);
}
if((ret = write_byte(sign, outfp)))
return(ret);
if((ret = write_byte(scale_ex, outfp)))
return(ret);
if((ret = write_uint(int_dat, outfp)))
return(ret);
}
for(coef = (hisz>>1); coef < hisz; coef++) {
dbl_tmp = hifilt[coef];
if(dbl_tmp >= 0.0) {
sign = 0;
}
else {
sign = 1;
dbl_tmp *= -1.0;
}
scale_ex = 0;
if(dbl_tmp == 0.0)
int_dat = 0;
else if(dbl_tmp < 4294967295.0) {
while(dbl_tmp < 4294967295.0) {
scale_ex += 1;
dbl_tmp *= 10.0;
}
scale_ex -= 1;
int_dat = (unsigned int)sround_uint(dbl_tmp / 10.0);
}
else {
dbl_tmp = hifilt[coef];
fprintf(stderr,
"ERROR: write_transform_table : hifilt[%d] to high at %f\n",
coef, dbl_tmp);
return(-81);
}
if(debug > 2) {
fprintf(stderr, "hi[%d] = %u\n", coef, int_dat);
fprintf(stderr, "hif[%d] = %0.15f\n", coef, hifilt[coef]);
}
if((ret = write_byte(sign, outfp)))
return(ret);
if((ret = write_byte(scale_ex, outfp)))
return(ret);
if((ret = write_uint(int_dat, outfp)))
return(ret);
}
if(debug > 0)
fprintf(stderr, "Finished writing transform table.\n\n");
return(0);
}
/************************************************/
/* Stores transform table to the output buffer. */
/************************************************/
int putc_transform_table(
float *lofilt, /* filter coefficients */
const int losz,
float *hifilt,
const int hisz,
unsigned char *odata, /* output byte buffer */
const int oalloc, /* allocated size of buffer */
int *olen) /* filled length of buffer */
{
int ret;
unsigned int coef; /* filter coefficient indicator */
unsigned int int_dat; /* temp variable */
float dbl_tmp; /* temp variable */
char scale_ex, sign; /* exponent scaling and sign parameters */
if(debug > 0)
fprintf(stderr, "Writing transform table.\n");
if((ret = putc_ushort(DTT_WSQ, odata, oalloc, olen)))
return(ret);
/* table size */
if((ret = putc_ushort(58, odata, oalloc, olen)))
return(ret);
/* number analysis lowpass coefficients */
if((ret = putc_byte(losz, odata, oalloc, olen)))
return(ret);
/* number analysis highpass coefficients */
if((ret = putc_byte(hisz, odata, oalloc, olen)))
return(ret);
for(coef = (losz>>1); coef < losz; coef++) {
dbl_tmp = lofilt[coef];
if(dbl_tmp >= 0.0) {
sign = 0;
}
else {
sign = 1;
dbl_tmp *= -1.0;
}
scale_ex = 0;
if(dbl_tmp == 0.0)
int_dat = 0;
else if(dbl_tmp < 4294967295.0) {
while(dbl_tmp < 4294967295.0) {
scale_ex += 1;
dbl_tmp *= 10.0;
}
scale_ex -= 1;
int_dat = (unsigned int)sround_uint(dbl_tmp / 10.0);
}
else {
dbl_tmp = lofilt[coef];
fprintf(stderr,
"ERROR: putc_transform_table : lofilt[%d] to high at %f\n",
coef, dbl_tmp);
return(-82);
}
if(debug > 2) {
fprintf(stderr, "lo[%d] = %u\n", coef, int_dat);
fprintf(stderr, "lof[%d] = %0.15f\n", coef, lofilt[coef]);
}
if((ret = putc_byte(sign, odata, oalloc, olen)))
return(ret);
if((ret = putc_byte(scale_ex, odata, oalloc, olen)))
return(ret);
if((ret = putc_uint(int_dat, odata, oalloc, olen)))
return(ret);
}
for(coef = (hisz>>1); coef < hisz; coef++) {
dbl_tmp = hifilt[coef];
if(dbl_tmp >= 0.0) {
sign = 0;
}
else {
sign = 1;
dbl_tmp *= -1.0;
}
scale_ex = 0;
if(dbl_tmp == 0.0)
int_dat = 0;
else if(dbl_tmp < 4294967295.0) {
while(dbl_tmp < 4294967295.0) {
scale_ex += 1;
dbl_tmp *= 10.0;
}
scale_ex -= 1;
int_dat = (unsigned int)sround_uint(dbl_tmp / 10.0);
}
else {
dbl_tmp = hifilt[coef];
fprintf(stderr,
"ERROR: putc_transform_table : hifilt[%d] to high at %f\n",
coef, dbl_tmp);
return(-83);
}
if(debug > 2) {
fprintf(stderr, "hi[%d] = %u\n", coef, int_dat);
fprintf(stderr, "hif[%d] = %0.15f\n", coef, hifilt[coef]);
}
if((ret = putc_byte(sign, odata, oalloc, olen)))
return(ret);
if((ret = putc_byte(scale_ex, odata, oalloc, olen)))
return(ret);
if((ret = putc_uint(int_dat, odata, oalloc, olen)))
return(ret);
}
if(debug > 0)
fprintf(stderr, "Finished writing transform table.\n\n");
return(0);
}
/*****************************************************/
/* Routine to read in quantization table parameters. */
/*****************************************************/
int read_quantization_table(
DQT_TABLE *dqt_table, /* quatization table structure */
FILE *infp) /* input file */
{
int ret;
unsigned short hdr_size; /* header size */
unsigned short cnt, shrt_dat; /* counter and temp short data */
unsigned char scale; /* scaling parameter */
if(debug > 0)
fprintf(stderr, "Reading quantization table.\n");
if((ret = read_ushort(&hdr_size, infp)))
return(ret);
if((ret = read_byte(&scale, infp)))
return(ret);
if((ret = read_ushort(&shrt_dat, infp)))
return(ret);
dqt_table->bin_center = (float)shrt_dat;
while(scale > 0) {
dqt_table->bin_center /= 10.0;
scale--;
}
for(cnt = 0; cnt < 64; cnt++) {
if((ret = read_byte(&scale, infp)))
return(ret);
if((ret = read_ushort(&shrt_dat, infp)))
return(ret);
dqt_table->q_bin[cnt] = (float)shrt_dat;
while(scale > 0) {
dqt_table->q_bin[cnt] /= 10.0;
scale--;
}
if((ret = read_byte(&scale, infp)))
return(ret);
if((ret = read_ushort(&shrt_dat, infp)))
return(ret);
dqt_table->z_bin[cnt] = (float)shrt_dat;
while(scale > 0) {
dqt_table->z_bin[cnt] /= 10.0;
scale--;
}
if(debug > 2)
fprintf(stderr, "q[%d] = %f :: z[%d] = %f\n",
cnt, dqt_table->q_bin[cnt], cnt, dqt_table->z_bin[cnt]);
}
dqt_table->dqt_def = 1;
if(debug > 0)
fprintf(stderr, "Finished reading quantization table.\n\n");
return(0);
}
/************************************************************************/
/* Routine to read in quantization table parameters from memory buffer. */
/************************************************************************/
int getc_quantization_table(
DQT_TABLE *dqt_table, /* quatization table structure */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned short hdr_size; /* header size */
unsigned short cnt, shrt_dat; /* counter and temp short data */
unsigned char scale; /* scaling parameter */
if(debug > 0)
fprintf(stderr, "Reading quantization table.\n");
if((ret = getc_ushort(&hdr_size, cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(&scale, cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&shrt_dat, cbufptr, ebufptr)))
return(ret);
dqt_table->bin_center = (float)shrt_dat;
while(scale > 0) {
dqt_table->bin_center /= 10.0;
scale--;
}
for(cnt = 0; cnt < 64; cnt++) {
if((ret = getc_byte(&scale, cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&shrt_dat, cbufptr, ebufptr)))
return(ret);
dqt_table->q_bin[cnt] = (float)shrt_dat;
while(scale > 0) {
dqt_table->q_bin[cnt] /= 10.0;
scale--;
}
if((ret = getc_byte(&scale, cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&shrt_dat, cbufptr, ebufptr)))
return(ret);
dqt_table->z_bin[cnt] = (float)shrt_dat;
while(scale > 0) {
dqt_table->z_bin[cnt] /= 10.0;
scale--;
}
if(debug > 2)
fprintf(stderr, "q[%d] = %f :: z[%d] = %f\n",
cnt, dqt_table->q_bin[cnt], cnt, dqt_table->z_bin[cnt]);
}
dqt_table->dqt_def = 1;
if(debug > 0)
fprintf(stderr, "Finished reading quantization table.\n\n");
return(0);
}
/***********************************************/
/* Writes quantization table to the open file. */
/***********************************************/
int write_quantization_table(
QUANT_VALS *quant_vals, /* quantization parameters */
FILE *outfp) /* compressed file */
{
int ret, sub; /* subband indicators */
char scale_ex, scale_ex2; /* exponent scaling parameters */
unsigned short shrt_dat, shrt_dat2; /* temp variables */
float flt_tmp; /* temp variable */
if(debug > 0)
fprintf(stderr, "Writing quantization table.\n");
if((ret = write_ushort(DQT_WSQ, outfp)))
return(ret);
/* table size */
if((ret = write_ushort(389, outfp)))
return(ret);
/* exponent scaling value */
if((ret = write_byte(2, outfp)))
return(ret);
/* quantizer bin center parameter */
if((ret = write_ushort(44, outfp)))
return(ret);
for(sub = 0; sub < 64; sub ++) {
if(sub >= 0 && sub < 60) {
if(quant_vals->qbss[sub] != 0.0) {
flt_tmp = quant_vals->qbss[sub];
scale_ex = 0;
if(flt_tmp < 65535) {
while(flt_tmp < 65535) {
scale_ex += 1;
flt_tmp *= 10;
}
scale_ex -= 1;
shrt_dat = (unsigned short)sround(flt_tmp / 10.0);
}
else {
flt_tmp = quant_vals->qbss[sub];
fprintf(stderr,
"ERROR : write_quantization_table : Q[%d] to high at %f\n",
sub, flt_tmp);
return(-84);
}
flt_tmp = quant_vals->qzbs[sub];
scale_ex2 = 0;
if(flt_tmp < 65535) {
while(flt_tmp < 65535) {
scale_ex2 += 1;
flt_tmp *= 10;
}
scale_ex2 -= 1;
shrt_dat2 = (unsigned short)sround(flt_tmp / 10.0);
}
else {
flt_tmp = quant_vals->qzbs[sub];
fprintf(stderr,
"ERROR : write_quantization_table : Z[%d] to high at %f\n",
sub, flt_tmp);
return(-85);
}
}
else {
scale_ex = 0;
scale_ex2 = 0;
shrt_dat = 0;
shrt_dat2 = 0;
}
}
else {
scale_ex = 0;
scale_ex2 = 0;
shrt_dat = 0;
shrt_dat2 = 0;
}
if(debug > 2) {
fprintf(stderr,
"qi[%d] = %d :: zi[%d] = %d\n", sub, shrt_dat, sub, shrt_dat2);
fprintf(stderr,
"q[%d] = %5.7f :: z[%d] = %5.7f\n", sub, quant_vals->qbss[sub],
sub, quant_vals->qzbs[sub]);
}
if((ret = write_byte(scale_ex, outfp)))
return(ret);
if((ret = write_ushort(shrt_dat, outfp)))
return(ret);
if((ret = write_byte(scale_ex2, outfp)))
return(ret);
if((ret = write_ushort(shrt_dat2, outfp)))
return(ret);
}
if(debug > 0)
fprintf(stderr, "Finished writing quantization table.\n\n");
return(0);
}
/***************************************************/
/* Stores quantization table in the output buffer. */
/***************************************************/
int putc_quantization_table(
QUANT_VALS *quant_vals, /* quantization parameters */
unsigned char *odata, /* output byte buffer */
const int oalloc, /* allocated size of buffer */
int *olen) /* filled length of buffer */
{
int ret, sub; /* subband indicators */
char scale_ex, scale_ex2; /* exponent scaling parameters */
unsigned short shrt_dat, shrt_dat2; /* temp variables */
float flt_tmp; /* temp variable */
if(debug > 0)
fprintf(stderr, "Writing quantization table.\n");
if((ret = putc_ushort(DQT_WSQ, odata, oalloc, olen)))
return(ret);
/* table size */
if((ret = putc_ushort(389, odata, oalloc, olen)))
return(ret);
/* exponent scaling value */
if((ret = putc_byte(2, odata, oalloc, olen)))
return(ret);
/* quantizer bin center parameter */
if((ret = putc_ushort(44, odata, oalloc, olen)))
return(ret);
for(sub = 0; sub < 64; sub ++) {
if(sub >= 0 && sub < 60) {
if(quant_vals->qbss[sub] != 0.0) {
flt_tmp = quant_vals->qbss[sub];
scale_ex = 0;
if(flt_tmp < 65535) {
while(flt_tmp < 65535) {
scale_ex += 1;
flt_tmp *= 10;
}
scale_ex -= 1;
shrt_dat = (unsigned short)sround(flt_tmp / 10.0);
}
else {
flt_tmp = quant_vals->qbss[sub];
fprintf(stderr,
"ERROR : putc_quantization_table : Q[%d] to high at %f\n",
sub, flt_tmp);
return(-86);
}
flt_tmp = quant_vals->qzbs[sub];
scale_ex2 = 0;
if(flt_tmp < 65535) {
while(flt_tmp < 65535) {
scale_ex2 += 1;
flt_tmp *= 10;
}
scale_ex2 -= 1;
shrt_dat2 = (unsigned short)sround(flt_tmp / 10.0);
}
else {
flt_tmp = quant_vals->qzbs[sub];
fprintf(stderr,
"ERROR : putc_quantization_table : Z[%d] to high at %f\n",
sub, flt_tmp);
return(-87);
}
}
else {
scale_ex = 0;
scale_ex2 = 0;
shrt_dat = 0;
shrt_dat2 = 0;
}
}
else {
scale_ex = 0;
scale_ex2 = 0;
shrt_dat = 0;
shrt_dat2 = 0;
}
if(debug > 2) {
fprintf(stderr,
"qi[%d] = %d :: zi[%d] = %d\n", sub, shrt_dat, sub, shrt_dat2);
fprintf(stderr,
"q[%d] = %5.7f :: z[%d] = %5.7f\n", sub, quant_vals->qbss[sub],
sub, quant_vals->qzbs[sub]);
}
if((ret = putc_byte(scale_ex, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(shrt_dat, odata, oalloc, olen)))
return(ret);
if((ret = putc_byte(scale_ex2, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(shrt_dat2, odata, oalloc, olen)))
return(ret);
}
if(debug > 0)
fprintf(stderr, "Finished writing quantization table.\n\n");
return(0);
}
/************************************************/
/* Routine to read in huffman table parameters. */
/************************************************/
int read_huffman_table_wsq(
DHT_TABLE *dht_table, /* huffman table structure */
FILE *infp) /* input file */
{
int ret;
unsigned char table_id; /* huffman table indicator */
unsigned char *huffbits;
unsigned char *huffvalues;
int bytes_left;
/* First time, read table len. */
if((ret = read_huffman_table(&table_id, &huffbits, &huffvalues,
MAX_HUFFCOUNTS_WSQ, infp,
READ_TABLE_LEN, &bytes_left)))
return(ret);
/* Store table into global structure list. */
memcpy((dht_table+table_id)->huffbits, huffbits, MAX_HUFFBITS);
memcpy((dht_table+table_id)->huffvalues, huffvalues, MAX_HUFFCOUNTS_WSQ+1);
(dht_table+table_id)->tabdef = 1;
free(huffbits);
free(huffvalues);
while(bytes_left){
/* Read next table without rading table len. */
if((ret = read_huffman_table(&table_id, &huffbits, &huffvalues,
MAX_HUFFCOUNTS_WSQ, infp,
NO_READ_TABLE_LEN, &bytes_left)))
return(ret);
/* If table is already defined ... */
if((dht_table+table_id)->tabdef){
free(huffbits);
free(huffvalues);
fprintf(stderr, "ERROR : read_huffman_table_wsq : ");
fprintf(stderr, "huffman table ID = %d already defined\n", table_id);
return(-2);
}
/* Store table into global structure list. */
memcpy((dht_table+table_id)->huffbits, huffbits, MAX_HUFFBITS);
memcpy((dht_table+table_id)->huffvalues, huffvalues, MAX_HUFFCOUNTS_WSQ+1);
(dht_table+table_id)->tabdef = 1;
free(huffbits);
free(huffvalues);
}
return(0);
}
/*******************************************************************/
/* Routine to read in huffman table parameters from memory buffer. */
/*******************************************************************/
int getc_huffman_table_wsq(
DHT_TABLE *dht_table, /* huffman table structure */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned char table_id; /* huffman table indicator */
unsigned char *huffbits;
unsigned char *huffvalues;
int bytes_left;
/* First time, read table len. */
if((ret = getc_huffman_table(&table_id, &huffbits, &huffvalues,
MAX_HUFFCOUNTS_WSQ, cbufptr, ebufptr,
READ_TABLE_LEN, &bytes_left)))
return(ret);
/* Store table into global structure list. */
memcpy((dht_table+table_id)->huffbits, huffbits, MAX_HUFFBITS);
memcpy((dht_table+table_id)->huffvalues, huffvalues,
MAX_HUFFCOUNTS_WSQ+1);
(dht_table+table_id)->tabdef = 1;
free(huffbits);
free(huffvalues);
while(bytes_left){
/* Read next table without rading table len. */
if((ret = getc_huffman_table(&table_id, &huffbits, &huffvalues,
MAX_HUFFCOUNTS_WSQ, cbufptr, ebufptr,
NO_READ_TABLE_LEN, &bytes_left)))
return(ret);
/* If table is already defined ... */
if((dht_table+table_id)->tabdef){
free(huffbits);
free(huffvalues);
fprintf(stderr, "ERROR : getc_huffman_table_wsq : ");
fprintf(stderr, "huffman table ID = %d already defined\n", table_id);
return(-2);
}
/* Store table into global structure list. */
memcpy((dht_table+table_id)->huffbits, huffbits, MAX_HUFFBITS);
memcpy((dht_table+table_id)->huffvalues, huffvalues,
MAX_HUFFCOUNTS_WSQ+1);
(dht_table+table_id)->tabdef = 1;
free(huffbits);
free(huffvalues);
}
return(0);
}
/***********************************************/
/* Routine to read in frame header parameters. */
/***********************************************/
int read_frame_header_wsq(
FRM_HEADER_WSQ *frm_header, /* frame header structure */
FILE *infp) /* input file */
{
int ret;
unsigned short hdr_size, shrt_dat; /* header size and data pointer */
unsigned char scale; /* exponent scaling parameter */
if(debug > 0)
fprintf(stderr, "Reading frame header.\n");
if((ret = read_ushort(&hdr_size, infp)))
return(ret);
if((ret = read_byte(&(frm_header->black), infp)))
return(ret);
if((ret = read_byte(&(frm_header->white), infp)))
return(ret);
if((ret = read_ushort(&(frm_header->height), infp)))
return(ret);
if((ret = read_ushort(&(frm_header->width), infp)))
return(ret);
if((ret = read_byte(&scale, infp)))
return(ret);
if((ret = read_ushort(&shrt_dat, infp)))
return(ret);
frm_header->m_shift = (float) shrt_dat;
while(scale > 0) {
frm_header->m_shift /= 10.0;
scale--;
}
if((ret = read_byte(&scale, infp)))
return(ret);
if((ret = read_ushort(&shrt_dat, infp)))
return(ret);
frm_header->r_scale = (float) shrt_dat;
while(scale > 0) {
frm_header->r_scale /= 10.0;
scale--;
}
if((ret = read_byte(&(frm_header->wsq_encoder), infp)))
return(ret);
if((ret = read_ushort(&(frm_header->software), infp)))
return(ret);
if(debug > 2) {
fprintf(stderr, "black = %d :: white = %u\n",
frm_header->black, frm_header->white);
fprintf(stderr, "w = %d :: h = %d\n",
frm_header->width, frm_header->height);
fprintf(stderr, "m_shift = %f :: r_scale = %f\n",
frm_header->m_shift,frm_header->r_scale);
fprintf(stdout, "WSQ_encoder = %d\n",
frm_header->wsq_encoder);
fprintf(stdout, "Software = %d\n", frm_header->software);
}
if(debug > 0)
fprintf(stderr, "Finished reading frame header.\n\n");
return(0);
}
/******************************************************************/
/* Routine to read in frame header parameters from memory buffer. */
/******************************************************************/
int getc_frame_header_wsq(
FRM_HEADER_WSQ *frm_header, /* frame header structure */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned short hdr_size, shrt_dat; /* header size and data pointer */
unsigned char scale; /* exponent scaling parameter */
if(debug > 0)
fprintf(stderr, "Reading frame header.\n");
if((ret = getc_ushort(&hdr_size, cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(&(frm_header->black), cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(&(frm_header->white), cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&(frm_header->height), cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&(frm_header->width), cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(&scale, cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&shrt_dat, cbufptr, ebufptr)))
return(ret);
frm_header->m_shift = (float) shrt_dat;
while(scale > 0) {
frm_header->m_shift /= 10.0;
scale--;
}
if((ret = getc_byte(&scale, cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&shrt_dat, cbufptr, ebufptr)))
return(ret);
frm_header->r_scale = (float) shrt_dat;
while(scale > 0) {
frm_header->r_scale /= 10.0;
scale--;
}
if((ret = getc_byte(&(frm_header->wsq_encoder), cbufptr, ebufptr)))
return(ret);
if((ret = getc_ushort(&(frm_header->software), cbufptr, ebufptr)))
return(ret);
if(debug > 2) {
fprintf(stderr, "black = %d :: white = %u\n",
frm_header->black, frm_header->white);
fprintf(stderr, "w = %d :: h = %d\n",
frm_header->width, frm_header->height);
fprintf(stderr, "m_shift = %f :: r_scale = %f\n",
frm_header->m_shift,frm_header->r_scale);
fprintf(stdout, "WSQ_encoder = %d\n",
frm_header->wsq_encoder);
fprintf(stdout, "Software = %d\n", frm_header->software);
}
if(debug > 0)
fprintf(stderr, "Finished reading frame header.\n\n");
return(0);
}
/*****************************************/
/* Writes frame header to the open file. */
/*****************************************/
int write_frame_header_wsq(
const int width, /* image width */
const int height, /* image height */
const float m_shift, /* image shifting parameter */
const float r_scale, /* image scaling parameter */
FILE *outfp) /* compressed file */
{
int ret;
float flt_tmp; /* temp variable */
char scale_ex; /* exponent scaling parameter */
unsigned short shrt_dat; /* temp variable */
if(debug > 0)
fprintf(stderr, "Writing frame header.\n");
if((ret = write_ushort(SOF_WSQ, outfp)))
return(ret);
/* size of frame header */
if((ret = write_ushort(17, outfp)))
return(ret);
/* black pixel */
if((ret = write_byte(0, outfp)))
return(ret);
/* white pixel */
if((ret = write_byte(255, outfp)))
return(ret);
if((ret = write_ushort(height, outfp)))
return(ret);
if((ret = write_ushort(width, outfp)))
return(ret);
if(debug > 2)
fprintf(stderr,
"m_shift = %f :: r_scale = %f\n", m_shift, r_scale);
flt_tmp = m_shift;
scale_ex = 0;
if(flt_tmp != 0.0) {
while(flt_tmp < 65535) {
scale_ex += 1;
flt_tmp *= 10;
}
scale_ex -= 1;
shrt_dat = (unsigned short)sround(flt_tmp / 10.0);
}
else
shrt_dat = 0;
if((ret = write_byte(scale_ex, outfp)))
return(ret);
if((ret = write_ushort(shrt_dat, outfp)))
return(ret);
flt_tmp = r_scale;
scale_ex = 0;
if(flt_tmp != 0.0) {
while(flt_tmp < 65535) {
scale_ex += 1;
flt_tmp *= 10;
}
scale_ex -= 1;
shrt_dat = (unsigned short)sround(flt_tmp / 10.0);
}
else
shrt_dat = 0;
if((ret = write_byte(scale_ex, outfp)))
return(ret);
if((ret = write_ushort(shrt_dat, outfp)))
return(ret);
if((ret = write_byte(2, outfp)))
return(ret);
if((ret = write_ushort(0, outfp)))
return(ret);
if(debug > 0)
fprintf(stderr, "Finished writing frame header.\n\n");
return(0);
}
/*********************************************/
/* Stores frame header to the output buffer. */
/*********************************************/
int putc_frame_header_wsq(
const int width, /* image width */
const int height, /* image height */
const float m_shift, /* image shifting parameter */
const float r_scale, /* image scaling parameter */
unsigned char *odata, /* output byte buffer */
const int oalloc, /* allocated size of buffer */
int *olen) /* filled length of buffer */
{
int ret;
float flt_tmp; /* temp variable */
char scale_ex; /* exponent scaling parameter */
unsigned short shrt_dat; /* temp variable */
if(debug > 0)
fprintf(stderr, "Writing frame header.\n");
if((ret = putc_ushort(SOF_WSQ, odata, oalloc, olen)))
return(ret);
/* size of frame header */
if((ret = putc_ushort(17, odata, oalloc, olen)))
return(ret);
/* black pixel */
if((ret = putc_byte(0, odata, oalloc, olen)))
return(ret);
/* white pixel */
if((ret = putc_byte(255, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(height, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(width, odata, oalloc, olen)))
return(ret);
if(debug > 2)
fprintf(stderr,
"m_shift = %f :: r_scale = %f\n", m_shift, r_scale);
flt_tmp = m_shift;
scale_ex = 0;
if(flt_tmp != 0.0) {
while(flt_tmp < 65535) {
scale_ex += 1;
flt_tmp *= 10;
}
scale_ex -= 1;
shrt_dat = (unsigned short)sround(flt_tmp / 10.0);
}
else
shrt_dat = 0;
if((ret = putc_byte(scale_ex, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(shrt_dat, odata, oalloc, olen)))
return(ret);
flt_tmp = r_scale;
scale_ex = 0;
if(flt_tmp != 0.0) {
while(flt_tmp < 65535) {
scale_ex += 1;
flt_tmp *= 10;
}
scale_ex -= 1;
shrt_dat = (unsigned short)sround(flt_tmp / 10.0);
}
else
shrt_dat = 0;
if((ret = putc_byte(scale_ex, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(shrt_dat, odata, oalloc, olen)))
return(ret);
if((ret = putc_byte(2, odata, oalloc, olen)))
return(ret);
if((ret = putc_ushort(0, odata, oalloc, olen)))
return(ret);
if(debug > 0)
fprintf(stderr, "Finished writing frame header.\n\n");
return(0);
}
/***********************************************/
/* Routine to read in block header parameters. */
/***********************************************/
int read_block_header(
unsigned char *huff_table, /* huffman table indicator */
FILE *infp) /* input file */
{
int ret;
unsigned short hdr_size; /* block header size */
if(debug > 0)
fprintf(stderr, "Reading block header.\n");
if((ret = read_ushort(&hdr_size, infp)))
return(ret);
if((ret = read_byte(huff_table, infp)))
return(ret);
if(debug > 2)
fprintf(stderr, "huff_table = %d\n", *huff_table);
if(debug > 0)
fprintf(stderr, "Finished reading block header.\n\n");
return(0);
}
/******************************************************************/
/* Routine to read in block header parameters from memory buffer. */
/******************************************************************/
int getc_block_header(
unsigned char *huff_table, /* huffman table indicator */
unsigned char **cbufptr, /* current byte in input buffer */
unsigned char *ebufptr) /* end of input buffer */
{
int ret;
unsigned short hdr_size; /* block header size */
if(debug > 0)
fprintf(stderr, "Reading block header.\n");
if((ret = getc_ushort(&hdr_size, cbufptr, ebufptr)))
return(ret);
if((ret = getc_byte(huff_table, cbufptr, ebufptr)))
return(ret);
if(debug > 2)
fprintf(stderr, "huff_table = %d\n", *huff_table);
if(debug > 0)
fprintf(stderr, "Finished reading block header.\n\n");
return(0);
}
/*****************************************/
/* Writes block header to the open file. */
/*****************************************/
int write_block_header(
const int table, /* huffman table indicator */
FILE *outfp) /* compressed file */
{
int ret;
if(debug > 0)
fprintf(stderr, "Writing block header.\n");
if((ret = write_ushort(SOB_WSQ, outfp)))
return(ret);
/* block header size */
if((ret = write_ushort(3, outfp)))
return(ret);
if((ret = write_byte(table, outfp)))
return(ret);
if(debug > 0)
fprintf(stderr, "Finished writing block header.\n\n");
return(0);
}
/*********************************************/
/* Stores block header to the output buffer. */
/*********************************************/
int putc_block_header(
const int table, /* huffman table indicator */
unsigned char *odata, /* output byte buffer */
const int oalloc, /* allocated size of buffer */
int *olen) /* filled length of buffer */
{
int ret;
if(debug > 0)
fprintf(stderr, "Writing block header.\n");
if((ret = putc_ushort(SOB_WSQ, odata, oalloc, olen)))
return(ret);
/* block header size */
if((ret = putc_ushort(3, odata, oalloc, olen)))
return(ret);
if((ret = putc_byte((unsigned char)table, odata, oalloc, olen)))
return(ret);
if(debug > 0)
fprintf(stderr, "Finished writing block header.\n\n");
return(0);
}
/*******************************************/
int add_comment_wsq(unsigned char **ocdata, int *oclen, unsigned char *idata,
const int ilen, unsigned char *comment)
{
int ret, nlen, nalloc;
unsigned short marker;
unsigned char *ndata, *cbufptr, *ebufptr;
unsigned char *ocomment;
if((comment == (unsigned char *)NULL) ||
(strlen((char *)comment) == 0)){
fprintf(stderr,
"ERROR : add_comment_wsq : empty comment passed\n");
return(-2);
}
/* New compressed byte stream length including: */
/* orig byte strem + marker + header length + comment bytes */
nalloc = ilen + (sizeof(unsigned short) << 1) + strlen((char *)comment);
/* Initialize current filled length to 0. */
nlen = 0;
/* Allocate new compressed byte stream. */
if((ndata = (unsigned char *)malloc(nalloc * sizeof(unsigned char)))
== (unsigned char *)NULL){
fprintf(stderr, "ERROR : add_comment_wsq : malloc : ndata\n");
return(-3);
}
cbufptr = idata;
ebufptr = idata + ilen;
/* Parse idata and determine comment destination in byte stream. */
/* Parse SOI */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/* Copy SOI */
if((ret = putc_ushort(marker, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
/* Read next marker. */
if((ret = getc_ushort(&marker, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/* If COM segment ... */
if (marker == COM_WSQ){
/* Do ... while COM segments exist in input byte stream ... */
do{
/* Read COM_WSQ segment. */
if((ret = getc_comment(&ocomment, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
/* Copy COM segment. */
if((ret = putc_comment(COM_WSQ, ocomment, strlen((char *)ocomment),
ndata, nalloc, &nlen))){
free(ndata);
free(ocomment);
return(ret);
}
free(ocomment);
/* Read next marker. */
if((ret = getc_ushort(&marker, &cbufptr, ebufptr))){
free(ndata);
return(ret);
}
}while(marker == COM_WSQ);
}
/* Back up to start of last marker read. */
cbufptr -= sizeof(unsigned short);
/* Insert Comment Segment */
if((ret = putc_comment(COM_WSQ, comment, strlen((char *)comment),
ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
/* Append remaining byte stream */
if((ret = putc_bytes(cbufptr, ebufptr - cbufptr, ndata, nalloc, &nlen))){
free(ndata);
return(ret);
}
*ocdata = ndata;
*oclen = nalloc;
return(0);
}
/*******************************************/
int putc_nistcom_wsq(char *comment_text, const int w, const int h,
const int d, const int ppi, const int lossyflag,
const float r_bitrate,
unsigned char *odata, const int oalloc, int *olen)
{
int ret, gencomflag;
NISTCOM *nistcom;
char *comstr;
/* Add Comment(s) here. */
nistcom = (NISTCOM *)NULL;
gencomflag = 0;
if(comment_text != (char *)NULL){
/* if NISTCOM ... */
if(strncmp(comment_text, NCM_HEADER, strlen(NCM_HEADER)) == 0){
if((ret = string2fet(&nistcom, comment_text))){
return(ret);
}
}
/* If general comment ... */
else{
gencomflag = 1;
}
}
/* Otherwise, no comment passed ... */
/* Combine image attributes to NISTCOM. */
if((ret = combine_wsq_nistcom(&nistcom, w, h, d, ppi, lossyflag, r_bitrate))){
if(nistcom != (NISTCOM *)NULL)
freefet(nistcom);
return(ret);
}
/* Put NISTCOM ... */
/* NISTCOM to string. */
if((ret = fet2string(&comstr, nistcom))){
freefet(nistcom);
return(ret);
}
/* Put NISTCOM comment string. */
if((ret = putc_comment(COM_WSQ, (unsigned char *)comstr, strlen(comstr),
odata, oalloc, olen))){
freefet(nistcom);
free(comstr);
return(ret);
}
freefet(nistcom);
free(comstr);
/* If general comment exists ... */
if(gencomflag){
/* Put general comment to its own segment. */
if((ret = putc_comment(COM_WSQ, (unsigned char *)comment_text,
strlen(comment_text), odata, oalloc, olen)))
return(ret);
}
return(0);
}
/************************************************/
/* Get and return first NISTCOM from open file.**/
/************************************************/
int read_nistcom_wsq(NISTCOM **onistcom, FILE *infp)
{
int ret;
long savepos;
unsigned short marker;
NISTCOM *nistcom;
char *value, *comment_text;
unsigned char *ucharptr;
int id_len;
/* Get SOI */
if((ret = read_marker_wsq(&marker, SOI_WSQ, infp)))
return(ret);
/* Get next marker. */
if((ret = read_marker_wsq(&marker, ANY_WSQ, infp)))
return(ret);
/* Allocate temporary buffer the size of the NIST_COM Header ID. */
id_len = strlen(NCM_HEADER);
value = (char *)calloc(id_len, sizeof(char));
if(value == (char *)NULL){
fprintf(stderr, "ERROR : read_nistcom_wsq : calloc : value\n");
return(-2);
}
/* While not at Start of Block (SOB) - */
/* the start of encoded image data ... */
while(marker != SOB_WSQ){
if(marker == COM_WSQ){
if((savepos = ftell(infp)) < 0){
fprintf(stderr, "ERROR : read_nistcom_wsq : ");
fprintf(stderr, "ftell : unable to determine current position\n");
free(value);
return(-3);
}
/* Skip Length (short) Bytes */
if(fseek(infp, 2L, SEEK_CUR) < 0){
fprintf(stderr, "ERROR : read_nistcom_wsq : ");
fprintf(stderr, "fseek : unable to skip length bytes\n");
free(value);
return(-4);
}
/* Should be a safe assumption here that we can read */
/* id_len bytes without reaching EOF, so if we don't */
/* read all id_len bytes, then flag error. */
ret = fread(value, sizeof(char), id_len, infp);
if(ret != id_len){
fprintf(stderr, "ERROR : read_nistcom_wsq : ");
fprintf(stderr, "fread : only %d of %d bytes read\n",
ret, id_len);
free(value);
return(-5);
}
/* Reset file pointer to original position. */
if(fseek(infp, savepos, SEEK_SET) < 0){
fprintf(stderr, "ERROR : read_nistcom_wsq : ");
fprintf(stderr, "fseek : unable to reset file position\n");
free(value);
return(-6);
}
if(strncmp(value, NCM_HEADER, id_len) == 0){
if((ret = read_comment(&ucharptr, infp))){
free(value);
return(ret);
}
comment_text = (char *)ucharptr;
if((ret = string2fet(&nistcom, comment_text))){
free(value);
return(ret);
}
free(value);
*onistcom = nistcom;
return(0);
}
}
/* Skip marker segment. */
if((ret = read_skip_marker_segment(marker, infp))){
free(value);
return(ret);
}
/* Get next marker. */
if((ret = read_marker_wsq(&marker, ANY_WSQ, infp))){
free(value);
return(ret);
}
}
free(value);
/* NISTCOM not found ... */
*onistcom = (NISTCOM *)NULL;
return(0);
}
/*****************************************************************/
/* Get and return first NISTCOM from encoded data stream. */
/*****************************************************************/
int getc_nistcom_wsq(NISTCOM **onistcom, unsigned char *idata,
const int ilen)
{
int ret;
unsigned short marker;
unsigned char *cbufptr, *ebufptr;
NISTCOM *nistcom;
char *comment_text;
unsigned char *ucharptr;
cbufptr = idata;
ebufptr = idata + ilen;
/* Get SOI */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr)))
return(ret);
/* Get next marker. */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr)))
return(ret);
/* While not at Start of Block (SOB) - */
/* the start of encoded image data ... */
while(marker != SOB_WSQ){
if(marker == COM_WSQ){
if(strncmp((char *)cbufptr+2 /* skip Length */,
NCM_HEADER, strlen(NCM_HEADER)) == 0){
if((ret = getc_comment(&ucharptr, &cbufptr,
ebufptr)))
return(ret);
comment_text = (char *)ucharptr;
if((ret = string2fet(&nistcom, comment_text))){
free(comment_text);
return(ret);
}
*onistcom = nistcom;
free(comment_text);
return(0);
}
}
/* Skip marker segment. */
if((ret = getc_skip_marker_segment(marker, &cbufptr, ebufptr)))
return(ret);
/* Get next marker. */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr)))
return(ret);
}
/* NISTCOM not found ... */
*onistcom = (NISTCOM *)NULL;
return(0);
}
/*****************************************************************/
/* Prints the first NISTCOM from encoded data stream to a */
/* specified file pointer. */
/*****************************************************************/
int print_comments_wsq(FILE *ofp, unsigned char *idata, const int ilen)
{
int ret;
unsigned short marker;
unsigned char *cbufptr, *ebufptr;
unsigned char *comment_text;
cbufptr = idata;
ebufptr = idata + ilen;
/* Get SOI */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr)))
return(ret);
/* Get next marker. */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr)))
return(ret);
/* While not at Start of Block (SOB) - */
/* the start of encoded image data ... */
while(marker != SOB_WSQ){
if(marker == COM_WSQ){
if((ret = getc_comment(&comment_text, &cbufptr, ebufptr)))
return(ret);
fprintf(ofp, "%s\n", comment_text);
free(comment_text);
}
else
/* Skip marker segment. */
if((ret = getc_skip_marker_segment(marker, &cbufptr, ebufptr)))
return(ret);
/* Get next marker. */
if((ret = getc_marker_wsq(&marker, ANY_WSQ, &cbufptr, ebufptr)))
return(ret);
}
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/ihead/prntihdr.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IHEAD - IHead Image Utilities
FILE: PRNTIHDR.C
AUTHORS: <NAME>
DATE: 04/26/1989
UPDATED: 03/14/2005 by MDG
Contains routines responsible for printing the contents of
an IHead header.
ROUTINES:
#cat: printihdr - formats the attributes of a specified IHead structure
#cat: into a report and prints it to an open file pointer.
***********************************************************************/
#include <stdio.h>
#include <ihead.h>
/************************************************************/
/* Printihdr() prints the contents of an ihead structure to */
/* the passed file pointer. */
/************************************************************/
void printihdr(IHEAD *head, FILE *fp)
{
fprintf(fp,"IMAGE FILE HEADER\n");
fprintf(fp,"~~~~~~~~~~~~~~~~~\n");
fprintf(fp,"Identity\t: %s\n", head->id);
fprintf(fp,"Header Size\t: %d (bytes)\n",sizeof(IHEAD));
fprintf(fp,"Date Created\t: %s\n", head->created);
fprintf(fp,"Width\t\t: %s (pixels)\n",head->width);
fprintf(fp,"Height\t\t: %s (pixels)\n",head->height);
fprintf(fp,"Bits per Pixel\t: %s\n",head->depth);
fprintf(fp,"Resolution\t: %s (ppi)\n",head->density);
fprintf(fp,"Compression\t: %s (code)\n",head->compress);
fprintf(fp,"Compress Length\t: %s (bytes)\n",head->complen);
fprintf(fp,"Scan Alignment\t: %s (bits)\n",head->align);
fprintf(fp,"Image Data Unit\t: %s (bits)\n",head->unitsize);
if(head->byte_order == HILOW)
fprintf(fp,"Byte Order\t: High-Low\n");
else
fprintf(fp,"Byte Order\t: Low-High\n");
if(head->sigbit == MSBF)
fprintf(fp,"MSBit\t\t: First\n");
else
fprintf(fp,"MSBit\t\t: Last\n");
fprintf(fp,"Column Offset\t: %s (pixels)\n",head->pix_offset);
fprintf(fp,"White Pixel\t: %s\n",head->whitepix);
if(head->issigned == SIGNED)
fprintf(fp,"Data Units\t: Signed\n");
else
fprintf(fp,"Data Units\t: Unsigned\n");
fprintf(fp,"Scan Order\t: ");
if(head->rm_cm == ROW_MAJ)
fprintf(fp,"Row Major,\n");
else
fprintf(fp,"Column Major,\n");
if(head->tb_bt == TOP2BOT)
fprintf(fp,"\t\t Top to Bottom,\n");
else
fprintf(fp,"\t\t Bottom to Top,\n");
if(head->lr_rl == LEFT2RIGHT)
fprintf(fp,"\t\t Left to Right\n");
else
fprintf(fp,"\t\t Right to Left\n");
/* EDIT MDG 1/25/99
if(*(head->parent) != NULL){
*/
if(*(head->parent) != '\0'){
fprintf(fp,"Parent\t\t: %s\n",head->parent);
fprintf(fp,"X Origin\t: %s (pixels)\n",head->par_x);
fprintf(fp,"Y Origin\t: %s (pixels)\n",head->par_y);
}
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/sunrast.c
|
<filename>library/src/main/cpp/nbis/imgtools/src/lib/image/sunrast.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: SUNRAST.C
AUTHOR: <NAME>
DATE: 08/19/1990
UPDATED: 03/15/2005 by MDG
UPDATE: 12/02/2008 by <NAME> - Fix to support 64-bit
Contains routines responsible for reading and writing
Sun Rasterfiles.
ROUTINES:
#cat: ReadSunRaster - takes the name of a binary or grayscale Sun Rasterfile
#cat: and loads the image into memory, returning relevant
#cat: image attributes.
#cat: WriteSunRaster - writes the given binary or grayscale image data to
#cat: the specified file in Sun Rasterfile format.
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sunrast.h>
#include <binops.h>
#include <swap.h>
/* Grayscale RGB Colormap (static==>keep it local to the file for now). */
#define COLORMAP_LEN 768
static unsigned char colormap[COLORMAP_LEN] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255
};
/************************************************************/
int ReadSunRaster(const char *ifile, SUNHEAD **osunhead,
unsigned char **ocolormap, int *omaplen, unsigned char **odata,
int *oscan_w, int *oimg_w, int *oimg_h, int *oimg_d)
{
SUNHEAD *sunhead;
FILE *fp;
unsigned char *colormap, *idata;
int scan_width;
if((fp = fopen(ifile,"rb")) == NULL){
fprintf(stderr,"ERROR : ReadSunRaster : fopen : %s\n", ifile);
return(-2);
}
sunhead = (SUNHEAD *)malloc(sizeof(SUNHEAD));
if(sunhead == (SUNHEAD *)NULL){
fprintf(stderr,"ERROR : ReadSunRaster : malloc : sunhead\n");
return(-3);
}
if(fread(sunhead, sizeof(SUNHEAD), 1, fp) != 1){
fprintf(stderr,"ERROR : ReadSunRaster : fread : sunhead\n");
free(sunhead);
fclose(fp);
return(-4);
}
#ifdef __NBISLE__
/*
fprintf(stderr, "Bytes in Rasterfile header being swapped.\n");
*/
swap_uint_bytes(sunhead->magic);
swap_uint_bytes(sunhead->width);
swap_uint_bytes(sunhead->height);
swap_uint_bytes(sunhead->depth);
swap_uint_bytes(sunhead->raslength);
swap_uint_bytes(sunhead->rastype);
swap_uint_bytes(sunhead->maptype);
swap_uint_bytes(sunhead->maplength);
#endif
if(sunhead->rastype != SUN_STANDARD){
free(sunhead);
fprintf(stderr,
"ERROR : ReadSunRaster : unsupported Sun raster type %d\n",
sunhead->rastype);
return(-5);
}
if(sunhead->maplength == 0){
colormap = (unsigned char *)NULL;
}
else{
colormap = (unsigned char *)malloc(sunhead->maplength);
if(colormap == (unsigned char *)NULL){
free(sunhead);
fclose(fp);
fprintf(stderr,"ERROR : ReadSunRaster : malloc : colormap\n");
return(-6);
}
if(fread(colormap, 1, sunhead->maplength, fp) != sunhead->maplength){
free(sunhead);
free(colormap);
fclose(fp);
fprintf(stderr,"ERROR : ReadSunRaster : fread : colormap\n");
return(-7);
}
}
idata = (unsigned char *)malloc(sunhead->raslength);
if(idata == (unsigned char *)NULL){
free(sunhead);
if(colormap != (unsigned char *)NULL)
free(colormap);
fclose(fp);
fprintf(stderr,"ERROR : ReadSunRaster : malloc : idata\n");
return(-8);
}
if(fread(idata, 1, sunhead->raslength,fp) != sunhead->raslength){
free(sunhead);
if(colormap != (unsigned char *)NULL)
free(colormap);
free(idata);
fclose(fp);
fprintf(stderr,"ERROR : ReadSunRaster : fread : colormap\n");
return(-9);
}
fclose(fp);
/* Sun Rasterfiles permit the image width to be less than the actual */
/* scanline. Return both the scan width and the image width, and */
/* let the application decide which it wants to deal with. */
if((sunhead->depth == 1) &&
((sunhead->width * sunhead->height)>>3 != sunhead->raslength)){
scan_width = (sunhead->raslength / sunhead->height)<<3;
}
else
scan_width = sunhead->width;
*osunhead = sunhead;
*ocolormap = colormap;
*omaplen = sunhead->maplength;
*odata = idata;
*oscan_w = scan_width;
*oimg_w = sunhead->width;
*oimg_h = sunhead->height;
*oimg_d = sunhead->depth;
return(0);
}
/************************************************************/
int WriteSunRaster(char *ofile, unsigned char *data,
const int width, const int height, const int depth)
{
SUNHEAD sunhead;
int ret, pad = 0;
int ras_length, map_length;
int iw, ih;
FILE *fp;
iw = width;
ih = height;
switch (depth){
case 1:
if(iw%8){
fprintf(stderr,
"ERROR : WriteSunRaster : pixel width of bitmap must be multiple of 8\n");
return(-2);
}
/* Sun rasterfile bitmaps need to be 16-bit aligned in width. */
if(iw%16){
/* NOTE: Data will point to a new image memory, and the memory */
/* previously pointed to WILL remain allocated/unchanged. */
/* I have accounted for this. */
if((ret = binary_image_mpad(&data, (unsigned int *)&iw,
(unsigned int *)&ih,
16, 1, 0)) <= 0)
return(-3);
pad = 1;
}
sunhead.raslength = (iw * ih)>>3;
sunhead.maplength = 0;
sunhead.maptype = MAP_NONE;
break;
case 8:
sunhead.raslength = iw * ih;
sunhead.maplength = COLORMAP_LEN;
sunhead.maptype = MAP_EQUAL_RGB;
break;
default:
fprintf(stderr, "ERROR : WriteSunRaster : can't handle depth = %d\n",
depth);
return(-4);
}
sunhead.magic = SUN_MAGIC;
sunhead.width = width;
sunhead.height = ih;
sunhead.depth = depth;
ras_length = sunhead.raslength;
map_length = sunhead.maplength;
sunhead.rastype = SUN_STANDARD;
#ifdef __NBISLE__
/*
fprintf(stderr, "Bytes in Rasterfile header being swapped.\n");
*/
swap_uint_bytes(sunhead.magic);
swap_uint_bytes(sunhead.width);
swap_uint_bytes(sunhead.height);
swap_uint_bytes(sunhead.depth);
swap_uint_bytes(sunhead.raslength);
swap_uint_bytes(sunhead.rastype);
swap_uint_bytes(sunhead.maptype);
swap_uint_bytes(sunhead.maplength);
#endif
if ((fp = fopen(ofile, "wb")) == (FILE *)NULL){
fprintf(stderr, "ERROR : WriteSunRaster : fopen : %s\n", ofile);
return(-5);
}
if (1 != fwrite(&sunhead, sizeof(SUNHEAD), 1, fp)){
fprintf(stderr, "ERROR : WriteSunRaster : fwrite : sunhead\n");
return(-6);
}
/*
printf("wrote header = %d bytes\n", sizeof(SUNHEAD));
*/
if (map_length){
if (map_length != fwrite(colormap, 1, map_length, fp)){
fprintf(stderr, "ERROR : WriteSunRaster : fwrite : colormap\n");
return(-7);
}
}
/*
printf("wrote colormap = %d bytes\n", map_length);
*/
if (ras_length != fwrite(data, 1, ras_length,fp)){
fprintf(stderr, "ERROR : WriteSunRaster : fwrite : data\n");
return(-8);
}
/* Image_mpad makes a copy of the input image data, so free up */
/* the copy. The caller still points to the original image data. */
if(pad)
free(data);
/*
printf("wrote image = %d bytes\n", ras_length);
*/
if (ferror(fp)){
(void)unlink(ofile);
fprintf(stderr, "ERROR : WriteSunRaster : ferror : %s\n", ofile);
return(-9);
}
if (fclose(fp) == EOF){
fprintf(stderr, "ERROR : WriteSunRaster : fclose : %s\n", ofile);
return(-10);
}
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/dpyimage/dpymain.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
PACKAGE: NIST Image Display
FILE: DPYMAIN.C
AUTHORS: <NAME>
<NAME>
DATE: 12/03/1990
UPDATED: 05/10/2005 by MDG
UPDATED: 09/30/2008 by <NAME> - add version option.
UPDATED: 02/11/2009 by <NAME> - make raw option POSIX compliant
#cat: dpyimage - Takes an IHead, WSQ, JPEGB, JPEGL, or raw image file,
#cat: reconstructs the image pixmap (if needed), and renders
#cat: the pixmap in an X11 Window.
***********************************************************************/
#include <usebsd.h>
#include <stdlib.h>
#include <string.h>
#include <dpyimage.h>
#include <version.h>
#include <unistd.h>
void procargs(int, char **);
void usage(void);
extern char *optarg;
extern int optind, opterr, optopt;
/*********************************************************************/
int main(int argc, char *argv[])
{
int ret;
setlinebuf(stdout);
procargs(argc,argv);
if (optind >= argc)
usage();
if((ret = xconnect()))
exit(ret);
screen = DefaultScreen(display);
def_cmap = DefaultColormap(display,screen);
dw = DisplayWidth(display,screen);
dh = DisplayHeight(display,screen);
rw = RootWindow(display,screen);
visual = DefaultVisual(display,screen);
bp = BlackPixel(display,screen);
wp = WhitePixel(display,screen);
if ((optind == argc - 1) || (dpy_mode == DPY_NORM)){
if((ret = dpynorm(argc,argv)))
exit(ret);
}
else if (dpy_mode == DPY_PIPE){
if ((ret = pipecomm(argc,argv))){
exit(ret);
}
/* Parent does not know if child exits on error, so */
/* parent thread should exit here because some X Resources */
/* might not be allocated so cannot be "cleaned up" below */
exit(0);
}
else { /* dpy_mode == DPY_TMP */
if (tmpdir == def_tmpdir) { /* if not set on command line, */
char *p; /* check environment for TMPDIR */
p = getenv("TMPDIR");
if (p != (char *) NULL)
tmpdir = p;
}
tmpcomm(argc,argv);
}
cleanup();
if (verbose)
(void) printf("Errors: %d\n",errors);
exit(errors?1:0);
}
/************************************************************************/
void procargs(int argc, char **argv)
{
int c;
char *option_spec = "Aa:b:D:d:H:kN:Onr:s:T:tvW:xX:Y:";
char *raw_attribs;
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
program = rindex(*argv,'/');
if (program == (char *) NULL)
program = *argv;
else
program++;
while ((c = getopt(argc,argv,option_spec)) != EOF){
switch (c) {
case 'A': automatic = True;
break;
case 'a': accelerator = MAX(1,atoi(optarg));
break;
case 'b': border_width = atoi(optarg);
break;
case 'D': tmpdir = optarg;
break;
case 'd': display_name = optarg;
break;
case 'H': init_wh = atoi(optarg);
break;
case 'N': nicevalue = atoi(optarg);
break;
case 'n': dpy_mode = DPY_NORM;
break;
case 'r': raw = True;
/* Ignore "aw" in "-raw" for consistency among NBIS progams */
if (strcmp(optarg, "aw") == 0)
raw_attribs = argv[optind++];
else
raw_attribs = optarg;
c = sscanf(raw_attribs,"%u,%u,%u,%u",
&raw_w,&raw_h,
&raw_depth,&raw_whitepix);
if (c != 4) {
(void) fprintf(stderr,
"%s: cannot parse raw parameters\n", program);
usage();
}
break;
case 's': sleeptime = atoi(optarg);
break;
case 'T': title = optarg;
break;
case 't': dpy_mode = DPY_TMP;
break;
case 'v': verbose++;
break;
case 'X': wx = atoi(optarg);
break;
case 'x': debug++;
break;
case 'Y': wy = atoi(optarg);
break;
case 'W': init_ww = atoi(optarg);
break;
case 'O': no_window_mgr = True;
break;
case 'k': no_keyboard_input = True;
break;
default: usage();
break;
}/* switch */
}
}
/****************************************************************
Print usage message and exit.
****************************************************************/
void usage(void)
{
static char usage_msg[] = "\
Usage:\n\
%s [options] image-file ...\n\
-r, raw w,h,d,wp files are raw data with given width, height\n\
depth and white pixel\n\
-A auto advance through images\n\
-s n sleep n seconds before advancing [%d]\n\
-a n set drag accelerator [1]\n\
-v verbose\n\
-x debug mode (create core dump on X11 error)\n\
-b n set border width to n [%d]\n\
-N n nice I/O process with increment n\n\
-O override redirect on window (no window\n\
manager)\n\
-k no keyboard input\n\
-W n set window width to n\n\
-H n set window height to n\n\
-X n set window x pixels from display border [0]\n\
-Y n set window y pixels from display border [0]\n\
-n do not fork; one process reads and displays\n\
images\n\
-T title set title for images [filename]\n\
-t transfer images by temporary files\n\
-D dir create temporary files in directory [%s]\n\
-d display connect to alternate X11 server\n";
(void) fprintf(stderr,
usage_msg,
program,DEF_SLEEPTIME,DEF_BORDER_WIDTH,DEF_TMPDIR);
exit(1);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/fft/cfftb.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/* Changed each _( to plain (. GTC 14 July 1995. */
/* UPDATED: 03/14/2005 by MDG */
/* cfftb.f -- translated by f2c (version of 15 October 1990 19:58:17).
You must link the resulting object file with the libraries:
-lF77 -lI77 -lm -lc (in that order)
*/
#include "f2c.h"
extern /* Subroutine */ int cfftb1(int *, real *, real *, real *,
int *);
/* Subroutine */ int cfftb(int *n, real *c, real *wsave)
{
static int iw1, iw2;
/* ***BEGIN PROLOGUE CFFTB */
/* ***DATE WRITTEN 790601 (YYMMDD) */
/* ***REVISION DATE 830401 (YYMMDD) */
/* ***CATEGORY NO. J1A2 */
/* ***KEYWORDS FOURIER TRANSFORM */
/* ***AUTHOR SWARZTRAUBER, <NAME>., (NCAR) */
/* ***PURPOSE Unnormalized inverse of CFFTF. */
/* ***DESCRIPTION */
/* Subroutine CFFTB computes the backward complex discrete Fourier */
/* transform (the Fourier synthesis). Equivalently, CFFTB computes */
/* a complex periodic sequence from its Fourier coefficients. */
/* The transform is defined below at output parameter C. */
/* A call of CFFTF followed by a call of CFFTB will multiply the */
/* sequence by N. */
/* The array WSAVE which is used by subroutine CFFTB must be */
/* initialized by calling subroutine CFFTI(N,WSAVE). */
/* Input Parameters */
/* N the length of the complex sequence C. The method is */
/* more efficient when N is the product of small primes. */
/* C a complex array of length N which contains the sequence */
/* WSAVE a real work array which must be dimensioned at least 4*N+15 */
/* in the program that calls CFFTB. The WSAVE array must be */
/* initialized by calling subroutine CFFTI(N,WSAVE), and a */
/* different WSAVE array must be used for each different */
/* value of N. This initialization does not have to be */
/* repeated so long as N remains unchanged. Thus subsequent */
/* transforms can be obtained faster than the first. */
/* The same WSAVE array can be used by CFFTF and CFFTB. */
/* Output Parameters */
/* C For J=1,...,N */
/* C(J)=the sum from K=1,...,N of */
/* C(K)*EXP(I*J*K*2*PI/N) */
/* where I=SQRT(-1) */
/* WSAVE contains initialization calculations which must not be */
/* destroyed between calls of subroutine CFFTF or CFFTB */
/* ***REFERENCES (NONE) */
/* ***ROUTINES CALLED CFFTB1 */
/* ***END PROLOGUE CFFTB */
/* ***FIRST EXECUTABLE STATEMENT CFFTB */
/* Parameter adjustments */
--wsave;
--c;
/* Function Body */
if (*n == 1) {
return 0;
}
iw1 = *n + *n + 1;
iw2 = iw1 + *n + *n;
cfftb1(n, &c[1], &wsave[1], &wsave[iw1], (int *)&wsave[iw2]);
return 0;
} /* cfftb_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slarfg.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slarfg_(int *n, real *alpha, real *x, int *incx,
real *tau)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SLARFG generates a real elementary reflector H of order n, such
that
H * ( alpha ) = ( beta ), H' * H = I.
( x ) ( 0 )
where alpha and beta are scalars, and x is an (n-1)-element real
vector. H is represented in the form
H = I - tau * ( 1 ) * ( 1 v' ) ,
( v )
where tau is a real scalar and v is a real (n-1)-element
vector.
If the elements of x are all zero, then tau = 0 and H is taken to be
the unit matrix.
Otherwise 1 <= tau <= 2.
Arguments
=========
N (input) INTEGER
The order of the elementary reflector.
ALPHA (input/output) REAL
On entry, the value alpha.
On exit, it is overwritten with the value beta.
X (input/output) REAL array, dimension
(1+(N-2)*abs(INCX))
On entry, the vector x.
On exit, it is overwritten with the vector v.
INCX (input) INTEGER
The increment between elements of X. INCX > 0.
TAU (output) REAL
The value tau.
=====================================================================
Parameter adjustments
Function Body */
/* System generated locals */
int i__1;
real r__1;
/* Builtin functions */
double r_sign(real *, real *);
/* Local variables */
static real beta;
extern doublereal snrm2_(int *, real *, int *);
static int j;
extern /* Subroutine */ int sscal_(int *, real *, real *, int *);
static real xnorm;
extern doublereal slapy2_(real *, real *), slamch_(char *);
static real safmin, rsafmn;
static int knt;
#define X(I) x[(I)-1]
if (*n <= 1) {
*tau = 0.f;
return 0;
}
i__1 = *n - 1;
xnorm = snrm2_(&i__1, &X(1), incx);
if (xnorm == 0.f) {
/* H = I */
*tau = 0.f;
} else {
/* general case */
r__1 = slapy2_(alpha, &xnorm);
beta = -(doublereal)r_sign(&r__1, alpha);
safmin = slamch_("S") / slamch_("E");
if (dabs(beta) < safmin) {
/* XNORM, BETA may be inaccurate; scale X and recompute
them */
rsafmn = 1.f / safmin;
knt = 0;
L10:
++knt;
i__1 = *n - 1;
sscal_(&i__1, &rsafmn, &X(1), incx);
beta *= rsafmn;
*alpha *= rsafmn;
if (dabs(beta) < safmin) {
goto L10;
}
/* New BETA is at most 1, at least SAFMIN */
i__1 = *n - 1;
xnorm = snrm2_(&i__1, &X(1), incx);
r__1 = slapy2_(alpha, &xnorm);
beta = -(doublereal)r_sign(&r__1, alpha);
*tau = (beta - *alpha) / beta;
i__1 = *n - 1;
r__1 = 1.f / (*alpha - beta);
sscal_(&i__1, &r__1, &X(1), incx);
/* If ALPHA is subnormal, it may lose relative accuracy
*/
*alpha = beta;
i__1 = knt;
for (j = 1; j <= knt; ++j) {
*alpha *= safmin;
/* L20: */
}
} else {
*tau = (beta - *alpha) / beta;
i__1 = *n - 1;
r__1 = 1.f / (*alpha - beta);
sscal_(&i__1, &r__1, &X(1), incx);
*alpha = beta;
}
}
return 0;
/* End of SLARFG */
} /* slarfg_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/grp4comp.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: GRP4COMP.C
AUTHORS: CALS Test Network
DATE: 01/25/1990
Contains routines responsible for CCITT Group 4 encoding
a binary image pixel datastream.
ROUTINES:
#cat: grp4comp - CCITT Group 4 compresses a binary image (bitmap).
#cat:
***********************************************************************/
/********************************************************************
* Modified: <NAME> *
* <NAME> *
* Date: January 25, 1990 *
* Modified 12/90 by <NAME> *
* flush_buffer() was adding an extra byte to data *
* whether it was already byte-aligned or not *
* Modified 12/94 by <NAME> *
* Reclared the all variables of type "short" to be *
* "int", using a macro SHORT defined in the include *
* file grp4comp.h. *
* On images with more than 2^15 rows the *
* result was garbage because of an overflowed line *
* counter. The new declaration has a limit of 2^31 *
* Updated: 03/15/2005 by MDG *
* *
* Contents: ccitt4_compress() *
* read_uncompressed_file_into_memory() *
* control_compression() *
* prepare_to_compress() *
* compress_image() *
* make_array_of_changing_elements() *
* set_up_first_and_last_changing_elements_c() *
* prepare_to_compress_next_line() *
* set_up_first_line() *
* crash_c() *
* *
********************************************************************/
#ifdef TIME
#include <sys/time.h>
#endif
#include <memory.h>
#include <grp4comp.h>
/* Added by MDG in order have option of passing alloc responsibilities */
/* to caller */
#define NOALLOC 0
#define ALLOC 1
int comp_alloc_flag = ALLOC;
int comp_write_init_flag;
#ifdef TIME
struct timeval t1, t2;
struct timezone tz;
#endif
/***********************************************************************
* grp4comp is the main routine of this file. It does pre- *
* liminary setup, calls routines, and does final processing. *
************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* indata - buffer containing the uncompressed data. *
* inbytes - the number of bytes in indata. *
* width - Width in pixels of scan line in indata. *
* height - Number of lines in indata. *
* Returned: *
* outdata - buffer containing the compressed data. *
* outbytes - the number of bytes in outdata. *
************************************************************************/
void grp4comp(unsigned char *indata, int inbytes, int width, int height,
unsigned char *outdata, int *outbytes)
{
struct uncompressed_descriptor uncompressed;
struct compressed_descriptor compressed;
uncompressed.pixels_per_line = width;
uncompressed.number_of_lines = height;
uncompressed.data = indata;
comp_alloc_flag = NOALLOC;
comp_write_init_flag = True;
read_uncompressed_file_into_memory( &uncompressed);
compressed.data = outdata;
control_compression( &uncompressed, &compressed );
*outbytes = compressed.length_in_bytes;
/* printf("\ncompressed:lines: %d, pixels:%d, length:%d\n",
compressed.number_of_lines, compressed.pixels_per_line,
compressed.length_in_bytes); */
}
/***************************** control_compression **************************
calls the functions that compress the image
*****************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* uncompressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the uncompressed data. *
* Returned: *
* compressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the compressed data. *
************************************************************************/
void control_compression(struct uncompressed_descriptor *uncompressed,
struct compressed_descriptor *compressed)
{
struct parameters sole_parameters;
struct parameters *params = &sole_parameters;
#ifdef TIME
SHORT i;
tz.tz_minuteswest = 0;
tz.tz_dsttime = 0;
gettimeofday(&t1, &tz);
#endif
prepare_to_compress( uncompressed, compressed, params );
compress_image( uncompressed, compressed, params );
/* memory deallocation added by <NAME> 2/26/90 */
free(params->reference_line);
free(params->coding_line);
#ifdef TIME
gettimeofday(&t2, &tz);
printf("\ntime difference: %ld:%ld\n", t2.tv_sec - t1.tv_sec,
t2.tv_usec - t1.tv_usec);
for(i=0; i<5; i++) printf("%c",'\07');*/
#endif
}
/************************ read_uncompressed_file_into_memory *******************
allocates memory for the uncompressed image.
*****************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* uncompressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the uncompressed data. *
* Returned: *
* uncompressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the compressed data. *
************************************************************************/
void read_uncompressed_file_into_memory(
struct uncompressed_descriptor *uncompressed)
{
int file_size;
if(comp_alloc_flag){
file_size = uncompressed->pixels_per_line * uncompressed->number_of_lines
/ Pixels_per_byte;
if((uncompressed->data = (unsigned char *)calloc( file_size,
sizeof(unsigned char) )) == NULL) {
printf("\nCannot allocate enough memory for uncomp file.\n");
crash_c();
}
}
else
if(uncompressed->data == NULL){
printf("\nNo memory allocated for input data!\n");
crash_c();
}
} /* end read_uncompressed_file_into_memory() */
/*************************** prepare_to_compress ****************************
initializes variables in preperation for compression
*****************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* uncompressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the uncompressed data. *
* Returned: *
* compressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the compressed data. *
* params - structure storing information needed for *
* comparison and other tasks. *
************************************************************************/
void prepare_to_compress(struct uncompressed_descriptor *uncompressed,
struct compressed_descriptor *compressed,
struct parameters *params)
{
params->max_pixel = uncompressed->pixels_per_line;
compressed->pixels_per_line = uncompressed->pixels_per_line;
compressed->number_of_lines = uncompressed->number_of_lines;
set_up_first_line_c( params );
prepare_to_write_bits_c( compressed );
} /* end prepare_to_compress() */
/****************************** compress_image *******************************
compresses the image
*****************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* uncompressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the uncompressed data. *
* Returned: *
* compressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the compressed data. *
* params - structure storing information need for *
* comparison and other tasks. *
************************************************************************/
void compress_image(struct uncompressed_descriptor *uncompressed,
struct compressed_descriptor *compressed,
struct parameters *params)
{
SHORT line;
for(line = 0; line < uncompressed->number_of_lines; line++) {
make_array_of_changing_elements( params, uncompressed, line );
set_up_first_and_last_changing_elements_c( params );
compress_line( params );
prepare_to_compress_next_line( params );
} /* end for each line loop */
write_bits_c("000000000001000000000001");
compressed->length_in_bytes = flush_buffer();
}
/************************ make_array_of_changing_elements *********************
stores in a list pointed to by "params->coding_line" the pixel numbers
of all the changing elements in the coding line
*****************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* uncompressed - structure containing the # of pixels *
* per line, the number of lines, and *
* the uncompressed data. *
* line_number - the number of the line in the image *
* Returned: *
* params - structure storing information need for *
* comparison and other tasks. *
************************************************************************/
void make_array_of_changing_elements(struct parameters *params,
struct uncompressed_descriptor *uncompressed,
SHORT line_number)
{
SHORT bytes_per_line;
int line_offset;
SHORT byte_offset;
bytes_per_line = params->max_pixel / Pixels_per_byte;
line_offset = bytes_per_line * line_number;
for(byte_offset=0; byte_offset < bytes_per_line; byte_offset++) {
process_char(*(uncompressed->data+line_offset+byte_offset),params);
}
} /* end make_array_of_changing_elements() */
/******************* set_up_first_and_last_changing_elements_c *****************
initializes the first and last changing elements in the coding line
******************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information need for *
* comparison and other tasks. *
* Returned: *
* params - structure storing information need for *
* comparison and other tasks. *
************************************************************************/
void set_up_first_and_last_changing_elements_c(struct parameters *params)
{
*(params->coding_line) = Invalid;
*(params->coding_line + ++params->index) = params->max_pixel;
*(params->coding_line + ++params->index) = params->max_pixel;
*(params->coding_line + ++params->index) = params->max_pixel;
/* the previous lines may be necessary if when searching for b1, you
skip some elements because you know that they are the wrong color */
}
/************************ prepare_to_compress_next_line ***********************
initializes variables in preperation for compressing another line
******************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information need for *
* comparison and other tasks. *
* Returned: *
* params - structure storing information need for *
* comparison and other tasks. *
************************************************************************/
void prepare_to_compress_next_line(struct parameters *params)
{
SHORT *temp;
/* swap the reference and unchanged coding lines */
temp = params->reference_line;
params->reference_line = params->coding_line;
params->coding_line = temp;
params->pixel = 0;
params->index = 0;
params->previous_color = White;
} /* end prepare_to_read_next_line() */
/******************************* set_up_first_line_c ***************************
initializes variables in preperation for compressing the first line
******************************************************************************/
/***********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information need for *
* comparison and other tasks. *
* Returned: *
* params - structure storing information need for *
* comparison and other tasks. *
************************************************************************/
void set_up_first_line_c(struct parameters *params)
{
params->reference_line = (SHORT *) malloc( (params->max_pixel +
Extra_positions) * sizeof(SHORT) );
params->coding_line = (SHORT *) malloc( (params->max_pixel +
Extra_positions) * sizeof(SHORT) );
*(params->reference_line + 0) = Invalid;
*(params->reference_line + 1) = params->max_pixel;
*(params->reference_line + 2) = params->max_pixel;
*(params->reference_line + 3) = params->max_pixel;
/* initialize first changing element on coding line (A0 = -1) */
*(params->coding_line) = Invalid;
params->pixel = 0;
params->index = 0;
params->previous_color = White;
} /* end set_up_first_line_c() */
/*********************************** crash_c ***********************************
forces the program to crash and create a core file
*****************************************************************************/
void crash_c()
{
FILE *crash_program = NULL;
fprintf(crash_program,"This will kill the program and create a core file");
}
/***************************************************************************/
/* Originally mode.c */
/***************************************************************************/
static SHORT A0, A0_color,
A1, a2,
b1, b2;
/******************************* compress_line ********************************
compresses a single line of the image
*****************************************************************************/
void compress_line(struct parameters *params)
{
#if Debug
static SHORT line = 0;
printf("\nLINE %d. ",line);
line++;
#endif
A0 = Invalid; /* set A0 equal to imaginary first array element */
A0_color = White;
A1 = 1;
initialize_b1(params);
b2 = b1 + 1;
#if Debug
printf("\nA0:%d A1:%d b1:%d b2:%d ",
A0, *(params->coding_line+A1),
*(params->reference_line+b1),*(params->reference_line+b2));
#endif
do {
if (*(params->reference_line + b2) < *(params->coding_line + A1)) {
pass_mode_c(params);
continue;
} else
if (abs(*(params->coding_line+A1)-*(params->reference_line+b1)) <=3)
vertical_mode_c(params);
else
horizontal_mode_c(params);
#if Debug
printf("\nA0:%d A1:%d b1:%d b2:%d ",
A0, *(params->coding_line+A1),
*(params->reference_line+b1),*(params->reference_line+b2));
#endif
} while( A0 < params->max_pixel);
}
/******************************* initialize_b1 ********************************
locates b1's first position in the reference line
*****************************************************************************/
void initialize_b1(struct parameters *params)
{
SHORT last_bit_of_b1;
b1 = 1;
last_bit_of_b1 = b1 & Last_bit_mask;
while( ((*(params->reference_line +b1) <=A0) || (A0_color ==last_bit_of_b1))
&& (*(params->reference_line + b1) < params->max_pixel) ){
b1++;
last_bit_of_b1 = b1 & Last_bit_mask;
} /* end while loop */
#if Debug
printf("\nb1:%d :%d, A0:%d", b1,
*(params->reference_line+b1), A0);
#endif
}
/********************************** pass_mode_c ********************************
compresses a pass mode
*****************************************************************************/
void pass_mode_c(struct parameters *params)
{
write_bits_c("0001");
#if Debug
printf(" P ");
#endif
/*
* Reset the value A0 points to to a'0 (the value that b2 points to).
*/
A0 = *(params->reference_line + b2);
/*
* Since A0 is now greater than the pixel b1 points to, both b1 and b2
* must be advanced twice to maintain the color difference between A0 and
* b1, and the positional requirement that b1 point to a pixel greater than
* the one A0 points to.
*/
b1 += 2;
b2 += 2;
/*
* Note that the b's can be advanced by two positions without fear of
* moving them beyond the last changing element because pass_mode cannot
* occur if b2 is already pointing to max_pixel.
*/
}
/****************************** vertical_mode_c ********************************
compresses a vertical mode
*****************************************************************************/
void vertical_mode_c(struct parameters *params)
{
SHORT difference;
difference = *(params->coding_line + A1) - *(params->reference_line + b1);
A0 = *(params->coding_line + A1);
A0_color = !A0_color;
A1++;
#if Debug
printf(" V%d ", difference);
#endif
switch(difference) {
case 0:
write_bits_c("1");
if(*(params->reference_line + b1) != params->max_pixel ) {
b1++;
b2++;
} /* end if b1 is not on the last changing element */
break;
case 1:
write_bits_c("011");
b1++;
b2++;
if((*(params->reference_line + b1) <= A0) &&
(*(params->reference_line + b1) != params->max_pixel) ) {
b1 += 2;
b2 += 2;
}
break;
case -1:
write_bits_c("010");
if(*(params->reference_line + b1) != params->max_pixel ) {
b1++;
b2++;
} /* end if b1 is not on the last changing element */
break;
case 2:
write_bits_c("000011");
b1++;
b2++;
if((*(params->reference_line + b1) <= A0) &&
(*(params->reference_line + b1) != params->max_pixel) ) {
b1 += 2;
b2 += 2;
}
break;
case -2:
write_bits_c("000010");
if(*(params->reference_line + b1 - 1) > A0 ) {
b1--;
b2--;
} else if(*(params->reference_line + b1) != params->max_pixel){
b1++;
b2++;
}
break;
case 3:
write_bits_c("0000011");
b1++;
b2++;
while ((*(params->reference_line + b1) <= A0) &&
(*(params->reference_line + b1) != params->max_pixel) ) {
b1 += 2;
b2 += 2;
}
break;
case -3:
write_bits_c("0000010");
if(*(params->reference_line + b1 - 1) > A0 ) {
b1--;
b2--;
} else if(*(params->reference_line + b1) != params->max_pixel){
b1++;
b2++;
}
break;
default:
printf("ERROR in vertical_mode_c() ");
} /* end case of difference */
}
/**************************** horizontal_mode_c ********************************
compresses a horizontal mode
*****************************************************************************/
void horizontal_mode_c(struct parameters *params)
{
SHORT run_length;
#if Debug
printf(" a2:%d H ",*(params->coding_line + a2));
#endif
a2 = A1 + 1;
write_bits_c("001");
if(A0 == Invalid) /* on imaginary first pixel */
run_length = *(params->coding_line + A1);
else
run_length = *(params->coding_line + A1) - A0;
write_run_length(run_length, A0_color );
/* the last bit contains the color of the changing element */
run_length = *(params->coding_line + a2) - *(params->coding_line + A1);
write_run_length(run_length, !A0_color);
/*
* Must use !A0_color instead of A1 because in cases in which A1 occurs
* on max_pixel, its color is bogus.
*/
/* NOTE: is the above statement true? if A1 were on max_pixel, you should
not get horizontal mode. */
A0 = *(params->coding_line + a2);
A1 = a2 + 1;
while((*(params->reference_line + b1) <= *(params->coding_line + a2)) &&
( *(params->reference_line + b1) < params->max_pixel) )
{
b1 += 2; /* must move ahead by 2 to maintain color difference with */
b2 += 2; /* A0, whose color does not change in this mode. */
}
}
/***************************************************************************/
/* Originally write_bits_c.c */
/***************************************************************************/
static SHORT bit_place_mark;
static int byte_place_mark;
static unsigned char *output_area;
static char write_one[Pixels_per_byte] =
{
(char)0x80,
(char)0x40,
(char)0x20,
(char)0x10,
(char)0x8,
(char)0x4,
(char)0x2,
(char)0x1,
};
static char write_zero[Pixels_per_byte] =
{
(char)0x7F,
(char)0xBF,
(char)0xDF,
(char)0xEF,
(char)0xF7,
(char)0xFB,
(char)0xFD,
(char)0xFE,
};
/*************************** prepare_to_write_bits_c **************************
initializes variables in preperation for writing compressed images
*****************************************************************************/
void prepare_to_write_bits_c(struct compressed_descriptor *compressed)
{
if(comp_alloc_flag){
compressed->data = (unsigned char *)calloc(
(compressed->pixels_per_line *
compressed->number_of_lines / Pixels_per_byte),
sizeof(unsigned char) );
}
/*
* This allocation is usually very wasteful, but because there is no
* way of knowing how much space is needed, I decided to be generous.
*/
if (compressed->data == NULL){
printf("\nMemory allocation error for compressed output data.\n");
crash_c();
}
output_area = compressed->data;
}
/******************************** write_bits_c **********************************
writes a variable length series of bits represented by a string of '1's
and '0's, which it receives as a parameter
*****************************************************************************/
void write_bits_c(char *string_ptr)
{
/* global switch added by <NAME> 2/26/90 */
if(comp_write_init_flag){
bit_place_mark = 0;
byte_place_mark = 0;
comp_write_init_flag = False;
}
/* EDIT MDG 1/25/99
while(*string_ptr != NULL) {
*/
while(*string_ptr != '\0') {
if(*string_ptr == '1')
*(output_area + byte_place_mark) |= write_one[bit_place_mark];
else
*(output_area + byte_place_mark) &= write_zero[bit_place_mark];
if(bit_place_mark == Last_bit_in_a_byte) {
bit_place_mark = 0;
byte_place_mark++;
} /* end if byte is full */
else
bit_place_mark++;
string_ptr++;
} /* end while */
}
/******************************** flush_buffer *******************************
writes to memory whatever bits are left in the bit buffer followed by
enough zero-bits to pad the compressed image out to a byte boundary.
*****************************************************************************/
unsigned int flush_buffer()
{
SHORT i;
if (bit_place_mark != 0) {
for (i=bit_place_mark; i<Pixels_per_byte; i++)
*(output_area + byte_place_mark) &= write_zero[i];
/*
* pad the rest of the last byte with '0' bits.
*/
++byte_place_mark;
}
return byte_place_mark;
}
/***************************************************************************/
/* Originally write_run.c */
/***************************************************************************/
/******************************************************************************
The arrays that follow contain character representations of the binary
run length codes written during compression.
******************************************************************************/
static char *white_terminating_code[64] =
{
"00110101",
"000111",
"0111",
"1000",
"1011",
"1100",
"1110",
"1111",
"10011",
"10100",
"00111",
"01000",
"001000",
"000011",
"110100",
"110101",
"101010",
"101011",
"0100111",
"0001100",
"0001000",
"0010111",
"0000011",
"0000100",
"0101000",
"0101011",
"0010011",
"0100100",
"0011000",
"00000010",
"00000011",
"00011010",
"00011011",
"00010010",
"00010011",
"00010100",
"00010101",
"00010110",
"00010111",
"00101000",
"00101001",
"00101010",
"00101011",
"00101100",
"00101101",
"00000100",
"00000101",
"00001010",
"00001011",
"01010010",
"01010011",
"01010100",
"01010101",
"00100100",
"00100101",
"01011000",
"01011001",
"01011010",
"01011011",
"01001010",
"01001011",
"00110010",
"00110011",
"00110100",
};/* end array of white terminating code */
static char *black_terminating_code[64] =
{
"0000110111",
"010",
"11",
"10",
"011",
"0011",
"0010",
"00011",
"000101",
"000100",
"0000100",
"0000101",
"0000111",
"00000100",
"00000111",
"000011000",
"0000010111",
"0000011000",
"0000001000",
"00001100111",
"00001101000",
"00001101100",
"00000110111",
"00000101000",
"00000010111",
"00000011000",
"000011001010",
"000011001011",
"000011001100",
"000011001101",
"000001101000",
"000001101001",
"000001101010",
"000001101011",
"000011010010",
"000011010011",
"000011010100",
"000011010101",
"000011010110",
"000011010111",
"000001101100",
"000001101101",
"000011011010",
"000011011011",
"000001010100",
"000001010101",
"000001010110",
"000001010111",
"000001100100",
"000001100101",
"000001010010",
"000001010011",
"000000100100",
"000000110111",
"000000111000",
"000000100111",
"000000101000",
"000001011000",
"000001011001",
"000000101011",
"000000101100",
"000001011010",
"000001100110",
"000001100111",
}; /* end black_terminating_array */
static char *white_make_up_code[40] =
{
"11011",
"10010",
"010111",
"0110111",
"00110110",
"00110111",
"01100100",
"01100101",
"01101000",
"01100111",
"011001100",
"011001101",
"011010010",
"011010011",
"011010100",
"011010101",
"011010110",
"011010111",
"011011000",
"011011001",
"011011010",
"011011011",
"010011000",
"010011001",
"010011010",
"011000",
"010011011",
/*
* from this line on, the codes are colorless and represnt runs from
* 1792 pixels to 2560 pixels. In other words, the longest run length
* codes have been added onto both the white make up codes and the black
* make up codes. This has been done to make the procedure
* "write_run_length()" easier to write and to understand. No other
* procedure in the compression algorithm is affected by this merging of
* different types of run length codes, and the compatibility of the
* program is in no way effected.
*/
"00000001000",
"00000001100",
"00000001101",
"000000010010",
"000000010011",
"000000010100",
"000000010101",
"000000010110",
"000000010111",
"000000011100",
"000000011101",
"000000011110",
"000000011111",
}; /* end case of white makeup code */
static char *black_make_up_code[40] =
{
"0000001111",
"000011001000",
"000011001001",
"000001011011",
"000000110011",
"000000110100",
"000000110101",
"0000001101100",
"0000001101101",
"0000001001010",
"0000001001011",
"0000001001100",
"0000001001101",
"0000001110010",
"0000001110011",
"0000001110100",
"0000001110101",
"0000001110110",
"0000001110111",
"0000001010010",
"0000001010011",
"0000001010100",
"0000001010101",
"0000001011010",
"0000001011011",
"0000001100100",
"0000001100101",
/*
* from this line on, the codes are colorless and represnt runs from
* 1792 pixels to 2560 pixels. In other words, the longest run length
* codes have been added onto both the white make up codes and the black
* make up codes. This has been done to make the procedure
* "write_run_length()" easier to write and to understand. No other
* procedure in the compression algorithm is affected by this merging of
* different types of run length codes, and the compatibility of the
* program is in no way compromised.
*/
"00000001000",
"00000001100",
"00000001101",
"000000010010",
"000000010011",
"000000010100",
"000000010101",
"000000010110",
"000000010111",
"000000011100",
"000000011101",
"000000011110",
"000000011111",
}; /* end black makeup code */
char *largest_colorless_code =
{
"000000011111"
};
/****************************** write_run_length() *****************************
writes the code, or series of codes, that represent a given run length
of a given color.
******************************************************************************/
void write_run_length(SHORT length, SHORT color)
{
SHORT multiples_of_largest_code,
make_up_code_index,
remainder,
i;
multiples_of_largest_code = length / Largest_code;
length %= Largest_code;
for(i=0 ; i < multiples_of_largest_code ; i++)
write_bits_c( largest_colorless_code );
remainder = length % Size_of_make_up_code_increments;
/* remainder in the range 0 - 63 */
make_up_code_index = length / Size_of_make_up_code_increments;
/*
* make_up_code_index in the range 0 - 39, and represents a run length
* of 64 times its value (i.e. 0 - 2496). To translate this value into
* an index into the arrays that store the bit sequence that represents
* the appropriate run length, 1 must be subtracted from make_up_code_
* index. If this results in the value -1, no make up code should be
* written.
*/
make_up_code_index--;
if(make_up_code_index != Invalid) {
if(color == White)
write_bits_c(white_make_up_code[make_up_code_index]);
else
write_bits_c(black_make_up_code[make_up_code_index]);
}
if(color == White)
write_bits_c(white_terminating_code[remainder]);
else
write_bits_c(black_terminating_code[remainder]);
} /* end write run length() */
/***************************************************************************/
/* Originally table.c */
/***************************************************************************/
struct byte_descriptor {
SHORT pixel[9];
};
static struct byte_descriptor table[Number_of_different_bytes] =
{
{{-1, -1, -1, -1, -1, -1, -1, -1, -1}},
{{7, -1, -1, -1, -1, -1, -1, -1, -1}},
{{6, 7, -1, -1, -1, -1, -1, -1, -1}},
{{6, -1, -1, -1, -1, -1, -1, -1, -1}},
{{5, 6, -1, -1, -1, -1, -1, -1, -1}},
{{5, 6, 7, -1, -1, -1, -1, -1, -1}},
{{5, 7, -1, -1, -1, -1, -1, -1, -1}},
{{5, -1, -1, -1, -1, -1, -1, -1, -1}},
{{4, 5, -1, -1, -1, -1, -1, -1, -1}},
{{4, 5, 7, -1, -1, -1, -1, -1, -1}},
{{4, 5, 6, 7, -1, -1, -1, -1, -1}},
{{4, 5, 6, -1, -1, -1, -1, -1, -1}},
{{4, 6, -1, -1, -1, -1, -1, -1, -1}},
{{4, 6, 7, -1, -1, -1, -1, -1, -1}},
{{4, 7, -1, -1, -1, -1, -1, -1, -1}},
{{4, -1, -1, -1, -1, -1, -1, -1, -1}},
{{3, 4, -1, -1, -1, -1, -1, -1, -1}},
{{3, 4, 7, -1, -1, -1, -1, -1, -1}},
{{3, 4, 6, 7, -1, -1, -1, -1, -1}},
{{3, 4, 6, -1, -1, -1, -1, -1, -1}},
{{3, 4, 5, 6, -1, -1, -1, -1, -1}},
{{3, 4, 5, 6, 7, -1, -1, -1, -1}},
{{3, 4, 5, 7, -1, -1, -1, -1, -1}},
{{3, 4, 5, -1, -1, -1, -1, -1, -1}},
{{3, 5, -1, -1, -1, -1, -1, -1, -1}},
{{3, 5, 7, -1, -1, -1, -1, -1, -1}},
{{3, 5, 6, 7, -1, -1, -1, -1, -1}},
{{3, 5, 6, -1, -1, -1, -1, -1, -1}},
{{3, 6, -1, -1, -1, -1, -1, -1, -1}},
{{3, 6, 7, -1, -1, -1, -1, -1, -1}},
{{3, 7, -1, -1, -1, -1, -1, -1, -1}},
{{3, -1, -1, -1, -1, -1, -1, -1, -1}},
{{2, 3, -1, -1, -1, -1, -1, -1, -1}},
{{2, 3, 7, -1, -1, -1, -1, -1, -1}},
{{2, 3, 6, 7, -1, -1, -1, -1, -1}},
{{2, 3, 6, -1, -1, -1, -1, -1, -1}},
{{2, 3, 5, 6, -1, -1, -1, -1, -1}},
{{2, 3, 5, 6, 7, -1, -1, -1, -1}},
{{2, 3, 5, 7, -1, -1, -1, -1, -1}},
{{2, 3, 5, -1, -1, -1, -1, -1, -1}},
{{2, 3, 4, 5, -1, -1, -1, -1, -1}},
{{2, 3, 4, 5, 7, -1, -1, -1, -1}},
{{2, 3, 4, 5, 6, 7, -1, -1, -1}},
{{2, 3, 4, 5, 6, -1, -1, -1, -1}},
{{2, 3, 4, 6, -1, -1, -1, -1, -1}},
{{2, 3, 4, 6, 7, -1, -1, -1, -1}},
{{2, 3, 4, 7, -1, -1, -1, -1, -1}},
{{2, 3, 4, -1, -1, -1, -1, -1, -1}},
{{2, 4, -1, -1, -1, -1, -1, -1, -1}},
{{2, 4, 7, -1, -1, -1, -1, -1, -1}},
{{2, 4, 6, 7, -1, -1, -1, -1, -1}},
{{2, 4, 6, -1, -1, -1, -1, -1, -1}},
{{2, 4, 5, 6, -1, -1, -1, -1, -1}},
{{2, 4, 5, 6, 7, -1, -1, -1, -1}},
{{2, 4, 5, 7, -1, -1, -1, -1, -1}},
{{2, 4, 5, -1, -1, -1, -1, -1, -1}},
{{2, 5, -1, -1, -1, -1, -1, -1, -1}},
{{2, 5, 7, -1, -1, -1, -1, -1, -1}},
{{2, 5, 6, 7, -1, -1, -1, -1, -1}},
{{2, 5, 6, -1, -1, -1, -1, -1, -1}},
{{2, 6, -1, -1, -1, -1, -1, -1, -1}},
{{2, 6, 7, -1, -1, -1, -1, -1, -1}},
{{2, 7, -1, -1, -1, -1, -1, -1, -1}},
{{2, -1, -1, -1, -1, -1, -1, -1, -1}},
{{1, 2, -1, -1, -1, -1, -1, -1, -1}},
{{1, 2, 7, -1, -1, -1, -1, -1, -1}},
{{1, 2, 6, 7, -1, -1, -1, -1, -1}},
{{1, 2, 6, -1, -1, -1, -1, -1, -1}},
{{1, 2, 5, 6, -1, -1, -1, -1, -1}},
{{1, 2, 5, 6, 7, -1, -1, -1, -1}},
{{1, 2, 5, 7, -1, -1, -1, -1, -1}},
{{1, 2, 5, -1, -1, -1, -1, -1, -1}},
{{1, 2, 4, 5, -1, -1, -1, -1, -1}},
{{1, 2, 4, 5, 7, -1, -1, -1, -1}},
{{1, 2, 4, 5, 6, 7, -1, -1, -1}},
{{1, 2, 4, 5, 6, -1, -1, -1, -1}},
{{1, 2, 4, 6, -1, -1, -1, -1, -1}},
{{1, 2, 4, 6, 7, -1, -1, -1, -1}},
{{1, 2, 4, 7, -1, -1, -1, -1, -1}},
{{1, 2, 4, -1, -1, -1, -1, -1, -1}},
{{1, 2, 3, 4, -1, -1, -1, -1, -1}},
{{1, 2, 3, 4, 7, -1, -1, -1, -1}},
{{1, 2, 3, 4, 6, 7, -1, -1, -1}},
{{1, 2, 3, 4, 6, -1, -1, -1, -1}},
{{1, 2, 3, 4, 5, 6, -1, -1, -1}},
{{1, 2, 3, 4, 5, 6, 7, -1, -1}},
{{1, 2, 3, 4, 5, 7, -1, -1, -1}},
{{1, 2, 3, 4, 5, -1, -1, -1, -1}},
{{1, 2, 3, 5, -1, -1, -1, -1, -1}},
{{1, 2, 3, 5, 7, -1, -1, -1, -1}},
{{1, 2, 3, 5, 6, 7, -1, -1, -1}},
{{1, 2, 3, 5, 6, -1, -1, -1, -1}},
{{1, 2, 3, 6, -1, -1, -1, -1, -1}},
{{1, 2, 3, 6, 7, -1, -1, -1, -1}},
{{1, 2, 3, 7, -1, -1, -1, -1, -1}},
{{1, 2, 3, -1, -1, -1, -1, -1, -1}},
{{1, 3, -1, -1, -1, -1, -1, -1, -1}},
{{1, 3, 7, -1, -1, -1, -1, -1, -1}},
{{1, 3, 6, 7, -1, -1, -1, -1, -1}},
{{1, 3, 6, -1, -1, -1, -1, -1, -1}},
{{1, 3, 5, 6, -1, -1, -1, -1, -1}},
{{1, 3, 5, 6, 7, -1, -1, -1, -1}},
{{1, 3, 5, 7, -1, -1, -1, -1, -1}},
{{1, 3, 5, -1, -1, -1, -1, -1, -1}},
{{1, 3, 4, 5, -1, -1, -1, -1, -1}},
{{1, 3, 4, 5, 7, -1, -1, -1, -1}},
{{1, 3, 4, 5, 6, 7, -1, -1, -1}},
{{1, 3, 4, 5, 6, -1, -1, -1, -1}},
{{1, 3, 4, 6, -1, -1, -1, -1, -1}},
{{1, 3, 4, 6, 7, -1, -1, -1, -1}},
{{1, 3, 4, 7, -1, -1, -1, -1, -1}},
{{1, 3, 4, -1, -1, -1, -1, -1, -1}},
{{1, 4, -1, -1, -1, -1, -1, -1, -1}},
{{1, 4, 7, -1, -1, -1, -1, -1, -1}},
{{1, 4, 6, 7, -1, -1, -1, -1, -1}},
{{1, 4, 6, -1, -1, -1, -1, -1, -1}},
{{1, 4, 5, 6, -1, -1, -1, -1, -1}},
{{1, 4, 5, 6, 7, -1, -1, -1, -1}},
{{1, 4, 5, 7, -1, -1, -1, -1, -1}},
{{1, 4, 5, -1, -1, -1, -1, -1, -1}},
{{1, 5, -1, -1, -1, -1, -1, -1, -1}},
{{1, 5, 7, -1, -1, -1, -1, -1, -1}},
{{1, 5, 6, 7, -1, -1, -1, -1, -1}},
{{1, 5, 6, -1, -1, -1, -1, -1, -1}},
{{1, 6, -1, -1, -1, -1, -1, -1, -1}},
{{1, 6, 7, -1, -1, -1, -1, -1, -1}},
{{1, 7, -1, -1, -1, -1, -1, -1, -1}},
{{1, -1, -1, -1, -1, -1, -1, -1, -1}},
{{0, 1, -1, -1, -1, -1, -1, -1, -1}},
{{0, 1, 7, -1, -1, -1, -1, -1, -1}},
{{0, 1, 6, 7, -1, -1, -1, -1, -1}},
{{0, 1, 6, -1, -1, -1, -1, -1, -1}},
{{0, 1, 5, 6, -1, -1, -1, -1, -1}},
{{0, 1, 5, 6, 7, -1, -1, -1, -1}},
{{0, 1, 5, 7, -1, -1, -1, -1, -1}},
{{0, 1, 5, -1, -1, -1, -1, -1, -1}},
{{0, 1, 4, 5, -1, -1, -1, -1, -1}},
{{0, 1, 4, 5, 7, -1, -1, -1, -1}},
{{0, 1, 4, 5, 6, 7, -1, -1, -1}},
{{0, 1, 4, 5, 6, -1, -1, -1, -1}},
{{0, 1, 4, 6, -1, -1, -1, -1, -1}},
{{0, 1, 4, 6, 7, -1, -1, -1, -1}},
{{0, 1, 4, 7, -1, -1, -1, -1, -1}},
{{0, 1, 4, -1, -1, -1, -1, -1, -1}},
{{0, 1, 3, 4, -1, -1, -1, -1, -1}},
{{0, 1, 3, 4, 7, -1, -1, -1, -1}},
{{0, 1, 3, 4, 6, 7, -1, -1, -1}},
{{0, 1, 3, 4, 6, -1, -1, -1, -1}},
{{0, 1, 3, 4, 5, 6, -1, -1, -1}},
{{0, 1, 3, 4, 5, 6, 7, -1, -1}},
{{0, 1, 3, 4, 5, 7, -1, -1, -1}},
{{0, 1, 3, 4, 5, -1, -1, -1, -1}},
{{0, 1, 3, 5, -1, -1, -1, -1, -1}},
{{0, 1, 3, 5, 7, -1, -1, -1, -1}},
{{0, 1, 3, 5, 6, 7, -1, -1, -1}},
{{0, 1, 3, 5, 6, -1, -1, -1, -1}},
{{0, 1, 3, 6, -1, -1, -1, -1, -1}},
{{0, 1, 3, 6, 7, -1, -1, -1, -1}},
{{0, 1, 3, 7, -1, -1, -1, -1, -1}},
{{0, 1, 3, -1, -1, -1, -1, -1, -1}},
{{0, 1, 2, 3, -1, -1, -1, -1, -1}},
{{0, 1, 2, 3, 7, -1, -1, -1, -1}},
{{0, 1, 2, 3, 6, 7, -1, -1, -1}},
{{0, 1, 2, 3, 6, -1, -1, -1, -1}},
{{0, 1, 2, 3, 5, 6, -1, -1, -1}},
{{0, 1, 2, 3, 5, 6, 7, -1, -1}},
{{0, 1, 2, 3, 5, 7, -1, -1, -1}},
{{0, 1, 2, 3, 5, -1, -1, -1, -1}},
{{0, 1, 2, 3, 4, 5, -1, -1, -1}},
{{0, 1, 2, 3, 4, 5, 7, -1, -1}},
{{0, 1, 2, 3, 4, 5, 6, 7, -1}},
{{0, 1, 2, 3, 4, 5, 6, -1, -1}},
{{0, 1, 2, 3, 4, 6, -1, -1, -1}},
{{0, 1, 2, 3, 4, 6, 7, -1, -1}},
{{0, 1, 2, 3, 4, 7, -1, -1, -1}},
{{0, 1, 2, 3, 4, -1, -1, -1, -1}},
{{0, 1, 2, 4, -1, -1, -1, -1, -1}},
{{0, 1, 2, 4, 7, -1, -1, -1, -1}},
{{0, 1, 2, 4, 6, 7, -1, -1, -1}},
{{0, 1, 2, 4, 6, -1, -1, -1, -1}},
{{0, 1, 2, 4, 5, 6, -1, -1, -1}},
{{0, 1, 2, 4, 5, 6, 7, -1, -1}},
{{0, 1, 2, 4, 5, 7, -1, -1, -1}},
{{0, 1, 2, 4, 5, -1, -1, -1, -1}},
{{0, 1, 2, 5, -1, -1, -1, -1, -1}},
{{0, 1, 2, 5, 7, -1, -1, -1, -1}},
{{0, 1, 2, 5, 6, 7, -1, -1, -1}},
{{0, 1, 2, 5, 6, -1, -1, -1, -1}},
{{0, 1, 2, 6, -1, -1, -1, -1, -1}},
{{0, 1, 2, 6, 7, -1, -1, -1, -1}},
{{0, 1, 2, 7, -1, -1, -1, -1, -1}},
{{0, 1, 2, -1, -1, -1, -1, -1, -1}},
{{0, 2, -1, -1, -1, -1, -1, -1, -1}},
{{0, 2, 7, -1, -1, -1, -1, -1, -1}},
{{0, 2, 6, 7, -1, -1, -1, -1, -1}},
{{0, 2, 6, -1, -1, -1, -1, -1, -1}},
{{0, 2, 5, 6, -1, -1, -1, -1, -1}},
{{0, 2, 5, 6, 7, -1, -1, -1, -1}},
{{0, 2, 5, 7, -1, -1, -1, -1, -1}},
{{0, 2, 5, -1, -1, -1, -1, -1, -1}},
{{0, 2, 4, 5, -1, -1, -1, -1, -1}},
{{0, 2, 4, 5, 7, -1, -1, -1, -1}},
{{0, 2, 4, 5, 6, 7, -1, -1, -1}},
{{0, 2, 4, 5, 6, -1, -1, -1, -1}},
{{0, 2, 4, 6, -1, -1, -1, -1, -1}},
{{0, 2, 4, 6, 7, -1, -1, -1, -1}},
{{0, 2, 4, 7, -1, -1, -1, -1, -1}},
{{0, 2, 4, -1, -1, -1, -1, -1, -1}},
{{0, 2, 3, 4, -1, -1, -1, -1, -1}},
{{0, 2, 3, 4, 7, -1, -1, -1, -1}},
{{0, 2, 3, 4, 6, 7, -1, -1, -1}},
{{0, 2, 3, 4, 6, -1, -1, -1, -1}},
{{0, 2, 3, 4, 5, 6, -1, -1, -1}},
{{0, 2, 3, 4, 5, 6, 7, -1, -1}},
{{0, 2, 3, 4, 5, 7, -1, -1, -1}},
{{0, 2, 3, 4, 5, -1, -1, -1, -1}},
{{0, 2, 3, 5, -1, -1, -1, -1, -1}},
{{0, 2, 3, 5, 7, -1, -1, -1, -1}},
{{0, 2, 3, 5, 6, 7, -1, -1, -1}},
{{0, 2, 3, 5, 6, -1, -1, -1, -1}},
{{0, 2, 3, 6, -1, -1, -1, -1, -1}},
{{0, 2, 3, 6, 7, -1, -1, -1, -1}},
{{0, 2, 3, 7, -1, -1, -1, -1, -1}},
{{0, 2, 3, -1, -1, -1, -1, -1, -1}},
{{0, 3, -1, -1, -1, -1, -1, -1, -1}},
{{0, 3, 7, -1, -1, -1, -1, -1, -1}},
{{0, 3, 6, 7, -1, -1, -1, -1, -1}},
{{0, 3, 6, -1, -1, -1, -1, -1, -1}},
{{0, 3, 5, 6, -1, -1, -1, -1, -1}},
{{0, 3, 5, 6, 7, -1, -1, -1, -1}},
{{0, 3, 5, 7, -1, -1, -1, -1, -1}},
{{0, 3, 5, -1, -1, -1, -1, -1, -1}},
{{0, 3, 4, 5, -1, -1, -1, -1, -1}},
{{0, 3, 4, 5, 7, -1, -1, -1, -1}},
{{0, 3, 4, 5, 6, 7, -1, -1, -1}},
{{0, 3, 4, 5, 6, -1, -1, -1, -1}},
{{0, 3, 4, 6, -1, -1, -1, -1, -1}},
{{0, 3, 4, 6, 7, -1, -1, -1, -1}},
{{0, 3, 4, 7, -1, -1, -1, -1, -1}},
{{0, 3, 4, -1, -1, -1, -1, -1, -1}},
{{0, 4, -1, -1, -1, -1, -1, -1, -1}},
{{0, 4, 7, -1, -1, -1, -1, -1, -1}},
{{0, 4, 6, 7, -1, -1, -1, -1, -1}},
{{0, 4, 6, -1, -1, -1, -1, -1, -1}},
{{0, 4, 5, 6, -1, -1, -1, -1, -1}},
{{0, 4, 5, 6, 7, -1, -1, -1, -1}},
{{0, 4, 5, 7, -1, -1, -1, -1, -1}},
{{0, 4, 5, -1, -1, -1, -1, -1, -1}},
{{0, 5, -1, -1, -1, -1, -1, -1, -1}},
{{0, 5, 7, -1, -1, -1, -1, -1, -1}},
{{0, 5, 6, 7, -1, -1, -1, -1, -1}},
{{0, 5, 6, -1, -1, -1, -1, -1, -1}},
{{0, 6, -1, -1, -1, -1, -1, -1, -1}},
{{0, 6, 7, -1, -1, -1, -1, -1, -1}},
{{0, 7, -1, -1, -1, -1, -1, -1, -1}},
{{0, -1, -1, -1, -1, -1, -1, -1, -1}}
}; /* end of data for list of byte descriptors */
/****************************** process_char *********************************
writes the pixel number of each changing element within the character
being processed to the list "params->coding_line"
******************************************************************************/
void process_char(unsigned char data_byte, struct parameters *params)
{
static char color = 0;
SHORT i = 0;
color = -(data_byte & Last_bit_mask);
data_byte ^= params->previous_color;
/* if the previous color is black - which is contrary to our assumptions -
* the bits in the byte must all be changed so that the result, when used
* as an index into the array 'bytes,' yields the correct result. In the
* above operation, if the previous color is black (11111111b), all bits
* are changed; if the previous color is white (00000000b), no bits are
* changed. */
while(table[data_byte].pixel[i] != Invalid)
*( params->coding_line + ++params->index ) =
params->pixel + table[data_byte].pixel[i++];
params->pixel += Pixels_per_byte;
params->previous_color = color;
/* 'color' is a temporary holding place for the value of previous color */
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/dpyimage/dpyimage.h
|
<reponame>ThalesGroup/WSQForAndroid<filename>library/src/main/cpp/nbis/imgtools/src/bin/dpyimage/dpyimage.h
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
PACKAGE: NIST Image Display
FILE: DPYIMAGE.H
AUTHORS: <NAME>
<NAME>
DATE: 12/03/1990
UPDATED: 05/10/2005 by MDG
***********************************************************************/
#ifndef _DPYIMAGE_H
#define _DPYIMAGE_H
#include <dpyx.h>
/* X-Window global references. */
extern unsigned int dw, dh;
extern int window_up;
extern int got_click;
extern unsigned int depth;
extern unsigned int ww, wh, iw, ih;
extern int absx, absy, relx, rely;
extern int x_1, y_1;
/* X-Window Contols & command line globals. */
extern char *program;
extern char *filename;
extern int accelerator;
extern unsigned int init_ww, init_wh;
extern int nicevalue;
extern int pointwidth;
extern char *title;
extern unsigned int wx, wy;
extern int verbose;
extern int debug;
extern int errors;
extern int automatic;
extern unsigned int sleeptime;
extern int dpy_mode;
extern int raw;
extern unsigned int raw_w, raw_h, raw_depth, raw_whitepix;
extern char def_tmpdir[];
extern char *tmpdir;
extern int nist_flag;
extern int iafis_flag;
/************************************************************************/
/* dpyimage.c */
extern int dpyimage(char *, register unsigned char *, unsigned int,
unsigned int, unsigned int, unsigned int, int, int *);
extern int ImageBit8ToBit24Unit32(char **, char *, int, int);
extern void XMGetSubImageDataDepth24(char *, int, int, int, int,
char *, int, int);
extern int event_handler(register XImage *, register unsigned char *, int *);
extern void refresh_window(register XImage *);
extern int drag_image(register XImage *, register unsigned char *, int, int);
extern int move_image(register XImage *, register unsigned char *, int, int);
extern int button_release(XEvent *, register XImage *,
register unsigned char *);
extern void button_press(XEvent *);
/* dpyio.c */
extern int readfile(char *, unsigned char **, int *, unsigned int *,
unsigned int *, unsigned int *, unsigned int *, int *);
extern int createfile(char *);
extern void unlinkfile(char *);
extern void buildheader(struct header_t *, char *, unsigned int, unsigned int,
unsigned int, unsigned int, int);
extern int writeheader(FILE *, struct header_t *);
extern int readheader(FILE *, struct header_t *);
extern int writedata(FILE *, unsigned char *, int);
extern int readdata(FILE *, unsigned char *, int);
extern int fdclose(int, char *);
/* dpynorm.c */
extern int dpynorm(int, char **);
/* dpypipe.c */
extern int pipecomm(int, char **);
extern int pipe_parent(register FILE *);
extern int pipe_child(int, char **, register FILE *);
/* dpytmp.c */
extern int tmpcomm(int, char **);
extern int tmp_parent(pid_t);
extern int tmp_child(int, char **, pid_t);
/* tally.c */
extern int bitcount(register unsigned int);
extern void bytecount(register unsigned char *, register unsigned int,
register unsigned int *);
extern void pixelcount(register unsigned char *, register unsigned int,
register unsigned int *, register unsigned int *);
#endif
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/ssteqr.c
|
<filename>library/src/main/cpp/nbis/commonnbis/src/lib/clapck/ssteqr.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int ssteqr_(char *compz, int *n, real *d, real *e, real *
z, int *ldz, real *work, int *info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SSTEQR computes all eigenvalues and, optionally, eigenvectors of a
symmetric tridiagonal matrix using the implicit QL or QR method.
The eigenvectors of a full or band symmetric matrix can also be found
if SSYTRD or SSPTRD or SSBTRD has been used to reduce this matrix to
tridiagonal form.
Arguments
=========
COMPZ (input) CHARACTER*1
= 'N': Compute eigenvalues only.
= 'V': Compute eigenvalues and eigenvectors of the original
symmetric matrix. On entry, Z must contain the
orthogonal matrix used to reduce the original matrix
to tridiagonal form.
= 'I': Compute eigenvalues and eigenvectors of the
tridiagonal matrix. Z is initialized to the identity
matrix.
N (input) INTEGER
The order of the matrix. N >= 0.
D (input/output) REAL array, dimension (N)
On entry, the diagonal elements of the tridiagonal matrix.
On exit, if INFO = 0, the eigenvalues in ascending order.
E (input/output) REAL array, dimension (N-1)
On entry, the (n-1) subdiagonal elements of the tridiagonal
matrix.
On exit, E has been destroyed.
Z (input/output) REAL array, dimension (LDZ, N)
On entry, if COMPZ = 'V', then Z contains the orthogonal
matrix used in the reduction to tridiagonal form.
On exit, if INFO = 0, then if COMPZ = 'V', Z contains the
orthonormal eigenvectors of the original symmetric matrix,
and if COMPZ = 'I', Z contains the orthonormal eigenvectors
of the symmetric tridiagonal matrix.
If COMPZ = 'N', then Z is not referenced.
LDZ (input) INTEGER
The leading dimension of the array Z. LDZ >= 1, and if
eigenvectors are desired, then LDZ >= max(1,N).
WORK (workspace) REAL array, dimension (max(1,2*N-2))
If COMPZ = 'N', then WORK is not referenced.
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
> 0: the algorithm has failed to find all the eigenvalues in
a total of 30*N iterations; if INFO = i, then i
elements of E have not converged to zero; on exit, D
and E contain the elements of a symmetric tridiagonal
matrix which is orthogonally similar to the original
matrix.
=====================================================================
Test the input parameters.
Parameter adjustments
Function Body */
/* Table of constant values */
static real c_b9 = 0.f;
static real c_b10 = 1.f;
static int c__0 = 0;
static int c__1 = 1;
static int c__2 = 2;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int z_dim1, z_offset;
*/
int i__1, i__2;
real r__1, r__2;
/* Builtin functions */
double sqrt(doublereal), r_sign(real *, real *);
/* Local variables */
static int lend, jtot;
extern /* Subroutine */ int slae2_(real *, real *, real *, real *, real *)
;
static real b, c, f, g;
static int i, j, k, l, m;
static real p, r, s;
extern logical lsame_(char *, char *);
static real anorm;
extern /* Subroutine */ int slasr_(char *, char *, char *, int *,
int *, real *, real *, real *, int *);
static int l1;
extern /* Subroutine */ int sswap_(int *, real *, int *, real *,
int *);
static int lendm1, lendp1;
extern /* Subroutine */ int slaev2_(real *, real *, real *, real *, real *
, real *, real *);
extern doublereal slapy2_(real *, real *);
static int ii, mm, iscale;
extern doublereal slamch_(char *);
static real safmin;
extern /* Subroutine */ int xerbla_(char *, int *);
static real safmax;
extern /* Subroutine */ int slascl_(char *, int *, int *, real *,
real *, int *, int *, real *, int *, int *);
static int lendsv;
extern /* Subroutine */ int slartg_(real *, real *, real *, real *, real *
), slaset_(char *, int *, int *, real *, real *, real *,
int *);
static real ssfmin;
static int nmaxit, icompz;
static real ssfmax;
extern doublereal slanst_(char *, int *, real *, real *);
extern /* Subroutine */ int slasrt_(char *, int *, real *, int *);
static int lm1, mm1, nm1;
static real rt1, rt2, eps;
static int lsv;
static real tst, eps2;
#define D(I) d[(I)-1]
#define E(I) e[(I)-1]
#define WORK(I) work[(I)-1]
#define Z(I,J) z[(I)-1 + ((J)-1)* ( *ldz)]
*info = 0;
if (lsame_(compz, "N")) {
icompz = 0;
} else if (lsame_(compz, "V")) {
icompz = 1;
} else if (lsame_(compz, "I")) {
icompz = 2;
} else {
icompz = -1;
}
if (icompz < 0) {
*info = -1;
} else if (*n < 0) {
*info = -2;
/*
} else if (*ldz < 1 || icompz > 0 && *ldz < max(1,*n)) {
*/
/* Paretheses added by MDG on 03-09-05 */
} else if ((*ldz < 1 || icompz > 0) && (*ldz < max(1,*n))) {
*info = -6;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SSTEQR", &i__1);
return 0;
}
/* Quick return if possible */
if (*n == 0) {
return 0;
}
if (*n == 1) {
if (icompz == 2) {
Z(1,1) = 1.f;
}
return 0;
}
/* Determine the unit roundoff and over/underflow thresholds. */
eps = slamch_("E");
/* Computing 2nd power */
r__1 = eps;
eps2 = r__1 * r__1;
safmin = slamch_("S");
safmax = 1.f / safmin;
ssfmax = sqrt(safmax) / 3.f;
ssfmin = sqrt(safmin) / eps2;
/* Compute the eigenvalues and eigenvectors of the tridiagonal
matrix. */
if (icompz == 2) {
slaset_("Full", n, n, &c_b9, &c_b10, &Z(1,1), ldz);
}
nmaxit = *n * 30;
jtot = 0;
/* Determine where the matrix splits and choose QL or QR iteration
for each block, according to whether top or bottom diagonal
element is smaller. */
l1 = 1;
nm1 = *n - 1;
L10:
if (l1 > *n) {
goto L160;
}
if (l1 > 1) {
E(l1 - 1) = 0.f;
}
if (l1 <= nm1) {
i__1 = nm1;
for (m = l1; m <= nm1; ++m) {
tst = (r__1 = E(m), dabs(r__1));
if (tst == 0.f) {
goto L30;
}
if (tst <= sqrt((r__1 = D(m), dabs(r__1))) * sqrt((r__2 = D(m + 1)
, dabs(r__2))) * eps) {
E(m) = 0.f;
goto L30;
}
/* L20: */
}
}
m = *n;
L30:
l = l1;
lsv = l;
lend = m;
lendsv = lend;
l1 = m + 1;
if (lend == l) {
goto L10;
}
/* Scale submatrix in rows and columns L to LEND */
i__1 = lend - l + 1;
anorm = slanst_("I", &i__1, &D(l), &E(l));
iscale = 0;
if (anorm == 0.f) {
goto L10;
}
if (anorm > ssfmax) {
iscale = 1;
i__1 = lend - l + 1;
slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &D(l), n,
info);
i__1 = lend - l;
slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &E(l), n,
info);
} else if (anorm < ssfmin) {
iscale = 2;
i__1 = lend - l + 1;
slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &D(l), n,
info);
i__1 = lend - l;
slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &E(l), n,
info);
}
/* Choose between QL and QR iteration */
if ((r__1 = D(lend), dabs(r__1)) < (r__2 = D(l), dabs(r__2))) {
lend = lsv;
l = lendsv;
}
if (lend > l) {
/* QL Iteration
Look for small subdiagonal element. */
L40:
if (l != lend) {
lendm1 = lend - 1;
i__1 = lendm1;
for (m = l; m <= lendm1; ++m) {
/* Computing 2nd power */
r__2 = (r__1 = E(m), dabs(r__1));
tst = r__2 * r__2;
if (tst <= eps2 * (r__1 = D(m), dabs(r__1)) * (r__2 = D(m + 1)
, dabs(r__2)) + safmin) {
goto L60;
}
/* L50: */
}
}
m = lend;
L60:
if (m < lend) {
E(m) = 0.f;
}
p = D(l);
if (m == l) {
goto L80;
}
/* If remaining matrix is 2-by-2, use SLAE2 or SLAEV2
to compute its eigensystem. */
if (m == l + 1) {
if (icompz > 0) {
slaev2_(&D(l), &E(l), &D(l + 1), &rt1, &rt2, &c, &s);
WORK(l) = c;
WORK(*n - 1 + l) = s;
slasr_("R", "V", "B", n, &c__2, &WORK(l), &WORK(*n - 1 + l), &
Z(1,l), ldz);
} else {
slae2_(&D(l), &E(l), &D(l + 1), &rt1, &rt2);
}
D(l) = rt1;
D(l + 1) = rt2;
E(l) = 0.f;
l += 2;
if (l <= lend) {
goto L40;
}
goto L140;
}
if (jtot == nmaxit) {
goto L140;
}
++jtot;
/* Form shift. */
g = (D(l + 1) - p) / (E(l) * 2.f);
r = slapy2_(&g, &c_b10);
g = D(m) - p + E(l) / (g + r_sign(&r, &g));
s = 1.f;
c = 1.f;
p = 0.f;
/* Inner loop */
mm1 = m - 1;
i__1 = l;
for (i = mm1; i >= l; --i) {
f = s * E(i);
b = c * E(i);
slartg_(&g, &f, &c, &s, &r);
if (i != m - 1) {
E(i + 1) = r;
}
g = D(i + 1) - p;
r = (D(i) - g) * s + c * 2.f * b;
p = s * r;
D(i + 1) = g + p;
g = c * r - b;
/* If eigenvectors are desired, then save rotations. */
if (icompz > 0) {
WORK(i) = c;
WORK(*n - 1 + i) = -(doublereal)s;
}
/* L70: */
}
/* If eigenvectors are desired, then apply saved rotations. */
if (icompz > 0) {
mm = m - l + 1;
slasr_("R", "V", "B", n, &mm, &WORK(l), &WORK(*n - 1 + l), &Z(1,l), ldz);
}
D(l) -= p;
E(l) = g;
goto L40;
/* Eigenvalue found. */
L80:
D(l) = p;
++l;
if (l <= lend) {
goto L40;
}
goto L140;
} else {
/* QR Iteration
Look for small superdiagonal element. */
L90:
if (l != lend) {
lendp1 = lend + 1;
i__1 = lendp1;
for (m = l; m >= lendp1; --m) {
/* Computing 2nd power */
r__2 = (r__1 = E(m - 1), dabs(r__1));
tst = r__2 * r__2;
if (tst <= eps2 * (r__1 = D(m), dabs(r__1)) * (r__2 = D(m - 1)
, dabs(r__2)) + safmin) {
goto L110;
}
/* L100: */
}
}
m = lend;
L110:
if (m > lend) {
E(m - 1) = 0.f;
}
p = D(l);
if (m == l) {
goto L130;
}
/* If remaining matrix is 2-by-2, use SLAE2 or SLAEV2
to compute its eigensystem. */
if (m == l - 1) {
if (icompz > 0) {
slaev2_(&D(l - 1), &E(l - 1), &D(l), &rt1, &rt2, &c, &s);
WORK(m) = c;
WORK(*n - 1 + m) = s;
slasr_("R", "V", "F", n, &c__2, &WORK(m), &WORK(*n - 1 + m), &
Z(1,l-1), ldz);
} else {
slae2_(&D(l - 1), &E(l - 1), &D(l), &rt1, &rt2);
}
D(l - 1) = rt1;
D(l) = rt2;
E(l - 1) = 0.f;
l += -2;
if (l >= lend) {
goto L90;
}
goto L140;
}
if (jtot == nmaxit) {
goto L140;
}
++jtot;
/* Form shift. */
g = (D(l - 1) - p) / (E(l - 1) * 2.f);
r = slapy2_(&g, &c_b10);
g = D(m) - p + E(l - 1) / (g + r_sign(&r, &g));
s = 1.f;
c = 1.f;
p = 0.f;
/* Inner loop */
lm1 = l - 1;
i__1 = lm1;
for (i = m; i <= lm1; ++i) {
f = s * E(i);
b = c * E(i);
slartg_(&g, &f, &c, &s, &r);
if (i != m) {
E(i - 1) = r;
}
g = D(i) - p;
r = (D(i + 1) - g) * s + c * 2.f * b;
p = s * r;
D(i) = g + p;
g = c * r - b;
/* If eigenvectors are desired, then save rotations. */
if (icompz > 0) {
WORK(i) = c;
WORK(*n - 1 + i) = s;
}
/* L120: */
}
/* If eigenvectors are desired, then apply saved rotations. */
if (icompz > 0) {
mm = l - m + 1;
slasr_("R", "V", "F", n, &mm, &WORK(m), &WORK(*n - 1 + m), &Z(1,m), ldz);
}
D(l) -= p;
E(lm1) = g;
goto L90;
/* Eigenvalue found. */
L130:
D(l) = p;
--l;
if (l >= lend) {
goto L90;
}
goto L140;
}
/* Undo scaling if necessary */
L140:
if (iscale == 1) {
i__1 = lendsv - lsv + 1;
slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &D(lsv), n,
info);
i__1 = lendsv - lsv;
slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &E(lsv), n,
info);
} else if (iscale == 2) {
i__1 = lendsv - lsv + 1;
slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &D(lsv), n,
info);
i__1 = lendsv - lsv;
slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &E(lsv), n,
info);
}
/* Check for no convergence to an eigenvalue after a total
of N*MAXIT iterations. */
if (jtot < nmaxit) {
goto L10;
}
i__1 = *n - 1;
for (i = 1; i <= *n-1; ++i) {
if (E(i) != 0.f) {
++(*info);
}
/* L150: */
}
goto L190;
/* Order eigenvalues and eigenvectors. */
L160:
if (icompz == 0) {
/* Use Quick Sort */
slasrt_("I", n, &D(1), info);
} else {
/* Use Selection Sort to minimize swaps of eigenvectors */
i__1 = *n;
for (ii = 2; ii <= *n; ++ii) {
i = ii - 1;
k = i;
p = D(i);
i__2 = *n;
for (j = ii; j <= *n; ++j) {
if (D(j) < p) {
k = j;
p = D(j);
}
/* L170: */
}
if (k != i) {
D(k) = D(i);
D(i) = p;
sswap_(n, &Z(1,i), &c__1, &Z(1,k), &
c__1);
}
/* L180: */
}
}
L190:
return 0;
/* End of SSTEQR */
} /* ssteqr_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/wsq/decoder.c
|
<reponame>ThalesGroup/WSQForAndroid<filename>library/src/main/cpp/nbis/imgtools/src/lib/wsq/decoder.c<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: WSQ - Grayscale Image Compression
FILE: DECODER.C
AUTHORS: <NAME>
<NAME>
DATE: 12/02/1999
UPDATED: 02/24/2005 by MDG
Contains routines responsible for decoding a WSQ compressed
datastream.
ROUTINES:
#cat: wsq_decode_mem - Decodes a datastream of WSQ compressed bytes
#cat: from a memory buffer, returning a lossy
#cat: reconstructed pixmap.
#cat: wsq_decode_file - Decodes a datastream of WSQ compressed bytes
#cat: from an open file, returning a lossy
#cat: reconstructed pixmap.
#cat: huffman_decode_data_mem - Decodes a block of huffman encoded
#cat: data from a memory buffer.
#cat: huffman_decode_data_file - Decodes a block of huffman encoded
#cat: data from an open file.
#cat: decode_data_mem - Decodes huffman encoded data from a memory buffer.
#cat:
#cat: decode_data_file - Decodes huffman encoded data from an open file.
#cat:
#cat: nextbits_wsq - Gets next sequence of bits for data decoding from
#cat: an open file.
#cat: getc_nextbits_wsq - Gets next sequence of bits for data decoding
#cat: from a memory buffer.
***********************************************************************/
#include <stdio.h>
#include <wsq.h>
#include <dataio.h>
#include <android/log.h>
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "decoder.c",__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "decoder.c",__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO , "decoder.c",__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN , "decoder.c",__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , "decoder.c",__VA_ARGS__)
/************************************************************************/
/* This is an implementation based on the Crinimal */
/* Justice Information Services (CJIS) document */
/* "WSQ Gray-scale Fingerprint Compression */
/* Specification", Dec. 1997. */
/***************************************************************************/
/* WSQ Decoder routine. Takes an WSQ compressed memory buffer and decodes */
/* it, returning the reconstructed pixmap. */
/***************************************************************************/
int wsq_decode_mem(unsigned char **odata, int *ow, int *oh, int *od, int *oppi,
int *lossyflag, unsigned char *idata, const int ilen)
{
int ret, i;
unsigned short marker; /* WSQ marker */
int num_pix; /* image size and counter */
int width, height, ppi; /* image parameters */
unsigned char *cdata; /* image pointer */
float *fdata; /* image pointers */
short *qdata; /* image pointers */
unsigned char *cbufptr; /* points to current byte in buffer */
unsigned char *ebufptr; /* points to end of buffer */
/* Added by MDG on 02-24-05 */
init_wsq_decoder_resources();
/* Set memory buffer pointers. */
cbufptr = idata;
ebufptr = idata + ilen;
/* Init DHT Tables to 0. */
for(i = 0; i < MAX_DHT_TABLES; i++)
(dht_table + i)->tabdef = 0;
/* Read the SOI marker. */
if((ret = getc_marker_wsq(&marker, SOI_WSQ, &cbufptr, ebufptr))){
free_wsq_decoder_resources();
LOGE("error reading SOI marker (%d)", ret);
return(ret);
}
/* Read in supporting tables up to the SOF marker. */
if((ret = getc_marker_wsq(&marker, TBLS_N_SOF, &cbufptr, ebufptr))){
free_wsq_decoder_resources();
LOGE("error reading supporting tables (%d)", ret);
return(ret);
}
while(marker != SOF_WSQ) {
if((ret = getc_table_wsq(marker, &dtt_table, &dqt_table, dht_table,
&cbufptr, ebufptr))){
free_wsq_decoder_resources();
LOGE("error in getc_table_wsq (%d)", ret);
return(ret);
}
if((ret = getc_marker_wsq(&marker, TBLS_N_SOF, &cbufptr, ebufptr))){
free_wsq_decoder_resources();
LOGE("error in getc_marker_wsq (%d)", ret);
return(ret);
}
}
/* Read in the Frame Header. */
if((ret = getc_frame_header_wsq(&frm_header_wsq, &cbufptr, ebufptr))){
free_wsq_decoder_resources();
LOGE("error reading frame header (%d)", ret);
return(ret);
}
width = frm_header_wsq.width;
height = frm_header_wsq.height;
num_pix = width * height;
if((ret = getc_ppi_wsq(&ppi, idata, ilen))){
free_wsq_decoder_resources();
LOGE("error in getc_ppi_wsq (%d)", ret);
return(ret);
}
if(debug > 0)
fprintf(stderr, "SOI, tables, and frame header read\n\n");
/* Build WSQ decomposition trees. */
build_wsq_trees(w_tree, W_TREELEN, q_tree, Q_TREELEN, width, height);
if(debug > 0)
fprintf(stderr, "Tables for wavelet decomposition finished\n\n");
/* Allocate working memory. */
qdata = (short *) malloc(num_pix * sizeof(short));
if(qdata == (short *)NULL) {
fprintf(stderr,"ERROR: wsq_decode_mem : malloc : qdata1\n");
free_wsq_decoder_resources();
LOGE("error allocating memory for qdata (%d bytes)", num_pix * sizeof(short));
return(-20);
}
/* Decode the Huffman encoded data blocks. */
if((ret = huffman_decode_data_mem(qdata, &dtt_table, &dqt_table, dht_table,
&cbufptr, ebufptr))){
free(qdata);
free_wsq_decoder_resources();
LOGE("error in huffman_decode_data_mem (%d)", ret);
return(ret);
}
if(debug > 0)
fprintf(stderr,
"Quantized WSQ subband data blocks read and Huffman decoded\n\n");
/* Decode the quantize wavelet subband data. */
if((ret = unquantize(&fdata, &dqt_table, q_tree, Q_TREELEN,
qdata, width, height))){
free(qdata);
free_wsq_decoder_resources();
LOGE("error in unquantize (%d)", ret);
return(ret);
}
if(debug > 0)
fprintf(stderr, "WSQ subband data blocks unquantized\n\n");
/* Done with quantized wavelet subband data. */
free(qdata);
if((ret = wsq_reconstruct(fdata, width, height, w_tree, W_TREELEN,
&dtt_table))){
free(fdata);
free_wsq_decoder_resources();
LOGE("error in wsq_reconstruct (%d)", ret);
return(ret);
}
if(debug > 0)
fprintf(stderr, "WSQ reconstruction of image finished\n\n");
cdata = (unsigned char *)malloc(num_pix * sizeof(unsigned char));
if(cdata == (unsigned char *)NULL) {
free(fdata);
free_wsq_decoder_resources();
LOGE("error allocating memory for cdata (%d bytes)", num_pix * sizeof(unsigned char));
return(-21);
}
/* Convert floating point pixels to unsigned char pixels. */
conv_img_2_uchar(cdata, fdata, width, height,
frm_header_wsq.m_shift, frm_header_wsq.r_scale);
/* Done with floating point pixels. */
free(fdata);
/* Added by MDG on 02-24-05 */
free_wsq_decoder_resources();
if(debug > 0)
fprintf(stderr, "Doubleing point pixels converted to unsigned char\n\n");
/* Assign reconstructed pixmap and attributes to output pointers. */
*odata = cdata;
*ow = width;
*oh = height;
*od = 8;
*oppi = ppi;
*lossyflag = 1;
/* Return normally. */
return(0);
}
/**************************************************************************/
/* WSQ File Decoder routine. Takes an open WSQ compressed file and reads */
/* in the WSQ encoded data, returning a decoded reconstructed pixmap. */
/**************************************************************************/
int wsq_decode_file(unsigned char **odata, int *ow, int *oh, int *od, int *oppi,
int *lossyflag, FILE *infp)
{
int ret;
unsigned short marker; /* WSQ marker */
int num_pix; /* image size and counter */
int width, height, ppi; /* image parameters */
unsigned char *cdata; /* image pointer */
float *fdata; /* image pointers */
short *qdata; /* image pointers */
/* Added by MDG on 02-24-05 */
init_wsq_decoder_resources();
/* Read the SOI marker. */
if((ret = read_marker_wsq(&marker, SOI_WSQ, infp))){
free_wsq_decoder_resources();
return(ret);
}
/* Read in supporting tables up to the SOF marker. */
if((ret = read_marker_wsq(&marker, TBLS_N_SOF, infp))){
free_wsq_decoder_resources();
return(ret);
}
while(marker != SOF_WSQ) {
if((ret = read_table_wsq(marker, &dtt_table, &dqt_table, dht_table, infp))){
free_wsq_decoder_resources();
return(ret);
}
if((ret = read_marker_wsq(&marker, TBLS_N_SOF, infp))){
free_wsq_decoder_resources();
return(ret);
}
}
/* Read in the Frame Header. */
if((ret = read_frame_header_wsq(&frm_header_wsq, infp))){
free_wsq_decoder_resources();
return(ret);
}
width = frm_header_wsq.width;
height = frm_header_wsq.height;
num_pix = width * height;
if((ret = read_ppi_wsq(&ppi, infp))){
free_wsq_decoder_resources();
return(ret);
}
if(debug > 0)
fprintf(stderr, "SOI, tables, and frame header read\n\n");
/* Build WSQ decomposition trees. */
build_wsq_trees(w_tree, W_TREELEN, q_tree, Q_TREELEN, width, height);
if(debug > 0)
fprintf(stderr, "Tables for wavelet decomposition finished\n\n");
/* Allocate working memory. */
qdata = (short *) malloc(num_pix * sizeof(short));
if(qdata == (short *)NULL) {
free_wsq_decoder_resources();
fprintf(stderr,"ERROR: wsq_decode_file : malloc : qdata1\n");
return(-20);
}
/* Decode the Huffman encoded data blocks. */
if((ret = huffman_decode_data_file(qdata, &dtt_table, &dqt_table, dht_table,
infp))){
free(qdata);
free_wsq_decoder_resources();
return(ret);
}
if(debug > 0)
fprintf(stderr,
"Quantized WSQ subband data blocks read and Huffman decoded\n\n");
/* Decode the quantize wavelet subband data. */
if((ret = unquantize(&fdata, &dqt_table, q_tree, Q_TREELEN,
qdata, width, height))){
free(qdata);
free_wsq_decoder_resources();
return(ret);
}
if(debug > 0)
fprintf(stderr, "WSQ subband data blocks unquantized\n\n");
/* Done with quantized wavelet subband data. */
free(qdata);
if((ret = wsq_reconstruct(fdata, width, height, w_tree, W_TREELEN,
&dtt_table))){
free(fdata);
free_wsq_decoder_resources();
return(ret);
}
if(debug > 0)
fprintf(stderr, "WSQ reconstruction of image finished\n\n");
cdata = (unsigned char *)malloc(num_pix * sizeof(unsigned char));
if(cdata == (unsigned char *)NULL) {
free(fdata);
free_wsq_decoder_resources();
fprintf(stderr,"ERROR: wsq_decode_file : malloc : cdata\n");
return(-21);
}
/* Convert floating point pixels to unsigned char pixels. */
conv_img_2_uchar(cdata, fdata, width, height,
frm_header_wsq.m_shift, frm_header_wsq.r_scale);
/* Done with floating point pixels. */
free(fdata);
/* Added by MDG on 02-24-05 */
free_wsq_decoder_resources();
if(debug > 0)
fprintf(stderr, "Doubleing point pixels converted to unsigned char\n\n");
/* Assign reconstructed pixmap and attributes to output pointers. */
*odata = cdata;
*ow = width;
*oh = height;
*od = 8;
*oppi = ppi;
*lossyflag = 1;
/* Return normally. */
return(0);
}
/***************************************************************************/
/* Routine to decode an entire "block" of encoded data from memory buffer. */
/***************************************************************************/
int huffman_decode_data_mem(
short *ip, /* image pointer */
DTT_TABLE *dtt_table, /*transform table pointer */
DQT_TABLE *dqt_table, /* quantization table */
DHT_TABLE *dht_table, /* huffman table */
unsigned char **cbufptr, /* points to current byte in input buffer */
unsigned char *ebufptr) /* points to end of input buffer */
{
int ret;
int blk = 0; /* block number */
unsigned short marker; /* WSQ markers */
int bit_count; /* bit count for getc_nextbits_wsq routine */
int n; /* zero run count */
int nodeptr; /* pointers for decoding */
int last_size; /* last huffvalue */
unsigned char hufftable_id; /* huffman table number */
HUFFCODE *hufftable; /* huffman code structure */
int maxcode[MAX_HUFFBITS+1]; /* used in decoding data */
int mincode[MAX_HUFFBITS+1]; /* used in decoding data */
int valptr[MAX_HUFFBITS+1]; /* used in decoding data */
unsigned short tbits;
int ipc, ipc_mx, ipc_q; /* image byte count adjustment parameters */
if((ret = getc_marker_wsq(&marker, TBLS_N_SOB, cbufptr, ebufptr)))
return(ret);
bit_count = 0;
ipc = 0;
ipc_q = 0;
ipc_mx = frm_header_wsq.width * frm_header_wsq.height;
while(marker != EOI_WSQ) {
if(marker != 0) {
blk++;
while(marker != SOB_WSQ) {
if((ret = getc_table_wsq(marker, dtt_table, dqt_table,
dht_table, cbufptr, ebufptr)))
return(ret);
if((ret = getc_marker_wsq(&marker, TBLS_N_SOB, cbufptr, ebufptr)))
return(ret);
}
if(dqt_table->dqt_def && !ipc_q) {
for(n = 0; n < 64; n++)
if(dqt_table->q_bin[n] == 0.0)
ipc_mx -= q_tree[n].lenx*q_tree[n].leny;
ipc_q = 1;
}
if((ret = getc_block_header(&hufftable_id, cbufptr, ebufptr)))
return(ret);
if((dht_table+hufftable_id)->tabdef != 1) {
fprintf(stderr, "ERROR : huffman_decode_data_mem : ");
fprintf(stderr, "huffman table {%d} undefined.\n", hufftable_id);
return(-51);
}
/* the next two routines reconstruct the huffman tables */
if((ret = build_huffsizes(&hufftable, &last_size,
(dht_table+hufftable_id)->huffbits,
MAX_HUFFCOUNTS_WSQ)))
return(ret);
build_huffcodes(hufftable);
if((ret = check_huffcodes_wsq(hufftable, last_size)))
fprintf(stderr, " hufftable_id = %d\n", hufftable_id);
/* this routine builds a set of three tables used in decoding */
/* the compressed data*/
gen_decode_table(hufftable, maxcode, mincode, valptr,
(dht_table+hufftable_id)->huffbits);
free(hufftable);
bit_count = 0;
marker = 0;
}
/* get next huffman category code from compressed input data stream */
if((ret = decode_data_mem(&nodeptr, mincode, maxcode, valptr,
(dht_table+hufftable_id)->huffvalues,
cbufptr, ebufptr, &bit_count, &marker)))
return(ret);
if(nodeptr == -1) {
while(marker == COM_WSQ && blk == 3) {
if((ret = getc_table_wsq(marker, dtt_table, dqt_table,
dht_table, cbufptr, ebufptr)))
return(ret);
if((ret = getc_marker_wsq(&marker, ANY_WSQ, cbufptr, ebufptr)))
return(ret);
}
continue;
}
if(ipc > ipc_mx) {
fprintf(stderr, "ERROR : huffman_decode_data_mem [1]: ");
fprintf(stderr, "Decoded data extends past image buffer. ");
fprintf(stderr, "Encoded data appears corrupt or non-standard.\n");
fflush(stderr);
return(-51);
}
if(nodeptr > 0 && nodeptr <= 100) {
ipc += nodeptr;
if(ipc > ipc_mx) {
fprintf(stderr, "ERROR : huffman_decode_data_mem [2]: ");
fprintf(stderr, "Decoded data extends past image buffer. ");
fprintf(stderr, "Encoded data appears corrupt or non-standard.\n");
fflush(stderr);
return(-51);
}
for(n = 0; n < nodeptr; n++)
*ip++ = 0; /* z run */
}
else if(nodeptr > 106 && nodeptr < 0xff) {
*ip++ = nodeptr - 180;
ipc++;
}
else if(nodeptr == 101){
if((ret = getc_nextbits_wsq(&tbits, &marker, cbufptr, ebufptr,
&bit_count, 8)))
return(ret);
*ip++ = tbits;
ipc++;
}
else if(nodeptr == 102){
if((ret = getc_nextbits_wsq(&tbits, &marker, cbufptr, ebufptr,
&bit_count, 8)))
return(ret);
*ip++ = -tbits;
ipc++;
}
else if(nodeptr == 103){
if((ret = getc_nextbits_wsq(&tbits, &marker, cbufptr, ebufptr,
&bit_count, 16)))
return(ret);
*ip++ = tbits;
ipc++;
}
else if(nodeptr == 104){
if((ret = getc_nextbits_wsq(&tbits, &marker, cbufptr, ebufptr,
&bit_count, 16)))
return(ret);
*ip++ = -tbits;
ipc++;
}
else if(nodeptr == 105) {
if((ret = getc_nextbits_wsq(&tbits, &marker, cbufptr, ebufptr,
&bit_count, 8)))
return(ret);
ipc += tbits;
if(ipc > ipc_mx) {
fprintf(stderr, "ERROR : huffman_decode_data_mem [3]: ");
fprintf(stderr, "Decoded data extends past image buffer. ");
fprintf(stderr, "Encoded data appears corrupt or non-standard.\n");
fflush(stderr);
return(-51);
}
n = tbits;
while(n--)
*ip++ = 0;
}
else if(nodeptr == 106) {
if((ret = getc_nextbits_wsq(&tbits, &marker, cbufptr, ebufptr,
&bit_count, 16)))
return(ret);
ipc += tbits;
if(ipc > ipc_mx) {
fprintf(stderr, "ERROR : huffman_decode_data_mem [4]: ");
fprintf(stderr, "Decoded data extends past image buffer. ");
fprintf(stderr, "Encoded data appears corrupt or non-standard.\n");
fflush(stderr);
return(-51);
}
n = tbits;
while(n--)
*ip++ = 0;
}
else {
fprintf(stderr,
"ERROR: huffman_decode_data_mem : Invalid code %d (%x).\n",
nodeptr, nodeptr);
return(-52);
}
}
return(0);
}
/********************************************************************/
/* Routine to decode an entire "block" of encoded data from a file. */
/********************************************************************/
int huffman_decode_data_file(
short *ip, /* image pointer */
DTT_TABLE *dtt_table, /*transform table pointer */
DQT_TABLE *dqt_table, /* quantization table */
DHT_TABLE *dht_table, /* huffman table */
FILE *infp) /* input file */
{
int ret;
int blk = 0; /* block number */
unsigned short marker; /* WSQ markers */
int bit_count; /* bit count for nextbits_wsq routine */
int n; /* zero run count */
int nodeptr; /* pointers for decoding */
int last_size; /* last huffvalue */
unsigned char hufftable_id; /* huffman table number */
HUFFCODE *hufftable; /* huffman code structure */
int maxcode[MAX_HUFFBITS+1]; /* used in decoding data */
int mincode[MAX_HUFFBITS+1]; /* used in decoding data */
int valptr[MAX_HUFFBITS+1]; /* used in decoding data */
unsigned short tbits;
if((ret = read_marker_wsq(&marker, TBLS_N_SOB, infp)))
return(ret);
bit_count = 0;
while(marker != EOI_WSQ) {
if(marker != 0) {
blk++;
while(marker != SOB_WSQ) {
if((ret = read_table_wsq(marker, dtt_table, dqt_table,
dht_table, infp)))
return(ret);
if((ret = read_marker_wsq(&marker, TBLS_N_SOB, infp)))
return(ret);
}
if((ret = read_block_header(&hufftable_id, infp)))
return(ret);
if((dht_table+hufftable_id)->tabdef != 1) {
fprintf(stderr, "ERROR : huffman_decode_data_file : ");
fprintf(stderr, "huffman table {%d} undefined.\n", hufftable_id);
return(-53);
}
/* the next two routines reconstruct the huffman tables */
if((ret = build_huffsizes(&hufftable, &last_size,
(dht_table+hufftable_id)->huffbits, MAX_HUFFCOUNTS_WSQ)))
return(ret);
build_huffcodes(hufftable);
if((ret = check_huffcodes_wsq(hufftable, last_size)))
fprintf(stderr, " hufftable_id = %d\n", hufftable_id);
/* this routine builds a set of three tables used in decoding */
/* the compressed data*/
gen_decode_table(hufftable, maxcode, mincode, valptr,
(dht_table+hufftable_id)->huffbits);
free(hufftable);
bit_count = 0;
marker = 0;
}
/* get next huffman category code from compressed input data stream */
if((ret = decode_data_file(&nodeptr, mincode, maxcode, valptr,
(dht_table+hufftable_id)->huffvalues,
infp, &bit_count, &marker)))
return(ret);
if(nodeptr == -1) {
while(marker == COM_WSQ && blk == 3) {
if((ret = read_table_wsq(marker, dtt_table, dqt_table,
dht_table, infp)))
return(ret);
if((ret = read_marker_wsq(&marker, ANY_WSQ, infp)))
return(ret);
}
continue;
}
if(nodeptr > 0 && nodeptr <= 100)
for(n = 0; n < nodeptr; n++) {
*ip++ = 0; /* z run */
}
else if(nodeptr == 101){
if((ret = nextbits_wsq(&tbits, &marker, infp, &bit_count, 8)))
return(ret);
*ip++ = tbits;
}
else if(nodeptr == 102){
if((ret = nextbits_wsq(&tbits, &marker, infp, &bit_count, 8)))
return(ret);
*ip++ = -tbits;
}
else if(nodeptr == 103){
if((ret = nextbits_wsq(&tbits, &marker, infp, &bit_count, 16)))
return(ret);
*ip++ = tbits;
}
else if(nodeptr == 104){
if((ret = nextbits_wsq(&tbits, &marker, infp, &bit_count, 16)))
return(ret);
*ip++ = -tbits;
}
else if(nodeptr == 105) {
if((ret = nextbits_wsq(&tbits, &marker, infp, &bit_count, 8)))
return(ret);
n = tbits;
while(n--)
*ip++ = 0;
}
else if(nodeptr == 106) {
if((ret = nextbits_wsq(&tbits, &marker, infp, &bit_count, 16)))
return(ret);
n = tbits;
while(n--)
*ip++ = 0;
}
else if(nodeptr < 0xff)
*ip++ = nodeptr - 180;
else {
fprintf(stderr,
"ERROR: huffman_decode_data_file : Invalid code %d (%x).\n",
nodeptr, nodeptr);
return(-54);
}
}
return(0);
}
/**********************************************************/
/* Routine to decode the encoded data from memory buffer. */
/**********************************************************/
int decode_data_mem(
int *onodeptr, /* returned huffman code category */
int *mincode, /* points to minimum code value for */
/* a given code length */
int *maxcode, /* points to maximum code value for */
/* a given code length */
int *valptr, /* points to first code in the huffman */
/* code table for a given code length */
unsigned char *huffvalues, /* defines order of huffman code */
/* lengths in relation to code sizes */
unsigned char **cbufptr, /* points to current byte in input buffer */
unsigned char *ebufptr, /* points to end of input buffer */
int *bit_count, /* marks the bit to receive from the input byte */
unsigned short *marker)
{
int ret;
int inx, inx2; /*increment variables*/
unsigned short code, tbits; /* becomes a huffman code word
(one bit at a time)*/
if((ret = getc_nextbits_wsq(&code, marker, cbufptr, ebufptr, bit_count, 1)))
return(ret);
if(*marker != 0){
*onodeptr = -1;
return(0);
}
for(inx = 1; (int)code > maxcode[inx]; inx++) {
if((ret = getc_nextbits_wsq(&tbits, marker, cbufptr, ebufptr, bit_count, 1)))
return(ret);
code = (code << 1) + tbits;
if(*marker != 0){
*onodeptr = -1;
return(0);
}
}
inx2 = valptr[inx];
inx2 = inx2 + code - mincode[inx];
*onodeptr = huffvalues[inx2];
return(0);
}
/*************************************************/
/* Routine to decode the encoded data from file. */
/*************************************************/
int decode_data_file(
int *onodeptr, /* returned huffman code category */
int *mincode, /* points to minimum code value for */
/* a given code length */
int *maxcode, /* points to maximum code value for */
/* a given code length */
int *valptr, /* points to first code in the huffman */
/* code table for a given code length */
unsigned char *huffvalues, /* defines order of huffman code */
/* lengths in relation to code sizes */
FILE *infp, /* compressed input data file */
int *bit_count, /* marks the bit to receive from the input byte */
unsigned short *marker)
{
int ret;
int inx, inx2; /*increment variables*/
unsigned short code, tbits; /*becomes a huffman code word
(one bit at a time)*/
if((ret = nextbits_wsq(&code, marker, infp, bit_count, 1)))
return(ret);
if(*marker != 0){
*onodeptr = -1;
return(0);
}
for(inx = 1; (int)code > maxcode[inx]; inx++) {
if((ret = nextbits_wsq(&tbits, marker, infp, bit_count, 1)))
return(ret);
code = (code << 1) + tbits;
if(*marker != 0){
*onodeptr = -1;
return(0);
}
}
inx2 = valptr[inx];
inx2 = inx2 + code - mincode[inx];
*onodeptr = huffvalues[inx2];
return(0);
}
/*********************************************/
/* Routine to get nextbit(s) of data stream. */
/*********************************************/
int nextbits_wsq(
unsigned short *obits, /* returned bits */
unsigned short *marker, /* returned marker */
FILE *file, /* compressed input data file */
int *bit_count, /* marks the bit to receive from the input byte */
const int bits_req) /* number of bits requested */
{
int ret;
static unsigned char code; /*next byte of data*/
static unsigned char code2; /*stuffed byte of data*/
unsigned short bits, tbits; /*bits of current data byte requested*/
int bits_needed; /*additional bits required to finish request*/
/*used to "mask out" n number of
bits from data stream*/
static unsigned char bit_mask[9] = {0x00,0x01,0x03,0x07,0x0f,
0x1f,0x3f,0x7f,0xff};
if(*bit_count == 0) {
code = (unsigned char)getc(file);
*bit_count = 8;
if(code == 0xFF) {
code2 = (unsigned char)getc(file);
if(code2 != 0x00 && bits_req == 1) {
*marker = (code << 8) | code2;
*obits = 1;
return(0);
}
if(code2 != 0x00) {
fprintf(stderr, "ERROR: nextbits_wsq : No stuffed zeros\n");
return(-38);
}
}
}
if(bits_req <= *bit_count) {
bits = (code >>(*bit_count - bits_req)) & (bit_mask[bits_req]);
*bit_count -= bits_req;
code &= bit_mask[*bit_count];
}
else {
bits_needed = bits_req - *bit_count;
bits = code << bits_needed;
*bit_count = 0;
if((ret = nextbits_wsq(&tbits, (unsigned short *)NULL, file,
bit_count, bits_needed)))
return(ret);
bits |= tbits;
}
*obits = bits;
return(0);
}
/****************************************************************/
/* Routine to get nextbit(s) of data stream from memory buffer. */
/****************************************************************/
int getc_nextbits_wsq(
unsigned short *obits, /* returned bits */
unsigned short *marker, /* returned marker */
unsigned char **cbufptr, /* points to current byte in input buffer */
unsigned char *ebufptr, /* points to end of input buffer */
int *bit_count, /* marks the bit to receive from the input byte */
const int bits_req) /* number of bits requested */
{
int ret;
static unsigned char code; /*next byte of data*/
static unsigned char code2; /*stuffed byte of data*/
unsigned short bits, tbits; /*bits of current data byte requested*/
int bits_needed; /*additional bits required to finish request*/
/*used to "mask out" n number of
bits from data stream*/
static unsigned char bit_mask[9] = {0x00,0x01,0x03,0x07,0x0f,
0x1f,0x3f,0x7f,0xff};
if(*bit_count == 0) {
if((ret = getc_byte(&code, cbufptr, ebufptr))){
return(ret);
}
*bit_count = 8;
if(code == 0xFF) {
if((ret = getc_byte(&code2, cbufptr, ebufptr))){
return(ret);
}
if(code2 != 0x00 && bits_req == 1) {
*marker = (code << 8) | code2;
*obits = 1;
return(0);
}
if(code2 != 0x00) {
fprintf(stderr, "ERROR: getc_nextbits_wsq : No stuffed zeros\n");
return(-41);
}
}
}
if(bits_req <= *bit_count) {
bits = (code >>(*bit_count - bits_req)) & (bit_mask[bits_req]);
*bit_count -= bits_req;
code &= bit_mask[*bit_count];
}
else {
bits_needed = bits_req - *bit_count;
bits = code << bits_needed;
*bit_count = 0;
if((ret = getc_nextbits_wsq(&tbits, (unsigned short *)NULL, cbufptr,
ebufptr, bit_count, bits_needed)))
return(ret);
bits |= tbits;
}
*obits = bits;
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/cwsq/cwsq.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/************************************************************************
PACKAGE: IMAGE ENCODER/DECODER TOOLS
FILE: CWSQ.C
AUTHORS: <NAME>
<EMAIL>
<NAME>
<EMAIL>
DATE: 11/24/1999
UPDATED: 05/09/2005 by MDG
UPDATED: 09/30/2008 by Kenenth Ko - add version option.
#cat: cwsq - Takes an IHead or raw image pixmap and encodes it using WSQ.
#cat: This is an implementation based on the Crinimal Justice
#cat: Information Services (CJIS) document "WSQ Gray-scale
#cat: Fingerprint Compression Specification", Dec. 1997.
*************************************************************************/
/*****************/
/* Include files */
/*****************/
#include <stdio.h>
#include <sys/param.h>
#include <wsq.h>
#include <ihead.h>
#include <img_io.h>
#include <dataio.h>
#include <parsargs.h>
#include <version.h>
void procargs(int, char **, float *, char **, char **, int *,
int *, int *, int *, int *, char **);
void print_usage(char *);
/* Contols globally, the level of debug reporting */
/* in this application. */
int debug = 0;
/******************/
/*Start of Program*/
/******************/
int main(int argc, char *argv[])
{
int ret;
char *outext;
int rawflag; /* input image flag: 0 == Raw, 1 == IHead */
float r_bitrate; /* target bit compression rate */
char *ifile, *cfile, ofile[MAXPATHLEN]; /* Input/Output filenames */
IHEAD *ihead; /* Ihead pointer */
unsigned char *idata; /* Input data */
int width, height; /* image characteristic parameters */
int depth, ppi;
unsigned char *odata; /* Output data */
int olen; /* Number of bytes in output data. */
char *comment_text;
/* Process the command-line argument list. */
procargs(argc, argv, &r_bitrate, &outext, &ifile, &rawflag,
&width, &height, &depth, &ppi, &cfile);
/* Read the image into memory (IHead or raw pixmap). */
if((ret = read_raw_or_ihead_wsq(!rawflag, ifile,
&ihead, &idata, &width, &height, &depth)))
exit(ret);
if(debug > 0)
fprintf(stdout, "File %s read\n", ifile);
/* If IHead image file ... */
if(!rawflag){
/* Get PPI from IHead. */
ppi = get_density(ihead);
free(ihead);
}
if(cfile == (char *)NULL)
comment_text = (char *)NULL;
else{
if((ret = read_ascii_file(cfile, &comment_text))){
free(idata);
exit(ret);
}
}
/* Encode/compress the image pixmap. */
if((ret = wsq_encode_mem(&odata, &olen, r_bitrate,
idata, width, height, depth, ppi, comment_text))){
free(idata);
if(comment_text != (char *)NULL)
free(comment_text);
exit(ret);
}
free(idata);
if(comment_text != (char *)NULL)
free(comment_text);
if(debug > 0)
fprintf(stdout, "Image data encoded, compressed byte length = %d\n",
olen);
/* Generate the output filename. */
fileroot(ifile);
sprintf(ofile, "%s.%s", ifile, outext);
if((ret = write_raw_from_memsize(ofile, odata, olen))){
free(odata);
exit(ret);
}
if(debug > 0)
fprintf(stdout, "Image data written to file %s\n", ofile);
free(odata);
/* Exit normally. */
exit(0);
}
/*****************************************************************/
void procargs(int argc, char **argv, float *r_bitrate,
char **outext, char **ifile, int *rawflag,
int *width, int *height, int *depth, int *ppi, char **cfile)
{
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
if((argc < 4) || (argc > 7)){
print_usage(argv[0]);
exit(-1);
}
sscanf(argv[1], "%f", r_bitrate);
*outext = argv[2];
*ifile = argv[3];
*rawflag = 0;
*width = -1;
*height = -1;
*depth = -1;
*ppi = -1;
*cfile = (char *)NULL;
/* If argc == 4, we are done here. */
/* If IHead image file ... */
if(argc == 5){
*cfile = argv[4];
}
/* Otherwise Raw image file ... */
else if(argc == 6 || argc == 7){
/* If rawflag ... */
if((strncmp(argv[4], "-r", 2) == 0) ||
(strncmp(argv[4], "-raw", 4) == 0) ||
(strncmp(argv[4], "-raw_in", 7) == 0)){
*rawflag = 1;
parse_w_h_d_ppi(argv[5], argv[0], width, height, depth, ppi);
if(*depth != 8){
print_usage(argv[0]);
fprintf(stderr, " image depth = %d not 8\n", *depth);
exit(-1);
}
}
else{
print_usage(argv[0]);
fprintf(stderr,
" invalid arg 4, expected \"-raw_in\" option\n");
exit(-1);
}
/* If Comment file ... */
if(argc == 7){
*cfile = argv[6];
}
}
}
/*****************************************************************/
void print_usage(char *arg0)
{
fprintf(stderr, "Usage: %s ", arg0);
fprintf(stderr, "<r bitrate> <outext> <image file>\n");
fprintf(stderr,
" [-raw_in w,h,d,[ppi]] [comment file]\n\n");
fprintf(stderr,
" r bitrate = compression bit rate (2.25==>5:1, .75==>15:1)\n\n");
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/readihdr.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: READIHDR.C
AUTHOR: <NAME>
DATE: 04/28/1989
UPDATED: 03/15/2005 by MDG
Contains routines responsible for reading/reconstructing the
pixmap contained in an IHead image file into memory.
ROUTINES:
#cat: ReadBinaryRaster - reads the contents of a binary IHead image file
#cat: into an IHead structure and image memory.
#cat: ReadIheadRaster - reads the contents of a multi-level IHead image
#cat: file into an IHead structure and image memory.
***********************************************************************/
#include <img_io.h>
/************************************************************/
/* Routine: ReadBinaryRaster() */
/* Author: <NAME> */
/* Date: 4/28/89 */
/* Modifications: */
/* 8/90 Stan Janet */
/* only malloc 1 buffer if data is not */
/* compressed */
/* free() up temp buffer */
/* 9/20/90 Stan Janet */
/* check return codes */
/* 1/11/91 Stan Janet */
/* put filename in error messages */
/* 11/15/95 <NAME> */
/* use malloc instead of calloc */
/************************************************************/
/************************************************************/
/* ReadBinaryRaster() reads in a "headered" binary raster */
/* file and returns an ihead structure, raster data, and */
/* integer file specs. */
/************************************************************/
void ReadBinaryRaster(file,head,data,bpi,width,height)
char *file;
IHEAD **head;
unsigned char **data;
int *bpi,*width,*height;
{
FILE *fp;
IHEAD *ihead;
int outbytes, depth, comp, filesize, complen, n;
unsigned char *indata, *outdata;
/* open the image file */
fp = fopen(file,"rb");
if (fp == NULL)
syserr("ReadBinaryRaster",file,"fopen");
/* read in the image header */
(*head) = readihdr(fp);
ihead = *head;
depth = get_depth(ihead);
if(depth != 1)
fatalerr("ReadBinaryRaster",file,"not a binary file");
(*width) = get_width(ihead);
(*height) = get_height(ihead);
(*bpi) = get_density(ihead);
comp = get_compression(ihead);
complen = get_complen(ihead);
/* allocate a raster data buffer */
filesize = SizeFromDepth(*width, *height, depth);
malloc_uchar(&outdata, filesize, "ReadIheadRaster : outdata");
/* read in the raster data */
if(comp == UNCOMP) { /* file is uncompressed */
n = fread(outdata,1,filesize,fp);
if (n != filesize) {
(void) fprintf(stderr,
"ReadBinaryRaster: %s: fread returned %d (expected %d)\n",
file,n,filesize);
exit(1);
} /* IF */
} else {
malloc_uchar(&indata, complen, "ReadBinaryRaster : indata");
n = fread(indata,1,complen,fp); /* file compressed */
if (n != complen) {
(void) fprintf(stderr,
"ReadBinaryRaster: %s: fread returned %d (expected %d)\n",
file,n,complen);
} /* IF */
}
switch (comp) {
case RL:
rldecomp(indata,complen,outdata,&outbytes,filesize);
set_compression(ihead, UNCOMP);
set_complen(ihead, 0);
free((char *)indata);
break;
case CCITT_G4:
if((*head)->sigbit == LSBF) {
inv_bytes(indata, complen);
(*head)->sigbit = MSBF;
(*head)->byte_order = HILOW;
}
grp4decomp(indata,complen,*width,*height,outdata,&outbytes);
set_compression(ihead, UNCOMP);
set_complen(ihead, 0);
free((char *)indata);
break;
case UNCOMP:
break;
default:
fatalerr("ReadBinaryRaster",file,"Invalid compression code");
break;
}
*data = outdata;
/* close the image file */
(void) fclose(fp);
}
/************************************************************/
/* Routine: ReadIheadRaster() */
/* Author: <NAME> */
/* Date: 4/28/89 */
/* Modifications: */
/* 8/90 (Stan Janet) see ReadBinaryRaster */
/* 9/20/90 (Stan Janet) " " */
/************************************************************/
/************************************************************/
/* ReadIheadRaster() reads in a "iheadered" raster file and */
/* returns an ihead structure, raster data, and integer file*/
/* specs. */
/************************************************************/
void ReadIheadRaster(file,head,data,width,height,depth)
char *file;
IHEAD **head;
unsigned char **data;
int *width,*height,*depth;
{
FILE *fp;
IHEAD *ihead;
int outbytes, comp, filesize, complen, n;
unsigned char *indata, *outdata;
/* open the image file */
fp = fopen(file,"rb");
if (fp == NULL)
syserr("ReadIheadRaster",file,"fopen failed");
/* read in the image header */
*head = readihdr(fp);
ihead = *head;
n = sscanf((*head)->compress,"%d",&comp);
if (n != 1)
fatalerr("ReadIheadRaster",file,"sscanf failed on compress field");
/* convert string fields to integers */
n = sscanf((*head)->depth,"%d",depth);
if (n != 1)
fatalerr("ReadIheadRaster",file,"sscanf failed on depth field");
n = sscanf((*head)->width,"%d",width);
if (n != 1)
fatalerr("ReadIheadRaster",file,"sscanf failed on width field");
n = sscanf((*head)->height,"%d",height);
if (n != 1)
fatalerr("ReadIheadRaster",file,"sscanf failed on height field");
n = sscanf((*head)->complen,"%d",&complen);
if (n != 1)
fatalerr("ReadIheadRaster",file,"sscanf failed on complen field");
/* allocate a raster data buffer */
filesize = SizeFromDepth(*width,*height,*depth);
malloc_uchar(&outdata, filesize, "ReadIheadRaster : outdata");
/* read in the raster data */
if(comp == UNCOMP) { /* file is uncompressed */
n = fread(outdata,1,filesize,fp);
if (n != filesize) {
(void) fprintf(stderr,
"ReadIheadRaster: %s: fread returned %d (expected %d)\n",
file,n,filesize);
exit(1);
} /* IF */
} else {
malloc_uchar(&indata, complen, "ReadIheadRaster : indata");
n = fread(indata,1,complen,fp); /* file compressed */
if (n != complen) {
/* Typo corrected by MDG on 03-15-05 */
/* arg 'file' added for "%s" */
(void) fprintf(stderr,
"ReadIheadRaster: %s: fread returned %d (expected %d)\n",
file, n,complen);
exit(1);
} /* IF */
}
switch (comp) {
case RL:
rldecomp(indata,complen,outdata,&outbytes,filesize);
memset((*head)->complen,0,SHORT_CHARS);
memset((*head)->compress,0,SHORT_CHARS);
(void) sprintf((*head)->complen,"%d",0);
(void) sprintf((*head)->compress,"%d",UNCOMP);
*data = outdata;
free((char *)indata);
break;
case CCITT_G4:
if((*head)->sigbit == LSBF) {
inv_bytes(indata, complen);
(*head)->sigbit = MSBF;
(*head)->byte_order = HILOW;
}
grp4decomp(indata,complen,*width,*height,outdata,&outbytes);
memset((*head)->complen,0,SHORT_CHARS);
memset((*head)->compress,0,SHORT_CHARS);
(void) sprintf((*head)->complen,"%d",0);
(void) sprintf((*head)->compress,"%d",UNCOMP);
*data = outdata;
free((char *)indata);
break;
case UNCOMP:
*data = outdata;
break;
default:
fatalerr("ReadIheadRaster",file,"Invalid compression code");
break;
}
/* close the image file */
(void) fclose(fp);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/cblas/scopy.c
|
<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SCOPY.C from package CBLAS.
* Retrieved from NETLIB on Tue Mar 14 10:51:36 2000.
* ======================================================================
*/
/* -- translated by f2c (version 19940927).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include <f2c.h>
/* Subroutine */ int scopy_(int *n, real *sx, int *incx, real *sy,
int *incy)
{
/* System generated locals */
int i__1;
/* Local variables */
static int i, m, ix, iy, mp1;
/* copies a vector, x, to a vector, y.
uses unrolled loops for increments equal to 1.
<NAME>, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define SY(I) sy[(I)-1]
#define SX(I) sx[(I)-1]
if (*n <= 0) {
return 0;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments
not equal to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
SY(iy) = SX(ix);
ix += *incx;
iy += *incy;
/* L10: */
}
return 0;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 7;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
SY(i) = SX(i);
/* L30: */
}
if (*n < 7) {
return 0;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 7) {
SY(i) = SX(i);
SY(i + 1) = SX(i + 1);
SY(i + 2) = SX(i + 2);
SY(i + 3) = SX(i + 3);
SY(i + 4) = SX(i + 4);
SY(i + 5) = SX(i + 5);
SY(i + 6) = SX(i + 6);
/* L50: */
}
return 0;
} /* scopy_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slamc1.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slamc1_(int *beta, int *t, logical *rnd, logical
*ieee1)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAMC1 determines the machine parameters given by BETA, T, RND, and
IEEE1.
Arguments
=========
BETA (output) INTEGER
The base of the machine.
T (output) INTEGER
The number of ( BETA ) digits in the mantissa.
RND (output) LOGICAL
Specifies whether proper rounding ( RND = .TRUE. ) or
chopping ( RND = .FALSE. ) occurs in addition. This may not
be a reliable guide to the way in which the machine performs
its arithmetic.
IEEE1 (output) LOGICAL
Specifies whether rounding appears to be done in the IEEE
'round to nearest' style.
Further Details
===============
The routine is based on the routine ENVRON by Malcolm and
incorporates suggestions by Gentleman and Marovich. See
<NAME>. (1972) Algorithms to reveal properties of
floating-point arithmetic. Comms. of the ACM, 15, 949-951.
<NAME>. and <NAME>. (1974) More on algorithms
that reveal properties of floating point arithmetic units.
Comms. of the ACM, 17, 276-277.
=====================================================================
*/
/* Initialized data */
static logical first = TRUE_;
/* System generated locals */
real r__1, r__2;
/* Local variables */
static logical lrnd;
static real a, b, c, f;
static int lbeta;
static real savec;
static logical lieee1;
static real t1, t2;
extern doublereal slamc3_(real *, real *);
static int lt;
static real one, qtr;
if (first) {
first = FALSE_;
one = 1.f;
/* LBETA, LIEEE1, LT and LRND are the local values of BE
TA,
IEEE1, T and RND.
Throughout this routine we use the function SLAMC3 to ens
ure
that relevant values are stored and not held in registers,
or
are not affected by optimizers.
Compute a = 2.0**m with the smallest positive integer m s
uch
that
fl( a + 1.0 ) = a. */
a = 1.f;
c = 1.f;
/* + WHILE( C.EQ.ONE )LOOP */
L10:
if (c == one) {
a *= 2;
c = slamc3_(&a, &one);
r__1 = -(doublereal)a;
c = slamc3_(&c, &r__1);
goto L10;
}
/* + END WHILE
Now compute b = 2.0**m with the smallest positive integer
m
such that
fl( a + b ) .gt. a. */
b = 1.f;
c = slamc3_(&a, &b);
/* + WHILE( C.EQ.A )LOOP */
L20:
if (c == a) {
b *= 2;
c = slamc3_(&a, &b);
goto L20;
}
/* + END WHILE
Now compute the base. a and c are neighbouring floating po
int
numbers in the interval ( beta**t, beta**( t + 1 ) ) and
so
their difference is beta. Adding 0.25 to c is to ensure that
it
is truncated to beta and not ( beta - 1 ). */
qtr = one / 4;
savec = c;
r__1 = -(doublereal)a;
c = slamc3_(&c, &r__1);
lbeta = c + qtr;
/* Now determine whether rounding or chopping occurs, by addin
g a
bit less than beta/2 and a bit more than beta/2 to
a. */
b = (real) lbeta;
r__1 = b / 2;
r__2 = -(doublereal)b / 100;
f = slamc3_(&r__1, &r__2);
c = slamc3_(&f, &a);
if (c == a) {
lrnd = TRUE_;
} else {
lrnd = FALSE_;
}
r__1 = b / 2;
r__2 = b / 100;
f = slamc3_(&r__1, &r__2);
c = slamc3_(&f, &a);
if (lrnd && c == a) {
lrnd = FALSE_;
}
/* Try and decide whether rounding is done in the IEEE 'round
to
nearest' style. B/2 is half a unit in the last place of the
two
numbers A and SAVEC. Furthermore, A is even, i.e. has last
bit
zero, and SAVEC is odd. Thus adding B/2 to A should not cha
nge
A, but adding B/2 to SAVEC should change SAVEC. */
r__1 = b / 2;
t1 = slamc3_(&r__1, &a);
r__1 = b / 2;
t2 = slamc3_(&r__1, &savec);
lieee1 = t1 == a && t2 > savec && lrnd;
/* Now find the mantissa, t. It should be the integer part
of
log to the base beta of a, however it is safer to determine
t
by powering. So we find t as the smallest positive integer
for
which
fl( beta**t + 1.0 ) = 1.0. */
lt = 0;
a = 1.f;
c = 1.f;
/* + WHILE( C.EQ.ONE )LOOP */
L30:
if (c == one) {
++lt;
a *= lbeta;
c = slamc3_(&a, &one);
r__1 = -(doublereal)a;
c = slamc3_(&c, &r__1);
goto L30;
}
/* + END WHILE */
}
*beta = lbeta;
*t = lt;
*rnd = lrnd;
*ieee1 = lieee1;
return 0;
/* End of SLAMC1 */
} /* slamc1_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/diffbyts/diffbyts.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/************************************************************************
PACKAGE: IMAGE ENCODER/DECODER TOOLS
FILE: DIFFBYTS.C
AUTHORS: <NAME>
<EMAIL>
<NAME>
<EMAIL>
DATE: 11/24/1999
UPDATED: 05/09/2005 by MDG
UPDATED: 09/30/2008 by Kenenth Ko - add version option.
#cat: diff_bytes - Compares two input files byte by byte and returns
#cat: a histogram of the gray level differences.
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <img_io.h>
#include <version.h>
int main(int argc, char *argv[])
{
unsigned char *image1, *image2, *img1, *img2;
int diffs[256];
int df, i, t;
int ret, ilen1, ilen2;
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
if(argc != 3) {
fprintf(stderr,"Usage: %s <file1> <file2>\n", argv[0]);
exit(1);
}
if((ret = read_raw_from_filesize(argv[1], &image1, &ilen1)))
exit(ret);
if((ret = read_raw_from_filesize(argv[2], &image2, &ilen2)))
exit(ret);
if(ilen1 != ilen2){
fprintf(stderr, "ERROR : main : %s byte length %d != %s byte length %d\n",
argv[1], ilen1, argv[2], ilen2);
free(image1);
free(image2);
exit(-1);
}
img1 = image1;
img2 = image2;
for(i = 0; i < 256; i++)
diffs[i] = 0;
for(i = 0; i < ilen1; i++) {
if(*img1 > *img2)
df = *img1 - *img2;
else
df = *img2 - *img1;
diffs[df]++;
img1++;
img2++;
}
t = 0;
for(i = 0; i < 256; i++) {
t += diffs[i];
if(diffs[i] != 0) {
printf("d[%d] = %d : %f\n", i, diffs[i],
100.0 * ((float)t/(float)(ilen1)));
}
}
free(image1);
free(image2);
exit(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/dpyimage/dpyx.h
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
PACKAGE: NIST Image Display
FILE: DPYX.H
AUTHORS: <NAME>
<NAME>
DATE: 12/03/1990
UPDATED: 05/23/2005 by MDG
***********************************************************************/
#ifndef _DPYX_H
#define _DPYX_H
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
#include <limits.h>
#include <display.h>
#include <dpydepth.h>
#include <event.h>
#include <dpy.h>
#define WIN_XY_INCR 25
#define BITMAP_UNIT_24 4 /* 4 bytes ==> 32 bits */
#define PT(x,y,w,h) (((x)>=0)&&((x)<(w))&&((y)>=0)&&((y)<(h)))
#define ALL_BUTTONS ((unsigned int) (Button1Mask| \
Button2Mask| \
Button3Mask| \
Button4Mask| \
Button5Mask))
/* X-Window global references. */
extern Display *display;
extern char *display_name;
extern Window window, rw;
extern Visual *visual;
extern int screen;
extern Colormap def_cmap, cmap;
extern int cmap_size;
extern GC gc, boxgc, pointgc;
extern unsigned long bp, wp;
extern unsigned int border_width;
extern int no_window_mgr;
extern int no_keyboard_input;
/************************************************************************/
/* dpyx.c */
extern void cleanup(void);
extern int xconnect(void);
extern int initwin(unsigned int wx, unsigned int wy, unsigned int ww,
unsigned int wh, unsigned int depth, unsigned long wp);
extern int set_gray_colormap(Display *, Colormap, unsigned int, unsigned long);
extern int gray_colormap(Colormap *, Display *, Visual **, unsigned int);
#endif /* !_DPYX_H */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/sstein.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int sstein_(int *n, real *d, real *e, int *m, real *
w, int *iblock, int *isplit, real *z, int *ldz, real *
work, int *iwork, int *ifail, int *info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SSTEIN computes the eigenvectors of a real symmetric tridiagonal
matrix T corresponding to specified eigenvalues, using inverse
iteration.
The maximum number of iterations allowed for each eigenvector is
specified by an internal parameter MAXITS (currently set to 5).
Arguments
=========
N (input) INTEGER
The order of the matrix. N >= 0.
D (input) REAL array, dimension (N)
The n diagonal elements of the tridiagonal matrix T.
E (input) REAL array, dimension (N)
The (n-1) subdiagonal elements of the tridiagonal matrix
T, in elements 1 to N-1. E(N) need not be set.
M (input) INTEGER
The number of eigenvectors to be found. 0 <= M <= N.
W (input) REAL array, dimension (N)
The first M elements of W contain the eigenvalues for
which eigenvectors are to be computed. The eigenvalues
should be grouped by split-off block and ordered from
smallest to largest within the block. ( The output array
W from SSTEBZ with ORDER = 'B' is expected here. )
IBLOCK (input) INTEGER array, dimension (N)
The submatrix indices associated with the corresponding
eigenvalues in W; IBLOCK(i)=1 if eigenvalue W(i) belongs to
the first submatrix from the top, =2 if W(i) belongs to
the second submatrix, etc. ( The output array IBLOCK
from SSTEBZ is expected here. )
ISPLIT (input) INTEGER array, dimension (N)
The splitting points, at which T breaks up into submatrices.
The first submatrix consists of rows/columns 1 to
ISPLIT( 1 ), the second of rows/columns ISPLIT( 1 )+1
through ISPLIT( 2 ), etc.
( The output array ISPLIT from SSTEBZ is expected here. )
Z (output) REAL array, dimension (LDZ, M)
The computed eigenvectors. The eigenvector associated
with the eigenvalue W(i) is stored in the i-th column of
Z. Any vector which fails to converge is set to its current
iterate after MAXITS iterations.
LDZ (input) INTEGER
The leading dimension of the array Z. LDZ >= max(1,N).
WORK (workspace) REAL array, dimension (5*N)
IWORK (workspace) INTEGER array, dimension (N)
IFAIL (output) INTEGER array, dimension (M)
On normal exit, all elements of IFAIL are zero.
If one or more eigenvectors fail to converge after
MAXITS iterations, then their indices are stored in
array IFAIL.
INFO (output) INTEGER
= 0: successful exit.
< 0: if INFO = -i, the i-th argument had an illegal value
> 0: if INFO = i, then i eigenvectors failed to converge
in MAXITS iterations. Their indices are stored in
array IFAIL.
Internal Parameters
===================
MAXITS INTEGER, default = 5
The maximum number of iterations performed.
EXTRA INTEGER, default = 2
The number of iterations performed after norm growth
criterion is satisfied, should be at least 1.
=====================================================================
Test the input parameters.
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__2 = 2;
static int c__1 = 1;
static int c_n1 = -1;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int z_dim1, z_offset;
*/
int i__1, i__2, i__3;
real r__1, r__2, r__3, r__4, r__5;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
static int jblk, nblk, jmax;
extern doublereal sdot_(int *, real *, int *, real *, int *),
snrm2_(int *, real *, int *);
static int i, j, iseed[4], gpind, iinfo;
extern /* Subroutine */ int sscal_(int *, real *, real *, int *);
static int b1;
extern doublereal sasum_(int *, real *, int *);
static int j1;
extern /* Subroutine */ int scopy_(int *, real *, int *, real *,
int *);
static real ortol;
extern /* Subroutine */ int saxpy_(int *, real *, real *, int *,
real *, int *);
static int indrv1, indrv2, indrv3, indrv4, indrv5, bn;
static real xj;
extern doublereal slamch_(char *);
extern /* Subroutine */ int xerbla_(char *, int *), slagtf_(
int *, real *, real *, real *, real *, real *, real *,
int *, int *);
static int nrmchk;
extern int isamax_(int *, real *, int *);
extern /* Subroutine */ int slagts_(int *, int *, real *, real *,
real *, real *, int *, real *, real *, int *);
static int blksiz;
static real onenrm, pertol;
extern /* Subroutine */ int slarnv_(int *, int *, int *, real
*);
static real stpcrt, scl, eps, ctr, sep, nrm, tol;
static int its;
static real xjm, eps1;
#define ISEED(I) iseed[(I)]
#define D(I) d[(I)-1]
#define E(I) e[(I)-1]
#define W(I) w[(I)-1]
#define IBLOCK(I) iblock[(I)-1]
#define ISPLIT(I) isplit[(I)-1]
#define WORK(I) work[(I)-1]
#define IWORK(I) iwork[(I)-1]
#define IFAIL(I) ifail[(I)-1]
#define Z(I,J) z[(I)-1 + ((J)-1)* ( *ldz)]
*info = 0;
i__1 = *m;
for (i = 1; i <= *m; ++i) {
IFAIL(i) = 0;
/* L10: */
}
if (*n < 0) {
*info = -1;
} else if (*m < 0 || *m > *n) {
*info = -4;
} else if (*ldz < max(1,*n)) {
*info = -9;
} else {
i__1 = *m;
for (j = 2; j <= *m; ++j) {
if (IBLOCK(j) < IBLOCK(j - 1)) {
*info = -6;
goto L30;
}
if (IBLOCK(j) == IBLOCK(j - 1) && W(j) < W(j - 1)) {
*info = -5;
goto L30;
}
/* L20: */
}
L30:
;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SSTEIN", &i__1);
return 0;
}
/* Quick return if possible */
if (*n == 0 || *m == 0) {
return 0;
} else if (*n == 1) {
Z(1,1) = 1.f;
return 0;
}
/* Get machine constants. */
eps = slamch_("Precision");
/* Initialize seed for random number generator SLARNV. */
for (i = 1; i <= 4; ++i) {
ISEED(i - 1) = 1;
/* L40: */
}
/* Initialize pointers. */
indrv1 = 0;
indrv2 = indrv1 + *n;
indrv3 = indrv2 + *n;
indrv4 = indrv3 + *n;
indrv5 = indrv4 + *n;
/* Compute eigenvectors of matrix blocks. */
j1 = 1;
i__1 = IBLOCK(*m);
for (nblk = 1; nblk <= IBLOCK(*m); ++nblk) {
/* Find starting and ending indices of block nblk. */
if (nblk == 1) {
b1 = 1;
} else {
b1 = ISPLIT(nblk - 1) + 1;
}
bn = ISPLIT(nblk);
blksiz = bn - b1 + 1;
if (blksiz == 1) {
goto L60;
}
gpind = b1;
/* Compute reorthogonalization criterion and stopping criterion
. */
onenrm = (r__1 = D(b1), dabs(r__1)) + (r__2 = E(b1), dabs(r__2));
/* Computing MAX */
r__3 = onenrm, r__4 = (r__1 = D(bn), dabs(r__1)) + (r__2 = E(bn - 1),
dabs(r__2));
onenrm = dmax(r__3,r__4);
i__2 = bn - 1;
for (i = b1 + 1; i <= bn-1; ++i) {
/* Computing MAX */
r__4 = onenrm, r__5 = (r__1 = D(i), dabs(r__1)) + (r__2 = E(i - 1)
, dabs(r__2)) + (r__3 = E(i), dabs(r__3));
onenrm = dmax(r__4,r__5);
/* L50: */
}
ortol = onenrm * .001f;
stpcrt = sqrt(.1f / blksiz);
/* Loop through eigenvalues of block nblk. */
L60:
jblk = 0;
i__2 = *m;
for (j = j1; j <= *m; ++j) {
if (IBLOCK(j) != nblk) {
j1 = j;
goto L160;
}
++jblk;
xj = W(j);
/* Skip all the work if the block size is one. */
if (blksiz == 1) {
WORK(indrv1 + 1) = 1.f;
goto L120;
}
/* If eigenvalues j and j-1 are too close, add a relativ
ely
small perturbation. */
if (jblk > 1) {
eps1 = (r__1 = eps * xj, dabs(r__1));
pertol = eps1 * 10.f;
sep = xj - xjm;
if (sep < pertol) {
xj = xjm + pertol;
}
}
its = 0;
nrmchk = 0;
/* Get random starting vector. */
slarnv_(&c__2, iseed, &blksiz, &WORK(indrv1 + 1));
/* Copy the matrix T so it won't be destroyed in factori
zation. */
scopy_(&blksiz, &D(b1), &c__1, &WORK(indrv4 + 1), &c__1);
i__3 = blksiz - 1;
scopy_(&i__3, &E(b1), &c__1, &WORK(indrv2 + 2), &c__1);
i__3 = blksiz - 1;
scopy_(&i__3, &E(b1), &c__1, &WORK(indrv3 + 1), &c__1);
/* Compute LU factors with partial pivoting ( PT = LU )
*/
tol = 0.f;
slagtf_(&blksiz, &WORK(indrv4 + 1), &xj, &WORK(indrv2 + 2), &WORK(
indrv3 + 1), &tol, &WORK(indrv5 + 1), &IWORK(1), &iinfo);
/* Update iteration count. */
L70:
++its;
if (its > 5) {
goto L100;
}
/* Normalize and scale the righthand side vector Pb.
Computing MAX */
r__2 = eps, r__3 = (r__1 = WORK(indrv4 + blksiz), dabs(r__1));
scl = blksiz * onenrm * dmax(r__2,r__3) / sasum_(&blksiz, &WORK(
indrv1 + 1), &c__1);
sscal_(&blksiz, &scl, &WORK(indrv1 + 1), &c__1);
/* Solve the system LU = Pb. */
slagts_(&c_n1, &blksiz, &WORK(indrv4 + 1), &WORK(indrv2 + 2), &
WORK(indrv3 + 1), &WORK(indrv5 + 1), &IWORK(1), &WORK(
indrv1 + 1), &tol, &iinfo);
/* Reorthogonalize by modified Gram-Schmidt if eigenvalu
es are
close enough. */
if (jblk == 1) {
goto L90;
}
if ((r__1 = xj - xjm, dabs(r__1)) > ortol) {
gpind = j;
}
if (gpind != j) {
i__3 = j - 1;
for (i = gpind; i <= j-1; ++i) {
ctr = -(doublereal)sdot_(&blksiz, &WORK(indrv1 + 1), &
c__1, &Z(b1,i), &c__1);
saxpy_(&blksiz, &ctr, &Z(b1,i), &c__1, &WORK(
indrv1 + 1), &c__1);
/* L80: */
}
}
/* Check the infinity norm of the iterate. */
L90:
jmax = isamax_(&blksiz, &WORK(indrv1 + 1), &c__1);
nrm = (r__1 = WORK(indrv1 + jmax), dabs(r__1));
/* Continue for additional iterations after norm reaches
stopping criterion. */
if (nrm < stpcrt) {
goto L70;
}
++nrmchk;
if (nrmchk < 3) {
goto L70;
}
goto L110;
/* If stopping criterion was not satisfied, update info
and
store eigenvector number in array ifail. */
L100:
++(*info);
IFAIL(*info) = j;
/* Accept iterate as jth eigenvector. */
L110:
scl = 1.f / snrm2_(&blksiz, &WORK(indrv1 + 1), &c__1);
jmax = isamax_(&blksiz, &WORK(indrv1 + 1), &c__1);
if (WORK(indrv1 + jmax) < 0.f) {
scl = -(doublereal)scl;
}
sscal_(&blksiz, &scl, &WORK(indrv1 + 1), &c__1);
L120:
i__3 = *n;
for (i = 1; i <= *n; ++i) {
Z(i,j) = 0.f;
/* L130: */
}
i__3 = blksiz;
for (i = 1; i <= blksiz; ++i) {
Z(b1+i-1,j) = WORK(indrv1 + i);
/* L140: */
}
/* Save the shift to check eigenvalue spacing at next
iteration. */
xjm = xj;
/* L150: */
}
L160:
;
}
return 0;
/* End of SSTEIN */
} /* sstein_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slamc4.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slamc4_(int *emin, real *start, int *base)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAMC4 is a service routine for SLAMC2.
Arguments
=========
EMIN (output) EMIN
The minimum exponent before (gradual) underflow, computed by
setting A = START and dividing by BASE until the previous A
can not be recovered.
START (input) REAL
The starting point for determining EMIN.
BASE (input) INTEGER
The base of the machine.
=====================================================================
*/
/* System generated locals */
int i__1;
real r__1;
/* Local variables */
static real zero, a;
static int i;
static real rbase, b1, b2, c1, c2, d1, d2;
extern doublereal slamc3_(real *, real *);
static real one;
a = *start;
one = 1.f;
rbase = one / *base;
zero = 0.f;
*emin = 1;
r__1 = a * rbase;
b1 = slamc3_(&r__1, &zero);
c1 = a;
c2 = a;
d1 = a;
d2 = a;
/* + WHILE( ( C1.EQ.A ).AND.( C2.EQ.A ).AND.
$ ( D1.EQ.A ).AND.( D2.EQ.A ) )LOOP */
L10:
if (c1 == a && c2 == a && d1 == a && d2 == a) {
--(*emin);
a = b1;
r__1 = a / *base;
b1 = slamc3_(&r__1, &zero);
r__1 = b1 * *base;
c1 = slamc3_(&r__1, &zero);
d1 = zero;
i__1 = *base;
for (i = 1; i <= *base; ++i) {
d1 += b1;
/* L20: */
}
r__1 = a * rbase;
b2 = slamc3_(&r__1, &zero);
r__1 = b2 / rbase;
c2 = slamc3_(&r__1, &zero);
d2 = zero;
i__1 = *base;
for (i = 1; i <= *base; ++i) {
d2 += b2;
/* L30: */
}
goto L10;
}
/* + END WHILE */
return 0;
/* End of SLAMC4 */
} /* slamc4_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/lsame.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
logical lsame_(char *ca, char *cb)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
LSAME returns .TRUE. if CA is the same letter as CB regardless of
case.
Arguments
=========
CA (input) CHARACTER*1
CB (input) CHARACTER*1
CA and CB specify the single characters to be compared.
=====================================================================
Test if the characters are equal */
/* System generated locals */
logical ret_val;
/* Local variables */
static int inta, intb, zcode;
ret_val = *(unsigned char *)ca == *(unsigned char *)cb;
if (ret_val) {
return ret_val;
}
/* Now test for equivalence if both characters are alphabetic. */
zcode = 'Z';
/* Use 'Z' rather than 'A' so that ASCII can be detected on Prime
machines, on which ICHAR returns a value with bit 8 set.
ICHAR('A') on Prime machines returns 193 which is the same as
ICHAR('A') on an EBCDIC machine. */
inta = *(unsigned char *)ca;
intb = *(unsigned char *)cb;
if (zcode == 90 || zcode == 122) {
/* ASCII is assumed - ZCODE is the ASCII code of either lower o
r
upper case 'Z'. */
if (inta >= 97 && inta <= 122) {
inta += -32;
}
if (intb >= 97 && intb <= 122) {
intb += -32;
}
} else if (zcode == 233 || zcode == 169) {
/* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower
or
upper case 'Z'. */
/*
if (inta >= 129 && inta <= 137 || inta >= 145 && inta <= 153 || inta
>= 162 && inta <= 169) {
*/
/* Parentheses added by MDG on 03-09-05 */
if ((inta >= 129 && inta <= 137) || (inta >= 145 && inta <= 153) ||
(inta >= 162 && inta <= 169)) {
inta += 64;
}
/*
if (intb >= 129 && intb <= 137 || intb >= 145 && intb <= 153 || intb
>= 162 && intb <= 169) {
*/
/* Parentheses added by MDG on 03-09-05 */
if ((intb >= 129 && intb <= 137) || (intb >= 145 && intb <= 153) ||
(intb >= 162 && intb <= 169)) {
intb += 64;
}
} else if (zcode == 218 || zcode == 250) {
/* ASCII is assumed, on Prime machines - ZCODE is the ASCII cod
e
plus 128 of either lower or upper case 'Z'. */
if (inta >= 225 && inta <= 250) {
inta += -32;
}
if (intb >= 225 && intb <= 250) {
intb += -32;
}
}
ret_val = inta == intb;
/* RETURN
End of LSAME */
return ret_val;
} /* lsame_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/dpyimage/dpytmp.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
PACKAGE: NIST Image Display
FILE: DPYTMP.C
AUTHORS: <NAME>
<NAME>
DATE: 12/03/1990
UPDATED: 05/10/2005 by MDG
ROUTINES:
tmpcomm()
tmp_parent()
tmp_child()
***********************************************************************/
#include <usebsd.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/param.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <dpyimage.h>
extern int kill(pid_t, int);
extern int fileno(FILE *);
/*****************************************************************/
int tmpcomm(int argc, char **argv)
{
int ret;
pid_t pid, p;
char dir[MAXPATHLEN];
if (verbose)
(void) printf("In tmpcomm()\n");
p = getpid();
(void) sprintf(dir,OUTFILE_DIRFMT,tmpdir,(int)p);
if (mkdir(dir,OUTFILE_DIRMODE) < 0) {
perror(dir);
return(-2);
}
pid = fork();
if ((int)pid < 0) {
perror("Fork failed");
return(-3);
}
if ((int)pid) {
char cmd[2*MAXPATHLEN];
if((ret = tmp_parent(p)))
return(ret);
if((ret = kill(pid,SIGKILL)))
return(ret);
(void) sprintf(cmd,"/bin/rm -f %s/*",dir);
if (verbose)
(void) printf("%s\n",cmd);
(void) system(cmd);
if (rmdir(dir) < 0)
perror(dir);
} else {
extern int nicevalue;
extern char *program;
program = "[child]";
if((nicevalue >= 0) && (nice(nicevalue) < 0))
perror("Nice failed");
if((ret = fdclose(0,"stdin")))
return(ret);
if(open("/dev/null",O_RDWR) < 0) {
perror("Cannot open /dev/null");
return(-4);
}
if((ret = fdclose(ConnectionNumber(display),"X11 connection")))
return(ret);
if((ret = tmp_child(argc,argv,p)))
return(ret);
return(0);
}
return(0);
}
/************************************************************************/
int tmp_parent(pid_t pid)
{
int ret;
register FILE *fp;
int done=False, bytes, filenumber=0;
unsigned char *data;
unsigned int iw, ih, depth;
char outfile[MAXPATHLEN], ctrlfile[MAXPATHLEN];
struct header_t header;
struct stat s;
for (;;) {
(void) sprintf(outfile,OUTFILE_FMT,tmpdir,(int)pid,filenumber++);
(void) strcpy(ctrlfile,outfile);
(void) strcat(ctrlfile,OUTFILE_EXT);
/* wait for creation of control file */
while (access(ctrlfile,F_OK) < 0)
sleep((unsigned int)1);
if (verbose)
(void) printf("\tcontrol file %s exists\n",ctrlfile);
fp = fopen(outfile,"rb");
if (fp == (FILE *) NULL) {
(void) fprintf(stderr,"dpyimage: cannot open %s\n",outfile);
return(-2);
}
unlinkfile(outfile);
unlinkfile(ctrlfile);
if (fstat(fileno(fp),&s) < 0) {
perror(outfile);
return(-3);
}
if (s.st_size == 0)
break;
if((ret = readheader(fp,&header)))
return(ret);
iw = header.iw;
ih = header.ih;
depth = header.depth;
if (depth == 1)
bytes = howmany(iw,CHAR_BIT) * ih;
else if (depth == 8)
bytes = iw * ih;
else /* if(depth == 24) */
bytes = iw * ih * 3;
data = (unsigned char *) malloc((unsigned int) bytes);
if (data == (unsigned char *) NULL) {
(void) fprintf(stderr,"dpyimage: malloc(%d) failed\n", bytes);
return(-4);
}
if (verbose > 2) {
unsigned int zero, one;
(void) printf("%s:\n",header.filename);
(void) printf("\timage size: %u x %u (%d bytes)\n", iw,ih,bytes);
(void) printf("\tdepth: %u\n",depth);
pixelcount(data,bytes,&zero,&one);
(void) printf("\tpixel breakdown: %u zero, %u one\n\n",
zero,one);
}
if((ret = readdata(fp,data,bytes))){
free((char *)data);
return(ret);
}
if((ret = fclose(fp))){
free((char *)data);
return(ret);
}
if((ret = dpyimage(header.filename,data,iw,ih,depth,
header.whitepix,header.align,&done))){
free((char *)data);
return(ret);
}
free((char *)data);
if (done)
break;
} /* for */
return(0);
}
/*************************************************************/
int tmp_child(int argc, char **argv, pid_t ppid)
{
int ret;
char outfile[MAXPATHLEN], ctrlfile[MAXPATHLEN];
register FILE *fp;
int align, bpi, bytes, filenumber=0;
unsigned char *data;
unsigned int iw, ih, depth, whitepix;
struct header_t header;
extern int optind;
while ( optind <= argc ) {
(void) sprintf(outfile,OUTFILE_FMT,tmpdir,(int)ppid,filenumber++);
(void) strcpy(ctrlfile,outfile);
(void) strcat(ctrlfile,OUTFILE_EXT);
fp = fopen(outfile,"wb");
if (fp == (FILE *) NULL) {
(void) fprintf(stderr,"dpyimage: cannot open %s\n",outfile);
return(-2);
}
if (optind != argc) {
if((ret = readfile(argv[optind],&data,&bpi,&iw,&ih,&depth,
&whitepix,&align)))
return(ret);
buildheader(&header,argv[optind],iw,ih,depth,whitepix,align);
if((ret = writeheader(fp,&header))){
free((char *) data);
return(ret);
}
if (depth == 1)
bytes = howmany(iw,CHAR_BIT) * ih;
else if (depth == 8)
bytes = iw * ih;
else /* if (depth == 24) */
bytes = iw * ih * 3;
if (verbose)
(void) printf("(child) %d bytes\n",bytes);
if((ret = writedata(fp,data,bytes))){
free((char *) data);
return(ret);
}
} /* If */
if (optind != argc)
free((char *) data);
if((ret = fclose(fp)))
return(ret);
if((ret = createfile(ctrlfile)))
return(ret);
optind++;
} /* for */
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slagts.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slagts_(int *job, int *n, real *a, real *b, real
*c, real *d, int *in, real *y, real *tol, int *info)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAGTS may be used to solve one of the systems of equations
(T - lambda*I)*x = y or (T - lambda*I)'*x = y,
where T is an n by n tridiagonal matrix, for x, following the
factorization of (T - lambda*I) as
(T - lambda*I) = P*L*U ,
by routine SLAGTF. The choice of equation to be solved is
controlled by the argument JOB, and in each case there is an option
to perturb zero or very small diagonal elements of U, this option
being intended for use in applications such as inverse iteration.
Arguments
=========
JOB (input) INTEGER
Specifies the job to be performed by SLAGTS as follows:
= 1: The equations (T - lambda*I)x = y are to be solved,
but diagonal elements of U are not to be perturbed.
= -1: The equations (T - lambda*I)x = y are to be solved
and, if overflow would otherwise occur, the diagonal
elements of U are to be perturbed. See argument TOL
below.
= 2: The equations (T - lambda*I)'x = y are to be solved,
but diagonal elements of U are not to be perturbed.
= -2: The equations (T - lambda*I)'x = y are to be solved
and, if overflow would otherwise occur, the diagonal
elements of U are to be perturbed. See argument TOL
below.
N (input) INTEGER
The order of the matrix T.
A (input) REAL array, dimension (N)
On entry, A must contain the diagonal elements of U as
returned from SLAGTF.
B (input) REAL array, dimension (N-1)
On entry, B must contain the first super-diagonal elements of
U as returned from SLAGTF.
C (input) REAL array, dimension (N-1)
On entry, C must contain the sub-diagonal elements of L as
returned from SLAGTF.
D (input) REAL array, dimension (N-2)
On entry, D must contain the second super-diagonal elements
of U as returned from SLAGTF.
IN (input) INTEGER array, dimension (N)
On entry, IN must contain details of the matrix P as returned
from SLAGTF.
Y (input/output) REAL array, dimension (N)
On entry, the right hand side vector y.
On exit, Y is overwritten by the solution vector x.
TOL (input/output) REAL
On entry, with JOB .lt. 0, TOL should be the minimum
perturbation to be made to very small diagonal elements of U.
TOL should normally be chosen as about eps*norm(U), where eps
is the relative machine precision, but if TOL is supplied as
non-positive, then it is reset to eps*max( abs( u(i,j) ) ).
If JOB .gt. 0 then TOL is not referenced.
On exit, TOL is changed as described above, only if TOL is
non-positive on entry. Otherwise TOL is unchanged.
INFO (output) INTEGER
= 0 : successful exit
.lt. 0: if INFO = -i, the i-th argument had an illegal value
.gt. 0: overflow would occur when computing the INFO(th)
element of the solution vector x. This can only occur
when JOB is supplied as positive and either means
that a diagonal element of U is very small, or that
the elements of the right-hand side vector y are very
large.
=====================================================================
Parameter adjustments
Function Body */
/* System generated locals */
int i__1;
real r__1, r__2, r__3, r__4, r__5;
/* Builtin functions */
double r_sign(real *, real *);
/* Local variables */
static real temp, pert;
static int k;
static real absak, sfmin, ak;
extern doublereal slamch_(char *);
extern /* Subroutine */ int xerbla_(char *, int *);
static real bignum, eps;
#define Y(I) y[(I)-1]
#define IN(I) in[(I)-1]
#define D(I) d[(I)-1]
#define C(I) c[(I)-1]
#define B(I) b[(I)-1]
#define A(I) a[(I)-1]
*info = 0;
if (abs(*job) > 2 || *job == 0) {
*info = -1;
} else if (*n < 0) {
*info = -2;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SLAGTS", &i__1);
return 0;
}
if (*n == 0) {
return 0;
}
eps = slamch_("Epsilon");
sfmin = slamch_("Safe minimum");
bignum = 1.f / sfmin;
if (*job < 0) {
if (*tol <= 0.f) {
*tol = dabs(A(1));
if (*n > 1) {
/* Computing MAX */
r__1 = *tol, r__2 = dabs(A(2)), r__1 = max(r__1,r__2), r__2 =
dabs(B(1));
*tol = dmax(r__1,r__2);
}
i__1 = *n;
for (k = 3; k <= *n; ++k) {
/* Computing MAX */
r__4 = *tol, r__5 = (r__1 = A(k), dabs(r__1)), r__4 = max(
r__4,r__5), r__5 = (r__2 = B(k - 1), dabs(r__2)),
r__4 = max(r__4,r__5), r__5 = (r__3 = D(k - 2), dabs(
r__3));
*tol = dmax(r__4,r__5);
/* L10: */
}
*tol *= eps;
if (*tol == 0.f) {
*tol = eps;
}
}
}
if (abs(*job) == 1) {
i__1 = *n;
for (k = 2; k <= *n; ++k) {
if (IN(k - 1) == 0) {
Y(k) -= C(k - 1) * Y(k - 1);
} else {
temp = Y(k - 1);
Y(k - 1) = Y(k);
Y(k) = temp - C(k - 1) * Y(k);
}
/* L20: */
}
if (*job == 1) {
for (k = *n; k >= 1; --k) {
if (k <= *n - 2) {
temp = Y(k) - B(k) * Y(k + 1) - D(k) * Y(k + 2);
} else if (k == *n - 1) {
temp = Y(k) - B(k) * Y(k + 1);
} else {
temp = Y(k);
}
ak = A(k);
absak = dabs(ak);
if (absak < 1.f) {
if (absak < sfmin) {
if (absak == 0.f || dabs(temp) * sfmin > absak) {
*info = k;
return 0;
} else {
temp *= bignum;
ak *= bignum;
}
} else if (dabs(temp) > absak * bignum) {
*info = k;
return 0;
}
}
Y(k) = temp / ak;
/* L30: */
}
} else {
for (k = *n; k >= 1; --k) {
if (k <= *n - 2) {
temp = Y(k) - B(k) * Y(k + 1) - D(k) * Y(k + 2);
} else if (k == *n - 1) {
temp = Y(k) - B(k) * Y(k + 1);
} else {
temp = Y(k);
}
ak = A(k);
pert = r_sign(tol, &ak);
L40:
absak = dabs(ak);
if (absak < 1.f) {
if (absak < sfmin) {
if (absak == 0.f || dabs(temp) * sfmin > absak) {
ak += pert;
pert *= 2;
goto L40;
} else {
temp *= bignum;
ak *= bignum;
}
} else if (dabs(temp) > absak * bignum) {
ak += pert;
pert *= 2;
goto L40;
}
}
Y(k) = temp / ak;
/* L50: */
}
}
} else {
/* Come to here if JOB = 2 or -2 */
if (*job == 2) {
i__1 = *n;
for (k = 1; k <= *n; ++k) {
if (k >= 3) {
temp = Y(k) - B(k - 1) * Y(k - 1) - D(k - 2) * Y(k - 2);
} else if (k == 2) {
temp = Y(k) - B(k - 1) * Y(k - 1);
} else {
temp = Y(k);
}
ak = A(k);
absak = dabs(ak);
if (absak < 1.f) {
if (absak < sfmin) {
if (absak == 0.f || dabs(temp) * sfmin > absak) {
*info = k;
return 0;
} else {
temp *= bignum;
ak *= bignum;
}
} else if (dabs(temp) > absak * bignum) {
*info = k;
return 0;
}
}
Y(k) = temp / ak;
/* L60: */
}
} else {
i__1 = *n;
for (k = 1; k <= *n; ++k) {
if (k >= 3) {
temp = Y(k) - B(k - 1) * Y(k - 1) - D(k - 2) * Y(k - 2);
} else if (k == 2) {
temp = Y(k) - B(k - 1) * Y(k - 1);
} else {
temp = Y(k);
}
ak = A(k);
pert = r_sign(tol, &ak);
L70:
absak = dabs(ak);
if (absak < 1.f) {
if (absak < sfmin) {
if (absak == 0.f || dabs(temp) * sfmin > absak) {
ak += pert;
pert *= 2;
goto L70;
} else {
temp *= bignum;
ak *= bignum;
}
} else if (dabs(temp) > absak * bignum) {
ak += pert;
pert *= 2;
goto L70;
}
}
Y(k) = temp / ak;
/* L80: */
}
}
for (k = *n; k >= 2; --k) {
if (IN(k - 1) == 0) {
Y(k - 1) -= C(k - 1) * Y(k);
} else {
temp = Y(k - 1);
Y(k - 1) = Y(k);
Y(k) = temp - C(k - 1) * Y(k);
}
/* L90: */
}
}
/* End of SLAGTS */
return 0;
} /* slagts_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slansy.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
doublereal slansy_(char *norm, char *uplo, int *n, real *a, int *lda,
real *work)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLANSY returns the value of the one norm, or the Frobenius norm, or
the infinity norm, or the element of largest absolute value of a
real symmetric matrix A.
Description
===========
SLANSY returns the value
SLANSY = ( max(abs(A(i,j))), NORM = 'M' or 'm'
(
( norm1(A), NORM = '1', 'O' or 'o'
(
( normI(A), NORM = 'I' or 'i'
(
( normF(A), NORM = 'F', 'f', 'E' or 'e'
where norm1 denotes the one norm of a matrix (maximum column sum),
normI denotes the infinity norm of a matrix (maximum row sum) and
normF denotes the Frobenius norm of a matrix (square root of sum of
squares). Note that max(abs(A(i,j))) is not a matrix norm.
Arguments
=========
NORM (input) CHARACTER*1
Specifies the value to be returned in SLANSY as described
above.
UPLO (input) CHARACTER*1
Specifies whether the upper or lower triangular part of the
symmetric matrix A is to be referenced.
= 'U': Upper triangular part of A is referenced
= 'L': Lower triangular part of A is referenced
N (input) INTEGER
The order of the matrix A. N >= 0. When N = 0, SLANSY is
set to zero.
A (input) REAL array, dimension (LDA,N)
The symmetric matrix A. If UPLO = 'U', the leading n by n
upper triangular part of A contains the upper triangular part
of the matrix A, and the strictly lower triangular part of A
is not referenced. If UPLO = 'L', the leading n by n lower
triangular part of A contains the lower triangular part of
the matrix A, and the strictly upper triangular part of A is
not referenced.
LDA (input) INTEGER
The leading dimension of the array A. LDA >= max(N,1).
WORK (workspace) REAL array, dimension (LWORK),
where LWORK >= N when NORM = 'I' or '1' or 'O'; otherwise,
WORK is not referenced.
=====================================================================
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__1 = 1;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset;
*/
int i__1, i__2;
real ret_val, r__1, r__2, r__3;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
static real absa;
static int i, j;
static real scale;
extern logical lsame_(char *, char *);
static real value;
extern /* Subroutine */ int slassq_(int *, real *, int *, real *,
real *);
static real sum;
#define WORK(I) work[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
if (*n == 0) {
value = 0.f;
} else if (lsame_(norm, "M")) {
/* Find max(abs(A(i,j))). */
value = 0.f;
if (lsame_(uplo, "U")) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = j;
for (i = 1; i <= j; ++i) {
/* Computing MAX */
r__2 = value, r__3 = (r__1 = A(i,j), dabs(r__1)
);
value = dmax(r__2,r__3);
/* L10: */
}
/* L20: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *n;
for (i = j; i <= *n; ++i) {
/* Computing MAX */
r__2 = value, r__3 = (r__1 = A(i,j), dabs(r__1)
);
value = dmax(r__2,r__3);
/* L30: */
}
/* L40: */
}
}
} else if (lsame_(norm, "I") || lsame_(norm, "O") || *(
unsigned char *)norm == '1') {
/* Find normI(A) ( = norm1(A), since A is symmetric). */
value = 0.f;
if (lsame_(uplo, "U")) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
sum = 0.f;
i__2 = j - 1;
for (i = 1; i <= j-1; ++i) {
absa = (r__1 = A(i,j), dabs(r__1));
sum += absa;
WORK(i) += absa;
/* L50: */
}
WORK(j) = sum + (r__1 = A(j,j), dabs(r__1));
/* L60: */
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
/* Computing MAX */
r__1 = value, r__2 = WORK(i);
value = dmax(r__1,r__2);
/* L70: */
}
} else {
i__1 = *n;
for (i = 1; i <= *n; ++i) {
WORK(i) = 0.f;
/* L80: */
}
i__1 = *n;
for (j = 1; j <= *n; ++j) {
sum = WORK(j) + (r__1 = A(j,j), dabs(r__1));
i__2 = *n;
for (i = j + 1; i <= *n; ++i) {
absa = (r__1 = A(i,j), dabs(r__1));
sum += absa;
WORK(i) += absa;
/* L90: */
}
value = dmax(value,sum);
/* L100: */
}
}
} else if (lsame_(norm, "F") || lsame_(norm, "E")) {
/* Find normF(A). */
scale = 0.f;
sum = 1.f;
if (lsame_(uplo, "U")) {
i__1 = *n;
for (j = 2; j <= *n; ++j) {
i__2 = j - 1;
slassq_(&i__2, &A(1,j), &c__1, &scale, &sum);
/* L110: */
}
} else {
i__1 = *n - 1;
for (j = 1; j <= *n-1; ++j) {
i__2 = *n - j;
slassq_(&i__2, &A(j+1,j), &c__1, &scale, &sum);
/* L120: */
}
}
sum *= 2;
i__1 = *lda + 1;
slassq_(n, &A(1,1), &i__1, &scale, &sum);
value = scale * sqrt(sum);
}
ret_val = value;
return ret_val;
/* End of SLANSY */
} /* slansy_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/ssytd2.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int ssytd2_(char *uplo, int *n, real *a, int *lda,
real *d, real *e, real *tau, int *info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SSYTD2 reduces a real symmetric matrix A to symmetric tridiagonal
form T by an orthogonal similarity transformation: Q' * A * Q = T.
Arguments
=========
UPLO (input) CHARACTER*1
Specifies whether the upper or lower triangular part of the
symmetric matrix A is stored:
= 'U': Upper triangular
= 'L': Lower triangular
N (input) INTEGER
The order of the matrix A. N >= 0.
A (input/output) REAL array, dimension (LDA,N)
On entry, the symmetric matrix A. If UPLO = 'U', the leading
n-by-n upper triangular part of A contains the upper
triangular part of the matrix A, and the strictly lower
triangular part of A is not referenced. If UPLO = 'L', the
leading n-by-n lower triangular part of A contains the lower
triangular part of the matrix A, and the strictly upper
triangular part of A is not referenced.
On exit, if UPLO = 'U', the diagonal and first superdiagonal
of A are overwritten by the corresponding elements of the
tridiagonal matrix T, and the elements above the first
superdiagonal, with the array TAU, represent the orthogonal
matrix Q as a product of elementary reflectors; if UPLO
= 'L', the diagonal and first subdiagonal of A are over-
written by the corresponding elements of the tridiagonal
matrix T, and the elements below the first subdiagonal, with
the array TAU, represent the orthogonal matrix Q as a product
of elementary reflectors. See Further Details.
LDA (input) INTEGER
The leading dimension of the array A. LDA >= max(1,N).
D (output) REAL array, dimension (N)
The diagonal elements of the tridiagonal matrix T:
D(i) = A(i,i).
E (output) REAL array, dimension (N-1)
The off-diagonal elements of the tridiagonal matrix T:
E(i) = A(i,i+1) if UPLO = 'U', E(i) = A(i+1,i) if UPLO = 'L'.
TAU (output) REAL array, dimension (N-1)
The scalar factors of the elementary reflectors (see Further
Details).
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value.
Further Details
===============
If UPLO = 'U', the matrix Q is represented as a product of elementary
reflectors
Q = H(n-1) . . . H(2) H(1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in
A(1:i-1,i+1), and tau in TAU(i).
If UPLO = 'L', the matrix Q is represented as a product of elementary
reflectors
Q = H(1) H(2) . . . H(n-1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i),
and tau in TAU(i).
The contents of A on exit are illustrated by the following examples
with n = 5:
if UPLO = 'U': if UPLO = 'L':
( d e v2 v3 v4 ) ( d )
( d e v3 v4 ) ( e d )
( d e v4 ) ( v1 e d )
( d e ) ( v1 v2 e d )
( d ) ( v1 v2 v3 e d )
where d and e denote diagonal and off-diagonal elements of T, and vi
denotes an element of the vector defining H(i).
=====================================================================
Test the input parameters
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__1 = 1;
static real c_b8 = 0.f;
static real c_b14 = -1.f;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset;
*/
int i__1, i__2, i__3;
/* Local variables */
static real taui;
extern doublereal sdot_(int *, real *, int *, real *, int *);
static int i;
extern /* Subroutine */ int ssyr2_(char *, int *, real *, real *,
int *, real *, int *, real *, int *);
static real alpha;
extern logical lsame_(char *, char *);
static logical upper;
extern /* Subroutine */ int saxpy_(int *, real *, real *, int *,
real *, int *), ssymv_(char *, int *, real *, real *,
int *, real *, int *, real *, real *, int *),
xerbla_(char *, int *), slarfg_(int *, real *,
real *, int *, real *);
/* Unused variable commented out by MDG on 03-09-05
int k;
*/
#define D(I) d[(I)-1]
#define E(I) e[(I)-1]
#define TAU(I) tau[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
*info = 0;
upper = lsame_(uplo, "U");
if (! upper && ! lsame_(uplo, "L")) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*lda < max(1,*n)) {
*info = -4;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SSYTD2", &i__1);
return 0;
}
/* Quick return if possible */
if (*n <= 0) {
return 0;
}
if (upper) {
/* Reduce the upper triangle of A */
for (i = *n - 1; i >= 1; --i) {
/* Generate elementary reflector H(i) = I - tau * v * v'
to annihilate A(1:i-1,i+1) */
slarfg_(&i, &A(i,i+1), &A(1,i+1), &
c__1, &taui);
E(i) = A(i,i+1);
if (taui != 0.f) {
/* Apply H(i) from both sides to A(1:i,1:i) */
A(i,i+1) = 1.f;
/* Compute x := tau * A * v storing x in TAU(1:
i) */
ssymv_(uplo, &i, &taui, &A(1,1), lda, &A(1,i+1), &c__1, &c_b8, &TAU(1), &c__1);
/* Compute w := x - 1/2 * tau * (x'*v) * v */
alpha = taui * -.5f * sdot_(&i, &TAU(1), &c__1, &A(1,i+1), &c__1);
saxpy_(&i, &alpha, &A(1,i+1), &c__1, &TAU(1), &
c__1);
/* Apply the transformation as a rank-2 update:
A := A - v * w' - w * v' */
ssyr2_(uplo, &i, &c_b14, &A(1,i+1), &c__1, &
TAU(1), &c__1, &A(1,1), lda);
A(i,i+1) = E(i);
}
D(i + 1) = A(i+1,i+1);
TAU(i) = taui;
/* L10: */
}
D(1) = A(1,1);
} else {
/* Reduce the lower triangle of A */
i__1 = *n - 1;
for (i = 1; i <= *n-1; ++i) {
/* Generate elementary reflector H(i) = I - tau * v * v'
to annihilate A(i+2:n,i) */
i__2 = *n - i;
/* Computing MIN */
i__3 = i + 2;
slarfg_(&i__2, &A(i+1,i), &A(min(i+2,*n),i), &c__1, &taui);
E(i) = A(i+1,i);
if (taui != 0.f) {
/* Apply H(i) from both sides to A(i+1:n,i+1:n)
*/
A(i+1,i) = 1.f;
/* Compute x := tau * A * v storing y in TAU(i:
n-1) */
i__2 = *n - i;
ssymv_(uplo, &i__2, &taui, &A(i+1,i+1), lda,
&A(i+1,i), &c__1, &c_b8, &TAU(i), &c__1);
/* Compute w := x - 1/2 * tau * (x'*v) * v */
i__2 = *n - i;
alpha = taui * -.5f * sdot_(&i__2, &TAU(i), &c__1, &A(i+1,i), &c__1);
i__2 = *n - i;
saxpy_(&i__2, &alpha, &A(i+1,i), &c__1, &TAU(i),
&c__1);
/* Apply the transformation as a rank-2 update:
A := A - v * w' - w * v' */
i__2 = *n - i;
ssyr2_(uplo, &i__2, &c_b14, &A(i+1,i), &c__1, &
TAU(i), &c__1, &A(i+1,i+1), lda);
A(i+1,i) = E(i);
}
D(i) = A(i,i);
TAU(i) = taui;
/* L20: */
}
D(*n) = A(*n,*n);
}
return 0;
/* End of SSYTD2 */
} /* ssytd2_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slaev2.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* UPDATED: 08/16/2009 by BBandini - gcc 4.4.1 won't compile math function
when passed a constant; one mod: sqrt(x20)
instead of sqrt(2.0).
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slaev2_(real *a, real *b, real *c, real *rt1, real *rt2,
real *cs1, real *sn1)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAEV2 computes the eigendecomposition of a 2-by-2 symmetric matrix
[ A B ]
[ B C ].
On return, RT1 is the eigenvalue of larger absolute value, RT2 is the
eigenvalue of smaller absolute value, and (CS1,SN1) is the unit right
eigenvector for RT1, giving the decomposition
[ CS1 SN1 ] [ A B ] [ CS1 -SN1 ] = [ RT1 0 ]
[-SN1 CS1 ] [ B C ] [ SN1 CS1 ] [ 0 RT2 ].
Arguments
=========
A (input) REAL
The (1,1) element of the 2-by-2 matrix.
B (input) REAL
The (1,2) element and the conjugate of the (2,1) element of
the 2-by-2 matrix.
C (input) REAL
The (2,2) element of the 2-by-2 matrix.
RT1 (output) REAL
The eigenvalue of larger absolute value.
RT2 (output) REAL
The eigenvalue of smaller absolute value.
CS1 (output) REAL
SN1 (output) REAL
The vector (CS1, SN1) is a unit right eigenvector for RT1.
Further Details
===============
RT1 is accurate to a few ulps barring over/underflow.
RT2 may be inaccurate if there is massive cancellation in the
determinant A*C-B*B; higher precision or correctly rounded or
correctly truncated arithmetic would be needed to compute RT2
accurately in all cases.
CS1 and SN1 are accurate to a few ulps barring over/underflow.
Overflow is possible only if RT1 is within a factor of 5 of overflow.
Underflow is harmless if the input data is 0 or exceeds
underflow_threshold / macheps.
=====================================================================
Compute the eigenvalues */
/* System generated locals */
real r__1;
/* Builtin functions */
double sqrt(doublereal);
/* Local variables */
static real acmn, acmx, ab, df, cs, ct, tb, sm, tn, rt, adf, acs;
static int sgn1, sgn2;
sm = *a + *c;
df = *a - *c;
adf = dabs(df);
tb = *b + *b;
ab = dabs(tb);
if (dabs(*a) > dabs(*c)) {
acmx = *a;
acmn = *c;
} else {
acmx = *c;
acmn = *a;
}
if (adf > ab) {
/* Computing 2nd power */
r__1 = ab / adf;
rt = adf * sqrt(r__1 * r__1 + 1.f);
} else if (adf < ab) {
/* Computing 2nd power */
r__1 = adf / ab;
rt = ab * sqrt(r__1 * r__1 + 1.f);
} else {
/* Includes case AB=ADF=0 */
float x20 = 2.f;
rt = ab * sqrt(x20);
}
if (sm < 0.f) {
*rt1 = (sm - rt) * .5f;
sgn1 = -1;
/* Order of execution important.
To get fully accurate smaller eigenvalue,
next line needs to be executed in higher precision. */
*rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b;
} else if (sm > 0.f) {
*rt1 = (sm + rt) * .5f;
sgn1 = 1;
/* Order of execution important.
To get fully accurate smaller eigenvalue,
next line needs to be executed in higher precision. */
*rt2 = acmx / *rt1 * acmn - *b / *rt1 * *b;
} else {
/* Includes case RT1 = RT2 = 0 */
*rt1 = rt * .5f;
*rt2 = rt * -.5f;
sgn1 = 1;
}
/* Compute the eigenvector */
if (df >= 0.f) {
cs = df + rt;
sgn2 = 1;
} else {
cs = df - rt;
sgn2 = -1;
}
acs = dabs(cs);
if (acs > ab) {
ct = -(doublereal)tb / cs;
*sn1 = 1.f / sqrt(ct * ct + 1.f);
*cs1 = ct * *sn1;
} else {
if (ab == 0.f) {
*cs1 = 1.f;
*sn1 = 0.f;
} else {
tn = -(doublereal)cs / tb;
*cs1 = 1.f / sqrt(tn * tn + 1.f);
*sn1 = tn * *cs1;
}
}
if (sgn1 == sgn2) {
tn = *cs1;
*cs1 = -(doublereal)(*sn1);
*sn1 = tn;
}
return 0;
/* End of SLAEV2 */
} /* slaev2_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/ihead/parsihdr.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IHEAD - IHead Image Utilities
FILE: PARSIHDR.C
AUTHOR: <NAME>
DATE: 11/30/1989
UPDATED: 03/14/2005 by MDG
Contains routines responsible for parsing information stored
in an IHead header's ID field.
ROUTINES:
#cat: parseihdrid - takes the identity attribute from an hsf box image
#cat: and parses out the box index and the reference string.
***********************************************************************/
#include <stdio.h>
#include <ihead.h>
/*******************************************************/
/* Routine: ParseIhdrID() */
/* Author: <NAME> */
/* Date: 11/30/89 */
/*******************************************************/
/* Parseihdrid() takes a ihead id string and parses out*/
/* the index number and reference string. */
/*******************************************************/
void parseihdrid(char *id, char *indxstr, char *refstr)
{
char *iptr;
iptr = id;
/* EDIT MDG 1/25/99
while((*iptr != NULL) && (*iptr != '_'))
*/
while((*iptr != '\0') && (*iptr != '_'))
iptr++;
/* EDIT MDG 1/25/99
if(*iptr == NULL){
*/
if(*iptr == '\0'){
/* start search for ref from beginning */
iptr = id;
}
else{
++iptr;
/* EDIT MDG 1/25/99
while((*iptr != NULL) && (*iptr != '.'))
*/
while((*iptr != '\0') && (*iptr != '.'))
*indxstr++ = *iptr++;
}
/* EDIT MDG 1/25/99
*indxstr = NULL;
*/
*indxstr = '\0';
/* EDIT MDG 1/25/99
while((*iptr != NULL) && (*iptr != '\"'))
*/
while((*iptr != '\0') && (*iptr != '\"'))
iptr++;
/* EDIT MDG 1/25/99
if(*iptr != NULL){
*/
if(*iptr != '\0'){
++iptr;
/* EDIT MDG 1/25/99
while((*iptr != NULL) && (*iptr != '\"'))
*/
while((*iptr != '\0') && (*iptr != '\"'))
*refstr++ = *iptr++;
}
/* EDIT MDG 1/25/99
*refstr = NULL;
*/
*refstr = '\0';
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/bincopy.c
|
<reponame>ThalesGroup/WSQForAndroid<filename>library/src/main/cpp/nbis/imgtools/src/lib/image/bincopy.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: BINCOPY.C
AUTHORS: <NAME>
DATE: 11/16/1990
UPDATED: 03/14/2005 by MDG
Contains routines responsible for copying a specified subimage
of a binary image bitmap.
ROUTINES:
#cat: binary_subimage_copy_8 - copies a binary subimage that is a multiple
#cat: of 8 bits wide.
#cat: binary_subimage_copy_gt - special condition when copying a
#cat: binary subimage.
#cat: binary_subimage_copy_lt - special condition when copying a
#cat: binary subimage.
#cat: binary_subimage_copy_eq - special condition when copying a
#cat: binary subimage.
#cat: binary_subimage_copy - copies a binary subimage to another image
#cat: at a specified location.
***********************************************************************/
/* LINTLIBRARY */
#include <stdio.h>
#include <memory.h>
#include <limits.h>
#include <masks.h>
#include <bitmasks.h>
#include <bits.h>
#include <binops.h>
#include <util.h>
void binary_subimage_copy_8 (
register unsigned char *src, int srcw, int srch,
register unsigned char *dst, int dstw, int dsth,
int srcx, int srcy,
int cpw, int cph,
int dstx, int dsty
)
{
int i, j, i_inv, j_inv, cpbw, srcbw, dstbw, dx, dy;
unsigned char m0, m1, m2;
register int bytes;
register unsigned char c;
if (src == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_8","Null source image pointer",(char *)NULL);
if (dst == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_8","Null destination image pointer",(char *)NULL);
if ((srcw < 0) || (srch < 0))
fatalerr("binary_subimage_copy_8","Negative source image dimension(s)",(char *)NULL);
if ((dstw < 0) || (dsth < 0))
fatalerr("binary_subimage_copy_8","Negative destination image dimension(s)",(char *)NULL);
if ((cpw < 0) || (cph < 0))
fatalerr("binary_subimage_copy_8","Negative subimage dimension(s)",(char *)NULL);
if (srcw % BITSPERBYTE)
fatalerr("binary_subimage_copy_8",
"Source image width must be a multiple of 8",(char *)NULL);
if (dstw % BITSPERBYTE)
fatalerr("binary_subimage_copy_8",
"Destination image width must be byte aligned",(char *)NULL);
if (((srcx + cpw) > srcw) || ((srcy + cph) > srch))
fatalerr("binary_subimage_copy_8",
"Subimage exceeds source image dimension(s)",(char *)NULL);
if (((dstx + cpw) > dstw) || ((dsty + cph) > dsth))
fatalerr("binary_subimage_copy_8",
"Subimage exceeds destination image dimension(s)",(char *)NULL);
if (!cpw || !cph)
return;
if (!srcw || !srch)
return;
if (!dstw || !dsth)
return;
i = srcx % BITSPERBYTE;
i_inv = BITSPERBYTE - i;
j = dstx % BITSPERBYTE;
j_inv = BITSPERBYTE - j;
if (cpw % BITSPERBYTE)
fatalerr("binary_subimage_copy_8",
"Copy width not a multiple of eight",(char *)NULL);
srcbw = srcw / BITSPERBYTE;
dstbw = dstw / BITSPERBYTE;
cpbw = cpw / BITSPERBYTE;
/* Increment src to the byte in the upper left corner of the */
/* subimage to be copied. Increment dst to the upper left corner */
/* of the byte in the destination that will be modified. */
src += srcy * srcbw + srcx / BITSPERBYTE;
dst += dsty * dstbw + dstx / BITSPERBYTE;
/* Set dx (dy) to be the increment needed to get src (dst) to the */
/* first byte in the next scan line to be copied (or modified) from */
/* the last byte in the current scan line. */
dx = srcbw - cpbw;
dy = dstbw - cpbw;
if (!i && !j) { /* Both src & dst are byte-aligned. */
while (cph--) {
bytes = cpbw;
while (bytes--)
*dst++ = *src++;
src += dx;
dst += dy;
}
return;
}
if (!j) { /* Dst is byte-aligned. */
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = (*src << i) | (*(src+1) >> i_inv);
*dst++ = c;
src++;
}
src += dx;
dst += dy;
}
return;
}
if (!i) { /* Src is byte-aligned. */
m1 = mask_end_0[j_inv]; /* eg. 11110000 */
m2 = mask_begin_0[j]; /* eg. 00001111 */
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = *src++;
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
}
;
src += dx;
dst += dy;
}
return;
}
if (i == j) {
m0 = mask_begin_1[i];
m1 = mask_end_0[i_inv];
m2 = mask_end_1[i_inv];
/* Neither src nor dst is byte-aligned, but they */
/* are offset by the same amount, so we can copy */
/* (cpbw - 1) bytes directly from src to dst. The */
/* bits in the other byte are on the ends of the */
/* scan line and are treated specially. */
if (cpbw == 1) {
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
*dst = (*dst & m2) | (*src & m0);
;
src += dx;
dst += dy;
}
return;
}
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
bytes = cpbw - 1;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m2) | (*src & m0);
;
src += dx;
dst += dy;
}
return;
}
m1 = mask_end_0[j_inv]; /* eg. 11111000 */
m2 = mask_begin_0[j]; /* eg. 00000111 */
while (cph--) { /* The absolute worst case. Neither */
bytes = cpbw; /* src nor dst is byte-aligned, and */
while (bytes--) { /* they are offset by diff. amounts. */
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
src++;
}
;
src += dx;
dst += dy;
}
}
/* LINTLIBRARY */
/****************************************************************/
/* */
/* Routines: binary_subimage_<op>_8() */
/* binary_subimage_<op>_gt() */
/* binary_subimage_<op>_lt() */
/* binary_subimage_<op>_eq() */
/* where <op> is copy, and, or, */
/* xor, invert, zero, or one */
/* */
/* Author: <NAME> */
/* Date: 11/16/90 */
/* */
/* binary_subimage_copy_8() is a bit-level copy utility for */
/* subimages that are a multiple of 8 bits wide. */
/* binary_subimage_copy_{gt,lt,eq}() are bit-level copy */
/* utilities for subimages that are not a multiple of 8 */
/* bits wide and where the space remaining in the last */
/* byte in every destination scan line will be (respect- */
/* ively) greater than, less than, or equal to the */
/* number of bits by which the subimage width exceeds 8. */
/* If binary_subimage_copy() is told to copy a subimage */
/* that is a multiple of 8 bits wide, it calls */
/* binary_subimage_copy_8(). Otherwise it calls one of */
/* the other functions as appropriate. */
/* binary_subimage_or_8() is a bit-level logical or utility for */
/* subimages that are a multiple of 8 bits wide. */
/* binary_subimage_{or,and,xor,invert}_{8,gt,lt,eq}() are */
/* bit-level logical or, and, xor and invert utilities for */
/* subimages that are analogous to the copy utilities */
/* described above. */
/* binary_subimage_{zero,one}_{8,gt,lt,eq} are bit-level util- */
/* ities for setting all bits in a subimage to zero and */
/* one, respectively. */
/* All dimensions are taken to be in bit units. */
/****************************************************************/
void binary_subimage_copy_gt (
register unsigned char *src, int srcw, int srch,
register unsigned char *dst, int dstw, int dsth,
int srcx, int srcy,
int cpw, int cph,
int dstx, int dsty
)
{
int i, j, i_inv, j_inv, cpbw, srcbw, dstbw, dx, dy;
unsigned char m0, m1, m2;
register int bytes;
register unsigned char c;
unsigned char m3, m4;
int b, b_inv, diff;
if (src == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_gt","Null source image pointer",(char *)NULL);
if (dst == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_gt","Null destination image pointer",(char *)NULL);
if ((srcw < 0) || (srch < 0))
fatalerr("binary_subimage_copy_gt","Negative source image dimension(s)",(char *)NULL);
if ((dstw < 0) || (dsth < 0))
fatalerr("binary_subimage_copy_gt","Negative destination image dimension(s)",(char *)NULL);
if ((cpw < 0) || (cph < 0))
fatalerr("binary_subimage_copy_gt","Negative subimage dimension(s)",(char *)NULL);
if (srcw % BITSPERBYTE)
fatalerr("binary_subimage_copy_gt",
"Source image width must be a multiple of 8",(char *)NULL);
if (dstw % BITSPERBYTE)
fatalerr("binary_subimage_copy_gt",
"Destination image width must be byte aligned",(char *)NULL);
if (((srcx + cpw) > srcw) || ((srcy + cph) > srch))
fatalerr("binary_subimage_copy_gt",
"Subimage exceeds source image dimension(s)",(char *)NULL);
if (((dstx + cpw) > dstw) || ((dsty + cph) > dsth))
fatalerr("binary_subimage_copy_gt",
"Subimage exceeds destination image dimension(s)",(char *)NULL);
if (!cpw || !cph)
return;
if (!srcw || !srch)
return;
if (!dstw || !dsth)
return;
i = srcx % BITSPERBYTE;
i_inv = BITSPERBYTE - i;
j = dstx % BITSPERBYTE;
j_inv = BITSPERBYTE - j;
b = cpw % BITSPERBYTE;
b_inv = BITSPERBYTE - b;
diff = j_inv - b;
if (diff <= 0)
fatalerr("binary_subimage_copy_gt","bad diff",(char *)NULL);
srcbw = srcw / BITSPERBYTE;
dstbw = dstw / BITSPERBYTE;
cpbw = cpw / BITSPERBYTE;
/* Increment src to the byte in the upper left corner of the */
/* subimage to be copied. Increment dst to the upper left corner */
/* of the byte in the destination that will be modified. */
src += srcy * srcbw + srcx / BITSPERBYTE;
dst += dsty * dstbw + dstx / BITSPERBYTE;
/* Set dx (dy) to be the increment needed to get src (dst) to the */
/* first byte in the next scan line to be copied (or modified) from */
/* the last byte in the current scan line. */
dx = srcbw - cpbw;
dy = dstbw - cpbw;
if (!i && !j) { /* Both src & dst are byte-aligned. */
m3 = mask_end_1[b_inv]; /* eg. 00000111 */
m4 = mask_begin_1[b]; /* eg. 11111000 */
while (cph--) {
bytes = cpbw;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m3) | (*src & m4);
src += dx;
dst += dy;
}
return;
}
if (!j) { /* Dst is byte-aligned. */
m3 = mask_end_1[b_inv]; /* eg. 00000111 */
m4 = mask_begin_1[b]; /* eg. 11111000 */
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = (*src << i) | (*(src+1) >> i_inv);
*dst++ = c;
src++;
}
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m3) | (c & m4);
src += dx;
dst += dy;
}
return;
}
if (!i) { /* Src is byte-aligned. */
m1 = mask_end_0[j_inv]; /* eg. 11110000 */
m2 = mask_begin_0[j]; /* eg. 00001111 */
if (diff > 0) {
/* j_inv > b */
m3 = m1 | mask_end_1[diff]; /* eg. 11110011 */
m4 = mask_end_0[diff]; /* eg. 11111100 */
} else if (diff) {
/* j_inv < b */
m3 = mask_end_1[BITSPERBYTE+diff]; /* eg. 00111111 */
m4 = mask_begin_1[-diff]; /* eg. 11000000 */
}
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = *src++;
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
}
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
if (i == j) {
m0 = mask_begin_1[i];
m1 = mask_end_0[i_inv];
m2 = mask_end_1[i_inv];
if (diff > 0) {
m3 = m1 | mask_end_1[diff];
m4 = mask_end_0[diff];
} else if (diff) {
m3 = mask_end_1[BITSPERBYTE+diff];
m4 = mask_begin_1[-diff];
}
/* Neither src nor dst is byte-aligned, but they */
/* are offset by the same amount, so we can copy */
/* (cpbw - 1) bytes directly from src to dst. The */
/* bits in the other byte are on the ends of the */
/* scan line and are treated specially. */
/* We don't need this case in binary_subimage_*_8(). If cpbw==0, */
/* then cpw was 0 and we would have already returned. */
if (! cpbw) {
while (cph--) {
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
if (cpbw == 1) {
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
*dst = (*dst & m2) | (*src & m0);
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
bytes = cpbw - 1;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m2) | (*src & m0);
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
m1 = mask_end_0[j_inv]; /* eg. 11111000 */
m2 = mask_begin_0[j]; /* eg. 00000111 */
if (diff > 0) {
m3 = m1 | mask_end_1[diff];
m4 = mask_end_0[diff];
} else if (diff) {
m3 = mask_end_1[BITSPERBYTE+diff];
m4 = mask_begin_1[-diff];
}
while (cph--) { /* The absolute worst case. Neither */
bytes = cpbw; /* src nor dst is byte-aligned, and */
while (bytes--) { /* they are offset by diff. amounts. */
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
src++;
}
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
}
/* LINTLIBRARY */
/****************************************************************/
/* */
/* Routines: binary_subimage_<op>_8() */
/* binary_subimage_<op>_gt() */
/* binary_subimage_<op>_lt() */
/* binary_subimage_<op>_eq() */
/* where <op> is copy, and, or, */
/* xor, invert, zero, or one */
/* */
/* Author: <NAME> */
/* Date: 11/16/90 */
/* */
/* binary_subimage_copy_8() is a bit-level copy utility for */
/* subimages that are a multiple of 8 bits wide. */
/* binary_subimage_copy_{gt,lt,eq}() are bit-level copy */
/* utilities for subimages that are not a multiple of 8 */
/* bits wide and where the space remaining in the last */
/* byte in every destination scan line will be (respect- */
/* ively) greater than, less than, or equal to the */
/* number of bits by which the subimage width exceeds 8. */
/* If binary_subimage_copy() is told to copy a subimage */
/* that is a multiple of 8 bits wide, it calls */
/* binary_subimage_copy_8(). Otherwise it calls one of */
/* the other functions as appropriate. */
/* binary_subimage_or_8() is a bit-level logical or utility for */
/* subimages that are a multiple of 8 bits wide. */
/* binary_subimage_{or,and,xor,invert}_{8,gt,lt,eq}() are */
/* bit-level logical or, and, xor and invert utilities for */
/* subimages that are analogous to the copy utilities */
/* described above. */
/* binary_subimage_{zero,one}_{8,gt,lt,eq} are bit-level util- */
/* ities for setting all bits in a subimage to zero and */
/* one, respectively. */
/* All dimensions are taken to be in bit units. */
/****************************************************************/
void binary_subimage_copy_lt (
register unsigned char *src, int srcw, int srch,
register unsigned char *dst, int dstw, int dsth,
int srcx, int srcy,
int cpw, int cph,
int dstx, int dsty
)
{
int i, j, i_inv, j_inv, cpbw, srcbw, dstbw, dx, dy;
unsigned char m0, m1, m2;
register int bytes;
register unsigned char c;
unsigned char m3, m4;
int b, b_inv, diff;
if (src == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_lt","Null source image pointer",(char *)NULL);
if (dst == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_lt","Null destination image pointer",(char *)NULL);
if ((srcw < 0) || (srch < 0))
fatalerr("binary_subimage_copy_lt","Negative source image dimension(s)",(char *)NULL);
if ((dstw < 0) || (dsth < 0))
fatalerr("binary_subimage_copy_lt","Negative destination image dimension(s)",(char *)NULL);
if ((cpw < 0) || (cph < 0))
fatalerr("binary_subimage_copy_lt","Negative subimage dimension(s)",(char *)NULL);
if (srcw % BITSPERBYTE)
fatalerr("binary_subimage_copy_lt",
"Source image width must be a multiple of 8",(char *)NULL);
if (dstw % BITSPERBYTE)
fatalerr("binary_subimage_copy_lt",
"Destination image width must be byte aligned",(char *)NULL);
if (((srcx + cpw) > srcw) || ((srcy + cph) > srch))
fatalerr("binary_subimage_copy_lt",
"Subimage exceeds source image dimension(s)",(char *)NULL);
if (((dstx + cpw) > dstw) || ((dsty + cph) > dsth))
fatalerr("binary_subimage_copy_lt",
"Subimage exceeds destination image dimension(s)",(char *)NULL);
if (!cpw || !cph)
return;
if (!srcw || !srch)
return;
if (!dstw || !dsth)
return;
i = srcx % BITSPERBYTE;
i_inv = BITSPERBYTE - i;
j = dstx % BITSPERBYTE;
j_inv = BITSPERBYTE - j;
b = cpw % BITSPERBYTE;
b_inv = BITSPERBYTE - b;
diff = j_inv - b;
if (diff >= 0)
fatalerr("binary_subimage_copy_lt","bad diff",(char *)NULL);
srcbw = srcw / BITSPERBYTE;
dstbw = dstw / BITSPERBYTE;
cpbw = cpw / BITSPERBYTE;
/* Increment src to the byte in the upper left corner of the */
/* subimage to be copied. Increment dst to the upper left corner */
/* of the byte in the destination that will be modified. */
src += srcy * srcbw + srcx / BITSPERBYTE;
dst += dsty * dstbw + dstx / BITSPERBYTE;
/* Set dx (dy) to be the increment needed to get src (dst) to the */
/* first byte in the next scan line to be copied (or modified) from */
/* the last byte in the current scan line. */
dx = srcbw - cpbw;
dy = dstbw - cpbw;
if (!i && !j) { /* Both src & dst are byte-aligned. */
m3 = mask_end_1[b_inv]; /* eg. 00000111 */
m4 = mask_begin_1[b]; /* eg. 11111000 */
while (cph--) {
bytes = cpbw;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m3) | (*src & m4);
src += dx;
dst += dy;
}
return;
}
if (!j) { /* Dst is byte-aligned. */
m3 = mask_end_1[b_inv]; /* eg. 00000111 */
m4 = mask_begin_1[b]; /* eg. 11111000 */
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = (*src << i) | (*(src+1) >> i_inv);
*dst++ = c;
src++;
}
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m3) | (c & m4);
src += dx;
dst += dy;
}
return;
}
if (!i) { /* Src is byte-aligned. */
m1 = mask_end_0[j_inv]; /* eg. 11110000 */
m2 = mask_begin_0[j]; /* eg. 00001111 */
if (diff > 0) {
/* j_inv > b */
m3 = m1 | mask_end_1[diff]; /* eg. 11110011 */
m4 = mask_end_0[diff]; /* eg. 11111100 */
} else if (diff) {
/* j_inv < b */
m3 = mask_end_1[BITSPERBYTE+diff]; /* eg. 00111111 */
m4 = mask_begin_1[-diff]; /* eg. 11000000 */
}
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = *src++;
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
}
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
if (i == j) {
m0 = mask_begin_1[i];
m1 = mask_end_0[i_inv];
m2 = mask_end_1[i_inv];
if (diff > 0) {
m3 = m1 | mask_end_1[diff];
m4 = mask_end_0[diff];
} else if (diff) {
m3 = mask_end_1[BITSPERBYTE+diff];
m4 = mask_begin_1[-diff];
}
/* Neither src nor dst is byte-aligned, but they */
/* are offset by the same amount, so we can copy */
/* (cpbw - 1) bytes directly from src to dst. The */
/* bits in the other byte are on the ends of the */
/* scan line and are treated specially. */
/* We don't need this case in binary_subimage_*_8(). If cpbw==0, */
/* then cpw was 0 and we would have already returned. */
if (! cpbw) {
while (cph--) {
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
if (cpbw == 1) {
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
*dst = (*dst & m2) | (*src & m0);
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
bytes = cpbw - 1;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m2) | (*src & m0);
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
m1 = mask_end_0[j_inv]; /* eg. 11111000 */
m2 = mask_begin_0[j]; /* eg. 00000111 */
if (diff > 0) {
m3 = m1 | mask_end_1[diff];
m4 = mask_end_0[diff];
} else if (diff) {
m3 = mask_end_1[BITSPERBYTE+diff];
m4 = mask_begin_1[-diff];
}
while (cph--) { /* The absolute worst case. Neither */
bytes = cpbw; /* src nor dst is byte-aligned, and */
while (bytes--) { /* they are offset by diff. amounts. */
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
src++;
}
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
}
/* LINTLIBRARY */
/****************************************************************/
/* */
/* Routines: binary_subimage_<op>_8() */
/* binary_subimage_<op>_gt() */
/* binary_subimage_<op>_lt() */
/* binary_subimage_<op>_eq() */
/* where <op> is copy, and, or, */
/* xor, invert, zero, or one */
/* */
/* Author: <NAME> */
/* Date: 11/16/90 */
/* */
/* binary_subimage_copy_8() is a bit-level copy utility for */
/* subimages that are a multiple of 8 bits wide. */
/* binary_subimage_copy_{gt,lt,eq}() are bit-level copy */
/* utilities for subimages that are not a multiple of 8 */
/* bits wide and where the space remaining in the last */
/* byte in every destination scan line will be (respect- */
/* ively) greater than, less than, or equal to the */
/* number of bits by which the subimage width exceeds 8. */
/* If binary_subimage_copy() is told to copy a subimage */
/* that is a multiple of 8 bits wide, it calls */
/* binary_subimage_copy_8(). Otherwise it calls one of */
/* the other functions as appropriate. */
/* binary_subimage_or_8() is a bit-level logical or utility for */
/* subimages that are a multiple of 8 bits wide. */
/* binary_subimage_{or,and,xor,invert}_{8,gt,lt,eq}() are */
/* bit-level logical or, and, xor and invert utilities for */
/* subimages that are analogous to the copy utilities */
/* described above. */
/* binary_subimage_{zero,one}_{8,gt,lt,eq} are bit-level util- */
/* ities for setting all bits in a subimage to zero and */
/* one, respectively. */
/* All dimensions are taken to be in bit units. */
/****************************************************************/
void binary_subimage_copy_eq (
register unsigned char *src, int srcw, int srch,
register unsigned char *dst, int dstw, int dsth,
int srcx, int srcy,
int cpw, int cph,
int dstx, int dsty
)
{
int i, j, i_inv, j_inv, cpbw, srcbw, dstbw, dx, dy;
unsigned char m0, m1, m2;
register int bytes;
register unsigned char c;
unsigned char m3, m4;
int b, b_inv, diff;
if (src == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_eq","Null source image pointer",(char *)NULL);
if (dst == (unsigned char *) NULL)
fatalerr("binary_subimage_copy_eq","Null destination image pointer",(char *)NULL);
if ((srcw < 0) || (srch < 0))
fatalerr("binary_subimage_copy_eq","Negative source image dimension(s)",(char *)NULL);
if ((dstw < 0) || (dsth < 0))
fatalerr("binary_subimage_copy_eq","Negative destination image dimension(s)",(char *)NULL);
if ((cpw < 0) || (cph < 0))
fatalerr("binary_subimage_copy_eq","Negative subimage dimension(s)",(char *)NULL);
if (srcw % BITSPERBYTE)
fatalerr("binary_subimage_copy_eq",
"Source image width must be a multiple of 8",(char *)NULL);
if (dstw % BITSPERBYTE)
fatalerr("binary_subimage_copy_eq",
"Destination image width must be byte aligned",(char *)NULL);
if (((srcx + cpw) > srcw) || ((srcy + cph) > srch))
fatalerr("binary_subimage_copy_eq",
"Subimage exceeds source image dimension(s)",(char *)NULL);
if (((dstx + cpw) > dstw) || ((dsty + cph) > dsth))
fatalerr("binary_subimage_copy_eq",
"Subimage exceeds destination image dimension(s)",(char *)NULL);
if (!cpw || !cph)
return;
if (!srcw || !srch)
return;
if (!dstw || !dsth)
return;
i = srcx % BITSPERBYTE;
i_inv = BITSPERBYTE - i;
j = dstx % BITSPERBYTE;
j_inv = BITSPERBYTE - j;
b = cpw % BITSPERBYTE;
b_inv = BITSPERBYTE - b;
diff = j_inv - b;
if (diff)
fatalerr("binary_subimage_copy_eq","bad diff",(char *)NULL);
srcbw = srcw / BITSPERBYTE;
dstbw = dstw / BITSPERBYTE;
cpbw = cpw / BITSPERBYTE;
/* Increment src to the byte in the upper left corner of the */
/* subimage to be copied. Increment dst to the upper left corner */
/* of the byte in the destination that will be modified. */
src += srcy * srcbw + srcx / BITSPERBYTE;
dst += dsty * dstbw + dstx / BITSPERBYTE;
/* Set dx (dy) to be the increment needed to get src (dst) to the */
/* first byte in the next scan line to be copied (or modified) from */
/* the last byte in the current scan line. */
dx = srcbw - cpbw;
dy = dstbw - cpbw;
if (!i && !j) { /* Both src & dst are byte-aligned. */
m3 = mask_end_1[b_inv]; /* eg. 00000111 */
m4 = mask_begin_1[b]; /* eg. 11111000 */
while (cph--) {
bytes = cpbw;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m3) | (*src & m4);
src += dx;
dst += dy;
}
return;
}
if (!j) { /* Dst is byte-aligned. */
m3 = mask_end_1[b_inv]; /* eg. 00000111 */
m4 = mask_begin_1[b]; /* eg. 11111000 */
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = (*src << i) | (*(src+1) >> i_inv);
*dst++ = c;
src++;
}
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m3) | (c & m4);
src += dx;
dst += dy;
}
return;
}
if (!i) { /* Src is byte-aligned. */
m1 = mask_end_0[j_inv]; /* eg. 11110000 */
m2 = mask_begin_0[j]; /* eg. 00001111 */
if (diff > 0) {
/* j_inv > b */
m3 = m1 | mask_end_1[diff]; /* eg. 11110011 */
m4 = mask_end_0[diff]; /* eg. 11111100 */
} else if (diff) {
/* j_inv < b */
m3 = mask_end_1[BITSPERBYTE+diff]; /* eg. 00111111 */
m4 = mask_begin_1[-diff]; /* eg. 11000000 */
}
while (cph--) {
bytes = cpbw;
while (bytes--) {
c = *src++;
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
}
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
if (i == j) {
m0 = mask_begin_1[i];
m1 = mask_end_0[i_inv];
m2 = mask_end_1[i_inv];
if (diff > 0) {
m3 = m1 | mask_end_1[diff];
m4 = mask_end_0[diff];
} else if (diff) {
m3 = mask_end_1[BITSPERBYTE+diff];
m4 = mask_begin_1[-diff];
}
/* Neither src nor dst is byte-aligned, but they */
/* are offset by the same amount, so we can copy */
/* (cpbw - 1) bytes directly from src to dst. The */
/* bits in the other byte are on the ends of the */
/* scan line and are treated specially. */
/* We don't need this case in binary_subimage_*_8(). If cpbw==0, */
/* then cpw was 0 and we would have already returned. */
if (! cpbw) {
while (cph--) {
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
if (cpbw == 1) {
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
*dst = (*dst & m2) | (*src & m0);
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
while (cph--) {
*dst = (*dst & m0) | (*src++ & m2);
dst++;
bytes = cpbw - 1;
while (bytes--)
*dst++ = *src++;
*dst = (*dst & m2) | (*src & m0);
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
return;
}
m1 = mask_end_0[j_inv]; /* eg. 11111000 */
m2 = mask_begin_0[j]; /* eg. 00000111 */
if (diff > 0) {
m3 = m1 | mask_end_1[diff];
m4 = mask_end_0[diff];
} else if (diff) {
m3 = mask_end_1[BITSPERBYTE+diff];
m4 = mask_begin_1[-diff];
}
while (cph--) { /* The absolute worst case. Neither */
bytes = cpbw; /* src nor dst is byte-aligned, and */
while (bytes--) { /* they are offset by diff. amounts. */
c = (*src << i) | (*(src+1) >> i_inv);
*dst = (*dst & m1) | (c >> j);
dst++;
*dst = (*dst & m2) | (c << j_inv);
src++;
}
binary_fill_partial(BINARY_COPY,src,i,dst,j,b);
src += dx;
dst += dy;
}
}
/* LINTLIBRARY */
/************************************************************/
/* */
/* Routines: binary_subimage_copy() */
/* binary_subimage_or() */
/* binary_subimage_and() */
/* binary_subimage_xor() */
/* binary_subimage_invert() */
/* binary_subimage_zero() */
/* binary_subimage_one() */
/* */
/* Author: <NAME> */
/* Date: 11/16/90 */
/* */
/* binary_subimage_copy() is an all-purpose bit-level copy */
/* utility. */
/* If the subimage to be copied is a multiple of 8 bits */
/* wide, it calls binary_subimage_copy_8(). Otherwise it */
/* calls one binary_subimage_copy_{gt,lt,eq}(). */
/* binary_subimage_copy_{gt,lt,eq}() are bit-level copy */
/* utilities for subimages that are not a multiple of 8 */
/* bits wide and where the space remaining in the last */
/* byte in every destination scan line will be (respect- */
/* ively) greater than, less than, or equal to the num- */
/* ber of bits by which the subimage width exceeds 8. */
/* binary_subimage_{or,and,xor,invert}() are all-purpose */
/* bit-level logical or, and, xor, and invert utilities */
/* that works analogously to the copier described above. */
/* binary_subimage_{zero,one}() are all-purpose bit-level */
/* utilities to set all bits in a subimage to zero and */
/* one, respectively. */
/* All dimensions are taken to be in bit units. */
/************************************************************/
void binary_subimage_copy (
register unsigned char *src, int srcw, int srch,
register unsigned char *dst, int dstw, int dsth,
int srcx, int srcy,
int cpw, int cph,
int dstx, int dsty
)
{
register int j_inv, b, diff;
if (src == (unsigned char *) NULL)
fatalerr("binary_subimage_copy",
"Null source image pointer",(char *)NULL);
if (dst == (unsigned char *) NULL)
fatalerr("binary_subimage_copy",
"Null destination image pointer",(char *)NULL);
if ((srcw < 0) || (srch < 0))
fatalerr("binary_subimage_copy",
"Negative source image dimension(s)",(char *)NULL);
if ((dstw < 0) || (dsth < 0))
fatalerr("binary_subimage_copy",
"Negative destination image dimension(s)",(char *)NULL);
if ((cpw < 0) || (cph < 0))
fatalerr("binary_subimage_copy",
"Negative subimage dimension(s)",(char *)NULL);
if (srcw % BITSPERBYTE)
fatalerr("binary_subimage_copy",
"Source data width must be a multiple of 8",(char *)NULL);
if (dstw % BITSPERBYTE)
fatalerr("binary_subimage_copy",
"Destination data width must be a multiple of 8",(char *)NULL);
if (((srcx + cpw) > srcw) || ((srcy + cph) > srch))
fatalerr("binary_subimage_copy",
"Source bit addresses exceed data range",(char *)NULL);
if (((dstx + cpw) > dstw) || ((dsty + cph) > dsth))
fatalerr("binary_subimage_copy",
"Destination bit addresses exceed data range",(char *)NULL);
if (!cpw || !cph)
return;
if (!srcw || !srch)
return;
if (!dstw || !dsth)
return;
b = cpw % BITSPERBYTE;
if (!b) {
binary_subimage_copy_8(src,srcw,srch,
dst,dstw,dsth,
srcx,srcy,cpw,cph,dstx,dsty);
return;
}
j_inv = BITSPERBYTE - dstx % BITSPERBYTE;
diff = j_inv - b;
if (diff > 0) {
binary_subimage_copy_gt(src,srcw,srch,
dst,dstw,dsth,
srcx,srcy,cpw,cph,dstx,dsty);
return;
}
if (diff < 0) {
binary_subimage_copy_lt(src,srcw,srch,
dst,dstw,dsth,
srcx,srcy,cpw,cph,dstx,dsty);
return;
}
binary_subimage_copy_eq(src,srcw,srch,
dst,dstw,dsth,
srcx,srcy,cpw,cph,dstx,dsty);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/cblas/strmm.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Source for module STRMM.C from package CBLAS.
* Retrieved from NETLIB on Tue Mar 14 10:53:42 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
/* -- translated by f2c (version 19940927).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include <f2c.h>
/* Subroutine */ int strmm_(char *side, char *uplo, char *transa, char *diag,
int *m, int *n, real *alpha, real *a, int *lda, real *b,
int *ldb)
{
/* System generated locals */
/* Unused variable commented out by MDG on 03-09-05
int a_dim1, a_offset, b_dim1, b_offset;
*/
int i__1, i__2, i__3;
/* Local variables */
static int info;
static real temp;
static int i, j, k;
static logical lside;
extern logical lsame_(char *, char *);
static int nrowa;
static logical upper;
extern /* Subroutine */ int xerbla_(char *, int *);
static logical nounit;
/* Purpose
=======
STRMM performs one of the matrix-matrix operations
B := alpha*op( A )*B, or B := alpha*B*op( A ),
where alpha is a scalar, B is an m by n matrix, A is a unit, or
non-unit, upper or lower triangular matrix and op( A ) is one of
op( A ) = A or op( A ) = A'.
Parameters
==========
SIDE - CHARACTER*1.
On entry, SIDE specifies whether op( A ) multiplies B from
the left or right as follows:
SIDE = 'L' or 'l' B := alpha*op( A )*B.
SIDE = 'R' or 'r' B := alpha*B*op( A ).
Unchanged on exit.
UPLO - CHARACTER*1.
On entry, UPLO specifies whether the matrix A is an upper or
lower triangular matrix as follows:
UPLO = 'U' or 'u' A is an upper triangular matrix.
UPLO = 'L' or 'l' A is a lower triangular matrix.
Unchanged on exit.
TRANSA - CHARACTER*1.
On entry, TRANSA specifies the form of op( A ) to be used in
the matrix multiplication as follows:
TRANSA = 'N' or 'n' op( A ) = A.
TRANSA = 'T' or 't' op( A ) = A'.
TRANSA = 'C' or 'c' op( A ) = A'.
Unchanged on exit.
DIAG - CHARACTER*1.
On entry, DIAG specifies whether or not A is unit triangular
as follows:
DIAG = 'U' or 'u' A is assumed to be unit triangular.
DIAG = 'N' or 'n' A is not assumed to be unit
triangular.
Unchanged on exit.
M - INTEGER.
On entry, M specifies the number of rows of B. M must be at
least zero.
Unchanged on exit.
N - INTEGER.
On entry, N specifies the number of columns of B. N must be
at least zero.
Unchanged on exit.
ALPHA - REAL .
On entry, ALPHA specifies the scalar alpha. When alpha is
zero then A is not referenced and B need not be set before
entry.
Unchanged on exit.
A - REAL array of DIMENSION ( LDA, k ), where k is m
when SIDE = 'L' or 'l' and is n when SIDE = 'R' or 'r'.
Before entry with UPLO = 'U' or 'u', the leading k by k
upper triangular part of the array A must contain the upper
triangular matrix and the strictly lower triangular part of
A is not referenced.
Before entry with UPLO = 'L' or 'l', the leading k by k
lower triangular part of the array A must contain the lower
triangular matrix and the strictly upper triangular part of
A is not referenced.
Note that when DIAG = 'U' or 'u', the diagonal elements of
A are not referenced either, but are assumed to be unity.
Unchanged on exit.
LDA - INTEGER.
On entry, LDA specifies the first dimension of A as declared
in the calling (sub) program. When SIDE = 'L' or 'l' then
LDA must be at least max( 1, m ), when SIDE = 'R' or 'r'
then LDA must be at least max( 1, n ).
Unchanged on exit.
B - REAL array of DIMENSION ( LDB, n ).
Before entry, the leading m by n part of the array B must
contain the matrix B, and on exit is overwritten by the
transformed matrix.
LDB - INTEGER.
On entry, LDB specifies the first dimension of B as declared
in the calling (sub) program. LDB must be at least
max( 1, m ).
Unchanged on exit.
Level 3 Blas routine.
-- Written on 8-February-1989.
<NAME>, Argonne National Laboratory.
<NAME>, <NAME>.
<NAME>, Numerical Algorithms Group Ltd.
<NAME>, Numerical Algorithms Group Ltd.
Test the input parameters.
Parameter adjustments
Function Body */
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
#define B(I,J) b[(I)-1 + ((J)-1)* ( *ldb)]
lside = lsame_(side, "L");
if (lside) {
nrowa = *m;
} else {
nrowa = *n;
}
nounit = lsame_(diag, "N");
upper = lsame_(uplo, "U");
info = 0;
if (! lside && ! lsame_(side, "R")) {
info = 1;
} else if (! upper && ! lsame_(uplo, "L")) {
info = 2;
} else if (! lsame_(transa, "N") && ! lsame_(transa, "T")
&& ! lsame_(transa, "C")) {
info = 3;
} else if (! lsame_(diag, "U") && ! lsame_(diag, "N")) {
info = 4;
} else if (*m < 0) {
info = 5;
} else if (*n < 0) {
info = 6;
} else if (*lda < max(1,nrowa)) {
info = 9;
} else if (*ldb < max(1,*m)) {
info = 11;
}
if (info != 0) {
xerbla_("STRMM ", &info);
return 0;
}
/* Quick return if possible. */
if (*n == 0) {
return 0;
}
/* And when alpha.eq.zero. */
if (*alpha == 0.f) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) = 0.f;
/* L10: */
}
/* L20: */
}
return 0;
}
/* Start the operations. */
if (lside) {
if (lsame_(transa, "N")) {
/* Form B := alpha*A*B. */
if (upper) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (k = 1; k <= *m; ++k) {
if (B(k,j) != 0.f) {
temp = *alpha * B(k,j);
i__3 = k - 1;
for (i = 1; i <= k-1; ++i) {
B(i,j) += temp * A(i,k);
/* L30: */
}
if (nounit) {
temp *= A(k,k);
}
B(k,j) = temp;
}
/* L40: */
}
/* L50: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
for (k = *m; k >= 1; --k) {
if (B(k,j) != 0.f) {
temp = *alpha * B(k,j);
B(k,j) = temp;
if (nounit) {
B(k,j) *= A(k,k);
}
i__2 = *m;
for (i = k + 1; i <= *m; ++i) {
B(i,j) += temp * A(i,k);
/* L60: */
}
}
/* L70: */
}
/* L80: */
}
}
} else {
/* Form B := alpha*B*A'. */
if (upper) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
for (i = *m; i >= 1; --i) {
temp = B(i,j);
if (nounit) {
temp *= A(i,i);
}
i__2 = i - 1;
for (k = 1; k <= i-1; ++k) {
temp += A(k,i) * B(k,j);
/* L90: */
}
B(i,j) = *alpha * temp;
/* L100: */
}
/* L110: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp = B(i,j);
if (nounit) {
temp *= A(i,i);
}
i__3 = *m;
for (k = i + 1; k <= *m; ++k) {
temp += A(k,i) * B(k,j);
/* L120: */
}
B(i,j) = *alpha * temp;
/* L130: */
}
/* L140: */
}
}
}
} else {
if (lsame_(transa, "N")) {
/* Form B := alpha*B*A. */
if (upper) {
for (j = *n; j >= 1; --j) {
temp = *alpha;
if (nounit) {
temp *= A(j,j);
}
i__1 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) = temp * B(i,j);
/* L150: */
}
i__1 = j - 1;
for (k = 1; k <= j-1; ++k) {
if (A(k,j) != 0.f) {
temp = *alpha * A(k,j);
i__2 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) += temp * B(i,k);
/* L160: */
}
}
/* L170: */
}
/* L180: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
temp = *alpha;
if (nounit) {
temp *= A(j,j);
}
i__2 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) = temp * B(i,j);
/* L190: */
}
i__2 = *n;
for (k = j + 1; k <= *n; ++k) {
if (A(k,j) != 0.f) {
temp = *alpha * A(k,j);
i__3 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) += temp * B(i,k);
/* L200: */
}
}
/* L210: */
}
/* L220: */
}
}
} else {
/* Form B := alpha*B*A'. */
if (upper) {
i__1 = *n;
for (k = 1; k <= *n; ++k) {
i__2 = k - 1;
for (j = 1; j <= k-1; ++j) {
if (A(j,k) != 0.f) {
temp = *alpha * A(j,k);
i__3 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) += temp * B(i,k);
/* L230: */
}
}
/* L240: */
}
temp = *alpha;
if (nounit) {
temp *= A(k,k);
}
if (temp != 1.f) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
B(i,k) = temp * B(i,k);
/* L250: */
}
}
/* L260: */
}
} else {
for (k = *n; k >= 1; --k) {
i__1 = *n;
for (j = k + 1; j <= *n; ++j) {
if (A(j,k) != 0.f) {
temp = *alpha * A(j,k);
i__2 = *m;
for (i = 1; i <= *m; ++i) {
B(i,j) += temp * B(i,k);
/* L270: */
}
}
/* L280: */
}
temp = *alpha;
if (nounit) {
temp *= A(k,k);
}
if (temp != 1.f) {
i__1 = *m;
for (i = 1; i <= *m; ++i) {
B(i,k) = temp * B(i,k);
/* L290: */
}
}
/* L300: */
}
}
}
}
return 0;
/* End of STRMM . */
} /* strmm_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slarnv.c
|
<filename>library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slarnv.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slarnv_(int *idist, int *iseed, int *n, real
*x)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SLARNV returns a vector of n random real numbers from a uniform or
normal distribution.
Arguments
=========
IDIST (input) INTEGER
Specifies the distribution of the random numbers:
= 1: uniform (0,1)
= 2: uniform (-1,1)
= 3: normal (0,1)
ISEED (input/output) INTEGER array, dimension (4)
On entry, the seed of the random number generator; the array
elements must be between 0 and 4095, and ISEED(4) must be
odd.
On exit, the seed is updated.
N (input) INTEGER
The number of random numbers to be generated.
X (output) REAL array, dimension (N)
The generated random numbers.
Further Details
===============
This routine calls the auxiliary routine SLARUV to generate random
real numbers from a uniform (0,1) distribution, in batches of up to
128 using vectorisable code. The Box-Muller method is used to
transform numbers from a uniform to a normal distribution.
=====================================================================
Parameter adjustments
Function Body */
/* System generated locals */
int i__1, i__2, i__3;
/* Builtin functions */
double log(doublereal), sqrt(doublereal), cos(doublereal);
/* Local variables */
static int i;
static real u[128];
static int il, iv, il2;
extern /* Subroutine */ int slaruv_(int *, int *, real *);
#define X(I) x[(I)-1]
#define ISEED(I) iseed[(I)-1]
i__1 = *n;
for (iv = 1; iv <= *n; iv += 64) {
/* Computing MIN */
i__2 = 64, i__3 = *n - iv + 1;
il = min(i__2,i__3);
if (*idist == 3) {
il2 = il << 1;
} else {
il2 = il;
}
/* Call SLARUV to generate IL2 numbers from a uniform (0,1)
distribution (IL2 <= LV) */
slaruv_(&ISEED(1), &il2, u);
if (*idist == 1) {
/* Copy generated numbers */
i__2 = il;
for (i = 1; i <= il; ++i) {
X(iv + i - 1) = u[i - 1];
/* L10: */
}
} else if (*idist == 2) {
/* Convert generated numbers to uniform (-1,1) distribut
ion */
i__2 = il;
for (i = 1; i <= il; ++i) {
X(iv + i - 1) = u[i - 1] * 2.f - 1.f;
/* L20: */
}
} else if (*idist == 3) {
/* Convert generated numbers to normal (0,1) distributio
n */
i__2 = il;
for (i = 1; i <= il; ++i) {
X(iv + i - 1) = sqrt(log(u[(i << 1) - 2]) * -2.f) * cos(u[(i
<< 1) - 1] * 6.2831853071795864769252867663f);
/* L30: */
}
}
/* L40: */
}
return 0;
/* End of SLARNV */
} /* slarnv_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/grp4deco.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: GRP4DECO.C
AUTHORS: CALS Test Network
DATE: 01/25/1990
Contains routines responsible for CCITT Group 4 encoding
a binary image pixel datastream.
ROUTINES:
#cat: grp4decomp - decodes and reconstructs a CCITT Group 4 compressed
#cat: binary image (bitmap).
***********************************************************************/
/********************************************************************
* Modified: <NAME> *
* <NAME> *
* Date: January 25, 1990 *
* Updated: 03/14/2005 by MDG *
* Package: CCITT4 compression routines *
* *
* Contents: ccitt4_decompress() *
* read_compressed_file_into_memory() *
* control_decompression() *
* prepare_to_decompress() *
* set_up_first_and_last_changing_elements_d() *
* prepare_to_decompress_next_line() *
* set_up_first_line_d() *
* crash_d() *
********************************************************************/
#include <grp4deco.h>
#ifdef TIME
#include <sys/time.h>
#endif
#define NOALLOC 0
#define ALLOC 1
int decomp_alloc_flag;
int decomp_write_init_flag;
int decomp_read_init_flag;
static char *all_white,
*output_area,
*all_black;
#ifdef TIME
struct timeval t1, t2;
struct timezone tz;
#endif
/********************************************************************
* grp4decomp is the main routine of this file. It does pre- *
* liminary setup, calls routines, and does final processing. *
********************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* indata - buffer containing the compressed data. *
* inbytes - the number of bytes in indata. *
* width - Width in pixels of uncompressed data. *
* height - Number of lines of uncompressed data. *
* Returned: *
* outdata - buffer containing the decompressed data*
* outbytes - the number of bytes in outdata. *
********************************************************************/
void grp4decomp(unsigned char *indata, int inbytes, int width, int height,
unsigned char *outdata, int *outbytes)
{
struct compressed_descriptor compressed;
struct decompressed_descriptor decompressed;
compressed.pixels_per_line = width;
compressed.number_of_lines = height;
compressed.length_in_bytes = inbytes;
compressed.data = (char *)indata;
decomp_alloc_flag = NOALLOC;
decomp_write_init_flag = True;
decomp_read_init_flag = True;
read_compressed_file_into_memory(&compressed);
decompressed.data = (char *)outdata;
control_decompression( &compressed, &decompressed );
*outbytes =
(decompressed.pixels_per_line >> 3) * decompressed.number_of_lines;
}
/***************************** control_decompression **************************
calls the functions that decompress the compressed file
*****************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* compressed - structure containing the # of *
* pixels per line, the number of *
* lines, and the compressed data. *
* Returned: *
* decompressed - structure containing the # of *
* pixels per line, the number of *
* lines, and the compressed data. *
********************************************************************/
void control_decompression( struct compressed_descriptor *compressed,
struct decompressed_descriptor *decompressed )
{
struct parameters sole_parameters;
struct parameters *params = &sole_parameters;
#ifdef TIME
SHORT i;
tz.tz_minuteswest = 0;
tz.tz_dsttime = 0;
gettimeofday(&t1, &tz);
#endif
prepare_to_decompress( compressed, decompressed, params );
while(decompress_line( params ) != EOFB )
prepare_to_decompress_next_line( params );
/* memory deallocation added by <NAME> 2/23/90 */
free(params->reference_line);
free(params->coding_line);
free(all_white);
free(all_black);
#ifdef TIME
gettimeofday(&t2, &tz);
printf("\ntime difference: %ld:%ld\n", t2.tv_sec - t1.tv_sec,
t2.tv_usec - t1.tv_usec);
for(i=0; i<5; i++) printf("%c",'\07');
#endif
}
/************************ read_compressed_file_into_memory *********************
allocates memory for the compressed image
*****************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* compressed - structure containing the # of *
* pixels per line, the number of *
* lines, and the compressed data. *
* Returned: *
* compressed - structure containing the # of *
* pixels per line, the number of *
* lines, and the compressed data. *
********************************************************************/
void read_compressed_file_into_memory(struct compressed_descriptor *compressed)
{
if(decomp_alloc_flag){
if((compressed->data = (char *)calloc(compressed->length_in_bytes,
sizeof(char))) == NULL) {
printf("\nCannot allocate enough memory for compressed file.\n");
exit(1);
}
}
else
if(compressed->data == NULL){
printf("\nNo memory allocated for input data!\n");
exit(1);
}
} /* end read_compressed_file_into_memory() */
/*************************** prepare_to_decompress ****************************
initializes variables in preperation for decompression
*****************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* compressed - structure containing the # of *
* pixels per line, the number of *
* lines, and the compressed data. *
* Returned: *
* decompressed - structure containing the # of *
* pixels per line, the number of *
* lines, and the compressed data. *
* params - structure storing information needed *
* for comparison and other tasks. *
********************************************************************/
void prepare_to_decompress(struct compressed_descriptor *compressed,
struct decompressed_descriptor *decompressed,
struct parameters *params)
{
params->max_pixel = compressed->pixels_per_line;
decompressed->pixels_per_line = compressed->pixels_per_line;
decompressed->number_of_lines = compressed->number_of_lines;
set_up_first_line_d( params );
prepare_to_read_bits( compressed->data );
if(decomp_alloc_flag){
decompressed->data = (char *)calloc(
compressed->pixels_per_line *compressed->number_of_lines /Pixels_per_byte,
sizeof(char) );
}
else
if(decompressed->data == NULL){
printf("\nNo memory allocated for decompressed data!\n");
exit(1);
}
prepare_to_write_bits_d( decompressed->data,
(compressed->pixels_per_line / Pixels_per_byte) );
} /* end decompress() */
/******************************* set_up_first_line_d ***************************
initializes variables in preperation for decompressing the first line
******************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information needed *
* for comparison and other tasks. *
* Returned: *
* params - structure storing information needed *
* for comparison and other tasks. *
********************************************************************/
void set_up_first_line_d(struct parameters *params)
{
params->reference_line = (SHORT *)malloc( (params->max_pixel +
Extra_positions) * sizeof(SHORT) );
params->coding_line = (SHORT *)malloc( (params->max_pixel +
Extra_positions) * sizeof(SHORT) );
*(params->reference_line + 0) = Invalid;
*(params->reference_line + 1) = params->max_pixel;
*(params->reference_line + 2) = params->max_pixel;
*(params->reference_line + 3) = params->max_pixel;
/* initialize first changing element on coding line (a0 = -1) */
*(params->coding_line) = Invalid;
params->index = 0;
} /* end set_up_first_line_d() */
/******************* set_up_first_and_last_changing_elements_d *****************
initializes the first and last changing elements in the coding line
******************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information needed *
* for comparison and other tasks. *
* Returned: *
* params - structure storing information needed *
* for comparison and other tasks. *
********************************************************************/
void set_up_first_and_last_changing_elements_d(struct parameters *params)
{
*(params->coding_line) = Invalid;
/*
* set up the imaginary first changing pixel with an illegal value.
*/
*(params->coding_line + ++params->index) = params->max_pixel;
*(params->coding_line + ++params->index) = params->max_pixel;
*(params->coding_line + ++params->index) = params->max_pixel;
/*
* set up three changing pixels at the end of the line, all of which
* contain the end-of-line flag "max_pixel." It is necessary to create
* three of these flags because the changing elements a0 - b2 are sometimes
* advanced by more than one element at a time (and therefore could skip
* over a single flag).
*/
}
/*********************** prepare_to_decompress_next_line *********************
initializes variables in preperation for decompressing another line
******************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information needed *
* for comparison and other tasks. *
* Returned: *
* params - structure storing information needed *
* for comparison and other tasks. *
********************************************************************/
void prepare_to_decompress_next_line(struct parameters *params)
{
set_up_first_and_last_changing_elements_d( params );
swap_the_reference_and_coding_lines( params );
params->index = 0;
} /* end prepare_to_decompress_next_line() */
/******************** swap_the_reference_and_coding_lines ********************
swaps the reference and coding lines
*****************************************************************************/
/********************************************************************
* Arguments *
* --------- *
* Passed in: *
* params - structure storing information needed *
* for comparison and other tasks. *
* Returned: *
* params - structure storing information needed *
* for comparison and other tasks. *
********************************************************************/
void swap_the_reference_and_coding_lines(struct parameters *params)
{
SHORT *temp;
temp = params->reference_line;
params->reference_line = params->coding_line;
params->coding_line = temp;
} /* end swap_the_reference_and_coding_lines() */
/*********************************** crash_d ***********************************
forces the program to crash and create a core file
******************************************************************************/ void crash_d()
{
FILE *crash_program = NULL;
fprintf(crash_program,"This will kill the program and create a core file");
}
/***************************************************************************/
/* Originally decomp.c */
/***************************************************************************/
static struct changing_element {
SHORT color; /* the color of the pixel */
SHORT pixel; /* the position of the pixel on the line */
} a0, a1;
static SHORT b1, b2; /* an index into reference_line */
/******************************* decompress_line *****************************
decompress one line of the compressed image
******************************************************************************/
SHORT decompress_line(struct parameters *params)
{
SHORT mode;
#if Debug
static SHORT current_line = 0;
printf("\n\nLINE: %d\n", current_line);
current_line++;
#endif
b1 = 1; /* this puts b1 on the first black element in the reference line ,
* which is appropriate because a0 is white and on -1 */
a0.pixel = 0;
a0.color = White;
do {
#if Debug
printf("a0:%d, a1:%d, b1:%d", a0.pixel, a1.pixel,
*(params->reference_line + b1));
#endif
mode = get_mode();
switch( mode ) {
case V0:
case VR1:
case VL1:
case VR2:
case VL2:
case VR3:
case VL3: vertical_mode_d( params, mode );
break;
case H: horizontal_mode_d( params );
break;
case P: pass_mode_d( params );
continue;
case EOFB: return( EOFB );
default: crash_d();
} /* end case of different modes */
} while(a0.pixel < params->max_pixel);
return( Not_done_yet );
} /* end decompress_line */
/********************************** get_mode **********************************
read a mode code from the compressed image
******************************************************************************/
SHORT get_mode()
{
SHORT i;
if (read_bit() == 1)
return(V0); /* 1 */
if (read_bit() == 1) {
if (read_bit() == 1)
return(VR1); /* 011 */
else
return(VL1); /* 010 */
}
else {
if (read_bit() == 1)
return(H); /* 001 */
if (read_bit() == 1)
return(P); /* 0001 */
if (read_bit() == 1) {
if (read_bit() == 1)
return(VR2); /* 000011 */
else
return(VL2); /* 000010 */
}
else {
if (read_bit() == 1) {
if (read_bit() == 1)
return(VR3); /* 0000011 */
else
return(VL3); /* 0000010 */
}
else {
/*
* Have read 6 zero's so far. The only valid code now
* possible is EOFB: 00000000000100000000001.
*/
for(i=0;i<5;i++)
if (read_bit() != 0)
crash_d();
if (read_bit() != 1)
crash_d();
for(i=0;i<11;i++)
if (read_bit() != 0)
crash_d();
if (read_bit() != 1)
crash_d();
return(EOFB); /* 00000000000100000000001 */
}
}
}
} /* end get_mode() */
/********************************** pass_mode_d ********************************
decompress a pass mode code
******************************************************************************/
void pass_mode_d(struct parameters *params)
{
SHORT run_length;
b2 = b1 + 1;
run_length = *(params->reference_line + b2) - a0.pixel;
write_bits_d(run_length, a0.color);
#if Debug
printf(" P Run:%d, Color:%d\n", run_length, a0.color);
#endif
a0.pixel += run_length;
/* a0.color does not change during pass_mode_d() */
b1 += 2;
} /* end pass_mode_d() */
/******************************* vertical_mode_d *******************************
decompress a vertical mode code
******************************************************************************/
void vertical_mode_d(struct parameters *params, SHORT offset)
{
SHORT run_length;
a1.pixel = *(params->reference_line + b1) + offset;
run_length = a1.pixel - a0.pixel;
write_bits_d(run_length, a0.color);
#if Debug
printf(" V%d Run:%d, Color:%d\n", offset, run_length, a0.color);
#endif
a0.pixel = a1.pixel;
a0.color = ! a0.color;
*(params->coding_line + ++params->index) = a0.pixel;
/*
* The color of a0 changes after each vertical mode coding.
*/
if ((offset == -1) || (offset == 0)) {
if ( *(params->reference_line + b1) != params->max_pixel )
b1++;
return;
}
if ((offset == 1) || (offset == 2)) {
b1++;
if ( (*(params->reference_line + b1) <= a0.pixel) &&
(*(params->reference_line + b1) != params->max_pixel) )
b1 += 2;
return;
}
if ((offset == -2) || (offset == -3)) {
if ( *(params->reference_line + b1 - 1) > a0.pixel )
b1--;
else { if ( *(params->reference_line + b1) != params->max_pixel )
b1++;
return;
}
}
if (offset == 3) {
b1++;
while ( (*(params->reference_line + b1) <= a0.pixel) &&
(*(params->reference_line + b1) != params->max_pixel) )
b1 += 2;
return;
}
} /* end vertical_mode_d() */
/******************************* horizontal_mode_d *****************************
decompress a horizontal mode code
******************************************************************************/
void horizontal_mode_d(struct parameters *params)
{
SHORT length, total_length = 0;
do {
length = find_run_length_code(a0.color);
total_length += length;
} while (length > Max_terminating_length);
/*
* Run lengths greater than 63 are followed by terminating codes.
* Thus if "length" is greater than 63, the terminating code must
* also be fetched in order to determine the total run length.
*
*/
write_bits_d(total_length, a0.color);
#if Debug
printf(" H Run:%d, Color:%d\n", total_length, a0.color);
#endif
a0.pixel += total_length;
a0.color = !a0.color;
*(params->coding_line + ++params->index) = a0.pixel;
/*
* a0's color changes after each run color.
*/
total_length = 0;
do {
length = find_run_length_code(a0.color);
total_length += length;
} while (length > Max_terminating_length);
write_bits_d(total_length, a0.color);
#if Debug
printf(" Run:%d, Color:%d\n", total_length, a0.color);
#endif
a0.pixel += total_length;
a0.color = !a0.color;
*(params->coding_line + ++params->index) = a0.pixel;
while ( (*(params->reference_line + b1) <= a0.pixel) &&
( *(params->reference_line + b1) < params->max_pixel) )
{
b1 += 2; /* must move ahead by 2 to maintain color difference with */
/* a0, whose color does not change in this mode. */
}
} /* end horizontal_mode_d() */
/***************************************************************************/
/* Originally write.c */
/***************************************************************************/
static char write_one[Pixels_per_byte] =
{
(char)0x80, /* 10000000b: with | operator, it writes a one to bit 0 */
(char)0x40, /* 01000000b: with | operator, it writes a one to bit 1 */
(char)0x20, /* 00100000b: with | operator, it writes a one to bit 2 */
(char)0x10, /* 00010000b: with | operator, it writes a one to bit 3 */
(char)0x8, /* 00001000b: with | operator, it writes a one to bit 4 */
(char)0x4, /* 00000100b: with | operator, it writes a one to bit 5 */
(char)0x2, /* 00000010b: with | operator, it writes a one to bit 6 */
(char)0x1, /* 00000001b: with | operator, it writes a one to bit 7 */
};
static char write_zero[Pixels_per_byte] =
{
(char)0x7F, /* 01111111b: with & operator, it writes a zero to bit 0 */
(char)0xBF, /* 10111111b: with & operator, it writes a zero to bit 1 */
(char)0xDF, /* 11011111b: with & operator, it writes a zero to bit 2 */
(char)0xEF, /* 11101111b: with & operator, it writes a zero to bit 3 */
(char)0xF7, /* 11110111b: with & operator, it writes a zero to bit 4 */
(char)0xFB, /* 11111011b: with & operator, it writes a zero to bit 5 */
(char)0xFD, /* 11111101b: with & operator, it writes a zero to bit 6 */
(char)0xFE, /* 11111110b: with & operator, it writes a zero to bit 7 */
};
/************************* prepare_to_write_bits_d ******************************
initializes variables in preperation for writing decompressed data
******************************************************************************/
void prepare_to_write_bits_d(char *output_pointer, SHORT bytes_per_line)
{
output_area = output_pointer;
all_white = (char *)calloc( bytes_per_line, sizeof(char) );
all_black = (char *)calloc( bytes_per_line, sizeof(char) );
memset(all_black, Black_byte, bytes_per_line);
/* set all the pixels in "all_black" to '1' */
}
/******************************* write_bits_d ***********************************
writes a number of bits of the same color to the memory buffer that holds
the decompressed image.
******************************************************************************/
void write_bits_d(unsigned SHORT length, unsigned SHORT color)
{
static unsigned SHORT write_on_this_bit = 0;
static unsigned int write_on_this_byte = 0;
unsigned int bytes;
/* global switch added by <NAME> 2/23/90 */
if(decomp_write_init_flag){
write_on_this_bit = 0;
write_on_this_byte = 0;
decomp_write_init_flag = False;
}
if (color == Black) {
while( (length>0) && (write_on_this_bit != 0) ) {
*(output_area + write_on_this_byte) |= write_one[write_on_this_bit];
length--;
if (write_on_this_bit == Last_bit_in_a_byte) {
write_on_this_bit = 0;
write_on_this_byte++;
}
else
write_on_this_bit++;
}
memcpy((output_area+write_on_this_byte), all_black, (bytes=(length/8)));
write_on_this_byte += bytes;
length %= Bits_per_byte;
while( length>0 ) {
*(output_area + write_on_this_byte) |= write_one[write_on_this_bit];
length--;
if (write_on_this_bit == Last_bit_in_a_byte) {
write_on_this_bit = 0;
write_on_this_byte++;
}
else
write_on_this_bit++;
}
} /* end if color is black */
else {
while( (length>0) && (write_on_this_bit != 0) ) {
*(output_area + write_on_this_byte) &=write_zero[write_on_this_bit];
length--;
if (write_on_this_bit == Last_bit_in_a_byte) {
write_on_this_bit = 0;
write_on_this_byte++;
}
else
write_on_this_bit++;
}
memcpy((output_area+write_on_this_byte), all_white, (bytes=(length/8)));
write_on_this_byte += bytes;
length %= Bits_per_byte;
while( length>0 ) {
*(output_area + write_on_this_byte) &=write_zero[write_on_this_bit];
length--;
if (write_on_this_bit == Last_bit_in_a_byte) {
write_on_this_bit = 0;
write_on_this_byte++;
}
else
write_on_this_bit++;
}
} /* end if color is white */
} /* end write_bits_d() */
/***************************************************************************/
/* Originally read.c */
/***************************************************************************/
static char *input_area;
static char read_bit_mask[Pixels_per_byte] =
{
(char)0x80, /* 10000000b: with & operator, it reads bit 0 */
(char)0x40, /* 01000000b: with & operator, it reads bit 1 */
(char)0x20, /* 00100000b: with & operator, it reads bit 2 */
(char)0x10, /* 00010000b: with & operator, it reads bit 3 */
(char)0x8, /* 00001000b: with & operator, it reads bit 4 */
(char)0x4, /* 00000100b: with & operator, it reads bit 5 */
(char)0x2, /* 00000010b: with & operator, it reads bit 6 */
(char)0x1, /* 00000001b: with & operator, it reads bit 7 */
};
/************************* prepare_to_read_bits ******************************
initialize a local, static variable, input_area
******************************************************************************/
void prepare_to_read_bits(char *input_pointer)
{
input_area = input_pointer;
}
/******************************* read_bit *************************************
returns the value of the current bit of the compressed image (e.g. 1 or 0)
******************************************************************************/
SHORT read_bit()
{
SHORT bit;
static unsigned SHORT read_this_bit = 0;
static unsigned int read_this_byte = 0;
/* global switch added by <NAME> 2/23/90 */
if(decomp_read_init_flag){
read_this_bit = 0;
read_this_byte = 0;
decomp_read_init_flag = False;
}
/*
* read_bits gets one bit from the compressed data file,
* and returns it as an integer value of 0 or 1.
*/
bit = *(input_area + read_this_byte) & read_bit_mask[read_this_bit];
if(read_this_bit == Last_bit_in_a_byte) {
read_this_bit = 0;
read_this_byte++;
} /* end if current byte completely read */
else
read_this_bit++;
/*
* NOTE: bit contains 0 if the bit read was 0,
* or a non-zero number if the bit was 1.
*/
return( !(bit == 0) );
/*
* the above operation returns a zero if bit is equal to zero, or a
* one if bit is not equal to zero.
*/
} /* end read_bit() */
/***************************************************************************/
/* Originally tree.c */
/***************************************************************************/
struct node {
SHORT value;
struct node *child_zero;
struct node *child_one;
}; /* end node struct */
static struct node *node_ptr;
/*****************************************************************************
The following declarations create two ordered, unbalanced, binary trees.
The trees contain run length values, and are ordered by the Huffman codes
that correspond to those values.
******************************************************************************/
struct node black_tree[] =
{
{-1, &black_tree[ 2], &black_tree[ 1]},
{-1, &black_tree[ 4], &black_tree[ 3]},
{-1, &black_tree[ 6], &black_tree[ 5]},
{2, NULL, NULL},
{3, NULL, NULL},
{-1, &black_tree[ 8], &black_tree[ 7]},
{-1, &black_tree[ 10], &black_tree[ 9]},
{4, NULL, NULL},
{1, NULL, NULL},
{-1, &black_tree[ 12], &black_tree[ 11]},
{-1, &black_tree[ 14], &black_tree[ 13]},
{5, NULL, NULL},
{6, NULL, NULL},
{-1, &black_tree[ 16], &black_tree[ 15]},
{-1, &black_tree[ 18], &black_tree[ 17]},
{7, NULL, NULL},
{-1, &black_tree[ 20], &black_tree[ 19]},
{-1, &black_tree[ 22], &black_tree[ 21]},
{-1, &black_tree[ 24], &black_tree[ 23]},
{8, NULL, NULL},
{9, NULL, NULL},
{-1, &black_tree[ 26], &black_tree[ 25]},
{-1, &black_tree[ 28], &black_tree[ 27]},
{-1, &black_tree[ 30], &black_tree[ 29]},
{-1, &black_tree[ 32], &black_tree[ 31]},
{12, NULL, NULL},
{-1, &black_tree[ 34], &black_tree[ 33]},
{11, NULL, NULL},
{10, NULL, NULL},
{-1, &black_tree[ 36], &black_tree[ 35]},
{-1, &black_tree[ 38], &black_tree[ 37]},
{-1, &black_tree[ 40], &black_tree[ 39]},
{-1, NULL, &black_tree[ 41]},
{-1, &black_tree[ 43], &black_tree[ 42]},
{-1, &black_tree[ 45], &black_tree[ 44]},
{14, NULL, NULL},
{-1, &black_tree[ 47], &black_tree[ 46]},
{-1, &black_tree[ 49], &black_tree[ 48]},
{13, NULL, NULL},
{-1, &black_tree[ 51], &black_tree[ 50]},
{-1, &black_tree[ 53], &black_tree[ 52]},
{-1, &black_tree[ 55], &black_tree[ 54]},
{-1, &black_tree[ 57], &black_tree[ 56]},
{-1, &black_tree[ 59], &black_tree[ 58]},
{-1, &black_tree[ 61], &black_tree[ 60]},
{15, NULL, NULL},
{-1, &black_tree[ 63], &black_tree[ 62]},
{-1, &black_tree[ 65], &black_tree[ 64]},
{-1, &black_tree[ 67], &black_tree[ 66]},
{-1, &black_tree[ 69], &black_tree[ 68]},
{-1, &black_tree[ 71], &black_tree[ 70]},
{-1, &black_tree[ 73], &black_tree[ 72]},
{-1, &black_tree[ 75], &black_tree[ 74]},
{-1, &black_tree[ 77], &black_tree[ 76]},
{-1, &black_tree[ 79], &black_tree[ 78]},
{-1, &black_tree[ 81], &black_tree[ 80]},
{0, NULL, NULL},
{-1, &black_tree[ 83], &black_tree[ 82]},
{-1, &black_tree[ 85], &black_tree[ 84]},
{-1, &black_tree[ 87], &black_tree[ 86]},
{-1, &black_tree[ 89], &black_tree[ 88]},
{-1, &black_tree[ 91], &black_tree[ 90]},
{-1, &black_tree[ 93], &black_tree[ 92]},
{-1, &black_tree[ 95], &black_tree[ 94]},
{-1, &black_tree[ 97], &black_tree[ 96]},
{17, NULL, NULL},
{16, NULL, NULL},
{-1, &black_tree[ 99], &black_tree[ 98]},
{-1, &black_tree[101], &black_tree[100]},
{-1, &black_tree[103], &black_tree[102]},
{64, NULL, NULL},
{-1, &black_tree[105], &black_tree[104]},
{-1, &black_tree[107], &black_tree[106]},
{-1, &black_tree[109], &black_tree[108]},
{-1, &black_tree[111], &black_tree[110]},
{-1, &black_tree[113], &black_tree[112]},
{-1, &black_tree[115], &black_tree[114]},
{18, NULL, NULL},
{-1, &black_tree[117], &black_tree[116]},
{-1, &black_tree[119], &black_tree[118]},
{-1, &black_tree[121], &black_tree[120]},
{-1, &black_tree[123], &black_tree[122]},
{-1, &black_tree[125], &black_tree[124]},
{21, NULL, NULL},
{-1, &black_tree[127], &black_tree[126]},
{-1, &black_tree[129], &black_tree[128]},
{-1, &black_tree[131], &black_tree[130]},
{20, NULL, NULL},
{19, NULL, NULL},
{-1, &black_tree[133], &black_tree[132]},
{-1, &black_tree[135], &black_tree[134]},
{-1, &black_tree[137], &black_tree[136]},
{22, NULL, NULL},
{-1, &black_tree[139], &black_tree[138]},
{-1, &black_tree[141], &black_tree[140]},
{-1, &black_tree[143], &black_tree[142]},
{-1, &black_tree[145], &black_tree[144]},
{-1, &black_tree[147], &black_tree[146]},
{-1, &black_tree[149], &black_tree[148]},
{-1, &black_tree[151], &black_tree[150]},
{-1, &black_tree[153], &black_tree[152]},
{-1, &black_tree[155], &black_tree[154]},
{-1, &black_tree[157], &black_tree[156]},
{23, NULL, NULL},
{-1, &black_tree[159], &black_tree[158]},
{-1, &black_tree[161], &black_tree[160]},
{-1, &black_tree[163], &black_tree[162]},
{-1, &black_tree[165], &black_tree[164]},
{-1, &black_tree[167], &black_tree[166]},
{25, NULL, NULL},
{24, NULL, NULL},
{-1, &black_tree[169], &black_tree[168]},
{-1, &black_tree[171], &black_tree[170]},
{-1, &black_tree[173], &black_tree[172]},
{-1, &black_tree[175], &black_tree[174]},
{-1, &black_tree[177], &black_tree[176]},
{-1, &black_tree[179], &black_tree[178]},
{-1, &black_tree[181], &black_tree[180]},
{1920, NULL, NULL},
{1856, NULL, NULL},
{-1, &black_tree[183], &black_tree[182]},
{-1, &black_tree[185], &black_tree[184]},
{-1, &black_tree[187], &black_tree[186]},
{1792, NULL, NULL},
{43, NULL, NULL},
{42, NULL, NULL},
{39, NULL, NULL},
{38, NULL, NULL},
{37, NULL, NULL},
{36, NULL, NULL},
{35, NULL, NULL},
{34, NULL, NULL},
{29, NULL, NULL},
{28, NULL, NULL},
{27, NULL, NULL},
{26, NULL, NULL},
{192, NULL, NULL},
{128, NULL, NULL},
{41, NULL, NULL},
{40, NULL, NULL},
{33, NULL, NULL},
{32, NULL, NULL},
{31, NULL, NULL},
{30, NULL, NULL},
{63, NULL, NULL},
{62, NULL, NULL},
{49, NULL, NULL},
{48, NULL, NULL},
{256, NULL, NULL},
{61, NULL, NULL},
{58, NULL, NULL},
{57, NULL, NULL},
{47, NULL, NULL},
{46, NULL, NULL},
{45, NULL, NULL},
{44, NULL, NULL},
{51, NULL, NULL},
{50, NULL, NULL},
{-1, &black_tree[189], &black_tree[188]},
{-1, &black_tree[191], &black_tree[190]},
{-1, &black_tree[193], &black_tree[192]},
{54, NULL, NULL},
{53, NULL, NULL},
{-1, &black_tree[195], &black_tree[194]},
{448, NULL, NULL},
{384, NULL, NULL},
{320, NULL, NULL},
{-1, &black_tree[197], &black_tree[196]},
{-1, &black_tree[199], &black_tree[198]},
{60, NULL, NULL},
{59, NULL, NULL},
{-1, &black_tree[201], &black_tree[200]},
{-1, &black_tree[203], &black_tree[202]},
{56, NULL, NULL},
{55, NULL, NULL},
{-1, &black_tree[205], &black_tree[204]},
{-1, &black_tree[207], &black_tree[206]},
{52, NULL, NULL},
{2560, NULL, NULL},
{2496, NULL, NULL},
{2432, NULL, NULL},
{2368, NULL, NULL},
{2304, NULL, NULL},
{2240, NULL, NULL},
{2176, NULL, NULL},
{2112, NULL, NULL},
{2048, NULL, NULL},
{1984, NULL, NULL},
{1216, NULL, NULL},
{1152, NULL, NULL},
{1088, NULL, NULL},
{1024, NULL, NULL},
{960, NULL, NULL},
{896, NULL, NULL},
{576, NULL, NULL},
{512, NULL, NULL},
{1728, NULL, NULL},
{1664, NULL, NULL},
{1600, NULL, NULL},
{1536, NULL, NULL},
{1472, NULL, NULL},
{1408, NULL, NULL},
{1344, NULL, NULL},
{1280, NULL, NULL},
{832, NULL, NULL},
{768, NULL, NULL},
{704, NULL, NULL},
{640, NULL, NULL}
}; /* end black_tree */
struct node white_tree[] =
{
{-1, &white_tree[ 2], &white_tree[ 1]},
{-1, &white_tree[ 4], &white_tree[ 3]},
{-1, &white_tree[ 6], &white_tree[ 5]},
{-1, &white_tree[ 8], &white_tree[ 7]},
{-1, &white_tree[ 10], &white_tree[ 9]},
{-1, &white_tree[ 12], &white_tree[ 11]},
{-1, &white_tree[ 14], &white_tree[ 13]},
{-1, &white_tree[ 16], &white_tree[ 15]},
{-1, &white_tree[ 18], &white_tree[ 17]},
{-1, &white_tree[ 20], &white_tree[ 19]},
{-1, &white_tree[ 22], &white_tree[ 21]},
{-1, &white_tree[ 24], &white_tree[ 23]},
{-1, &white_tree[ 26], &white_tree[ 25]},
{-1, &white_tree[ 28], &white_tree[ 27]},
{-1, &white_tree[ 30], &white_tree[ 29]},
{7, NULL, NULL},
{6, NULL, NULL},
{-1, &white_tree[ 32], &white_tree[ 31]},
{5, NULL, NULL},
{4, NULL, NULL},
{-1, &white_tree[ 34], &white_tree[ 33]},
{-1, &white_tree[ 36], &white_tree[ 35]},
{3, NULL, NULL},
{2, NULL, NULL},
{-1, &white_tree[ 38], &white_tree[ 37]},
{-1, &white_tree[ 40], &white_tree[ 39]},
{-1, &white_tree[ 42], &white_tree[ 41]},
{-1, &white_tree[ 44], &white_tree[ 43]},
{-1, &white_tree[ 46], &white_tree[ 45]},
{-1, &white_tree[ 48], &white_tree[ 47]},
{-1, &white_tree[ 50], &white_tree[ 49]},
{64, NULL, NULL},
{-1, &white_tree[ 52], &white_tree[ 51]},
{-1, &white_tree[ 54], &white_tree[ 53]},
{9, NULL, NULL},
{8, NULL, NULL},
{128, NULL, NULL},
{-1, &white_tree[ 56], &white_tree[ 55]},
{-1, &white_tree[ 58], &white_tree[ 57]},
{-1, &white_tree[ 60], &white_tree[ 59]},
{-1, &white_tree[ 62], &white_tree[ 61]},
{-1, &white_tree[ 64], &white_tree[ 63]},
{11, NULL, NULL},
{10, NULL, NULL},
{-1, &white_tree[ 66], &white_tree[ 65]},
{-1, &white_tree[ 68], &white_tree[ 67]},
{-1, &white_tree[ 70], &white_tree[ 69]},
{-1, &white_tree[ 72], &white_tree[ 71]},
{-1, &white_tree[ 74], &white_tree[ 73]},
{-1, &white_tree[ 76], &white_tree[ 75]},
{-1, &white_tree[ 78], &white_tree[ 77]},
{15, NULL, NULL},
{14, NULL, NULL},
{17, NULL, NULL},
{16, NULL, NULL},
{-1, &white_tree[ 80], &white_tree[ 79]},
{-1, &white_tree[ 82], &white_tree[ 81]},
{-1, &white_tree[ 84], &white_tree[ 83]},
{1664, NULL, NULL},
{192, NULL, NULL},
{-1, &white_tree[ 86], &white_tree[ 85]},
{-1, &white_tree[ 88], &white_tree[ 87]},
{-1, &white_tree[ 90], &white_tree[ 89]},
{-1, &white_tree[ 92], &white_tree[ 91]},
{-1, &white_tree[ 94], &white_tree[ 93]},
{-1, &white_tree[ 96], &white_tree[ 95]},
{-1, &white_tree[ 98], &white_tree[ 97]},
{-1, &white_tree[100], &white_tree[ 99]},
{-1, &white_tree[102], &white_tree[101]},
{-1, &white_tree[104], &white_tree[103]},
{12, NULL, NULL},
{1, NULL, NULL},
{-1, &white_tree[106], &white_tree[105]},
{-1, &white_tree[108], &white_tree[107]},
{-1, &white_tree[110], &white_tree[109]},
{13, NULL, NULL},
{-1, &white_tree[112], &white_tree[111]},
{-1, &white_tree[114], &white_tree[113]},
{-1, &white_tree[116], &white_tree[115]},
{256, NULL, NULL},
{-1, &white_tree[118], &white_tree[117]},
{-1, &white_tree[120], &white_tree[119]},
{-1, &white_tree[122], &white_tree[121]},
{-1, &white_tree[124], &white_tree[123]},
{-1, &white_tree[126], &white_tree[125]},
{-1, &white_tree[128], &white_tree[127]},
{-1, &white_tree[130], &white_tree[129]},
{25, NULL, NULL},
{-1, &white_tree[132], &white_tree[131]},
{-1, &white_tree[134], &white_tree[133]},
{24, NULL, NULL},
{18, NULL, NULL},
{-1, &white_tree[136], &white_tree[135]},
{-1, &white_tree[138], &white_tree[137]},
{27, NULL, NULL},
{-1, &white_tree[140], &white_tree[139]},
{-1, &white_tree[142], &white_tree[141]},
{-1, &white_tree[144], &white_tree[143]},
{28, NULL, NULL},
{21, NULL, NULL},
{-1, &white_tree[146], &white_tree[145]},
{-1, &white_tree[148], &white_tree[147]},
{-1, &white_tree[150], &white_tree[149]},
{26, NULL, NULL},
{-1, &white_tree[152], &white_tree[151]},
{-1, &white_tree[154], &white_tree[153]},
{19, NULL, NULL},
{-1, &white_tree[156], &white_tree[155]},
{-1, &white_tree[158], &white_tree[157]},
{-1, &white_tree[160], &white_tree[159]},
{20, NULL, NULL},
{-1, &white_tree[162], &white_tree[161]},
{23, NULL, NULL},
{22, NULL, NULL},
{-1, &white_tree[164], &white_tree[163]},
{-1, &white_tree[166], &white_tree[165]},
{-1, NULL, &white_tree[167]},
{-1, &white_tree[169], &white_tree[168]},
{-1, &white_tree[171], &white_tree[170]},
{-1, &white_tree[173], &white_tree[172]},
{-1, &white_tree[175], &white_tree[174]},
{-1, &white_tree[177], &white_tree[176]},
{576, NULL, NULL},
{640, NULL, NULL},
{-1, &white_tree[179], &white_tree[178]},
{512, NULL, NULL},
{448, NULL, NULL},
{58, NULL, NULL},
{57, NULL, NULL},
{56, NULL, NULL},
{55, NULL, NULL},
{52, NULL, NULL},
{51, NULL, NULL},
{50, NULL, NULL},
{49, NULL, NULL},
{-1, &white_tree[181], &white_tree[180]},
{-1, &white_tree[183], &white_tree[182]},
{60, NULL, NULL},
{59, NULL, NULL},
{384, NULL, NULL},
{320, NULL, NULL},
{0, NULL, NULL},
{63, NULL, NULL},
{62, NULL, NULL},
{61, NULL, NULL},
{44, NULL, NULL},
{43, NULL, NULL},
{42, NULL, NULL},
{41, NULL, NULL},
{40, NULL, NULL},
{39, NULL, NULL},
{54, NULL, NULL},
{53, NULL, NULL},
{32, NULL, NULL},
{31, NULL, NULL},
{38, NULL, NULL},
{37, NULL, NULL},
{36, NULL, NULL},
{35, NULL, NULL},
{34, NULL, NULL},
{33, NULL, NULL},
{48, NULL, NULL},
{47, NULL, NULL},
{46, NULL, NULL},
{45, NULL, NULL},
{30, NULL, NULL},
{29, NULL, NULL},
{-1, &white_tree[185], &white_tree[184]},
{1408, NULL, NULL},
{1344, NULL, NULL},
{1280, NULL, NULL},
{1216, NULL, NULL},
{1152, NULL, NULL},
{1088, NULL, NULL},
{1024, NULL, NULL},
{960, NULL, NULL},
{896, NULL, NULL},
{832, NULL, NULL},
{768, NULL, NULL},
{704, NULL, NULL},
{1728, NULL, NULL},
{1600, NULL, NULL},
{1536, NULL, NULL},
{1472, NULL, NULL},
{-1, &white_tree[187], &white_tree[186]},
{-1, &white_tree[189], &white_tree[188]},
{-1, &white_tree[191], &white_tree[190]},
{-1, &white_tree[193], &white_tree[192]},
{-1, &white_tree[195], &white_tree[194]},
{-1, &white_tree[197], &white_tree[196]},
{-1, &white_tree[199], &white_tree[198]},
{-1, &white_tree[201], &white_tree[200]},
{1920, NULL, NULL},
{1856, NULL, NULL},
{-1, &white_tree[203], &white_tree[202]},
{-1, &white_tree[205], &white_tree[204]},
{-1, &white_tree[207], &white_tree[206]},
{1792, NULL, NULL},
{2560, NULL, NULL},
{2496, NULL, NULL},
{2432, NULL, NULL},
{2368, NULL, NULL},
{2304, NULL, NULL},
{2240, NULL, NULL},
{2176, NULL, NULL},
{2112, NULL, NULL},
{2048, NULL, NULL},
{1984, NULL, NULL}
}; /* end white_tree */
/************************* find_run_length_code ******************************
finds the length of the run in the compressed image
by traversing the above declared tree of run length codes.
******************************************************************************/
SHORT find_run_length_code(SHORT color)
{
if(color == White)
node_ptr = white_tree; /* point to root node */
else
node_ptr = black_tree; /* point to root node */
while(node_ptr->value == Invalid) { /* -1 */
if((read_bit()) == 0)
node_ptr = node_ptr->child_zero;
else
node_ptr = node_ptr->child_one;
} /* end while node does not contain a run length value */
/*
* When this line is reached, node_ptr points to a node that contains
* the run length code: return that value.
*/
return(node_ptr->value);
} /* end find_run_length_code */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/imgtype.c
|
<reponame>ThalesGroup/WSQForAndroid<filename>library/src/main/cpp/nbis/imgtools/src/lib/image/imgtype.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: IMGTYPE.C
AUTHOR: <NAME> & <NAME>
DATE: 08/31/2004
UPDATED: 03/15/2005 by MDG
UPDATED: 10/07/2008 by <NAME>
UPDATED: 01/06/2008 by Kenneth Ko - add support for HPUX compile
UPDATED: 07/10/2014 by <NAME>
02/25/2015 (Kenneth Ko) - Updated everything related to
OPENJPEG to OPENJP
Contains routines responsible for automatically determining the
format of a pixmap file based on its contents.
ROUTINES:
#cat: image_type - takes an image data stream and determines if it
#cat: is from a WSQ, JPEGL, JPEGB, IHead, ANSI_NIST
#cat: or UNKNOWN file.
#cat: jpeg_type - takes an image data stream and determines if it
#cat: is from a JPEGL or JPEGB file.
***********************************************************************/
#include <stdio.h>
#include <imgtype.h>
/*******************************************************************/
/* Determine if image data is of type IHEAD, WSQ, JPEGL, JPEGB or */
/* ANSI_NIST */
/*******************************************************************/
int image_type(int *img_type, unsigned char *idata, const int ilen)
{
int ret;
unsigned short marker;
unsigned char *cbufptr, *ebufptr;
char ihdr_size[SHORT_CHARS];
unsigned char header[8];
cbufptr = idata;
ebufptr = idata + ilen;
if((ret = getc_ushort(&marker, &cbufptr, ebufptr)))
return(ret);
if(marker == SOI_WSQ){
*img_type = WSQ_IMG;
return(0);
} else if(marker == SOI){
if((ret = jpeg_type(img_type, idata, ilen)))
return(ret);
return(0);
}
sprintf(ihdr_size, "%d", IHDR_SIZE);
if(strncmp((char *)idata, ihdr_size, strlen(ihdr_size)) == 0){
*img_type = IHEAD_IMG;
return(0);
}
#ifdef __NBIS_PNG__
memcpy(header, idata, 8);
if (!(png_sig_cmp(header, 0, 8))){
*img_type = PNG_IMG;
return(0);
}
#endif
#ifdef __NBIS_JASPER__
if (is_jp2(idata, ilen) > 0){
*img_type = JP2_IMG;
return(0);
}
#endif
#ifdef __NBIS_OPENJP2__
if (is_jp2(idata, ilen) > 0){
*img_type = JP2_IMG;
return(0);
}
#endif
ret = is_ANSI_NIST(idata, ilen);
/* if system error */
if(ret < 0)
return(ret);
if(ret == TRUE){
*img_type = ANSI_NIST_IMG;
return(0);
}
/* Otherwise, image type is UNKNOWN ... */
*img_type = UNKNOWN_IMG;
return(0);
}
/****************************************************************************/
/* Determines JPEG image type by finding SOF marker in the compressed data. */
/* The SOF's are different for each JPEG compression type JPEGL and JPEGB. */
/****************************************************************************/
int jpeg_type(int *img_type, unsigned char *idata, const int ilen)
{
int ret;
unsigned short marker;
unsigned char *cbufptr, *ebufptr;
cbufptr = idata;
ebufptr = idata + ilen;
/* Get SOI */
if((ret = getc_marker_jpegl(&marker, SOI, &cbufptr, ebufptr)))
return(ret);
/* Get next marker. */
if((ret = getc_marker_jpegl(&marker, ANY, &cbufptr, ebufptr)))
return(ret);
/* While not at Start of Scan (SOS) - */
/* the start of encoded image data ... */
while(marker != SOS){
if(marker == SOF3){
*img_type = JPEGL_IMG;
return(0);
}
else if(marker == SOF0){
*img_type = JPEGB_IMG;
return(0);
}
/* Skip marker segment. */
if((ret = getc_skip_marker_segment(marker, &cbufptr, ebufptr)))
return(ret);
/* Get next marker. */
if((ret = getc_marker_jpegl(&marker, ANY, &cbufptr, ebufptr)))
return(ret);
}
/* JPEG type not found ... */
fprintf(stderr, "ERROR : jpeg_type : Could not determine JPEG type ");
fprintf(stderr, "(ie. baseline or lossless)\n");
*img_type = -1;
return(-2);
}
/****************************************************************************/
/* Determines is JP2 format. */
/****************************************************************************/
#ifdef __NBIS_JASPER__
int is_jp2(unsigned char *idata, const int ilen)
{
jas_stream_t *in;
int ret;
if (jas_init()){
fprintf(stderr, "ERROR : is_jp2: init : jas\n");
return(-1);
}
/* The input image is to be read from buffer stream. */
in = jas_stream_memopen((char *)idata, ilen);
if (in == NULL){
fprintf(stderr, "ERROR : is_jp2: failed to open jas stream\n");
return(-2);
}
/* Check is JP2 format. */
ret = jas_image_getfmt(in);
/* General clean up. */
(void) jas_stream_close(in);
return(ret);
}
#endif
#ifdef __NBIS_OPENJP2__
int is_jp2(unsigned char *idata, const int ilen)
{
int ret;
int i;
unsigned char *nptr;
unsigned char buf[4];
ret = 0;
nptr = idata;
nptr += 4;
memcpy(buf, nptr, 4 * sizeof(unsigned char));
if (memcmp(buf, "jP ", 4 * sizeof(unsigned char)) == 0)
{
ret = 1;
}
return(ret);
}
#endif
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/util/ticks.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: UTIL - General Purpose Utility Routines
FILE: TICKS.C
AUTHOR: <NAME>
DATE: 11/13/1990
Contains routines responsible for accumulating the number of clock
cycles (ticks) used by a process.
ROUTINES:
#cat: ticks - returns the number of clock cycles (ticks) used by a process.
#cat:
#cat: ticksPerSec - returns the system definition for HZ, where 1/HZ seconds
#cat: is a tick (HZ = 60).
***********************************************************************/
#include <sys/types.h>
#include <sys/times.h>
#include <sys/param.h>
#include <time.h>
#include <unistd.h>
/* ticks 13-Nov-90 15:41
* Get number of ticks used by process.
*/
clock_t
ticks(void)
{
struct tms buff;
times(&buff);
return buff.tms_utime;
}
/* ticksPerSec 13-Nov-90 15:41
* Get number of ticks per second reported by times().
*/
int
ticksPerSec(void)
{
return (int)sysconf(_SC_CLK_TCK);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/ioutil/findfile.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IOUTIL - INPUT/OUTPUT Utilities
FILE: FINDFILE.C
AUTHOR: <NAME>
DATE: 11/27/1989
UPDATED: 03/15/2005 by MDG
Contains routines responsible for locating a file within a
specified directory path.
ROUTINES:
#cat: find_file - takes a directory path and a filename and determines if
#cat: the file exists.
***********************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include <dirent.h>
#define TRUE 1
#define FALSE 0
/**********************************************************************/
int find_file(char *path, char *file)
{
int flag,len;
DIR *dirp;
struct dirent *dp;
flag = 0;
if(strcmp(path,"") != 0){
len = strlen(file);
dirp = opendir(path);
for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp)){
#ifdef __STDC__
if((strlen(dp->d_name) == len) && !strcmp(dp->d_name,file)){
#else
if(dp->d_namlen == len && !strcmp(dp->d_name,file)){
#endif
flag = 1;
}
}
closedir(dirp);
}
if (flag == 1)
return(TRUE);
else
return(FALSE);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/ssterf.c
|
<filename>library/src/main/cpp/nbis/commonnbis/src/lib/clapck/ssterf.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int ssterf_(int *n, real *d, real *e, int *info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
SSTERF computes all eigenvalues of a symmetric tridiagonal matrix
using the Pal-Walker-Kahan variant of the QL or QR algorithm.
Arguments
=========
N (input) INTEGER
The order of the matrix. N >= 0.
D (input/output) REAL array, dimension (N)
On entry, the n diagonal elements of the tridiagonal matrix.
On exit, if INFO = 0, the eigenvalues in ascending order.
E (input/output) REAL array, dimension (N-1)
On entry, the (n-1) subdiagonal elements of the tridiagonal
matrix.
On exit, E has been destroyed.
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
> 0: the algorithm failed to find all of the eigenvalues in
a total of 30*N iterations; if INFO = i, then i
elements of E have not converged to zero.
=====================================================================
Test the input parameters.
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__0 = 0;
static int c__1 = 1;
static real c_b32 = 1.f;
/* System generated locals */
int i__1;
real r__1, r__2;
/* Builtin functions */
double sqrt(doublereal), r_sign(real *, real *);
/* Local variables */
static real oldc;
static int lend, jtot;
extern /* Subroutine */ int slae2_(real *, real *, real *, real *, real *)
;
static real c;
static int i, l, m;
static real p, gamma, r, s, alpha, sigma, anorm;
static int l1, lendm1, lendp1;
static real bb;
extern doublereal slapy2_(real *, real *);
static int iscale;
static real oldgam;
extern doublereal slamch_(char *);
static real safmin;
extern /* Subroutine */ int xerbla_(char *, int *);
static real safmax;
extern /* Subroutine */ int slascl_(char *, int *, int *, real *,
real *, int *, int *, real *, int *, int *);
static int lendsv;
static real ssfmin;
static int nmaxit;
static real ssfmax;
extern doublereal slanst_(char *, int *, real *, real *);
extern /* Subroutine */ int slasrt_(char *, int *, real *, int *);
static int lm1, mm1, nm1;
static real rt1, rt2, eps, rte;
static int lsv;
static real tst, eps2;
#define E(I) e[(I)-1]
#define D(I) d[(I)-1]
*info = 0;
/* Quick return if possible */
if (*n < 0) {
*info = -1;
i__1 = -(*info);
xerbla_("SSTERF", &i__1);
return 0;
}
if (*n <= 1) {
return 0;
}
/* Determine the unit roundoff for this environment. */
eps = slamch_("E");
/* Computing 2nd power */
r__1 = eps;
eps2 = r__1 * r__1;
safmin = slamch_("S");
safmax = 1.f / safmin;
ssfmax = sqrt(safmax) / 3.f;
ssfmin = sqrt(safmin) / eps2;
/* Compute the eigenvalues of the tridiagonal matrix. */
nmaxit = *n * 30;
sigma = 0.f;
jtot = 0;
/* Determine where the matrix splits and choose QL or QR iteration
for each block, according to whether top or bottom diagonal
element is smaller. */
l1 = 1;
nm1 = *n - 1;
L10:
if (l1 > *n) {
goto L170;
}
if (l1 > 1) {
E(l1 - 1) = 0.f;
}
if (l1 <= nm1) {
i__1 = nm1;
for (m = l1; m <= nm1; ++m) {
tst = (r__1 = E(m), dabs(r__1));
if (tst == 0.f) {
goto L30;
}
if (tst <= sqrt((r__1 = D(m), dabs(r__1))) * sqrt((r__2 = D(m + 1)
, dabs(r__2))) * eps) {
E(m) = 0.f;
goto L30;
}
/* L20: */
}
}
m = *n;
L30:
l = l1;
lsv = l;
lend = m;
lendsv = lend;
l1 = m + 1;
if (lend == l) {
goto L10;
}
/* Scale submatrix in rows and columns L to LEND */
i__1 = lend - l + 1;
anorm = slanst_("I", &i__1, &D(l), &E(l));
iscale = 0;
if (anorm > ssfmax) {
iscale = 1;
i__1 = lend - l + 1;
slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &D(l), n,
info);
i__1 = lend - l;
slascl_("G", &c__0, &c__0, &anorm, &ssfmax, &i__1, &c__1, &E(l), n,
info);
} else if (anorm < ssfmin) {
iscale = 2;
i__1 = lend - l + 1;
slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &D(l), n,
info);
i__1 = lend - l;
slascl_("G", &c__0, &c__0, &anorm, &ssfmin, &i__1, &c__1, &E(l), n,
info);
}
i__1 = lend - 1;
for (i = l; i <= lend-1; ++i) {
/* Computing 2nd power */
r__1 = E(i);
E(i) = r__1 * r__1;
/* L40: */
}
/* Choose between QL and QR iteration */
if ((r__1 = D(lend), dabs(r__1)) < (r__2 = D(l), dabs(r__2))) {
lend = lsv;
l = lendsv;
}
if (lend >= l) {
/* QL Iteration
Look for small subdiagonal element. */
L50:
if (l != lend) {
lendm1 = lend - 1;
i__1 = lendm1;
for (m = l; m <= lendm1; ++m) {
tst = (r__1 = E(m), dabs(r__1));
if (tst <= eps2 * (r__1 = D(m) * D(m + 1), dabs(r__1))) {
goto L70;
}
/* L60: */
}
}
m = lend;
L70:
if (m < lend) {
E(m) = 0.f;
}
p = D(l);
if (m == l) {
goto L90;
}
/* If remaining matrix is 2 by 2, use SLAE2 to compute its
eigenvalues. */
if (m == l + 1) {
rte = sqrt(E(l));
slae2_(&D(l), &rte, &D(l + 1), &rt1, &rt2);
D(l) = rt1;
D(l + 1) = rt2;
E(l) = 0.f;
l += 2;
if (l <= lend) {
goto L50;
}
goto L150;
}
if (jtot == nmaxit) {
goto L150;
}
++jtot;
/* Form shift. */
rte = sqrt(E(l));
sigma = (D(l + 1) - p) / (rte * 2.f);
r = slapy2_(&sigma, &c_b32);
sigma = p - rte / (sigma + r_sign(&r, &sigma));
c = 1.f;
s = 0.f;
gamma = D(m) - sigma;
p = gamma * gamma;
/* Inner loop */
mm1 = m - 1;
i__1 = l;
for (i = mm1; i >= l; --i) {
bb = E(i);
r = p + bb;
if (i != m - 1) {
E(i + 1) = s * r;
}
oldc = c;
c = p / r;
s = bb / r;
oldgam = gamma;
alpha = D(i);
gamma = c * (alpha - sigma) - s * oldgam;
D(i + 1) = oldgam + (alpha - gamma);
if (c != 0.f) {
p = gamma * gamma / c;
} else {
p = oldc * bb;
}
/* L80: */
}
E(l) = s * p;
D(l) = sigma + gamma;
goto L50;
/* Eigenvalue found. */
L90:
D(l) = p;
++l;
if (l <= lend) {
goto L50;
}
goto L150;
} else {
/* QR Iteration
Look for small superdiagonal element. */
L100:
if (l != lend) {
lendp1 = lend + 1;
i__1 = lendp1;
for (m = l; m >= lendp1; --m) {
tst = (r__1 = E(m - 1), dabs(r__1));
if (tst <= eps2 * (r__1 = D(m) * D(m - 1), dabs(r__1))) {
goto L120;
}
/* L110: */
}
}
m = lend;
L120:
if (m > lend) {
E(m - 1) = 0.f;
}
p = D(l);
if (m == l) {
goto L140;
}
/* If remaining matrix is 2 by 2, use SLAE2 to compute its
eigenvalues. */
if (m == l - 1) {
rte = sqrt(E(l - 1));
slae2_(&D(l), &rte, &D(l - 1), &rt1, &rt2);
D(l) = rt1;
D(l - 1) = rt2;
E(l - 1) = 0.f;
l += -2;
if (l >= lend) {
goto L100;
}
goto L150;
}
if (jtot == nmaxit) {
goto L150;
}
++jtot;
/* Form shift. */
rte = sqrt(E(l - 1));
sigma = (D(l - 1) - p) / (rte * 2.f);
r = slapy2_(&sigma, &c_b32);
sigma = p - rte / (sigma + r_sign(&r, &sigma));
c = 1.f;
s = 0.f;
gamma = D(m) - sigma;
p = gamma * gamma;
/* Inner loop */
lm1 = l - 1;
i__1 = lm1;
for (i = m; i <= lm1; ++i) {
bb = E(i);
r = p + bb;
if (i != m) {
E(i - 1) = s * r;
}
oldc = c;
c = p / r;
s = bb / r;
oldgam = gamma;
alpha = D(i + 1);
gamma = c * (alpha - sigma) - s * oldgam;
D(i) = oldgam + (alpha - gamma);
if (c != 0.f) {
p = gamma * gamma / c;
} else {
p = oldc * bb;
}
/* L130: */
}
E(lm1) = s * p;
D(l) = sigma + gamma;
goto L100;
/* Eigenvalue found. */
L140:
D(l) = p;
--l;
if (l >= lend) {
goto L100;
}
goto L150;
}
/* Undo scaling if necessary */
L150:
if (iscale == 1) {
i__1 = lendsv - lsv + 1;
slascl_("G", &c__0, &c__0, &ssfmax, &anorm, &i__1, &c__1, &D(lsv), n,
info);
}
if (iscale == 2) {
i__1 = lendsv - lsv + 1;
slascl_("G", &c__0, &c__0, &ssfmin, &anorm, &i__1, &c__1, &D(lsv), n,
info);
}
/* Check for no convergence to an eigenvalue after a total
of N*MAXIT iterations. */
if (jtot == nmaxit) {
i__1 = *n - 1;
for (i = 1; i <= *n-1; ++i) {
if (E(i) != 0.f) {
++(*info);
}
/* L160: */
}
return 0;
}
goto L10;
/* Sort eigenvalues in increasing order. */
L170:
slasrt_("I", n, &D(1), info);
return 0;
/* End of SSTERF */
} /* ssterf_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/sorg2l.c
|
<reponame>ThalesGroup/WSQForAndroid<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int sorg2l_(int *m, int *n, int *k, real *a,
int *lda, real *tau, real *work, int *info)
{
/* -- LAPACK routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
February 29, 1992
Purpose
=======
SORG2L generates an m by n real matrix Q with orthonormal columns,
which is defined as the last n columns of a product of k elementary
reflectors of order m
Q = H(k) . . . H(2) H(1)
as returned by SGEQLF.
Arguments
=========
M (input) INTEGER
The number of rows of the matrix Q. M >= 0.
N (input) INTEGER
The number of columns of the matrix Q. M >= N >= 0.
K (input) INTEGER
The number of elementary reflectors whose product defines the
matrix Q. N >= K >= 0.
A (input/output) REAL array, dimension (LDA,N)
On entry, the (n-k+i)-th column must contain the vector which
defines the elementary reflector H(i), for i = 1,2,...,k, as
returned by SGEQLF in the last k columns of its array
argument A.
On exit, the m by n matrix Q.
LDA (input) INTEGER
The first dimension of the array A. LDA >= max(1,M).
TAU (input) REAL array, dimension (K)
TAU(i) must contain the scalar factor of the elementary
reflector H(i), as returned by SGEQLF.
WORK (workspace) REAL array, dimension (N)
INFO (output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument has an illegal value
=====================================================================
Test the input arguments
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__1 = 1;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset;
*/
int i__1, i__2, i__3;
real r__1;
/* Local variables */
static int i, j, l;
extern /* Subroutine */ int sscal_(int *, real *, real *, int *),
slarf_(char *, int *, int *, real *, int *, real *,
real *, int *, real *);
static int ii;
extern /* Subroutine */ int xerbla_(char *, int *);
#define TAU(I) tau[(I)-1]
#define WORK(I) work[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0 || *n > *m) {
*info = -2;
} else if (*k < 0 || *k > *n) {
*info = -3;
} else if (*lda < max(1,*m)) {
*info = -5;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SORG2L", &i__1);
return 0;
}
/* Quick return if possible */
if (*n <= 0) {
return 0;
}
/* Initialise columns 1:n-k to columns of the unit matrix */
i__1 = *n - *k;
for (j = 1; j <= *n-*k; ++j) {
i__2 = *m;
for (l = 1; l <= *m; ++l) {
A(l,j) = 0.f;
/* L10: */
}
A(*m-*n+j,j) = 1.f;
/* L20: */
}
i__1 = *k;
for (i = 1; i <= *k; ++i) {
ii = *n - *k + i;
/* Apply H(i) to A(1:m-k+i,1:n-k+i) from the left */
A(*m-*n+ii,ii) = 1.f;
i__2 = *m - *n + ii;
i__3 = ii - 1;
slarf_("Left", &i__2, &i__3, &A(1,ii), &c__1, &TAU(i), &A(1,1), lda, &WORK(1));
i__2 = *m - *n + ii - 1;
r__1 = -(doublereal)TAU(i);
sscal_(&i__2, &r__1, &A(1,ii), &c__1);
A(*m-*n+ii,ii) = 1.f - TAU(i);
/* Set A(m-k+i+1:m,n-k+i) to zero */
i__2 = *m;
for (l = *m - *n + ii + 1; l <= *m; ++l) {
A(l,ii) = 0.f;
/* L30: */
}
/* L40: */
}
return 0;
/* End of SORG2L */
} /* sorg2l_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/fet/nistcom.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: FET - Feature File/List Utilities
FILE: NISTCOM.C
AUTHORS: <NAME>
<NAME>
DATE: 02/27/2001
UPDATED: 03/10/2005 by MDG
Contains routines responsible for manipulating a specialize
attribute-value list called a NISTCOM used to hold image
attributes relevant to image compression, decompression, and
classification.
ROUTINES:
#cat: combine_nistcom - takes an initialized FET NISTCOM structure
#cat: or allocates one if necessary, and updates the
#cat: structure with general image attributes.
#cat: combine_jpegl_nistcom - takes an initialized FET NISTCOM structure
#cat: or allocates one if necessary, and updates the
#cat: structure with JPEGL-specific image attributes.
#cat: combine_wsq_nistcom - takes an initialized FET NISTCOM structure
#cat: or allocates one if necessary, and updates the
#cat: structure with WSQ-specific image attributes.
#cat: combine_jpegb_nistcom - takes an initialized FET NISTCOM structure
#cat: or allocates one if necessary, and updates the
#cat: structure with JPEGB-specific image attributes.
#cat: del_jpegl_nistcom - takes an initialized FET NISTCOM structure
#cat: and removes JPEGL compression attributes.
#cat: del_wsq_nistcom - takes an initialized FET NISTCOM structure
#cat: and removes WSQ compression attributes.
#cat: del_jpegb_nistcom - takes an initialized FET NISTCOM structure
#cat: and removes JPEGB compression attributes.
#cat: sd_ihead_to_nistcom - takes an IHead header from a specified NIST
#cat: Special Database file, and parses specific attribute data
#cat: from the header into an FET NISTCOM structure.
#cat: sd4_ihead_to_nistcom - takes an IHead header from a NIST Special
#cat: Database 4 file, and parses specific attribute data
#cat: from the header into an FET NISTCOM structure.
#cat: sd9_10_14_ihead_to_nistcom - takes an IHead header from a NIST Special
#cat: Database 9,10,14 file, and parses specific attribute data
#cat: from the header into an FET NISTCOM structure.
#cat: sd18_ihead_to_nistcom - takes an IHead header from a NIST Special
#cat: Database 18 file, and parses specific attribute data
#cat: from the header into an FET NISTCOM structure.
#cat: get_sd_class - gets the class from a special database id field
#cat:
#cat: get_class_from_ncic_class_string - gets the class from a special
#cat: database ncic class string
***********************************************************************/
#include <stdio.h>
#include <string.h>
#include <ihead.h>
#include <nistcom.h>
/*****************************************************************/
int combine_nistcom(NISTCOM **onistcom, const int w, const int h,
const int d, const int ppi, const int lossyflag)
{
int ret, allocflag, n;
char *lossyval;
char cbuff[11];
NISTCOM *nistcom;
/* ALLOCATION ? */
if((*onistcom) == (NISTCOM *)NULL){
if((ret = allocfet_ret(&nistcom, 6)))
return(ret);
allocflag = 1;
/* HEADER */
if((ret = updatefet_ret(NCM_HEADER, "6", nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
}
else{
nistcom = *onistcom;
allocflag = 0;
n = 6;
}
/* WIDTH */
sprintf(cbuff, "%d", w);
if((ret = updatefet_ret(NCM_PIX_WIDTH, cbuff, nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
/* HEIGHT */
sprintf(cbuff, "%d", h);
if((ret = updatefet_ret(NCM_PIX_HEIGHT, cbuff, nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
/* DEPTH */
sprintf(cbuff, "%d", d);
if((ret = updatefet_ret(NCM_PIX_DEPTH, cbuff, nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
/* PPI */
sprintf(cbuff, "%d", ppi);
if((ret = updatefet_ret(NCM_PPI, cbuff, nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
/* LOSSY */
/* If exists, lookup current LOSSY value. */
ret = lookupfet(&lossyval, NCM_LOSSY, nistcom);
/* If error ... */
if(ret < 0){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
/* If LOSSY value found AND is set AND requesting to unset ... */
if(ret &&
(strcmp(lossyval,"0") != 0) &&
(lossyflag == 0)){
fprintf(stderr, "WARNING : combine_nistcom : ");
fprintf(stderr, "request to unset lossy flag ignored\n");
}
else{
sprintf(cbuff, "%d", lossyflag);
if((ret = updatefet_ret(NCM_LOSSY, cbuff, nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
}
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom))){
if(allocflag){
freefet(nistcom);
*onistcom = (NISTCOM *)NULL;
}
return(ret);
}
*onistcom = nistcom;
return(0);
}
/*****************************************************************/
int combine_jpegl_nistcom(NISTCOM **onistcom, const int w, const int h,
const int d, const int ppi, const int lossyflag,
const int n_cmpnts, int *hor_sampfctr, int *vrt_sampfctr,
const int intrlvflag, const int predict)
{
int ret, i, allocflag;
NISTCOM *nistcom;
char cbuff[MAXFETLENGTH], *cptr;
if(*onistcom == (NISTCOM *)NULL)
allocflag = 1;
else
allocflag = 0;
/* Combine image attributes to NISTCOM. */
if((ret = combine_nistcom(onistcom, w, h, d, ppi, lossyflag)))
return(ret);
nistcom = *onistcom;
/* COLORSPACE - only sure of GRAY */
if(n_cmpnts == 1){
if((ret = updatefet_ret(NCM_COLORSPACE, "GRAY", nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
}
if(n_cmpnts > 1){
/* NUM_COMPONENTS */
sprintf(cbuff, "%d", n_cmpnts);
if((ret = updatefet_ret(NCM_N_CMPNTS, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* HV FACTORS */
cptr = cbuff;
sprintf(cptr, "%d,%d", hor_sampfctr[0], vrt_sampfctr[0]);
cptr = cbuff + strlen(cbuff);
for(i = 1; i < n_cmpnts; i++){
sprintf(cptr, ":%d,%d", hor_sampfctr[i], vrt_sampfctr[i]);
cptr = cbuff + strlen(cbuff);
}
if((ret = updatefet_ret(NCM_HV_FCTRS, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* INTERLEAVE */
sprintf(cbuff, "%d", intrlvflag);
if((ret = updatefet_ret(NCM_INTRLV, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
}
/* COMPRESSION */
if((ret = updatefet_ret(NCM_COMPRESSION, "JPEGL", nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* PREDICT */
sprintf(cbuff, "%d", predict);
if((ret = updatefet_ret(NCM_JPEGL_PREDICT, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
return(0);
}
/*****************************************************************/
int combine_wsq_nistcom(NISTCOM **onistcom, const int w, const int h,
const int d, const int ppi, const int lossyflag,
const float r_bitrate)
{
int ret, allocflag;
NISTCOM *nistcom;
char cbuff[MAXFETLENGTH];
if(*onistcom == (NISTCOM *)NULL)
allocflag = 1;
else
allocflag = 0;
/* Combine image attributes to NISTCOM. */
if((ret = combine_nistcom(onistcom, w, h, d, ppi, lossyflag)))
return(ret);
nistcom = *onistcom;
/* COLORSPACE */
if((ret = updatefet_ret(NCM_COLORSPACE, "GRAY", nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* COMPRESSION */
if((ret = updatefet_ret(NCM_COMPRESSION, "WSQ", nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* BITRATE */
sprintf(cbuff, "%f", r_bitrate);
if((ret = updatefet_ret(NCM_WSQ_RATE, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
return(0);
}
/*****************************************************************/
int combine_jpegb_nistcom(NISTCOM **onistcom, const int w, const int h,
const int d, const int ppi, const int lossyflag,
char *colorspace, const int n_cmpnts, const int intrlvflag,
const int quality)
{
int ret, allocflag;
NISTCOM *nistcom;
char cbuff[MAXFETLENGTH], *cptr;
if(*onistcom == (NISTCOM *)NULL)
allocflag = 1;
else
allocflag = 0;
/* Combine image attributes to NISTCOM. */
if((ret = combine_nistcom(onistcom, w, h, d, ppi, lossyflag)))
return(ret);
nistcom = *onistcom;
/* COLORSPACE */
if((ret = updatefet_ret(NCM_COLORSPACE, colorspace, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
if(n_cmpnts > 1){
/* NUM_COMPONENTS */
sprintf(cbuff, "%d", n_cmpnts);
if((ret = updatefet_ret(NCM_N_CMPNTS, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* HV_FACTORS */
if(strcmp(colorspace, "RGB") == 0)
cptr = "1,1:1,1:1,1";
else if(strcmp(colorspace, "YCbCr") == 0)
cptr = "2,2:1,1:1,1";
else{
fprintf(stderr, "ERROR : combine_jpegb_nistcom : ");
fprintf(stderr, "unknown/unsupported colorspace = %s\n",
colorspace);
if(allocflag)
freefet(nistcom);
return(-2);
}
if((ret = updatefet_ret(NCM_HV_FCTRS, cptr, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* INTERLEAVE */
sprintf(cbuff, "%d", intrlvflag);
if((ret = updatefet_ret(NCM_INTRLV, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
}
/* COMPRESSION */
if((ret = updatefet_ret(NCM_COMPRESSION, "JPEGB", nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* QUALITY */
sprintf(cbuff, "%d", quality);
if((ret = updatefet_ret(NCM_JPEGB_QUAL, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom))){
if(allocflag)
freefet(nistcom);
return(ret);
}
return(0);
}
/*****************************************************************/
int del_jpegl_nistcom(NISTCOM *nistcom)
{
int ret;
char cbuff[MAXFETLENGTH];
/* COMPRESSION */
if((ret = deletefet_ret(NCM_COMPRESSION, nistcom)))
return(ret);
/* PREDICT */
if((ret = deletefet_ret(NCM_JPEGL_PREDICT, nistcom)))
return(ret);
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom)))
return(ret);
return(0);
}
/*****************************************************************/
int del_wsq_nistcom(NISTCOM *nistcom)
{
int ret;
char cbuff[MAXFETLENGTH];
/* COMPRESSION */
if((ret = deletefet_ret(NCM_COMPRESSION, nistcom)))
return(ret);
/* BITRATE */
if((ret = deletefet_ret(NCM_WSQ_RATE, nistcom)))
return(ret);
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom)))
return(ret);
return(0);
}
/*****************************************************************/
int del_jpegb_nistcom(NISTCOM *nistcom)
{
int ret;
char cbuff[MAXFETLENGTH];
/* COMPRESSION */
if((ret = deletefet_ret(NCM_COMPRESSION, nistcom)))
return(ret);
/* QUALITY */
if((ret = deletefet_ret(NCM_JPEGB_QUAL, nistcom)))
return(ret);
/* UPDATE HEADER */
sprintf(cbuff, "%d", nistcom->num);
if((ret = updatefet_ret(NCM_HEADER, cbuff, nistcom)))
return(ret);
return(0);
}
/************************************/
/* Puts database Ihead into NISTCOM */
/************************************/
int sd_ihead_to_nistcom(NISTCOM **nistcom, IHEAD *ihead, int sd_id)
{
switch(sd_id) {
case 4:
return(sd4_ihead_to_nistcom(nistcom, ihead));
break;
case 9:
return(sd9_10_14_ihead_to_nistcom(nistcom, ihead, sd_id));
break;
case 10:
return(sd9_10_14_ihead_to_nistcom(nistcom, ihead, sd_id));
break;
case 14:
return(sd9_10_14_ihead_to_nistcom(nistcom, ihead, sd_id));
break;
case 18:
return(sd18_ihead_to_nistcom(nistcom, ihead));
break;
default:
fprintf(stderr,
"ERROR : sd_ihead_to_nistcom : invalid database id = %d\n",
sd_id);
fprintf(stderr, " expecting SD 4,9,10,14, or 18\n");
*nistcom = NULL;
return(-2);
}
}
/*******************************/
/* Puts SD4 Ihead into NISTCOM */
/*******************************/
int sd4_ihead_to_nistcom(NISTCOM **onistcom, IHEAD *ihead)
{
char *hst, *fname, *class_str, class, *sex, *pname;
int ret, hst_sz;
NISTCOM *nistcom = NULL;
char cbuff[11], id_str[BUFSIZE];
/** Get information needed from NIST IHEAD Structure **/
strcpy(id_str, ihead->id);
id_str[12] = '\0';
fname = id_str;
if(id_str[14] == ' ')
id_str[14] = '\0';
else
id_str[15] = '\0';
class_str = &(id_str[13]);
sex = &(id_str[16]);
pname = ihead->parent;
/* size of HISTORY field "<fname> <class_str> <pname>\0" */
hst_sz = 2 + strlen(fname) + strlen(class_str) + strlen(pname);
if((hst = (char *)malloc(hst_sz)) == (char *)NULL){
fprintf(stderr, "ERROR : sd4_ihead_to_nistcom : malloc : hst\n");
freefet(nistcom);
return(-2);
}
sprintf(hst, "%s %s %s", fname, class_str, pname);
/* Build the NISTCOM */
if((ret = allocfet_ret(&nistcom, 5))) {
return(ret);
free(hst);
}
if((ret = updatefet_ret(NCM_HEADER, "5", nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
if((ret = updatefet_ret(NCM_SD_ID, "4", nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
if((ret = updatefet_ret(NCM_HISTORY, hst, nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
free(hst);
if((ret = get_sd_class(ihead->id, 4, &class))){
freefet(nistcom);
return(ret);
}
sprintf(cbuff, "%c", class);
if((ret = updatefet_ret(NCM_FING_CLASS, cbuff, nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_SEX, sex, nistcom))) {
freefet(nistcom);
return(ret);
}
*onistcom = nistcom;
return(0);
}
/*****************************************/
/* Puts SD9 SD10 SD14 Ihead into NISTCOM */
/*****************************************/
int sd9_10_14_ihead_to_nistcom(NISTCOM **onistcom, IHEAD *ihead,
const int sd_id)
{
char *hst, *fname, *ncic, class, *sex, *pname, *ink_liv;
char *nptr;
int ret, hst_sz;
NISTCOM *nistcom = NULL;
char cbuff[11], id_str[BUFSIZE];
/* Get information needed from NIST IHEAD Structure */
strcpy(id_str, ihead->id);
id_str[12] = '\0';
fname = id_str;
id_str[14] = '\0';
sex = &(id_str[13]);
id_str[16] = '\0';
ink_liv = &(id_str[15]);
ncic = &(id_str[17]);
nptr = ncic;
/* put "_" in for " " in the "ncic fpw:??" cases to keep class together */
while(*nptr != '\0') {
if(*nptr == ' ')
*nptr = '_';
nptr++;
}
pname = ihead->parent;
/* size of HISTORY field "<fname> <ncic> <pname>\0" */
hst_sz = 3 + strlen(fname) + strlen(ncic) + strlen(pname);
if((hst = (char *)malloc(hst_sz)) == (char *)NULL){
fprintf(stderr, "ERROR : sd4_ihead_to_nistcom : malloc : hst\n");
freefet(nistcom);
return(-2);
}
/*
sprintf(hst, "%s %s %s\0", fname, ncic, pname);
*/
sprintf(hst, "%s %s %s%c", fname, ncic, pname, '\0');
/* Build the NISTCOM */
if((ret = allocfet_ret(&nistcom, 7))) {
free(hst);
return(ret);
}
if(sd_id == 14){
if((ret = updatefet_ret(NCM_HEADER, "7", nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
if((ret = updatefet_ret(NCM_PPI, ihead->density, nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
}
else{
if((ret = updatefet_ret(NCM_HEADER, "6", nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
}
sprintf(cbuff, "%d", sd_id);
if((ret = updatefet_ret(NCM_SD_ID, cbuff, nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
if((ret = updatefet_ret(NCM_HISTORY, hst, nistcom))) {
freefet(nistcom);
free(hst);
return(ret);
}
free(hst);
if((ret = get_sd_class(ihead->id, sd_id, &class))){
freefet(nistcom);
return(ret);
}
sprintf(cbuff, "%c", class);
if((ret = updatefet_ret(NCM_FING_CLASS, cbuff, nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_SEX, sex, nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_SCAN_TYPE, ink_liv, nistcom))) {
freefet(nistcom);
return(ret);
}
*onistcom = nistcom;
return(0);
}
/********************************/
/* Puts SD18 Ihead into NISTCOM */
/********************************/
int sd18_ihead_to_nistcom(NISTCOM **onistcom, IHEAD *ihead)
{
char *fname, *sex, *age;
int ret;
NISTCOM *nistcom;
char id_str[BUFSIZE];
/* Get information needed from NIST IHEAD Structure */
strcpy(id_str, ihead->id);
id_str[12] = '\0';
fname = id_str;
id_str[14] = '\0';
sex = &(id_str[13]);
age = &(id_str[15]);
/* Build the NISTCOM */
if((ret = allocfet_ret(&nistcom, 6)))
return(ret);
if((ret = updatefet_ret(NCM_HEADER, "6", nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_SD_ID, "18", nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_HISTORY, fname, nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_SEX, sex, nistcom))) {
freefet(nistcom);
return(ret);
}
if((ret = updatefet_ret(NCM_AGE, age, nistcom))) {
freefet(nistcom);
return(ret);
}
fname[1] = '\0';
if((ret = updatefet_ret(NCM_FACE_POS, fname, nistcom))) {
freefet(nistcom);
return(ret);
}
*onistcom = nistcom;
return(0);
}
/*******************************************************************/
int get_sd_class(char *id_str, const int sd_id, char *oclass)
{
int ret, n, seqnum;
char class, ncic_str[BUFSIZE];
if(sd_id == 4){
if((n = sscanf(id_str, "%*s %c", &class)) <= 0){
fprintf(stderr, "ERROR : get_sd_class : getting class");
fprintf(stderr, "letter for Special Database 4\n");
return(-2);
}
}
else if(sd_id == 10){
if((n = sscanf(id_str, "%*c%*c%d.%*s %*s %*s %s", &seqnum, ncic_str)) <= 0){
fprintf(stderr, "ERROR : get_sd_class : getting seqnum and ");
fprintf(stderr, "ncic classes for Special Database 10\n");
return(-3);
}
if((ret = get_class_from_ncic_class_string(ncic_str, seqnum, &class)))
return(ret);
}
else if(sd_id == 9 || sd_id == 14){
if((n = sscanf(id_str, "%*c%d.%*s %*s %*s %s", &seqnum, ncic_str)) <= 0){
fprintf(stderr, "ERROR : get_sd_class : getting seqnum and ");
fprintf(stderr, "ncic classes for Special Database 9 or 14\n");
return(-4);
}
if((ret = get_class_from_ncic_class_string(ncic_str, seqnum, &class)))
return(ret);
}
else{
fprintf(stderr, "ERROR : get_sd_class : Invalid");
fprintf(stderr, "database id number (%d)\n", sd_id);
return(-5);
}
*oclass = class;
return(0);
}
/*******************************************************************/
int get_class_from_ncic_class_string(char *ncic_str, const int seqnum, char *oclass)
{
char class, *cptr;
int fing_num, ridge_cnt;
cptr = ncic_str;
if(strncmp(cptr, "ac", 2) == 0)
cptr += 3;
if(strncmp(cptr, "aa", 2) == 0)
class = 'A';
else if(strncmp(cptr, "sr", 2) == 0)
class = 'S';
else if(strncmp(cptr, "tt", 2) == 0)
class = 'T';
else if(strncmp(cptr, "c", 1) == 0)
class = 'W';
else if(strncmp(cptr, "d", 1) == 0)
class = 'W';
else if(strncmp(cptr, "p", 1) == 0)
class = 'W';
else if(strncmp(cptr, "x", 1) == 0)
class = 'W';
else {
ridge_cnt = atoi(cptr);
if(ridge_cnt < 1 || ridge_cnt > 99){
fprintf(stderr, "ERROR : get_class_from_ncic_class_string : ");
fprintf(stderr, "invalid ridge count (%d) from ncic string\n", ridge_cnt);
return(-2);
}
fing_num = seqnum % 10;
if((fing_num && fing_num <= 5) == (ridge_cnt < 50))
class = 'R';
else
class = 'L';
}
*oclass = class;
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/fft/cffti1.c
|
<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/* Changed each _( to plain (. GTC 14 July 1995. */
/* UPDATED: 03/14/2005 by MDG
UPDATED: 08/16/2009 by BBandini - gcc 4.4.1 won't compile math function
when passed a constant; one mod: atan(x)
instead of atan((float)1.).
*/
/* cffti1.f -- translated by f2c (version of 15 October 1990 19:58:17).
You must link the resulting object file with the libraries:
-lF77 -lI77 -lm -lc (in that order)
*/
#include <math.h>
#include "f2c.h"
/* Subroutine */ int cffti1(int *n, real *wa, int *ifac)
{
/* Initialized data */
static int ntryh[4] = { 3,4,2,5 };
/* System generated locals */
int i_1, i_2, i_3;
/* Builtin functions */
/*
double atan(), cos(), sin();
*/
/* Local variables */
static real argh;
static int idot, ntry, i, j;
static real argld;
static int i1, k1, l1, l2, ib;
static real fi;
static int ld, ii, nf, ip, nl, nq, nr;
static real arg;
static int ido, ipm;
static real tpi;
/* ***BEGIN PROLOGUE CFFTI1 */
/* ***PURPOSE Initialize a real and an integer work array for CFFTF1 and
*/
/* CFFTB1. */
/* ***LIBRARY SLATEC (FFTPACK) */
/* ***CATEGORY J1A2 */
/* ***TYPE COMPLEX (RFFTI1-S, CFFTI1-C) */
/* ***KEYWORDS FFTPACK, FOURIER TRANSFORM */
/* ***AUTHOR Swarztrauber, <NAME>., (NCAR) */
/* ***DESCRIPTION */
/* Subroutine CFFTI1 initializes the work arrays WA and IFAC which are */
/* used in both CFFTF1 and CFFTB1. The prime factorization of N and a */
/* tabulation of the trigonometric functions are computed and stored in
*/
/* IFAC and WA, respectively. */
/* Input Parameter */
/* N the length of the sequence to be transformed */
/* Output Parameters */
/* WA a real work array which must be dimensioned at least 2*N. */
/* IFAC an integer work array which must be dimensioned at least 15.
*/
/* The same work arrays can be used for both CFFTF1 and CFFTB1 */
/* as long as N remains unchanged. Different WA and IFAC arrays
*/
/* are required for different values of N. The contents of */
/* WA and IFAC must not be changed between calls of CFFTF1 or */
/* CFFTB1. */
/* ***REFERENCES <NAME>, Vectorizing the FFTs, in Parallel */
/* Computations (<NAME>, ed.), Academic Press, */
/* 1982, pp. 51-83. */
/* ***ROUTINES CALLED (NONE) */
/* ***REVISION HISTORY (YYMMDD) */
/* 790601 DATE WRITTEN */
/* 830401 Modified to use SLATEC library source file format. */
/* 860115 Modified by <NAME> to adhere to Fortran 77 by */
/* (a) changing dummy array size declarations (1) to (*), */
/* (b) changing references to intrinsic function FLOAT */
/* to REAL, and */
/* (c) changing definition of variable TPI by using */
/* FORTRAN intrinsic function ATAN instead of a DATA */
/* statement. */
/* 881128 Modified by <NAME> to meet prologue standards. */
/* 890531 Changed all specific intrinsics to generic. (WRB) */
/* 891214 Prologue converted to Version 4.0 format. (BAB) */
/* 900131 Routine changed from subsidiary to user-callable. (WRB) */
/* 920501 Reformatted the REFERENCES section. (WRB) */
/* ***END PROLOGUE CFFTI1 */
/* Parameter adjustments */
--ifac;
--wa;
/* Function Body */
/* ***FIRST EXECUTABLE STATEMENT CFFTI1 */
nl = *n;
nf = 0;
j = 0;
L101:
++j;
if (j - 4 <= 0) {
goto L102;
} else {
goto L103;
}
L102:
ntry = ntryh[j - 1];
goto L104;
L103:
ntry += 2;
L104:
nq = nl / ntry;
nr = nl - ntry * nq;
if (nr != 0) {
goto L101;
} else {
goto L105;
}
L105:
++nf;
ifac[nf + 2] = ntry;
nl = nq;
if (ntry != 2) {
goto L107;
}
if (nf == 1) {
goto L107;
}
i_1 = nf;
for (i = 2; i <= i_1; ++i) {
ib = nf - i + 2;
ifac[ib + 2] = ifac[ib + 1];
/* L106: */
}
ifac[3] = 2;
L107:
if (nl != 1) {
goto L104;
}
ifac[1] = *n;
ifac[2] = nf;
float x = 1.f;
tpi = atan(x) * (float)8.;
argh = tpi / *n;
i = 2;
l1 = 1;
i_1 = nf;
for (k1 = 1; k1 <= i_1; ++k1) {
ip = ifac[k1 + 2];
ld = 0;
l2 = l1 * ip;
ido = *n / l2;
idot = ido + ido + 2;
ipm = ip - 1;
i_2 = ipm;
for (j = 1; j <= i_2; ++j) {
i1 = i;
wa[i - 1] = (float)1.;
wa[i] = (float)0.;
ld += l1;
fi = (float)0.;
argld = ld * argh;
i_3 = idot;
for (ii = 4; ii <= i_3; ii += 2) {
i += 2;
fi += (float)1.;
arg = fi * argld;
wa[i - 1] = cos(arg);
wa[i] = sin(arg);
/* L108: */
}
if (ip <= 5) {
goto L109;
}
wa[i1 - 1] = wa[i - 1];
wa[i1] = wa[i];
L109:
;
}
l1 = l2;
/* L110: */
}
return 0;
} /* cffti1_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/wrwsqcom/wrwsqcom.c
|
<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/************************************************************************
PACKAGE: IMAGE ENCODER/DECODER TOOLS
FILE: WRWSQCOM.C
AUTHORS: <NAME>
<EMAIL>
DATE: 02/02/2001
UPDATED: 05/10/2005 by MDG
UPDATED: 09/30/2008 by <NAME> - add version option.
#cat: wrwsqcom - takes a WSQ compressed image file and inserts a
#cat: comment in the file at the end of all other comments.
*************************************************************************/
#include <stdio.h>
#include <sys/param.h>
#include <wsq.h>
#include <img_io.h>
#include <imgtype.h>
#include <version.h>
void procargs(int, char **, char **, char **, char **);
int debug = 0;
/******************/
/*Start of Program*/
/******************/
int main(int argc, char *argv[])
{
int n, ret, img_type;
char *ifile, *cfile, *comment_text;
FILE *outfp;
unsigned char *idata, *cdata;
int ilen, clen;
procargs(argc, argv, &ifile, &cfile, &comment_text);
if((ret = read_raw_from_filesize(ifile, &idata, &ilen)))
exit(ret);
if((ret = image_type(&img_type, idata, ilen))) {
free(idata);
exit(ret);
}
if(img_type != WSQ_IMG) {
fprintf(stderr, "ERROR : main : image is not WSQ compressed\n");
free(idata);
exit(-1);
}
if(cfile != (char *)NULL)
if((ret = read_ascii_file(cfile, &comment_text))){
free(idata);
exit(ret);
}
if((ret = add_comment_wsq(&cdata, &clen, idata, ilen,
(unsigned char *)comment_text))) {
free(idata);
if(cfile != (char *)NULL)
free(comment_text);
exit(ret);
}
free(idata);
if(cfile != (char *)NULL)
free(comment_text);
if((outfp = fopen(ifile, "wb")) == NULL) {
fprintf(stderr, "ERROR: main : fopen : %s\n", ifile);
free(cdata);
exit(-2);
}
if((n = fwrite(cdata, 1, clen, outfp)) != clen){
fprintf(stderr, "ERROR: main : fwrite : ");
/* MDG added '%' to 's' in format below on 05/10/2005 */
fprintf(stderr, "only %d of %d bytes written from file %s\n",
n, clen, ifile);
free(cdata);
exit(-3);
}
free(cdata);
fclose(outfp);
exit(0);
}
/*****************************************************************/
void procargs(int argc, char *argv[], char **ifile, char **cfile,
char **ctext)
{
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
if(argc != 4){
fprintf(stderr, "Usage: %s <image file> ", argv[0]);
fprintf(stderr, "<-f comment file | -t comment text>\n");
exit(-1);
}
*ifile = argv[1];
*cfile = (char *)NULL;
*ctext = (char *)NULL;
if(strncmp(argv[2], "-f", 2) == 0)
*cfile = argv[3];
else if(strncmp(argv[2], "-t", 2) == 0)
*ctext = argv[3];
else {
fprintf(stderr, "Usage: %s <image file> ", argv[0]);
fprintf(stderr, "<-f comment file | -t comment text>\n");
exit(-1);
}
return;
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/intrlv.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: INTRLV.C
AUTHORS: <NAME>
<NAME>
DATE: 01/19/2001
UPDATED: 03/15/2005 by MDG
Contains routines responsible for interleaving and de-interleaving
an image pixmap.
ROUTINES:
#cat: intrlv2not_mem - takes an interleaved pixmap and de-interleaves
#cat: its pixels into separate component planes.
#cat: not2intrlv_mem - takes a non-interleaved pixmap and interleaves
#cat: its component planes into a single composite plane.
#cat: compute_component_padding - computes any pixel padding required to
#cat: interleave a pixmap.
#cat: pad_component_planes - pads component planes prior to interleaving
#cat: them into a single plane.
#cat: test_image_size - compares the byte size of a pixmap's datastream
#cat: to component plane downsampling factors passed
#cat: and detects any discrepancy.
***********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include <intrlv.h>
/*****************************************************************/
int intrlv2not_mem(unsigned char **oodata, int *oolen, unsigned char *idata,
const int width, const int height, const int depth,
int *hor_sampfctr, int *vrt_sampfctr, const int n_cmpnts)
{
unsigned char *odata, *iptr, *optrs[MAX_CMPNTS];
int c, a, b, offset, olen;
int samp_width[MAX_CMPNTS], samp_height[MAX_CMPNTS];
int pad_width[MAX_CMPNTS], pad_height[MAX_CMPNTS];
int last_tile_width[MAX_CMPNTS], last_tile_height[MAX_CMPNTS];
int skip_vrt_tile_pad[MAX_CMPNTS];
int max_hor, max_vrt;
int n_hor_tiles, n_vrt_tiles;
int tx, ty;
int ox[MAX_CMPNTS], oy[MAX_CMPNTS];
if(n_cmpnts > MAX_CMPNTS){
fprintf(stderr,
"ERROR : intrlv2not_mem : number of components = %d > %d\n",
n_cmpnts, MAX_CMPNTS);
return(-2);
}
/* Determine max tile dimensions across all components ... */
max_hor = -1;
max_vrt = -1;
for(c = 0; c < n_cmpnts; c++){
if(hor_sampfctr[c] > max_hor)
max_hor = hor_sampfctr[c];
if(vrt_sampfctr[c] > max_vrt)
max_vrt = vrt_sampfctr[c];
}
olen = 0;
for(c = 0; c < n_cmpnts; c++){
/* Compute the pixel width & height of the component's output plane */
/* MINUS ANY IMAGE PADDING according to requirements on the */
/* downsampling function. */
samp_width[c] = (int)ceil(width * (hor_sampfctr[c] / (double)max_hor));
samp_height[c] = (int)ceil(height * (vrt_sampfctr[c] / (double)max_vrt));
/* Increment required size of entire output buffer */
/* MINUS ANY IMAGE PADDING! */
olen += samp_width[c] * samp_height[c];
}
compute_component_padding(pad_width, pad_height,
width, height, samp_width, samp_height,
hor_sampfctr, vrt_sampfctr, n_cmpnts);
/* Allocate output buffer, which is a concatenation of the */
/* component planes MINUS ANY IMAGE PADDING! */
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : intrlv2not_mem : malloc : odata\n");
return(-3);
}
offset = 0;
for(c = 0; c < n_cmpnts; c++){
/* Set pointer to origin of output component plane. */
optrs[c] = odata + offset;
/* Skip to end of current plane in output buffer. */
offset += samp_width[c] * samp_height[c];
/* Initialize tile origin y-pixel coords to top of */
/* output component plane. */
oy[c] = 0;
}
/* Set input data pointer which will be sequantially */
/* addressed throughout the uninterleaving process. */
iptr = idata;
/* Foreach component ... */
for(c = 0; c < n_cmpnts; c++){
last_tile_width[c] = hor_sampfctr[c] - pad_width[c];
last_tile_height[c] = vrt_sampfctr[c] - pad_height[c];
skip_vrt_tile_pad[c] = pad_height[c] * hor_sampfctr[c];
}
/* Compute number of MCU tiles in each component plane. */
/* Note: All component planes are required to share the */
/* same "tile" dimensions. */
n_hor_tiles = (samp_width[0] + pad_width[0]) / hor_sampfctr[0];
n_vrt_tiles = (samp_height[0] + pad_height[0]) / vrt_sampfctr[0];
/* 1. Deal with all but bottom-most row of tiles. */
/* Foreach row of tiles in output component planes ... */
/* Stop one tile short in case of padding ... */
for(ty = 0; ty < n_vrt_tiles-1; ty++){
/* Reset tile origin x-pixel coords to left margin of */
/* each component plane. */
for(c = 0; c < n_cmpnts; c++)
ox[c] = 0;
/* 1a. Deal with all tile in row minus right-most tile. */
/* Foreach col of tiles in output component planes ... */
/* Stop one tile short in case of padding ... */
for(tx = 0; tx < n_hor_tiles-1; tx++){
/* Foreach component ... */
for(c = 0; c < n_cmpnts; c++){
/* Foreach row in component's tile ... */
for(b = 0; b < vrt_sampfctr[c]; b++){
/* Foreach column in component's tile ... */
for(a = 0; a < hor_sampfctr[c]; a++){
/* (Address component plane's origin) + */
*(optrs[c] +
/* (y-pixel offset into component's plane) + */
((oy[c]+b)*samp_width[c]) +
/* (x-pixel offset into component's plane) */
(ox[c]+a)) = *iptr++;
}
}
}
/* Advance to next tile to the right in each component plane. */
for(c = 0; c < n_cmpnts; c++)
ox[c] += hor_sampfctr[c];
}
/* 1b. Deal with right-most tile in row. */
/* Deal with residual in last tile in row. */
/* Foreach component ... */
for(c = 0; c < n_cmpnts; c++){
/* Foreach row in component's tile ... */
for(b = 0; b < vrt_sampfctr[c]; b++){
/* Foreach column in component's tile ... */
for(a = 0; a < last_tile_width[c]; a++){
/* (Address component plane's origin) + */
*(optrs[c] +
/* (y-pixel offset into component's plane) + */
((oy[c]+b)*samp_width[c]) +
/* (x-pixel offset into component's plane) */
(ox[c]+a)) = *iptr++;
}
/* Bump input data pointer. */
iptr += pad_width[c];
}
}
/* Advance to next tile down in each component plane. */
for(c = 0; c < n_cmpnts; c++)
oy[c] += vrt_sampfctr[c];
}
/* 2. Deal with bottom-most row of tiles minus last tile. */
/* Reset tile origin x-pixel coords to left margin of */
/* each component plane. */
for(c = 0; c < n_cmpnts; c++)
ox[c] = 0;
/* Foreach col in last row of tiles ... */
/* Stop one tile short in case of padding ... */
for(tx = 0; tx < n_hor_tiles-1; tx++){
/* Deal with residual in last row of tiles. */
/* Foreach component ... */
for(c = 0; c < n_cmpnts; c++){
/* Foreach row in component's tile ... */
for(b = 0; b < last_tile_height[c]; b++){
/* Foreach column in component's tile ... */
for(a = 0; a < hor_sampfctr[c]; a++){
/* (Address component plane's origin) + */
*(optrs[c] +
/* (y-pixel offset into component's plane) + */
((oy[c]+b)*samp_width[c]) +
/* (x-pixel offset into component's plane) */
(ox[c]+a)) = *iptr++;
}
}
/* Bump input data pointer. */
iptr += skip_vrt_tile_pad[c];
}
/* Advance to next tile to the right in each component plane. */
for(c = 0; c < n_cmpnts; c++)
ox[c] += hor_sampfctr[c];
}
/* 3. Deal with residual in bottom-rightmost tile. */
/* Foreach component ... */
for(c = 0; c < n_cmpnts; c++){
/* Foreach row in component's tile ... */
for(b = 0; b < last_tile_height[c]; b++){
/* Foreach column in component's tile ... */
for(a = 0; a < last_tile_width[c]; a++){
/* (Address component plane's origin) + */
*(optrs[c] +
/* (y-pixel offset into component's plane) + */
((oy[c]+b)*samp_width[c]) +
/* (x-pixel offset into component's plane) */
(ox[c]+a)) = *iptr++;
}
/* Bump input data pointer. */
iptr += pad_width[c];
}
/* Bump input data pointer. */
iptr += skip_vrt_tile_pad[c];
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
int not2intrlv_mem(unsigned char **oodata, int *oolen, unsigned char *idata,
const int width, const int height, const int depth,
int *hor_sampfctr, int *vrt_sampfctr, const int n_cmpnts)
{
unsigned char *odata, *optr, *iptrs[MAX_CMPNTS];
int ret, c, a, b, offset, olen;
int samp_width[MAX_CMPNTS], samp_height[MAX_CMPNTS];
int pad_width[MAX_CMPNTS], pad_height[MAX_CMPNTS];
int new_samp_width[MAX_CMPNTS], new_samp_height[MAX_CMPNTS];
int n_hor_tiles, n_vrt_tiles;
int tx, ty;
int ix[MAX_CMPNTS], iy[MAX_CMPNTS];
if(n_cmpnts > MAX_CMPNTS){
fprintf(stderr,
"ERROR : not2intrlv_mem : number of components = %d > %d\n",
n_cmpnts, MAX_CMPNTS);
return(-2);
}
/* 1. Compute Pixel Pads */
compute_component_padding(pad_width, pad_height,
width, height, samp_width, samp_height,
hor_sampfctr, vrt_sampfctr, n_cmpnts);
/* 2. Pad Component Planes */
if((ret = pad_component_planes(idata, &olen, new_samp_width,
new_samp_height, samp_width, samp_height,
pad_width, pad_height, n_cmpnts)))
return(ret);
/* 3. Interleave Component Planes */
/* Compute number of MCU tiles in each component plane. */
/* Note: All component planes are required to share the */
/* same "tile" dimensions. */
n_hor_tiles = new_samp_width[0] / hor_sampfctr[0];
n_vrt_tiles = new_samp_height[0] / vrt_sampfctr[0];
/* Allocate output buffer, which is same size as concatenation of the */
/* padded component planes. */
odata = (unsigned char *)malloc(olen * sizeof(unsigned char));
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : not2intrlv_mem : malloc : odata\n");
return(-3);
}
offset = 0;
for(c = 0; c < n_cmpnts; c++){
/* Set pointer to origin of input component plane. */
iptrs[c] = idata + offset;
/* Skip to end of current plane in padded input buffer. */
offset += new_samp_width[c] * new_samp_height[c];
/* Initialize tile origin y-pixel coords to top of */
/* input component plane. */
iy[c] = 0;
}
/* Set output data pointer which will be sequantially */
/* addressed throughout the interleaving process. */
optr = odata;
/* Foreach row of tiles in input component planes ... */
for(ty = 0; ty < n_vrt_tiles; ty++){
/* Reset tile origin x-pixel coords to left margin of */
/* each component plane. */
for(c = 0; c < n_cmpnts; c++)
ix[c] = 0;
/* Foreach col of tiles in input component planes ... */
for(tx = 0; tx < n_hor_tiles; tx++){
/* Foreach component ... */
for(c = 0; c < n_cmpnts; c++){
/* Foreach row in component's tile ... */
for(b = 0; b < vrt_sampfctr[c]; b++){
/* Foreach column in component's tile ... */
for(a = 0; a < hor_sampfctr[c]; a++){
/* (Address component plane's origin) + */
*optr++ = *(iptrs[c] +
/* (y-pixel offset into component's plane) + */
((iy[c]+b)*new_samp_width[c]) +
/* (x-pixel offset into component's plane) */
(ix[c]+a));
}
}
}
/* Advance to next tile to the right in each component plane. */
for(c = 0; c < n_cmpnts; c++)
ix[c] += hor_sampfctr[c];
}
/* Advance to next tile down in each component plane. */
for(c = 0; c < n_cmpnts; c++)
iy[c] += vrt_sampfctr[c];
}
*oodata = odata;
*oolen = olen;
return(0);
}
/*****************************************************************/
void compute_component_padding(int *pad_width, int *pad_height,
const int width, const int height,
int *samp_width, int *samp_height,
int *hor_sampfctr, int *vrt_sampfctr,
const int n_cmpnts)
{
int c;
int max_hor, max_vrt;
/* Determine max tile dimensions across all components ... */
max_hor = -1;
max_vrt = -1;
for(c = 0; c < n_cmpnts; c++){
if(hor_sampfctr[c] > max_hor)
max_hor = hor_sampfctr[c];
if(vrt_sampfctr[c] > max_vrt)
max_vrt = vrt_sampfctr[c];
}
/* Compute Pixel Pads */
/* Compute "real" pixel dimensions of component planes and */
/* compute potential pixel pads for each component plane. */
for(c = 0; c < n_cmpnts; c++){
/* Compute the pixel width of the component's output plane. */
samp_width[c] = (int)ceil(width * (hor_sampfctr[c] / (double)max_hor));
pad_width[c] = ((int)ceil(samp_width[c]/(double)hor_sampfctr[c]) *
hor_sampfctr[c]) - samp_width[c];
/* Compute the pixel height of the component's output plane. */
samp_height[c] = (int)ceil(height * (vrt_sampfctr[c] / (double)max_vrt));
pad_height[c] = ((int)ceil(samp_height[c]/(double)vrt_sampfctr[c]) *
vrt_sampfctr[c]) - samp_height[c];
}
}
/*****************************************************************/
int pad_component_planes(unsigned char *idata, int *onlen,
int *new_samp_width, int *new_samp_height,
int *samp_width, int *samp_height,
int *pad_width, int *pad_height, const int n_cmpnts)
{
int c, padflag, i, j, x, y, nlen;
unsigned char *soptr, *sptr, *doptr, *dptr, *d2ptr, *spptr, *dpptr;
int padval;
nlen = 0;
padflag = 0;
for(c = 0; c < n_cmpnts; c++){
if((pad_width[c] != 0) || (pad_height[c] != 0))
padflag = 1;
new_samp_width[c] = samp_width[c] + pad_width[c];
new_samp_height[c] = samp_height[c] + pad_height[c];
nlen += new_samp_width[c] * new_samp_height[c];
}
/* If not padding is necessary ... */
if(!padflag){
*onlen = nlen;
return(0);
}
if(realloc(idata, nlen * sizeof(unsigned char)) == (void *)NULL){
fprintf(stderr, "ERROR : pad_component_planes : realloc : idata\n");
return(-2);
}
/* Set pointer to origin of last component plane. */
soptr = idata;
doptr = idata;
for(c = 0; c < n_cmpnts-1; c++){
soptr += (samp_width[c] * samp_height[c]);
doptr += (new_samp_width[c] * new_samp_height[c]);
}
/* From last to first component plane ... */
for(c = n_cmpnts-1; c >= 0; c--){
/* Start at last scanline in source component plane. */
sptr = soptr + ((samp_height[c] - 1) * samp_width[c]);
/* Start at corresponding scanline in destination component plane. */
dptr = doptr + ((samp_height[c] - 1) * new_samp_width[c]);
/* Copy source scanline to destination component plane, */
/* ONE PIXEL AT A TIME for memory space reasons. */
spptr = sptr + samp_width[c] - 1;
dpptr = dptr + samp_width[c] - 1;
for(x = 0; x < samp_width[c]; x++){
*dpptr-- = *spptr--;
}
/* Pad right of bottom scanline. */
padval = *(dptr + samp_width[c] - 1);
for(i = 0; i < pad_width[c]; i++)
*(dptr+samp_width[c]+i) = padval;
/* Pad bottom of component plane, if needed. */
if(pad_height[c] > 0){
/* Set new destination pointer down one scanline. */
d2ptr = dptr + new_samp_width[c];
for(j = 0; j < pad_height[c]; j++){
/* Copy bottom scanline down. */
memcpy(d2ptr, dptr, new_samp_width[c]);
d2ptr += new_samp_width[c];
}
}
/* Back up one source scanline. */
sptr -= samp_width[c];
/* Back up one destination scanline. */
dptr -= new_samp_width[c];
/* Foreach row in original source component plane */
/* (minus the last one which is already copied) ... */
for(y = 1; y < samp_height[c]; y++){
/* Copy source scanline to destination component plane, */
/* ONE PIXEL AT A TIME for memory space reasons. */
spptr = sptr + samp_width[c] - 1;
dpptr = dptr + samp_width[c] - 1;
for(x = 0; x < samp_width[c]; x++){
*dpptr-- = *spptr--;
}
/* Pad right of destination scanline. */
padval = *(dptr + samp_width[c] - 1);
for(i = 0; i < pad_width[c]; i++)
*(dptr+samp_width[c]+i) = padval;
/* Back up one source scanline. */
sptr -= samp_width[c];
/* Back up one destination scanline. */
dptr -= new_samp_width[c];
}
/* If not at first component plane ... */
if(c > 0){
/* Set origin pointers to new component planes up the list. */
soptr -= (samp_width[c-1] * samp_height[c-1]);
doptr -= (new_samp_width[c-1] * new_samp_height[c-1]);
}
}
*onlen = nlen;
return(0);
}
/*****************************************************************/
int test_image_size(const int ilen, const int w, const int h, int *hor_sampfctr,
int *vrt_sampfctr, const int n_cmpnts, const int intrlvflag)
{
int c, olen;
int samp_width[MAX_CMPNTS], samp_height[MAX_CMPNTS];
int pad_width[MAX_CMPNTS], pad_height[MAX_CMPNTS];
int max_hor, max_vrt;
max_hor = -1;
max_vrt = -1;
for(c = 0; c < n_cmpnts; c++){
if(hor_sampfctr[c] > max_hor)
max_hor = hor_sampfctr[c];
if(vrt_sampfctr[c] > max_vrt)
max_vrt = vrt_sampfctr[c];
}
for(c = 0; c < n_cmpnts; c++){
/* Compute the pixel width & height for each plane in the image */
samp_width[c] = (int)ceil(w * (hor_sampfctr[c] / (double)max_hor));
samp_height[c] = (int)ceil(h * (vrt_sampfctr[c] / (double)max_vrt));
pad_width[c] = 0;
pad_height[c] = 0;
}
if(intrlvflag)
compute_component_padding(pad_width, pad_height,
w, h, samp_width, samp_height,
hor_sampfctr, vrt_sampfctr, n_cmpnts);
olen = 0;
for(c = 0; c < n_cmpnts; c++)
olen += (samp_width[c]+pad_width[c])*(samp_height[c]+pad_height[c]);
if(olen != ilen) {
fprintf(stderr, "ERROR : check_filesize : given file size %d ", ilen);
fprintf(stderr, "not equal to computed filesize %d\n", olen);
return(-2);
}
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/djpeglsd/djpeglsd.c
|
<reponame>ThalesGroup/WSQForAndroid<filename>library/src/main/cpp/nbis/imgtools/src/bin/djpeglsd/djpeglsd.c
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/************************************************************************
PACKAGE: IMAGE ENCODER/DECODER TOOLS
FILE: DJPEGL.C
AUTHORS: <NAME>
<EMAIL>
DATE: 12/15/2000
UPDATED: 05/09/2005 by MDG
UPDATED: 09/30/2008 by Kenenth Ko - add version option.
#cat: djpeglsd - Takes an IHead formatted, JPEGL compressed, image file,
#cat: such as those distributed with NIST Special Databases
#cat: {4,9,10,18} and decodes it, reconstructing a "lossless"
#cat: pixmap and saving it to an IHead or raw image file.
#cat: If the input file is from a NIST Special Database, then
#cat: image attributes are stored as a separate NISTCOM text file.
#cat: This program should be used to convert legacy data only.
#cat: The format of the files processed by this program should
#cat: be considered obsolete.
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <jpeglsd4.h>
#include <ihead.h>
#include <nistcom.h>
#include <memalloc.h>
#include <img_io.h>
#include <ioutil.h>
#include <version.h>
#define SD_NUM 4
int sd_list[] = {4,9,10,18};
/**************/
/*routine list*/
/**************/
void procargs(int, char **, char **, char **, int *, int *);
int debug = 0;
/**************/
/*main routine*/
/**************/
int main(int argc, char *argv[])
{
FILE *fp;
int ret, rawflag, sd_id;
char *outext, *ifile, ofile[MAXPATHLEN];
IHEAD *ihead;
int width, height, depth, ppi;
unsigned char *idata, *odata;
int i, complen, compcode;
NISTCOM *nistcom;
procargs(argc, argv, &outext, &ifile, &sd_id, &rawflag);
nistcom = (NISTCOM *)NULL;
/* Read ihead header to get image compression information */
fp = fopen(ifile, "rb");
if(fp == (FILE *)NULL) {
fprintf(stderr, "ERROR : main : fopen : %s\n", ifile);
exit(-1);
}
ihead = readihdr(fp);
if(ihead == (IHEAD *)NULL) {
fprintf(stderr, "ERROR : main : readihdr : ihead\n");
fclose(fp);
exit(-1);
}
/* Get image attributes from header */
sscanf(ihead->height,"%d", &height);
sscanf(ihead->width,"%d", &width);
sscanf(ihead->depth,"%d", &depth);
sscanf(ihead->density,"%d", &ppi);
sscanf(ihead->complen,"%d", &complen);
sscanf(ihead->compress,"%d", &compcode);
/* Convert image attributes to a nistcom comment */
if(sd_id){
if((ret = sd_ihead_to_nistcom(&nistcom, ihead, sd_id))) {
fclose(fp);
free(ihead);
exit(ret);
}
}
free(ihead);
if((ret = combine_jpegl_nistcom(&nistcom, width, height, depth, ppi, 0, 1,
(int *)NULL, (int *)NULL, 0, -1))) {
fclose(fp);
exit(ret);
}
if((ret = del_jpegl_nistcom(nistcom))){
freefet(nistcom);
fclose(fp);
exit(ret);
}
/* If old JPEGL compressed file ... */
if(compcode == JPEG_SD) {
/* Allocate space and read compressed data */
idata = (unsigned char *)malloc(complen * sizeof(unsigned char));
if(idata == (unsigned char *)NULL) {
fprintf(stderr, "ERROR : main : malloc : idata\n");
fclose(fp);
freefet(nistcom);
exit(-1);
}
i = fread(idata, sizeof(unsigned char), complen, fp);
if(i != complen) {
fprintf(stderr, "ERROR : main : fread : %s\n", ifile);
fclose(fp);
freefet(nistcom);
free(idata);
exit(-1);
}
fclose(fp);
/* Allocate space for decompressed data */
malloc_uchar(&odata, width*height, "main");
odata = (unsigned char *)malloc(width*height * sizeof(unsigned char));
if(odata == (unsigned char *)NULL) {
fprintf(stderr, "ERROR : main : malloc : odata\n");
freefet(nistcom);
free(idata);
exit(-1);
}
/* Decompress data block */
if((ret = jpegl_sd4_decode_mem(idata, complen,
width, height, depth, odata))){
freefet(nistcom);
free(idata);
free(odata);
exit(ret);
}
free(idata);
fileroot(ifile);
sprintf(ofile, "%s.%s", ifile, NCM_EXT);
/* Write a nistcom file */
if((ret = writefetfile_ret(ofile, nistcom))){
freefet(nistcom);
free(odata);
exit(ret);
}
freefet(nistcom);
sprintf(ofile, "%s.%s", ifile, outext);
/* Write decompressed data */
if((ret = write_raw_or_ihead(!rawflag, ofile, odata, width, height, depth, ppi))) {
free(odata);
exit(ret);
}
free(odata);
}
/* else, Not a old JPEGL compressed file ... */
else
fprintf(stderr, "WARNING : main : Image not JPEGL SD[4,9,10,18] compressed, DO NOTHING\n");
exit(0);
}
/*******************************************/
/*routine to process command line arguments*/
/*******************************************/
void procargs(int argc, char *argv[], char **outext, char **ifile,
int *sd_id, int *rawflag)
{
int i, argi, found;
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
if(argc < 3) {
fprintf(stderr, "Usage: %s <outext> <image file> [-sd #] [-raw_out]\n", argv[0]);
exit(-1);
}
*outext = argv[1];
*ifile = argv[2];
*rawflag = 0;
*sd_id = 0;
if(argc == 3)
return;
argi = 3;
if(strncmp(argv[argi], "-s", 2) == 0) {
argi++;
if(argc >= 5) {
*sd_id = atoi(argv[argi]);
found = 0;
for(i = 0; i < SD_NUM; i++){
if(*sd_id == sd_list[i]){
found = 1;
break;
}
}
if(!found){
fprintf(stderr, "Usage: %s <outext> <image file> [-sd #] [-raw_out]\n", argv[0]);
fprintf(stderr, " SD list = {4,9,10,18}\n");
fprintf(stderr, " SD %d is not a recognized database\n", *sd_id);
exit(-1);
}
}
else {
fprintf(stderr, "Usage: %s <outext> <image file> [-sd #] [-raw_out]\n", argv[0]);
exit(-1);
}
argi++;
if(argi >= argc)
return;
}
if((strncmp(argv[argi], "-r", 2) == 0) ||
(strncmp(argv[argi], "-raw", 4) == 0) ||
(strncmp(argv[argi], "-raw_out", 28) == 0)){
*rawflag = 1;
return;
}
else {
fprintf(stderr, "Usage: %s <outext> <image file> [-sd #] [-raw_out]\n", argv[0]);
exit(-1);
}
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/lib/image/imgdecod.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IMAGE - Image Manipulation and Processing Routines
FILE: IMGDECOD.C
AUTHORS: <NAME>
DATE: 03/08/2001
UPDATED: 03/15/2005 by MDG
01/24/2008 by <NAME>
UPDATED: 01/06/2009 by <NAME> - add support for HPUX compile
02/25/2015 (Kenneth Ko) - Updated everything related to
OPENJPEG to OPENJP2
Contains routines responsible for taking a formatted datastream
of potentially compressed image pixels, identifying the format
type of the datastream if possible, and then decoding the
datastream returning a reconstructed pixmap.
ROUTINES:
#cat: read_and_decode_grayscale_image - identifies and reconstructs a
#cat: potentially compressed datastream of grayscale image pixels
#cat: (including AN2K files) for use by fingerprint image applications
#cat: read_and_decode_image - identifies and reconstructs a
#cat: potentially compressed datastream of image pixels.
#cat: ihead_decode_mem - decodes (if necessary) a datastream of
#cat: IHead formatted pixels from a memory buffer.
***********************************************************************/
#include <stdio.h>
#include <defs.h>
#include <img_io.h>
#include <imgutil.h>
#include <imgdecod.h>
#include <grp4deco.h>
#include <intrlv.h>
#include <util.h>
#ifdef __NBIS_PNG__
#include <png_dec.h>
#endif
#ifdef __NBIS_JASPER__
#include <jpeg2k.h>
#endif
#ifdef __NBIS_OPENJP2__
#include <jpeg2k.h>
#endif
/*******************************************************************/
int read_and_decode_grayscale_image(char *ifile, int *oimg_type,
unsigned char **odata, int *olen,
int *ow, int *oh, int *od, int *oppi)
{
int ret;
unsigned char *idata;
int img_type, ilen;
int w, h, d, ppi;
int intrlvflag;
int hor_sampfctr[MAX_CMPNTS], vrt_sampfctr[MAX_CMPNTS], n_cmpnts;
ANSI_NIST *ansi_nist;
RECORD *imgrecord;
int img_idc, img_imp, imgrecord_i;
double ppmm;
*odata = (unsigned char *)NULL;
*olen = 0;
/* Is input image an ANSI_NIST file?*/
ret = is_ANSI_NIST_file(ifile);
/* If system error ... */
if(ret < 0)
return(ret);
/* YES, image is ANSI_NIST */
if(ret == TRUE){
/* Read the ANSI/NIST file into memory. */
if((ret = read_ANSI_NIST_file(ifile, &ansi_nist)))
return(ret);
/* Get first grayscale fingerprint record in ansi/nist file. */
ret = get_first_grayprint(&idata, &w, &h, &d,
&ppmm, &img_idc, &img_imp,
&imgrecord, &imgrecord_i, ansi_nist);
/* If error ... */
if(ret < 0){
free_ANSI_NIST(ansi_nist);
return(ret);
}
/* If grayscale fingerprint not found ... */
if(!ret){
fprintf(stderr, "ERROR : read_and_decode_grayscale_image : ");
fprintf(stderr, "grayscale image record not found in %s\n", ifile);
free_ANSI_NIST(ansi_nist);
return(-2);
}
free_ANSI_NIST(ansi_nist);
img_type = ANSI_NIST_IMG;
ilen = w * h;
ppi = sround(ppmm * MM_PER_INCH);
}
/* Image is not ANSI_NIST ... */
else {
/* Read in and decode image file. */
if((ret = read_and_decode_image(ifile, &img_type, &idata, &ilen,
&w, &h, &d, &ppi, &intrlvflag,
hor_sampfctr, vrt_sampfctr, &n_cmpnts))){
return(ret);
}
/* Image type UNKNOWN (perhaps raw), not supported */
if(img_type == UNKNOWN_IMG){
free(idata);
fprintf(stderr, "ERROR : read_and_decode_grayscale_image : ");
fprintf(stderr, "%s : image type UNKNOWN : not supported\n",
ifile);
return(-3);
}
/* Only desire grayscale images ... */
if(d != 8){
free(idata);
fprintf(stderr, "ERROR : read_and_decode_grayscale_image : ");
fprintf(stderr, "%s : image depth : %d != 8\n",
ifile, d);
return(-4);
}
}
*oimg_type = img_type;
*odata = idata;
*olen = ilen;
*ow = w;
*oh = h;
*od = d;
*oppi = ppi;
return(0);
}
/*******************************************************************/
int read_and_decode_dpyimage(char *ifile, int *oimg_type,
unsigned char **odata, int *olen,
int *ow, int *oh, int *od, int *oppi)
{
int ret, i, found;
unsigned char *idata, *ndata;
int img_type, ilen, nlen;
int w, h, d, ppi;
int intrlvflag;
int hor_sampfctr[MAX_CMPNTS], vrt_sampfctr[MAX_CMPNTS], n_cmpnts;
*odata = (unsigned char *)NULL;
*olen = 0;
/* Read in and decode image file. */
if((ret = read_and_decode_image(ifile, &img_type, &idata, &ilen,
&w, &h, &d, &ppi, &intrlvflag,
hor_sampfctr, vrt_sampfctr, &n_cmpnts))){
return(ret);
}
/* If image type is UNKNOWN ... simply return what was read. */
if(img_type == UNKNOWN_IMG){
*oimg_type = img_type;
*odata = idata;
*olen = ilen;
*ow = w;
*oh = h;
*od = d;
*oppi = ppi;
return(0);
}
/* Dpyimage can only handle these pixel depths ... */
if((d != 1) && (d != 8) && (d != 24)){
fprintf(stderr, "WARNING : read_and_decode_dpyimage : ");
fprintf(stderr, "file %s IGNORED : pixdepth = %d != {1,8,24}\n",
ifile, d);
return(IMG_IGNORE);
}
/* Dpyimage cannot handle downsampled component planes. */
if((img_type == JPEGL_IMG) && (n_cmpnts > 1)){
found = 0;
for(i = 0; i < n_cmpnts; i++){
if((hor_sampfctr[i] != 1) ||
(vrt_sampfctr[i] != 1)){
found = 1;
break;
}
}
if(found){
fprintf(stderr, "WARNING : read_and_decode_dpyimage : ");
fprintf(stderr, "file %s IGNORED : ", ifile);
fprintf(stderr, "contains HV sample factor(s) != 1\n");
return(IMG_IGNORE);
}
}
/* Dpyimage cannot handle non-interleaved pixel data, */
/* so interleave the image data if necessary. */
if((d == 24) && (!intrlvflag)){
if((ret = not2intrlv_mem(&ndata, &nlen, idata, w, h, d,
hor_sampfctr, vrt_sampfctr, n_cmpnts))){
free(idata);
return(ret);
}
free(idata);
idata = ndata;
ilen = nlen;
}
*oimg_type = img_type;
*odata = idata;
*olen = ilen;
*ow = w;
*oh = h;
*od = d;
*oppi = ppi;
return(0);
}
/*******************************************************************/
int read_and_decode_image(char *ifile, int *oimg_type,
unsigned char **odata, int *olen,
int *ow, int *oh, int *od, int *oppi, int *ointrlvflag,
int *hor_sampfctr, int *vrt_sampfctr, int *on_cmpnts)
{
int ret, i;
unsigned char *idata, *ndata;
int img_type, ilen, nlen;
int w, h, d, ppi, lossyflag, intrlvflag = 0, n_cmpnts;
IMG_DAT *img_dat;
if((ret = read_raw_from_filesize(ifile, &idata, &ilen)))
return(ret);
if((ret = image_type(&img_type, idata, ilen))){
free(idata);
return(ret);
}
switch(img_type){
case UNKNOWN_IMG:
/* Return raw image data as read from file. */
*oimg_type = img_type;
*odata = idata;
*olen = ilen;
*ow = -1;
*oh = -1;
*od = -1;
*oppi = -1;
*ointrlvflag = -1;
*on_cmpnts = -1;
return(0);
case WSQ_IMG:
if((ret = wsq_decode_mem(&ndata, &w, &h, &d, &ppi, &lossyflag,
idata, ilen))){
free(idata);
return(ret);
}
nlen = w * h;
/* Pix depth always 8 for WSQ ... */
n_cmpnts = 1;
hor_sampfctr[0] = 1;
vrt_sampfctr[0] = 1;
break;
case JPEGL_IMG:
if((ret = jpegl_decode_mem(&img_dat, &lossyflag, idata, ilen))){
free(idata);
return(ret);
}
if((ret = get_IMG_DAT_image(&ndata, &nlen, &w, &h, &d, &ppi,
img_dat))){
free(idata);
free_IMG_DAT(img_dat, FREE_IMAGE);
return(ret);
}
/* JPEGL always returns non-interleaved data. */
intrlvflag = 0;
n_cmpnts = img_dat->n_cmpnts;
if(d == 24){
for(i = 0; i < n_cmpnts; i++){
hor_sampfctr[i] = img_dat->hor_sampfctr[i];
vrt_sampfctr[i] = img_dat->vrt_sampfctr[i];
}
}
free_IMG_DAT(img_dat, FREE_IMAGE);
break;
case JPEGB_IMG:
if((ret = jpegb_decode_mem(&ndata, &w, &h, &d, &ppi, &lossyflag,
idata, ilen))){
free(idata);
return(ret);
}
if(d == 8){
n_cmpnts = 1;
intrlvflag = 0;
}
else if(d == 24){
n_cmpnts = 3;
intrlvflag = 1;
}
else{
fprintf(stderr, "ERROR : read_and_decode_image : ");
fprintf(stderr, "JPEGB decoder returned d=%d ", d);
fprintf(stderr, "not equal to 8 or 24\n");
free(idata);
return(-2);
}
nlen = w * h * (d>>3);
for(i = 0; i < n_cmpnts; i++){
hor_sampfctr[i] = 1;
vrt_sampfctr[i] = 1;
}
break;
case IHEAD_IMG:
if((ret = ihead_decode_mem(&ndata, &w, &h, &d, &ppi, &lossyflag,
idata, ilen))){
free(idata);
return(ret);
}
nlen = SizeFromDepth(w,h,d);
if((d == 1) || (d == 8)){
n_cmpnts = 1;
intrlvflag = 0;
}
else if(d == 24){
n_cmpnts = 3;
intrlvflag = 1;
}
else{
fprintf(stderr, "ERROR : read_and_decode_image : ");
fprintf(stderr, "IHead decoder returned d=%d ", d);
fprintf(stderr, "not equal to {1,8,24}\n");
free(idata);
return(-2);
}
for(i = 0; i < n_cmpnts; i++){
hor_sampfctr[i] = 1;
vrt_sampfctr[i] = 1;
}
break;
#ifdef __NBIS_JASPER__
case JP2_IMG:
if((ret = jpeg2k_decode_mem(&img_dat, &lossyflag, idata, ilen))){
free(idata);
return(ret);
}
if((ret = get_IMG_DAT_image(&ndata, &nlen, &w, &h, &d, &ppi,
img_dat))){
free(idata);
free_IMG_DAT(img_dat, FREE_IMAGE);
return(ret);
}
/* JPEG2K always returns non-interleaved data. */
intrlvflag = 0;
n_cmpnts = img_dat->n_cmpnts;
if(d == 24){
for(i = 0; i < n_cmpnts; i++){
hor_sampfctr[i] = img_dat->hor_sampfctr[i];
vrt_sampfctr[i] = img_dat->vrt_sampfctr[i];
}
}
free_IMG_DAT(img_dat, FREE_IMAGE);
break;
#endif
#ifdef __NBIS_OPENJP2__
case JP2_IMG:
if((ret = openjpeg2k_decode_mem(&img_dat, &lossyflag, idata, ilen))){
free(idata);
return(ret);
}
if((ret = get_IMG_DAT_image(&ndata, &nlen, &w, &h, &d, &ppi,
img_dat))){
free(idata);
free_IMG_DAT(img_dat, FREE_IMAGE);
return(ret);
}
/* OPENJPEG always returns non-interleaved data. */
intrlvflag = 0;
n_cmpnts = img_dat->n_cmpnts;
if(d == 24){
for(i = 0; i < n_cmpnts; i++){
hor_sampfctr[i] = img_dat->hor_sampfctr[i];
vrt_sampfctr[i] = img_dat->vrt_sampfctr[i];
}
}
free_IMG_DAT(img_dat, FREE_IMAGE);
break;
#endif
#ifdef __NBIS_PNG__
case PNG_IMG:
if((ret = png_decode_mem(&img_dat, &lossyflag, idata, ilen))){
free(idata);
return(ret);
}
if((ret = get_IMG_DAT_image(&ndata, &nlen, &w, &h, &d, &ppi,
img_dat))){
free(idata);
free_IMG_DAT(img_dat, FREE_IMAGE);
return(ret);
}
/* PNG always returns non-interleaved data. */
intrlvflag = 0;
n_cmpnts = img_dat->n_cmpnts;
if(d == 24){
for(i = 0; i < n_cmpnts; i++){
hor_sampfctr[i] = img_dat->hor_sampfctr[i];
vrt_sampfctr[i] = img_dat->vrt_sampfctr[i];
}
}
free_IMG_DAT(img_dat, FREE_IMAGE);
break;
#endif
default:
fprintf(stderr, "ERROR : read_and_decode_image : ");
fprintf(stderr, "illegal image type = %d\n", img_type);
return(-3);
}
free(idata);
*oimg_type = img_type;
*odata = ndata;
*olen = nlen;
*ow = w;
*oh = h;
*od = d;
*oppi = ppi;
*ointrlvflag = intrlvflag;
*on_cmpnts = n_cmpnts;
return(0);
}
/*******************************************************************/
int ihead_decode_mem(unsigned char **oodata, int *ow, int *oh, int *od,
int *oppi, int *lossyflag,
unsigned char *idata, const int ilen)
{
IHEAD *ihead;
unsigned char *odata, *iptr;
int olen, obytes, w, h, d, ppi;
int compcode, complen = 0;
/* Skip first fized length size field. */
iptr = idata + SHORT_CHARS;
ihead = (IHEAD *)iptr;
iptr += sizeof(IHEAD);
w = get_width(ihead);
h = get_height(ihead);
d = get_depth(ihead);
ppi = get_density(ihead);
compcode = get_compression(ihead);
olen = SizeFromDepth(w,h,d);
odata = (unsigned char *)malloc(olen);
if(odata == (unsigned char *)NULL){
fprintf(stderr, "ERROR : ihead_decode_mem : malloc : odata\n");
return(-2);
}
if(compcode != UNCOMP){
complen = get_complen(ihead);
}
switch (compcode) {
case RL:
rldecomp(iptr, complen, odata, &obytes, olen);
set_compression(ihead, UNCOMP);
set_complen(ihead, 0);
break;
case CCITT_G4:
if(ihead->sigbit == LSBF) {
inv_bytes(iptr, complen);
ihead->sigbit = MSBF;
ihead->byte_order = HILOW;
}
grp4decomp(iptr, complen, w, h, odata, &obytes);
set_compression(ihead, UNCOMP);
set_complen(ihead, 0);
break;
case UNCOMP:
memcpy(odata, iptr, olen);
break;
default:
fprintf(stderr, "ERROR : ihead_decode_mem : ");
fprintf(stderr, "invalid compression code = %d\n", compcode);
return(-3);
break;
}
*oodata = odata;
*ow = w;
*oh = h;
*od = d;
*oppi = ppi;
*lossyflag = 0;
return(0);
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/dwsq14/dwsq14.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/************************************************************************
PACKAGE: IMAGE ENCODER/DECODER TOOLS
FILE: DWSQ14.C
AUTHORS: <NAME>
<EMAIL>
<NAME>
<EMAIL>
DATE: 11/24/1999
UPDATED: 05/09/2005 by MDG
UPDATED: 09/30/2008 by Kenenth Ko - add version option.
#cat: dwsq14 - Takes an IHead formatted, WSQ compressed, image file,
#cat: such as those used in the distribution of legacy data on
#cat: NIST Special Database 14 and decodes it, reconstructing a
#cat: "lossy" pixmap and saving it to an IHead or raw image file.
#cat: This program should be used to convert legacy data only.
#cat: The format of the files processed by this program should
#cat: be considered obsolete.
*************************************************************************/
#include <stdio.h>
#include <sys/param.h>
#include <stdlib.h>
#include <wsq.h>
#include <ihead.h>
#include <nistcom.h>
#include <imgtype.h>
#include <img_io.h>
#include <version.h>
extern int wsq14_decode_file(unsigned char **, int *, int *, int *, int *,
FILE *);
void procargs(int, char **, char **, char **, int *);
int debug = 0;
/******************/
/*Start of Program*/
/******************/
int main(int argc, char *argv[])
{
int ret, rawflag, img_type;
unsigned char *idata, *odata;
int ilen, width, height, depth, ppi, lossyflag;
IHEAD *ihead;
FILE *fp;
char *outext, *ifile, ofile[MAXPATHLEN];
NISTCOM *nistcom;
procargs(argc, argv, &outext, &ifile, &rawflag);
/* Set ppi to unknown */
ppi = -1;
nistcom = (NISTCOM *)NULL;
/* Check image type */
if((ret = read_raw_from_filesize(ifile, &idata, &ilen)))
exit(ret);
if((ret = image_type(&img_type, idata, ilen))) {
free(idata);
exit(ret);
}
free(idata);
/* Open image file for reading based on image type */
if((fp = fopen(ifile,"rb")) == NULL) {
fprintf(stderr, "ERROR: main : fopen : %s\n",ifile);
exit(-1);
}
/* If img_type is ihead ... */
if(img_type == IHEAD_IMG){
/* Read ihead header and check for WSQ_SD14 compression */
ihead = readihdr(fp);
if(atoi(ihead->compress) != WSQ_SD14){
fprintf(stderr, "ERROR : main : input image not WSQ_SD14 compressed\n");
fprintf(stderr, " compression = %d, WSQ_SD14 = %d\n",
atoi(ihead->compress), WSQ_SD14);
fclose(fp);
free(ihead);
exit(-1);
}
/* Get ppi from ihead header */
sscanf(ihead->density,"%d", &ppi);
/* Create a nistcom for the image attributes */
if((ret = sd_ihead_to_nistcom(&nistcom, ihead, 14))) {
fclose(fp);
free(ihead);
exit(ret);
}
free(ihead);
}
/* If image not WSQ_IMG or IHEAD_IMG, ERROR!!! */
else if(img_type != WSQ_IMG) {
fprintf(stderr, "ERROR : main : Invalid image\n");
fprintf(stderr, "Expected a WSQ_SD14 compressed image in\n");
fprintf(stderr, "either raw or ihead format.\n");
fclose(fp);
exit(-1);
}
/* Decode compressed image */
if((ret = wsq14_decode_file(&odata, &width, &height, &depth, &lossyflag,
fp))){
fclose(fp);
if(img_type == IHEAD_IMG)
freefet(nistcom);
exit(ret);
}
fclose(fp);
if(debug > 1)
fprintf(stderr, "Image pixmap constructed\n");
/* Combine image attributes into current nistcom */
if((ret = combine_wsq_nistcom(&nistcom, width, height, depth, ppi,
lossyflag, -1.0))){
if(img_type == IHEAD_IMG)
freefet(nistcom);
free(odata);
exit(ret);
}
if((ret = del_wsq_nistcom(nistcom))){
free(odata);
freefet(nistcom);
exit(ret);
}
fileroot(ifile);
sprintf(ofile, "%s.%s", ifile, NCM_EXT);
/* Write NISTCOM */
if((ret = writefetfile_ret(ofile, nistcom))){
freefet(nistcom);
free(odata);
exit(ret);
}
freefet(nistcom);
/* Write decompressed image */
sprintf(ofile, "%s.%s", ifile, outext);
if((ret = write_raw_or_ihead(!rawflag, ofile, odata, width, height,
depth, ppi))){
free(odata);
exit(ret);
}
free(odata);
if(debug > 1)
fprintf(stderr, "Image pixmap written to %s\n", ofile);
exit(0);
}
/*****************************************************************/
void procargs(int argc, char *argv[], char **outext, char **ifile, int *rawflag)
{
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
if(argc < 3) {
fprintf(stderr,
"Usage: %s <outext> <image file> [-raw_out]\n", argv[0]);
exit(-1);
}
*outext = argv[1];
*ifile = argv[2];
*rawflag = 0;
if(argc == 3)
return;
if((strncmp(argv[3], "-r", 2) == 0) ||
(strncmp(argv[3], "-raw", 4) == 0) ||
(strncmp(argv[3], "-raw_out", 8) == 0)){
*rawflag = 1;
return;
}
else {
fprintf(stderr,
"Usage: %s <output extension> <filename> [-raw_out]\n", argv[0]);
exit(-1);
}
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slarft.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slarft_(char *direct, char *storev, int *n, int *
k, real *v, int *ldv, real *tau, real *t, int *ldt)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
February 29, 1992
Purpose
=======
SLARFT forms the triangular factor T of a real block reflector H
of order n, which is defined as a product of k elementary reflectors.
If DIRECT = 'F', H = H(1) H(2) . . . H(k) and T is upper triangular;
If DIRECT = 'B', H = H(k) . . . H(2) H(1) and T is lower triangular.
If STOREV = 'C', the vector which defines the elementary reflector
H(i) is stored in the i-th column of the array V, and
H = I - V * T * V'
If STOREV = 'R', the vector which defines the elementary reflector
H(i) is stored in the i-th row of the array V, and
H = I - V' * T * V
Arguments
=========
DIRECT (input) CHARACTER*1
Specifies the order in which the elementary reflectors are
multiplied to form the block reflector:
= 'F': H = H(1) H(2) . . . H(k) (Forward)
= 'B': H = H(k) . . . H(2) H(1) (Backward)
STOREV (input) CHARACTER*1
Specifies how the vectors which define the elementary
reflectors are stored (see also Further Details):
= 'C': columnwise
= 'R': rowwise
N (input) INTEGER
The order of the block reflector H. N >= 0.
K (input) INTEGER
The order of the triangular factor T (= the number of
elementary reflectors). K >= 1.
V (input/output) REAL array, dimension
(LDV,K) if STOREV = 'C'
(LDV,N) if STOREV = 'R'
The matrix V. See further details.
LDV (input) INTEGER
The leading dimension of the array V.
If STOREV = 'C', LDV >= max(1,N); if STOREV = 'R', LDV >= K.
TAU (input) REAL array, dimension (K)
TAU(i) must contain the scalar factor of the elementary
reflector H(i).
T (output) REAL array, dimension (LDT,K)
The k by k triangular factor T of the block reflector.
If DIRECT = 'F', T is upper triangular; if DIRECT = 'B', T is
lower triangular. The rest of the array is not used.
LDT (input) INTEGER
The leading dimension of the array T. LDT >= K.
Further Details
===============
The shape of the matrix V and the storage of the vectors which define
the H(i) is best illustrated by the following example with n = 5 and
k = 3. The elements equal to 1 are not stored; the corresponding
array elements are modified but restored on exit. The rest of the
array is not used.
DIRECT = 'F' and STOREV = 'C': DIRECT = 'F' and STOREV = 'R':
V = ( 1 ) V = ( 1 v1 v1 v1 v1 )
( v1 1 ) ( 1 v2 v2 v2 )
( v1 v2 1 ) ( 1 v3 v3 )
( v1 v2 v3 )
( v1 v2 v3 )
DIRECT = 'B' and STOREV = 'C': DIRECT = 'B' and STOREV = 'R':
V = ( v1 v2 v3 ) V = ( v1 v1 1 )
( v1 v2 v3 ) ( v2 v2 v2 1 )
( 1 v2 v3 ) ( v3 v3 v3 v3 1 )
( 1 v3 )
( 1 )
=====================================================================
Quick return if possible
Parameter adjustments
Function Body */
/* Table of constant values */
static int c__1 = 1;
static real c_b8 = 0.f;
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int t_dim1, t_offset, v_dim1, v_offset;
*/
int i__1, i__2, i__3;
real r__1;
/* Local variables */
static int i, j;
extern logical lsame_(char *, char *);
extern /* Subroutine */ int sgemv_(char *, int *, int *, real *,
real *, int *, real *, int *, real *, real *, int *), strmv_(char *, char *, char *, int *, real *,
int *, real *, int *);
static real vii;
#define TAU(I) tau[(I)-1]
#define V(I,J) v[(I)-1 + ((J)-1)* ( *ldv)]
#define T(I,J) t[(I)-1 + ((J)-1)* ( *ldt)]
if (*n == 0) {
return 0;
}
if (lsame_(direct, "F")) {
i__1 = *k;
for (i = 1; i <= *k; ++i) {
if (TAU(i) == 0.f) {
/* H(i) = I */
i__2 = i;
for (j = 1; j <= i; ++j) {
T(j,i) = 0.f;
/* L10: */
}
} else {
/* general case */
vii = V(i,i);
V(i,i) = 1.f;
if (lsame_(storev, "C")) {
/* T(1:i-1,i) := - tau(i) * V(i:n,1:i-1)'
* V(i:n,i) */
i__2 = *n - i + 1;
i__3 = i - 1;
r__1 = -(doublereal)TAU(i);
sgemv_("Transpose", &i__2, &i__3, &r__1, &V(i,1),
ldv, &V(i,i), &c__1, &c_b8, &T(1,i), &c__1);
} else {
/* T(1:i-1,i) := - tau(i) * V(1:i-1,i:n) *
V(i,i:n)' */
i__2 = i - 1;
i__3 = *n - i + 1;
r__1 = -(doublereal)TAU(i);
sgemv_("No transpose", &i__2, &i__3, &r__1, &V(1,i), ldv, &V(i,i), ldv, &c_b8, &T(1,i), &c__1);
}
V(i,i) = vii;
/* T(1:i-1,i) := T(1:i-1,1:i-1) * T(1:i-1,i) */
i__2 = i - 1;
strmv_("Upper", "No transpose", "Non-unit", &i__2, &T(1,1), ldt, &T(1,i), &c__1);
T(i,i) = TAU(i);
}
/* L20: */
}
} else {
for (i = *k; i >= 1; --i) {
if (TAU(i) == 0.f) {
/* H(i) = I */
i__1 = *k;
for (j = i; j <= *k; ++j) {
T(j,i) = 0.f;
/* L30: */
}
} else {
/* general case */
if (i < *k) {
if (lsame_(storev, "C")) {
vii = V(*n-*k+i,i);
V(*n-*k+i,i) = 1.f;
/* T(i+1:k,i) :=
- tau(i) * V(1:n-k+i,i+1
:k)' * V(1:n-k+i,i) */
i__1 = *n - *k + i;
i__2 = *k - i;
r__1 = -(doublereal)TAU(i);
sgemv_("Transpose", &i__1, &i__2, &r__1, &V(1,i+1), ldv, &V(1,i), &c__1, &
c_b8, &T(i+1,i), &c__1);
V(*n-*k+i,i) = vii;
} else {
vii = V(i,*n-*k+i);
V(i,*n-*k+i) = 1.f;
/* T(i+1:k,i) :=
- tau(i) * V(i+1:k,1:n-k
+i) * V(i,1:n-k+i)' */
i__1 = *k - i;
i__2 = *n - *k + i;
r__1 = -(doublereal)TAU(i);
sgemv_("No transpose", &i__1, &i__2, &r__1, &V(i+1,1), ldv, &V(i,1), ldv, &c_b8, &
T(i+1,i), &c__1);
V(i,*n-*k+i) = vii;
}
/* T(i+1:k,i) := T(i+1:k,i+1:k) * T(i+1:k,
i) */
i__1 = *k - i;
strmv_("Lower", "No transpose", "Non-unit", &i__1, &T(i+1,i+1), ldt, &T(i+1,i)
, &c__1);
}
T(i,i) = TAU(i);
}
/* L40: */
}
}
return 0;
/* End of SLARFT */
} /* slarft_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slamc2.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <stdio.h>
#include <f2c.h>
/* Subroutine */ int slamc2_(int *beta, int *t, logical *rnd, real *
eps, int *emin, real *rmin, int *emax, real *rmax)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAMC2 determines the machine parameters specified in its argument
list.
Arguments
=========
BETA (output) INTEGER
The base of the machine.
T (output) INTEGER
The number of ( BETA ) digits in the mantissa.
RND (output) LOGICAL
Specifies whether proper rounding ( RND = .TRUE. ) or
chopping ( RND = .FALSE. ) occurs in addition. This may not
be a reliable guide to the way in which the machine performs
its arithmetic.
EPS (output) REAL
The smallest positive number such that
fl( 1.0 - EPS ) .LT. 1.0,
where fl denotes the computed value.
EMIN (output) INTEGER
The minimum exponent before (gradual) underflow occurs.
RMIN (output) REAL
The smallest normalized number for the machine, given by
BASE**( EMIN - 1 ), where BASE is the floating point value
of BETA.
EMAX (output) INTEGER
The maximum exponent before overflow occurs.
RMAX (output) REAL
The largest positive number for the machine, given by
BASE**EMAX * ( 1 - EPS ), where BASE is the floating point
value of BETA.
Further Details
===============
The computation of EPS is based on a routine PARANOIA by
<NAME> of the University of California at Berkeley.
=====================================================================
*/
/* Table of constant values */
/* Unused variable commented out by MDG on 03-09-05
static int c__1 = 1;
*/
/* Initialized data */
static logical first = TRUE_;
static logical iwarn = FALSE_;
/* System generated locals */
int i__1;
real r__1, r__2, r__3, r__4, r__5;
/* Builtin functions */
double pow_ri(real *, int *);
/* Local variables */
static logical ieee;
static real half;
static logical lrnd;
static real leps, zero, a, b, c;
static int i, lbeta;
static real rbase;
static int lemin, lemax, gnmin;
static real small;
static int gpmin;
static real third, lrmin, lrmax, sixth;
static logical lieee1;
extern /* Subroutine */ int slamc1_(int *, int *, logical *,
logical *);
extern doublereal slamc3_(real *, real *);
extern /* Subroutine */ int slamc4_(int *, real *, int *),
slamc5_(int *, int *, int *, logical *, int *,
real *);
static int lt, ngnmin, ngpmin;
static real one, two;
if (first) {
first = FALSE_;
zero = 0.f;
one = 1.f;
two = 2.f;
/* LBETA, LT, LRND, LEPS, LEMIN and LRMIN are the local values
of
BETA, T, RND, EPS, EMIN and RMIN.
Throughout this routine we use the function SLAMC3 to ens
ure
that relevant values are stored and not held in registers,
or
are not affected by optimizers.
SLAMC1 returns the parameters LBETA, LT, LRND and LIEEE1.
*/
slamc1_(&lbeta, <, &lrnd, &lieee1);
/* Start to find EPS. */
b = (real) lbeta;
i__1 = -lt;
a = pow_ri(&b, &i__1);
leps = a;
/* Try some tricks to see whether or not this is the correct E
PS. */
b = two / 3;
half = one / 2;
r__1 = -(doublereal)half;
sixth = slamc3_(&b, &r__1);
third = slamc3_(&sixth, &sixth);
r__1 = -(doublereal)half;
b = slamc3_(&third, &r__1);
b = slamc3_(&b, &sixth);
b = dabs(b);
if (b < leps) {
b = leps;
}
leps = 1.f;
/* + WHILE( ( LEPS.GT.B ).AND.( B.GT.ZERO ) )LOOP */
L10:
if (leps > b && b > zero) {
leps = b;
r__1 = half * leps;
/* Computing 5th power */
r__3 = two, r__4 = r__3, r__3 *= r__3;
/* Computing 2nd power */
r__5 = leps;
r__2 = r__4 * (r__3 * r__3) * (r__5 * r__5);
c = slamc3_(&r__1, &r__2);
r__1 = -(doublereal)c;
c = slamc3_(&half, &r__1);
b = slamc3_(&half, &c);
r__1 = -(doublereal)b;
c = slamc3_(&half, &r__1);
b = slamc3_(&half, &c);
goto L10;
}
/* + END WHILE */
if (a < leps) {
leps = a;
}
/* Computation of EPS complete.
Now find EMIN. Let A = + or - 1, and + or - (1 + BASE**(-3
)).
Keep dividing A by BETA until (gradual) underflow occurs. T
his
is detected when we cannot recover the previous A. */
rbase = one / lbeta;
small = one;
for (i = 1; i <= 3; ++i) {
r__1 = small * rbase;
small = slamc3_(&r__1, &zero);
/* L20: */
}
a = slamc3_(&one, &small);
slamc4_(&ngpmin, &one, &lbeta);
r__1 = -(doublereal)one;
slamc4_(&ngnmin, &r__1, &lbeta);
slamc4_(&gpmin, &a, &lbeta);
r__1 = -(doublereal)a;
slamc4_(&gnmin, &r__1, &lbeta);
ieee = FALSE_;
if (ngpmin == ngnmin && gpmin == gnmin) {
if (ngpmin == gpmin) {
lemin = ngpmin;
/* ( Non twos-complement machines, no gradual under
flow;
e.g., VAX ) */
} else if (gpmin - ngpmin == 3) {
lemin = ngpmin - 1 + lt;
ieee = TRUE_;
/* ( Non twos-complement machines, with gradual und
erflow;
e.g., IEEE standard followers ) */
} else {
lemin = min(ngpmin,gpmin);
/* ( A guess; no known machine ) */
iwarn = TRUE_;
}
} else if (ngpmin == gpmin && ngnmin == gnmin) {
if ((i__1 = ngpmin - ngnmin, abs(i__1)) == 1) {
lemin = max(ngpmin,ngnmin);
/* ( Twos-complement machines, no gradual underflow
;
e.g., CYBER 205 ) */
} else {
lemin = min(ngpmin,ngnmin);
/* ( A guess; no known machine ) */
iwarn = TRUE_;
}
} else if ((i__1 = ngpmin - ngnmin, abs(i__1)) == 1 && gpmin == gnmin)
{
if (gpmin - min(ngpmin,ngnmin) == 3) {
lemin = max(ngpmin,ngnmin) - 1 + lt;
/* ( Twos-complement machines with gradual underflo
w;
no known machine ) */
} else {
lemin = min(ngpmin,ngnmin);
/* ( A guess; no known machine ) */
iwarn = TRUE_;
}
} else {
/* Computing MIN */
i__1 = min(ngpmin,ngnmin), i__1 = min(i__1,gpmin);
lemin = min(i__1,gnmin);
/* ( A guess; no known machine ) */
iwarn = TRUE_;
}
/* **
Comment out this if block if EMIN is ok */
if (iwarn) {
first = TRUE_;
printf("\n\n WARNING. The value EMIN may be incorrect:- ");
/*
printf("EMIN = %8i\n",lemin);
*/
/* %8ld added by MDG on 03-09-05
changed to %8d by JCK on 2009-02-02 because of change in f2c.h */
printf("EMIN = %8d\n",lemin);
printf("If, after inspection, the value EMIN looks acceptable");
printf("please comment out \n the IF block as marked within the");
printf("code of routine SLAMC2, \n otherwise supply EMIN");
printf("explicitly.\n");
}
/* **
Assume IEEE arithmetic if we found denormalised numbers abo
ve,
or if arithmetic seems to round in the IEEE style, determi
ned
in routine SLAMC1. A true IEEE machine should have both thi
ngs
true; however, faulty machines may have one or the other. */
ieee = ieee || lieee1;
/* Compute RMIN by successive division by BETA. We could comp
ute
RMIN as BASE**( EMIN - 1 ), but some machines underflow dur
ing
this computation. */
lrmin = 1.f;
i__1 = 1 - lemin;
for (i = 1; i <= 1-lemin; ++i) {
r__1 = lrmin * rbase;
lrmin = slamc3_(&r__1, &zero);
/* L30: */
}
/* Finally, call SLAMC5 to compute EMAX and RMAX. */
slamc5_(&lbeta, <, &lemin, &ieee, &lemax, &lrmax);
}
*beta = lbeta;
*t = lt;
*rnd = lrnd;
*eps = leps;
*emin = lemin;
*rmin = lrmin;
*emax = lemax;
*rmax = lrmax;
return 0;
/* End of SLAMC2 */
} /* slamc2_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slascl.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slascl_(char *type, int *kl, int *ku, real *
cfrom, real *cto, int *m, int *n, real *a, int *lda,
int *info)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
February 29, 1992
Purpose
=======
SLASCL multiplies the M by N real matrix A by the real scalar
CTO/CFROM. This is done without over/underflow as long as the final
result CTO*A(I,J)/CFROM does not over/underflow. TYPE specifies that
A may be full, upper triangular, lower triangular, upper Hessenberg,
or banded.
Arguments
=========
TYPE (input) CHARACTER*1
TYPE indices the storage type of the input matrix.
= 'G': A is a full matrix.
= 'L': A is a lower triangular matrix.
= 'U': A is an upper triangular matrix.
= 'H': A is an upper Hessenberg matrix.
= 'B': A is a symmetric band matrix with lower bandwidth KL
and upper bandwidth KU and with the only the lower
half stored.
= 'Q': A is a symmetric band matrix with lower bandwidth KL
and upper bandwidth KU and with the only the upper
half stored.
= 'Z': A is a band matrix with lower bandwidth KL and upper
bandwidth KU.
KL (input) INTEGER
The lower bandwidth of A. Referenced only if TYPE = 'B',
'Q' or 'Z'.
KU (input) INTEGER
The upper bandwidth of A. Referenced only if TYPE = 'B',
'Q' or 'Z'.
CFROM (input) REAL
CTO (input) REAL
The matrix A is multiplied by CTO/CFROM. A(I,J) is computed
without over/underflow if the final result CTO*A(I,J)/CFROM
can be represented without over/underflow. CFROM must be
nonzero.
M (input) INTEGER
The number of rows of the matrix A. M >= 0.
N (input) INTEGER
The number of columns of the matrix A. N >= 0.
A (input/output) REAL array, dimension (LDA,M)
The matrix to be multiplied by CTO/CFROM. See TYPE for the
storage type.
LDA (input) INTEGER
The leading dimension of the array A. LDA >= max(1,M).
INFO (output) INTEGER
0 - successful exit
<0 - if INFO = -i, the i-th argument had an illegal value.
=====================================================================
Test the input arguments
Parameter adjustments
Function Body */
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
integer a_dim1, a_offset;
*/
int i__1, i__2, i__3, i__4, i__5;
/* Local variables */
static logical done;
static real ctoc;
static int i, j;
extern logical lsame_(char *, char *);
static int itype, k1, k2, k3, k4;
static real cfrom1;
extern doublereal slamch_(char *);
static real cfromc;
extern /* Subroutine */ int xerbla_(char *, int *);
static real bignum, smlnum, mul, cto1;
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
*info = 0;
if (lsame_(type, "G")) {
itype = 0;
} else if (lsame_(type, "L")) {
itype = 1;
} else if (lsame_(type, "U")) {
itype = 2;
} else if (lsame_(type, "H")) {
itype = 3;
} else if (lsame_(type, "B")) {
itype = 4;
} else if (lsame_(type, "Q")) {
itype = 5;
} else if (lsame_(type, "Z")) {
itype = 6;
} else {
itype = -1;
}
if (itype == -1) {
*info = -1;
} else if (*cfrom == 0.f) {
*info = -4;
} else if (*m < 0) {
*info = -6;
/*
} else if (*n < 0 || itype == 4 && *n != *m || itype == 5 && *n != *m) {
*/
/* Parentheses added by MDG on 03-09-05 */
} else if (*n < 0 || (itype == 4 && *n != *m) ||
(itype == 5 && *n != *m)) {
*info = -7;
} else if (itype <= 3 && *lda < max(1,*m)) {
*info = -9;
} else if (itype >= 4) {
/* Computing MAX */
i__1 = *m - 1;
if (*kl < 0 || *kl > max(i__1,0)) {
*info = -2;
} else /* if(complicated condition) */ {
/* Computing MAX */
i__1 = *n - 1;
/*
if (*ku < 0 || *ku > max(i__1,0) || (itype == 4 || itype == 5) &&
*kl != *ku) {
*/
/* Parentheses added by MDG on 03-09-05 */
if (*ku < 0 || *ku > max(i__1,0) ||
((itype == 4 || itype == 5) && *kl != *ku)) {
*info = -3;
/*
} else if (itype == 4 && *lda < *kl + 1 || itype == 5 && *lda < *
ku + 1 || itype == 6 && *lda < (*kl << 1) + *ku + 1) {
*/
/* Parentheses added by MDG on 03-09-05 */
} else if ((itype == 4 && *lda < *kl + 1) ||
(itype == 5 && *lda < *ku + 1) ||
(itype == 6 && *lda < (*kl << 1) + *ku + 1)) {
*info = -9;
}
}
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("SLASCL", &i__1);
return 0;
}
/* Quick return if possible */
if (*n == 0 || *m == 0) {
return 0;
}
/* Get machine parameters */
smlnum = slamch_("S");
bignum = 1.f / smlnum;
cfromc = *cfrom;
ctoc = *cto;
L10:
cfrom1 = cfromc * smlnum;
cto1 = ctoc / bignum;
if (dabs(cfrom1) > dabs(ctoc) && ctoc != 0.f) {
mul = smlnum;
done = FALSE_;
cfromc = cfrom1;
} else if (dabs(cto1) > dabs(cfromc)) {
mul = bignum;
done = FALSE_;
ctoc = cto1;
} else {
mul = ctoc / cfromc;
done = TRUE_;
}
if (itype == 0) {
/* Full matrix */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
A(i,j) *= mul;
/* L20: */
}
/* L30: */
}
} else if (itype == 1) {
/* Lower triangular matrix */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = *m;
for (i = j; i <= *m; ++i) {
A(i,j) *= mul;
/* L40: */
}
/* L50: */
}
} else if (itype == 2) {
/* Upper triangular matrix */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
i__2 = min(j,*m);
for (i = 1; i <= min(j,*m); ++i) {
A(i,j) *= mul;
/* L60: */
}
/* L70: */
}
} else if (itype == 3) {
/* Upper Hessenberg matrix */
i__1 = *n;
for (j = 1; j <= *n; ++j) {
/* Computing MIN */
i__3 = j + 1;
i__2 = min(i__3,*m);
for (i = 1; i <= min(j+1,*m); ++i) {
A(i,j) *= mul;
/* L80: */
}
/* L90: */
}
} else if (itype == 4) {
/* Lower half of a symmetric band matrix */
k3 = *kl + 1;
k4 = *n + 1;
i__1 = *n;
for (j = 1; j <= *n; ++j) {
/* Computing MIN */
i__3 = k3, i__4 = k4 - j;
i__2 = min(i__3,i__4);
for (i = 1; i <= min(k3,k4-j); ++i) {
A(i,j) *= mul;
/* L100: */
}
/* L110: */
}
} else if (itype == 5) {
/* Upper half of a symmetric band matrix */
k1 = *ku + 2;
k3 = *ku + 1;
i__1 = *n;
for (j = 1; j <= *n; ++j) {
/* Computing MAX */
i__2 = k1 - j;
i__3 = k3;
for (i = max(k1-j,1); i <= k3; ++i) {
A(i,j) *= mul;
/* L120: */
}
/* L130: */
}
} else if (itype == 6) {
/* Band matrix */
k1 = *kl + *ku + 2;
k2 = *kl + 1;
k3 = (*kl << 1) + *ku + 1;
k4 = *kl + *ku + 1 + *m;
i__1 = *n;
for (j = 1; j <= *n; ++j) {
/* Computing MAX */
i__3 = k1 - j;
/* Computing MIN */
i__4 = k3, i__5 = k4 - j;
i__2 = min(i__4,i__5);
for (i = max(k1-j,k2); i <= min(k3,k4-j); ++i) {
A(i,j) *= mul;
/* L140: */
}
/* L150: */
}
}
if (! done) {
goto L10;
}
return 0;
/* End of SLASCL */
} /* slascl_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slasr.c
|
<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
*
* UPDATED: 03/09/2005 by MDG
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slasr_(char *side, char *pivot, char *direct, int *m,
int *n, real *c, real *s, real *a, int *lda)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLASR performs the transformation
A := P*A, when SIDE = 'L' or 'l' ( Left-hand side )
A := A*P', when SIDE = 'R' or 'r' ( Right-hand side )
where A is an m by n real matrix and P is an orthogonal matrix,
consisting of a sequence of plane rotations determined by the
parameters PIVOT and DIRECT as follows ( z = m when SIDE = 'L' or 'l'
and z = n when SIDE = 'R' or 'r' ):
When DIRECT = 'F' or 'f' ( Forward sequence ) then
P = P( z - 1 )*...*P( 2 )*P( 1 ),
and when DIRECT = 'B' or 'b' ( Backward sequence ) then
P = P( 1 )*P( 2 )*...*P( z - 1 ),
where P( k ) is a plane rotation matrix for the following planes:
when PIVOT = 'V' or 'v' ( Variable pivot ),
the plane ( k, k + 1 )
when PIVOT = 'T' or 't' ( Top pivot ),
the plane ( 1, k + 1 )
when PIVOT = 'B' or 'b' ( Bottom pivot ),
the plane ( k, z )
c( k ) and s( k ) must contain the cosine and sine that define the
matrix P( k ). The two by two plane rotation part of the matrix
P( k ), R( k ), is assumed to be of the form
R( k ) = ( c( k ) s( k ) ).
( -s( k ) c( k ) )
This version vectorises across rows of the array A when SIDE = 'L'.
Arguments
=========
SIDE (input) CHARACTER*1
Specifies whether the plane rotation matrix P is applied to
A on the left or the right.
= 'L': Left, compute A := P*A
= 'R': Right, compute A:= A*P'
DIRECT (input) CHARACTER*1
Specifies whether P is a forward or backward sequence of
plane rotations.
= 'F': Forward, P = P( z - 1 )*...*P( 2 )*P( 1 )
= 'B': Backward, P = P( 1 )*P( 2 )*...*P( z - 1 )
PIVOT (input) CHARACTER*1
Specifies the plane for which P(k) is a plane rotation
matrix.
= 'V': Variable pivot, the plane (k,k+1)
= 'T': Top pivot, the plane (1,k+1)
= 'B': Bottom pivot, the plane (k,z)
M (input) INTEGER
The number of rows of the matrix A. If m <= 1, an immediate
return is effected.
N (input) INTEGER
The number of columns of the matrix A. If n <= 1, an
immediate return is effected.
C, S (input) REAL arrays, dimension
(M-1) if SIDE = 'L'
(N-1) if SIDE = 'R'
c(k) and s(k) contain the cosine and sine that define the
matrix P(k). The two by two plane rotation part of the
matrix P(k), R(k), is assumed to be of the form
R( k ) = ( c( k ) s( k ) ).
( -s( k ) c( k ) )
A (input/output) REAL array, dimension (LDA,N)
The m by n matrix A. On exit, A is overwritten by P*A if
SIDE = 'R' or by A*P' if SIDE = 'L'.
LDA (input) INTEGER
The leading dimension of the array A. LDA >= max(1,M).
=====================================================================
Test the input parameters
Parameter adjustments
Function Body */
/* System generated locals */
/* Unused variables commented out by MDG on 03-09-05
int a_dim1, a_offset;
*/
int i__1, i__2;
/* Local variables */
static int info;
static real temp;
static int i, j;
extern logical lsame_(char *, char *);
static real ctemp, stemp;
extern /* Subroutine */ int xerbla_(char *, int *);
#define C(I) c[(I)-1]
#define S(I) s[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
info = 0;
if (! (lsame_(side, "L") || lsame_(side, "R"))) {
info = 1;
} else if (! (lsame_(pivot, "V") || lsame_(pivot, "T") ||
lsame_(pivot, "B"))) {
info = 2;
} else if (! (lsame_(direct, "F") || lsame_(direct, "B")))
{
info = 3;
} else if (*m < 0) {
info = 4;
} else if (*n < 0) {
info = 5;
} else if (*lda < max(1,*m)) {
info = 9;
}
if (info != 0) {
xerbla_("SLASR ", &info);
return 0;
}
/* Quick return if possible */
if (*m == 0 || *n == 0) {
return 0;
}
if (lsame_(side, "L")) {
/* Form P * A */
if (lsame_(pivot, "V")) {
if (lsame_(direct, "F")) {
i__1 = *m - 1;
for (j = 1; j <= *m-1; ++j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__2 = *n;
for (i = 1; i <= *n; ++i) {
temp = A(j+1,i);
A(j+1,i) = ctemp * temp - stemp * A(j,i);
A(j,i) = stemp * temp + ctemp * A(j,i);
/* L10: */
}
}
/* L20: */
}
} else if (lsame_(direct, "B")) {
for (j = *m - 1; j >= 1; --j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__1 = *n;
for (i = 1; i <= *n; ++i) {
temp = A(j+1,i);
A(j+1,i) = ctemp * temp - stemp * A(j,i);
A(j,i) = stemp * temp + ctemp * A(j,i);
/* L30: */
}
}
/* L40: */
}
}
} else if (lsame_(pivot, "T")) {
if (lsame_(direct, "F")) {
i__1 = *m;
for (j = 2; j <= *m; ++j) {
ctemp = C(j - 1);
stemp = S(j - 1);
if (ctemp != 1.f || stemp != 0.f) {
i__2 = *n;
for (i = 1; i <= *n; ++i) {
temp = A(j,i);
A(j,i) = ctemp * temp - stemp * A(1,i);
A(1,i) = stemp * temp + ctemp * A(1,i);
/* L50: */
}
}
/* L60: */
}
} else if (lsame_(direct, "B")) {
for (j = *m; j >= 2; --j) {
ctemp = C(j - 1);
stemp = S(j - 1);
if (ctemp != 1.f || stemp != 0.f) {
i__1 = *n;
for (i = 1; i <= *n; ++i) {
temp = A(j,i);
A(j,i) = ctemp * temp - stemp * A(1,i);
A(1,i) = stemp * temp + ctemp * A(1,i);
/* L70: */
}
}
/* L80: */
}
}
} else if (lsame_(pivot, "B")) {
if (lsame_(direct, "F")) {
i__1 = *m - 1;
for (j = 1; j <= *m-1; ++j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__2 = *n;
for (i = 1; i <= *n; ++i) {
temp = A(j,i);
A(j,i) = stemp * A(*m,i) +
ctemp * temp;
A(*m,i) = ctemp * A(*m,i) -
stemp * temp;
/* L90: */
}
}
/* L100: */
}
} else if (lsame_(direct, "B")) {
for (j = *m - 1; j >= 1; --j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__1 = *n;
for (i = 1; i <= *n; ++i) {
temp = A(j,i);
A(j,i) = stemp * A(*m,i) +
ctemp * temp;
A(*m,i) = ctemp * A(*m,i) -
stemp * temp;
/* L110: */
}
}
/* L120: */
}
}
}
} else if (lsame_(side, "R")) {
/* Form A * P' */
if (lsame_(pivot, "V")) {
if (lsame_(direct, "F")) {
i__1 = *n - 1;
for (j = 1; j <= *n-1; ++j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp = A(i,j+1);
A(i,j+1) = ctemp * temp - stemp *
A(i,j);
A(i,j) = stemp * temp + ctemp * A(i,j);
/* L130: */
}
}
/* L140: */
}
} else if (lsame_(direct, "B")) {
for (j = *n - 1; j >= 1; --j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__1 = *m;
for (i = 1; i <= *m; ++i) {
temp = A(i,j+1);
A(i,j+1) = ctemp * temp - stemp *
A(i,j);
A(i,j) = stemp * temp + ctemp * A(i,j);
/* L150: */
}
}
/* L160: */
}
}
} else if (lsame_(pivot, "T")) {
if (lsame_(direct, "F")) {
i__1 = *n;
for (j = 2; j <= *n; ++j) {
ctemp = C(j - 1);
stemp = S(j - 1);
if (ctemp != 1.f || stemp != 0.f) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp = A(i,j);
A(i,j) = ctemp * temp - stemp * A(i,1);
A(i,1) = stemp * temp + ctemp * A(i,1);
/* L170: */
}
}
/* L180: */
}
} else if (lsame_(direct, "B")) {
for (j = *n; j >= 2; --j) {
ctemp = C(j - 1);
stemp = S(j - 1);
if (ctemp != 1.f || stemp != 0.f) {
i__1 = *m;
for (i = 1; i <= *m; ++i) {
temp = A(i,j);
A(i,j) = ctemp * temp - stemp * A(i,1);
A(i,1) = stemp * temp + ctemp * A(i,1);
/* L190: */
}
}
/* L200: */
}
}
} else if (lsame_(pivot, "B")) {
if (lsame_(direct, "F")) {
i__1 = *n - 1;
for (j = 1; j <= *n-1; ++j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp = A(i,j);
A(i,j) = stemp * A(i,*n) +
ctemp * temp;
A(i,*n) = ctemp * A(i,*n) -
stemp * temp;
/* L210: */
}
}
/* L220: */
}
} else if (lsame_(direct, "B")) {
for (j = *n - 1; j >= 1; --j) {
ctemp = C(j);
stemp = S(j);
if (ctemp != 1.f || stemp != 0.f) {
i__1 = *m;
for (i = 1; i <= *m; ++i) {
temp = A(i,j);
A(i,j) = stemp * A(i,*n) +
ctemp * temp;
A(i,*n) = ctemp * A(i,*n) -
stemp * temp;
/* L230: */
}
}
/* L240: */
}
}
}
}
return 0;
/* End of SLASR */
} /* slasr_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/imgtools/src/bin/cjpegb/cjpegb.c
|
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/************************************************************************
PACKAGE: IMAGE ENCODER/DECODER TOOLS
FILE: CJPEGB.C
AUTHORS: <NAME>
<EMAIL>
<NAME>
<EMAIL>
DATE: 01/09/2001
UPDATED: 05/09/2005 by MDG
UPDATED: 09/30/2008 by Kenenth Ko - add version option.
UPDATED: 12/22/2008 by <NAME> - add read_raw()/read_ihead()
#cat: cjpegb - Takes an IHead or raw image pixmap and encodes it using
#cat: Baseline (Lossy) JPEG, writing the compressed data to file.
*************************************************************************/
#include <stdio.h>
#include <sys/param.h>
#include <jpegb.h>
#include <intrlv.h>
#include <ihead.h>
#include <img_io.h>
#include <dataio.h>
#include <parsargs.h>
#include <version.h>
void procargs(int, char **, int *, char **, char **, int *,
int *, int *, int *, int *, int *, char **);
void print_usage(char *);
int debug = 0;
/******************/
/*Start of Program*/
/******************/
int main(int argc, char *argv[])
{
int ret, i;
int quality, rawflag, intrlvflag;
char *outext; /* ouput file extension */
char *ifile, *cfile, ofile[MAXPATHLEN]; /* file names */
int width, height, depth, ppi; /* image parameters */
int ilen, olen;
IHEAD *ihead;
unsigned char *idata, *odata; /* image pointers */
char *comment_text;
int hor_sampfctr[MAX_CMPNTS], vrt_sampfctr[MAX_CMPNTS];
procargs(argc, argv, &quality, &outext, &ifile, &rawflag,
&width, &height, &depth, &ppi, &intrlvflag, &cfile);
/* If raw image flagged... */
if(rawflag) {
if((ret = read_raw(ifile, &idata, &width, &height, &depth)))
exit(ret);
}
/* Otherwise, input image is an IHead image */
else {
if((ret = read_ihead(ifile, &ihead, &idata, &width, &height, &depth)))
exit(ret);
}
if(debug > 0)
fprintf(stdout, "File %s read\n", ifile);
/* If IHead image file ... */
if(!rawflag){
/* Get PPI from IHead. */
ppi = get_density(ihead);
free(ihead);
}
if(cfile == (char *)NULL)
comment_text = (char *)NULL;
else{
if((ret = read_ascii_file(cfile, &comment_text))){
free(idata);
exit(ret);
}
}
/* If necessary, convert to interleaved. */
if((depth == 24) && (!intrlvflag)){
for(i = 0; i < MAX_CMPNTS; i++){
hor_sampfctr[i] = 1;
vrt_sampfctr[i] = 1;
}
if((ret = not2intrlv_mem(&odata, &olen, idata, width, height, depth,
hor_sampfctr, vrt_sampfctr, depth>>3))){
free(idata);
if(comment_text != (char *)NULL)
free(comment_text);
exit(ret);
}
free(idata);
idata = odata;
ilen = olen;
}
if((ret = jpegb_encode_mem(&odata, &olen, quality,
idata, width, height, depth, ppi, comment_text))){
free(idata);
if(comment_text != (char *)NULL)
free(comment_text);
return(ret);
}
free(idata);
if(comment_text != (char *)NULL)
free(comment_text);
if(debug > 0)
fprintf(stdout, "Image data encoded, compressed byte length = %d\n",
olen);
fileroot(ifile);
sprintf(ofile, "%s.%s", ifile, outext);
if((ret = write_raw_from_memsize(ofile, odata, olen))){
free(odata);
exit(ret);
}
if(debug > 0)
fprintf(stdout, "Image data written to file %s\n", ofile);
free(odata);
exit(0);
}
/*****************************************************************/
void procargs(int argc, char **argv, int *quality,
char **outext, char **ifile, int *rawflag,
int *width, int *height, int *depth, int *ppi,
int *intrlvflag, char **cfile)
{
int argi;
if ((argc == 2) && (strcmp(argv[1], "-version") == 0)) {
getVersion();
exit(0);
}
if((argc < 4) || (argc > 8)){
print_usage(argv[0]);
exit(-1);
}
*quality = atoi(argv[1]);
*outext = argv[2];
*ifile = argv[3];
*rawflag = 0;
*intrlvflag = 1;
*width = -1;
*height = -1;
*depth = -1;
*ppi = -1;
*cfile = (char *)NULL;
/* If argc == 4, we are done here. */
/* If IHead image file ... */
argi = 4;
if(argi >= argc)
return;
if(argc == 5){
*cfile = argv[argi];
return;
}
/* Otherwise (argc >= 6) expect raw flag ... */
if((strncmp(argv[argi], "-r", 2) == 0) ||
(strncmp(argv[argi], "-raw", 4) == 0) ||
(strncmp(argv[argi], "-raw_in", 7) == 0)) {
argi++;
if(argi >= argc){
print_usage(argv[0]);
fprintf(stderr,
" option \"-raw_in\" missing \"w,h,d,[ppi]\"\n");
exit(-1);
}
*rawflag = 1;
parse_w_h_d_ppi(argv[argi], argv[0], width, height, depth, ppi);
argi++;
if(argi >= argc)
return;
}
else{
print_usage(argv[0]);
fprintf(stderr,
" expected \"-raw_in\" option\n");
exit(-1);
}
/* If nonintrlv flag ... */
if(strncmp(argv[argi], "-n", 2) == 0){
*intrlvflag = 0;
argi++;
if(argi >= argc)
return;
}
/* If we get here, set comment file ... */
*cfile = argv[argi];
return;
}
/*****************************************************************/
void print_usage(char *arg0)
{
fprintf(stderr, "Usage: %s ", arg0);
fprintf(stderr, "<q=20-95> <outext> <image file>\n");
fprintf(stderr, " [-raw_in w,h,d,[ppi]\n");
fprintf(stderr, " [-nonintrlv]]\n");
fprintf(stderr, " [comment file]\n");
}
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/clapck/slamc5.c
|
<gh_stars>1-10
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/*
* ======================================================================
* NIST Guide to Available Math Software.
* Fullsource for module SSYEVX.C from package CLAPACK.
* Retrieved from NETLIB on Fri Mar 10 14:23:44 2000.
* ======================================================================
*/
#include <f2c.h>
/* Subroutine */ int slamc5_(int *beta, int *p, int *emin,
logical *ieee, int *emax, real *rmax)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
October 31, 1992
Purpose
=======
SLAMC5 attempts to compute RMAX, the largest machine floating-point
number, without overflow. It assumes that EMAX + abs(EMIN) sum
approximately to a power of 2. It will fail on machines where this
assumption does not hold, for example, the Cyber 205 (EMIN = -28625,
EMAX = 28718). It will also fail if the value supplied for EMIN is
too large (i.e. too close to zero), probably with overflow.
Arguments
=========
BETA (input) INTEGER
The base of floating-point arithmetic.
P (input) INTEGER
The number of base BETA digits in the mantissa of a
floating-point value.
EMIN (input) INTEGER
The minimum exponent before (gradual) underflow.
IEEE (input) LOGICAL
A logical flag specifying whether or not the arithmetic
system is thought to comply with the IEEE standard.
EMAX (output) INTEGER
The largest exponent before overflow
RMAX (output) REAL
The largest machine floating-point number.
=====================================================================
First compute LEXP and UEXP, two powers of 2 that bound
abs(EMIN). We then assume that EMAX + abs(EMIN) will sum
approximately to the bound that is closest to abs(EMIN).
(EMAX is the exponent of the required number RMAX). */
/* Table of constant values */
static real c_b5 = 0.f;
/* System generated locals */
int i__1;
real r__1;
/* Local variables */
static int lexp;
static real oldy;
static int uexp, i;
static real y, z;
static int nbits;
extern doublereal slamc3_(real *, real *);
static real recbas;
static int exbits, expsum, try__;
lexp = 1;
exbits = 1;
L10:
try__ = lexp << 1;
if (try__ <= -(*emin)) {
lexp = try__;
++exbits;
goto L10;
}
if (lexp == -(*emin)) {
uexp = lexp;
} else {
uexp = try__;
++exbits;
}
/* Now -LEXP is less than or equal to EMIN, and -UEXP is greater
than or equal to EMIN. EXBITS is the number of bits needed to
store the exponent. */
if (uexp + *emin > -lexp - *emin) {
expsum = lexp << 1;
} else {
expsum = uexp << 1;
}
/* EXPSUM is the exponent range, approximately equal to
EMAX - EMIN + 1 . */
*emax = expsum + *emin - 1;
nbits = exbits + 1 + *p;
/* NBITS is the total number of bits needed to store a
floating-point number. */
if (nbits % 2 == 1 && *beta == 2) {
/* Either there are an odd number of bits used to store a
floating-point number, which is unlikely, or some bits are
not used in the representation of numbers, which is possible
,
(e.g. Cray machines) or the mantissa has an implicit bit,
(e.g. IEEE machines, Dec Vax machines), which is perhaps the
most likely. We have to assume the last alternative.
If this is true, then we need to reduce EMAX by one because
there must be some way of representing zero in an implicit-b
it
system. On machines like Cray, we are reducing EMAX by one
unnecessarily. */
--(*emax);
}
if (*ieee) {
/* Assume we are on an IEEE machine which reserves one exponent
for infinity and NaN. */
--(*emax);
}
/* Now create RMAX, the largest machine number, which should
be equal to (1.0 - BETA**(-P)) * BETA**EMAX .
First compute 1.0 - BETA**(-P), being careful that the
result is less than 1.0 . */
recbas = 1.f / *beta;
z = *beta - 1.f;
y = 0.f;
i__1 = *p;
for (i = 1; i <= *p; ++i) {
z *= recbas;
if (y < 1.f) {
oldy = y;
}
y = slamc3_(&y, &z);
/* L20: */
}
if (y >= 1.f) {
y = oldy;
}
/* Now multiply by BETA**EMAX to get RMAX. */
i__1 = *emax;
for (i = 1; i <= *emax; ++i) {
r__1 = y * *beta;
y = slamc3_(&r__1, &c_b5);
/* L30: */
}
*rmax = y;
return 0;
/* End of SLAMC5 */
} /* slamc5_ */
|
ThalesGroup/WSQForAndroid
|
library/src/main/cpp/nbis/commonnbis/src/lib/ioutil/filetail.c
|
<reponame>ThalesGroup/WSQForAndroid
/*******************************************************************************
License:
This software and/or related materials was developed at the National Institute
of Standards and Technology (NIST) by employees of the Federal Government
in the course of their official duties. Pursuant to title 17 Section 105
of the United States Code, this software is not subject to copyright
protection and is in the public domain.
This software and/or related materials have been determined to be not subject
to the EAR (see Part 734.3 of the EAR for exact details) because it is
a publicly available technology and software, and is freely distributed
to any interested party with no licensing requirements. Therefore, it is
permissible to distribute this software as a free download from the internet.
Disclaimer:
This software and/or related materials was developed to promote biometric
standards and biometric technology testing for the Federal Government
in accordance with the USA PATRIOT Act and the Enhanced Border Security
and Visa Entry Reform Act. Specific hardware and software products identified
in this software were used in order to perform the software development.
In no case does such identification imply recommendation or endorsement
by the National Institute of Standards and Technology, nor does it imply that
the products and equipment identified are necessarily the best available
for the purpose.
This software and/or related materials are provided "AS-IS" without warranty
of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY,
NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY
or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the
licensed product, however used. In no event shall NIST be liable for any
damages and/or costs, including but not limited to incidental or consequential
damages of any kind, including economic damage or injury to property and lost
profits, regardless of whether NIST shall be advised, have reason to know,
or in fact shall know of the possibility.
By using this software, you agree to bear all risk relating to quality,
use and performance of the software and/or related materials. You agree
to hold the Government harmless from any claim arising from your use
of the software.
*******************************************************************************/
/***********************************************************************
LIBRARY: IOUTIL - INPUT/OUTPUT Utilities
FILE: FILETAIL.C
AUTHOR: <NAME>
DATE: 11/27/1989
UPDATED: 03/15/2005 by MDG
Contains routines responsible for extracing the "tail" of a
directory path contained in a file name string.
ROUTINES:
#cat: filetail - takes a full pathname and returns the information to the
#cat: right of the rightmost directory level.
***********************************************************************/
#include <string.h>
#include <sys/param.h>
/*************************************************************/
/* Filetail() is a destructive procedure which takes a path */
/* name and returns only the rightmost directory level. */
/*************************************************************/
void filetail(char *tail)
{
char *cptr;
char temp[MAXPATHLEN];
cptr = tail + strlen(tail);
while((cptr != tail) && (*cptr != '/'))
cptr--;
if(cptr != tail){
cptr++;
strcpy(temp,cptr);
strcpy(tail,temp);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.